// source --> http://www.kolarac.rs/wp-content/plugins/stachethemes_event_calendar/stachethemes/../front/js/stec.js?ver=4.8.25 
(function ($) {

    "use strict";
    
    /**
     * prefixes added to prevent conflicts
     * from jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
     */
    $.extend($.easing, {
        stecOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
        
        stecExpo: function (x, t, b, c, d) {
            if (t == 0) {
                return b;
            }
            
            if (t == d) {
                return b + c;
            }
            
            t = t / (d / 2);
            
            if (t < 1) {
                return c / 2 * Math.pow(2, 10 * (t - 1)) + b;
            }
            
            return c / 2 * (-Math.pow(2, -10 * --t) + 2) + b;
        }
    });
    
    /**
     *  Main Calendar front javascript
     */
    function stachethemesEventCalendar() {
        
        var moment = window.moment;
        
        var instance  = '',
            $instance = '';
    
        var stecLang = window.stecLang;
        
        var glob = {
            
            options: {
                day: 1,
                month: 2,
                year: 2016,
                view: 'month',
                monthLabelsShort: [
                    stecLang.jan, 
                    stecLang.feb, 
                    stecLang.mar, 
                    stecLang.apr, 
                    stecLang.may, 
                    stecLang.jun, 
                    stecLang.jul, 
                    stecLang.aug, 
                    stecLang.sep, 
                    stecLang.oct, 
                    stecLang.nov, 
                    stecLang.dec
                ],
                monthLabels: [
                    stecLang.january, 
                    stecLang.february, 
                    stecLang.march, 
                    stecLang.april, 
                    stecLang.may, 
                    stecLang.june, 
                    stecLang.july, 
                    stecLang.august, 
                    stecLang.september, 
                    stecLang.october, 
                    stecLang.november,
                    stecLang.december
                ],
                dayLabels: [
                    stecLang.sunday,
                    stecLang.monday, 
                    stecLang.tuesday, 
                    stecLang.wednesday,
                    stecLang.thursday,
                    stecLang.friday,
                    stecLang.saturday
                ],
                dayLabelsShort: [
                    stecLang.sun,
                    stecLang.mon, 
                    stecLang.tue, 
                    stecLang.wed,
                    stecLang.thu,
                    stecLang.fri,
                    stecLang.sat
                ],
                myLocation: ''
            },
            
            template: {
                event: '',
                eventInner: '',
                preloader: '',
                reminder: '',
                tooltip: '',
                eventCreateForm: ''
            },
            
            blockAction: false,
            
            ajax: null
        };
        
        var helper = {
            
            animate: false,
            
            isEmail: function (email) {
                var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
                return regex.test(email);
            },
            
            /**
             * Date to ICS time string
             * @returns yyyymmddThhmmssZ
             * NOTE UTC FORMAT!
             * 
             * NOTICE RFC IS 12 MONTHS, Adding + 1 to month!
             */
            dateToRFC: function(date) {
                
                date = helper.treatAsUTC(date);
                
                function addZero(num) {
                    return num < 10 ? '0' + num : num;
                };
                
                var string = date.getFullYear() + '' + addZero(date.getMonth() + 1) + '' + addZero(date.getDate()) + 'T' + addZero(date.getHours()) + '' + addZero(date.getMinutes()) + '' + addZero(date.getSeconds());
                
                return string + 'Z';
                
            },
            
            eventToGoogleCalImportLink: function(eventId, repeatOffset) {
                
                var event = calData.getEventById(eventId);
                
                var d1 = helper.dbDateTimeToDate(event.start_date);
                    d1.setTime(d1.getTime() + repeatOffset * 1000);
                
                var start_date = helper.dateToRFC(d1);
                
                var d2 = helper.dbDateTimeToDate(event.end_date);
                    d2.setTime(d2.getTime() + repeatOffset * 1000);
                
                var end_date = helper.dateToRFC(d2);
                
                var description = event.description_short;
                var location = event.location;
                
                return "https://calendar.google.com/calendar/render?action=TEMPLATE&text="+event.summary+"&dates="+start_date+"/"+end_date+"&details="+description+"&location="+location+"&sf=true&output=xml";
            },
            
            /**
             * Returns user friendly timespan
             * Accepted params for start and end are String (DbDate) or Date object
             * @param {mixed} start
             * @param {mixed} end 
             * @returns {String}
             */
            beautifyTimespan: function(start, end, all_day) {
                
                all_day = parseInt(all_day, 10);
                var d1  = start instanceof Date ? start : helper.dbDateTimeToDate(start);
                var d2  = end instanceof Date ? end : helper.dbDateTimeToDate(end);
                
                var format = '';
                    
                switch(glob.options.general_settings.date_format) {
                    case 'dd.mm.yy' :
                        format = 'd.M.y';
                    break;
                    case 'dd-mm-yy' :
                        format = 'd M y';
                    break;
                    case 'mm-dd-yy' :
                        format = 'M d y';
                    break;
                    case 'yy-mm-dd' :
                        format = 'y M d';
                    break;
                }
                
                // Show time only if not all_day event
                if (all_day != 1) { 
                    format += ' h:i';
                }
                
                var timespanLabel = '';
                
                // Same Day
                if (
                        d1.getDate()     == d2.getDate()     && 
                        d1.getMonth()    == d2.getMonth()    && 
                        d1.getFullYear() == d2.getFullYear()
                        
                    ) {
                
                    timespanLabel = helper.dateToFormat(format, d1);
                    
                    if (all_day != 1) {
                        timespanLabel += " - " + helper.dateToFormat('h:i', d2);
                    }
                    
                } else
                
                // Same Month & Year
                if (
                        d1.getDate()    != d2.getDate()      && 
                        d1.getMonth()    == d2.getMonth()    && 
                        d1.getFullYear() == d2.getFullYear()
                        
                    ) {
                    
                    var formatEnd = format.replace('y','');
                    
                    timespanLabel = helper.dateToFormat(format, d1);
                    timespanLabel += " - " + helper.dateToFormat(formatEnd, d2);
                    
                } 
                
                // Default
                else {
                    
                    timespanLabel = helper.dateToFormat(format, d1);
                    timespanLabel += " - " + helper.dateToFormat(format, d2);
                    
                } 
                
                return timespanLabel;
                
            },
            
            // @todo change with date.UTC ?
            // used for dateToRFC
            treatAsUTC: function (date) {
                
                var result = date instanceof Date ? date : new Date(date);
               
                var adjustedMinutes = result.getMinutes() + result.getTimezoneOffset(); 
                
                result.setMinutes(adjustedMinutes);
                
                return result;
            },
            
            diffDays: function (dt1, dt2) {
                return Math.abs(moment(dt2).diff(dt1, 'days'));
            },
            
            diffWeeks: function (d1, d2) {
                return Math.abs(moment(d2).diff(d1, 'weeks'));
            },
            
            focus: function(el) {
                
                if (parseInt(glob.options.general_settings.event_auto_focus, 10) !== 1) {
                    return;
                }
                
                $('html, body').animate({
                    scrollTop: $(el).offset().top - $("#wpadminbar").height() + parseInt(glob.options.general_settings.event_auto_focus_offset, 10)
                }, {
                    duration: 750,
                    easing: "stecExpo"
                });
            },
            
            nl2br: function (txt) {
                return txt.replace(/(\r\n|\n\r|\r|\n)/g, "<br>");
            },
            
            capitalize: function (text) {
                return text.charAt(0).toUpperCase() + text.slice(1);
            },
            
            imgLoaded: function ($img, callback, step) {

                if (typeof $.fn.imagesLoaded !== "undefined") {
                    // imagesLoaded script is loaded
                    $img.imagesLoaded(function () {
                        if (typeof callback === "function") {
                            callback.call($img);
                        }
                    });
                    return;
                }

                var total = $img.length;
                var loaded = 0;

                if (total <= 0) {
                    if (typeof callback === "function") {
                        callback.call($img);
                    }
                }

                $img.each(function () {
                    var image = new Image;
                    image.onload = function () {

                        if (typeof step === "function") {
                            step();
                        }

                        loaded++;
                        if (loaded >= total) {
                            if (typeof callback === "function") {
                                callback.call($img);
                            }
                        }
                    };

                    image.onerror = function () {
                        console.warn("Could not load image");
                    };

                    image.src = $(this).attr("src");
                });
            },
            
            capitalizeFirstLetter: function (string) {
                return string.charAt(0).toUpperCase() + string.slice(1);
            },
            
            /**
             * returns now Date for given calendar offset
             * @param {int} hoursOffset
             * @returns {Date} date object
             */
            getCalNow: function(hoursOffset) {
                
                var date   = new Date();
                    date.setMinutes(date.getMinutes() + date.getTimezoneOffset()); // UTC now
                    
                    date.setHours(date.getHours() + hoursOffset); // UTC now + hours offset
                    
                return date;
                
            },
            
            /**
             * @param {type} string dbDate string
             * @param {type} offset unixstamp
             * @returns {String} dbDate string
             */
            dbDateOffset: function(string, offset) {
                var date = this.dbDateTimeToDate(string);
                date.setTime(date.getTime() + offset * 1000);
                return this.dateToDbDateTime(date);
            },
            
            /**
             * expects months range 1-12
             * converts to 0-11
             * @param {str} string yy-mm-dd h:i:s
             */
            dbDateTimeToDate: function (string) {

                var date = string.replace(/(\s|:|-)/g,",").split(',');
                
                for(var i = 0; i < date.length; i++) {
                    date[i] = parseInt(date[i], 10);
                    
                    if (i == 1) {
                        date[i] = date[i] - 1;
                    }
                }
                
                var d = new Date(date[0], date[1], date[2], date[3], date[4]);
                    return d;
            },
            
            /*
             * Converts js date to db date
             * @param {obj} date
             * @returns {String}
             */
            dateToDbDateTime: function (date) {
                
                var string = '';
                
                var y = date.getFullYear();
                var m = date.getMonth() + 1;
                var d = date.getDate();
                var h = date.getHours();
                var i = date.getMinutes();
                var s = date.getSeconds();
                
                string += y;
                string += '-';
                string += m < 10 ? '0'+m : m;
                string += '-';
                string += d < 10 ? '0'+d : d;
                string += ' ';
                string += h < 10 ? '0'+h : h;
                string += ':';
                string += i < 10 ? '0'+i : i;
                string += ':';
                string += s < 10 ? '0'+s : s;
                
                return string;
            },
            
            dateToUnixStamp: function(date){
                return parseInt((date.getTime() / 1000).toFixed(0), 10);
            },
            
            dateToFormat: function(format, date){
                
                var hasTime = false;
                var ampm    = 'am';
                
                if (format === false) {
                    
                    switch (glob.options.general_settings.date_format) {
                        case 'dd-mm-yy' :
                            format = 'd m y';
                            break;
                        case 'mm-dd-yy' :
                            format = 'm d y';
                            break;
                        case 'yy-mm-dd' :
                            format = 'y m d';
                            break;
                    }
                    
                }
                
                format = format.split('');
                
                var string = '';
                
                $(format).each(function(){
                    switch(this) {
                        case 'y' :
                            string += date.getFullYear();
                        break;
                        case 'm' :
                            string += helper.capitalizeFirstLetter(glob.options.monthLabels[date.getMonth()]);
                        break;
                        case 'M' :
                            string += helper.capitalizeFirstLetter(glob.options.monthLabelsShort[date.getMonth()]);
                        break;
                        case 'd' :
                            string += date.getDate();
                        break;
                        case 'h' :
                            hasTime = true;
                            
                            var h = date.getHours();
                            
                            if (glob.options.general_settings.time_format == '12') {
                                
                                if (h == 12) {
                                    ampm = 'pm';
                                }
                                
                                if (h > 12) {
                                    h = h - 12;
                                    ampm = 'pm';
                                }
                                
                                if (h == 0) {
                                    h = 12;
                                    ampm = 'am';
                                }
                                
                                
                                string += h < 10 ? '0'+h : h;
                            } else {
                                string += h < 10 ? '0'+h : h;
                            }
                            
                        break;
                        case 'i' :
                            var m = date.getMinutes();
                            
                            m = m < 10 ? '0'+m : m;
                            
                            string += m;
                        break;
                        case 's' :
                            var s = date.getSeconds();
                            string += s < 10 ? '0'+s : s;
                        break;
                        
                        default: 
                            string += this;
                    }
                });
                
                if (hasTime && glob.options.general_settings.time_format == '12') {

                    string += ' ' + ampm;
                }
                
                return string;
            },
            
            getColorBrightness: function(hex){
                var hex = hex.substring(1);      // strip #
                var rgb = parseInt(hex, 16);   // convert rrggbb to decimal
                var r = (rgb >> 16) & 0xff;  // extract red
                var g = (rgb >> 8) & 0xff;   // extract green
                var b = (rgb >> 0) & 0xff;   // extract blue
                var luma = 0.2126 * r + 0.7152 * g + 0.0722 * b; // per ITU-R BT.709
                return luma;
            },
            
            extendBind: function(funcArr, sub, rtrn) {
                
                if (typeof window[funcArr] !== "undefined") {

                    if (sub) {

                        if (typeof window[funcArr][sub] !== "undefined") {
                            $(window[funcArr][sub]).each(function () {

                                if (typeof this == "function") {

                                    this({
                                        instance: instance,
                                        $instance: $instance,
                                        glob: glob,
                                        helper: helper,
                                        calData: calData,
                                        layout: layout,
                                        events: events
                                    }, rtrn ? rtrn : null);
                                }
                            });
                        }

                    } else {

                        $(window[funcArr]).each(function () {

                            if (typeof this == "function") {

                                this({
                                    instance: instance,
                                    $instance: $instance,
                                    glob: glob,
                                    helper: helper,
                                    calData: calData,
                                    layout: layout,
                                    events: events
                                }, rtrn ? rtrn : null);

                            }
                        });

                    }
                }

            },
            
            onResizeEnd: function (callback, time, keyslug) {
                var id;
                time = time ? time : 10;
                
                var handle = keyslug ? 'resize.'+keyslug : 'resize';
                
                $(window).on(handle, function () {

                    clearTimeout(id);
                    id = setTimeout(function () {
                        if (typeof callback === "function") {
                            callback.call();
                        }
                    }, time);
                });
            },
            
            iso8601Week: function (date) {
                var time;
                var 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;
            },
            
            /**
             * @param {Date} alt new Date()
             */
            getWeekInfo: function (alt) {

                var year, month, day;

                if (alt) {
                    year  = alt.getFullYear();
                    month = alt.getMonth();
                    day   = alt.getDate();
                } else {
                    year  = glob.options.year;
                    month = glob.options.month;
                    day   = glob.options.day;
                }

                var activeDate = new Date(year, month, day);
                
                switch (glob.options.general_settings.first_day_of_the_week) {
                    case 'mon' :
                        
                        if (activeDate.getDay() != 1) {
                            while (activeDate.getDay() != 1) {
                                activeDate.setDate(activeDate.getDate() - 1);
                            }
                        }
                        
                        break;

                    case 'sat' :
                        
                        if (activeDate.getDay() != 6) {
                            while (activeDate.getDay() != 6) {
                                activeDate.setDate(activeDate.getDate() - 1);
                            }
                        }
                        
                        break;

                    case 'sun' :
                        
                        if (activeDate.getDay() != 0) {
                            while (activeDate.getDay() != 0) {
                                activeDate.setDate(activeDate.getDate() - 1);
                            }
                        }
                        
                        break;
                }
                
                var firstDayOfTheWeek = new Date(activeDate);
                var lastDayOfTheWeek = new Date(firstDayOfTheWeek);
                    lastDayOfTheWeek.setDate(lastDayOfTheWeek.getDate() + 6);

                return {
                    start: {
                        day: firstDayOfTheWeek.getDate(),
                        month: firstDayOfTheWeek.getMonth(),
                        year: firstDayOfTheWeek.getFullYear()
                    },
                    end: {
                        day: lastDayOfTheWeek.getDate(),
                        month: lastDayOfTheWeek.getMonth(),
                        year: lastDayOfTheWeek.getFullYear()
                    },
                    week: helper.iso8601Week(activeDate)
                };
            },
            
            getMonthInfo: function (month, year) {

                if (isNaN(month)) {
                    month = parseInt(glob.options.month, 10);
                }

                if (isNaN(year)) {
                    year = parseInt(glob.options.year, 10);
                }

                var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

                var firstDay = new Date(year, month, 1);
                var startingDay = firstDay.getDay();

                var monthLength = daysInMonth[month];

                if (month == 1) {
                    if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
                        monthLength = 29;
                    }
                }

                var dayOffset = "";
                
                switch(glob.options.general_settings.first_day_of_the_week) {
                    case 'mon' :
                        dayOffset = startingDay - 1 < 0 ? startingDay + 6 : startingDay - 1;
                    break;
                    
                    case 'sat' :
                        dayOffset = startingDay - 7 < 0 ? startingDay + 1 : startingDay - 7;
                        
                    break;
                
                    case 'sun' :
                        dayOffset = startingDay;
                    break;
                }


                var monthInfo = {
                    startingDay: startingDay,
                    monthLength: monthLength,
                    year: year,
                    month: month,
                    dayOffset: dayOffset,
                    monthName: glob.options.monthLabels[month],
                    monthNameShort: glob.options.monthLabelsShort[month]
                };

                return monthInfo;
            },
            
            /**
             * data-date="yyyy-mm-dd" to Date()
             * @param {string} str yyyy-mm-dd
             * @returns {Date} returns new Date()
             */
            getDateFromData: function(str) {
                var d = str.split('-');
                return new Date(d[0],d[1],d[2]);
            },
            
            /**
             * Date() to yyy-mm-dd string
             * @param {Date} date
             * @returns {String}
             */
            getDataFromDate: function(date) {
                return date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate();
            },
            
            /**
             * Translates labels
             * @param {string} label
             * @param {object} week
             * @returns string
             */
            getWeekLabel: function (label, week) {
                
                return  label.replace(/sday/g, week.start.day)
                        .replace(/smonth/g, glob.options.monthLabelsShort[week.start.month])
                        .replace(/syear/g, week.start.year)
                        .replace(/eday/g, week.end.day)
                        .replace(/emonth/g, glob.options.monthLabelsShort[week.end.month])
                        .replace(/eyear/g, week.end.year);
                    
            },
        
            isMobile: function () {
                return (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) ? true : false;
            },
            
            clickHandle: function (sub) {
                
                var tap   = sub ? 'vclick.'  + sub   : 'vclick';
                var click = sub ? 'click.'  + sub   : 'click';
            
            
                return this.isMobile() ? tap : click;
                
            },
            
            instaClickHandle: function () {
                return this.isMobile() ? "touchstart" : "mousedown";
            }
        };
        
        this.init = function (options) {
            
            $.extend(glob.options, options);
            
            instance  = "#" + glob.options.id;
            $instance = $(instance);
            
            if ($instance.length <= 0) {
                console.log('Stachethemes Event Calendar - License is not activated');
                return;
            }
            
            if (helper.isMobile()) {
                $instance.addClass('stec-mobile');
            }
            
            $instance.$top    = $instance.children(".stec-top");                                 // top.inc.php wrap
            $instance.$agenda = $instance.children(".stec-layout").find(".stec-layout-agenda"); // layout.agenda.inc.php wrap
            $instance.$month  = $instance.children(".stec-layout").find(".stec-layout-month"); // layout.month.inc.php wrap
            $instance.$week   = $instance.children(".stec-layout").find(".stec-layout-week"); // layout.month.inc.php wrap
            $instance.$day    = $instance.children(".stec-layout").find(".stec-layout-day"); // layout.day.inc.php wrap
            $instance.$events = $instance.children(".stec-layout").find(".stec-layout-events"); // layout.event.inc.php wrap
            
            $instance.$top.path     = instance +  " .stec-top ";
            $instance.$agenda.path  = instance +  " .stec-layout .stec-layout-agenda ";
            $instance.$month.path   = instance +  " .stec-layout .stec-layout-month ";
            $instance.$week.path    = instance +  " .stec-layout .stec-layout-week ";
            $instance.$day.path     = instance +  " .stec-layout .stec-layout-day ";
            $instance.$events.path  = instance +  " .stec-layout-events ";
            
            glob.template.eventAapproval  = $instance.children(".stec-event-awaiting-approval-template").html();
            glob.template.eventCreateForm = $instance.children(".stec-event-create-form-template").html();
            glob.template.event           = $instance.children(".stec-event-template").html();
            glob.template.eventInner      = $instance.children(".stec-event-inner-template").html();
            glob.template.tooltip         = $instance.children(".stec-tooltip-template").html();
            glob.template.preloader       = $instance.children(".stec-preloader-template").html();
            glob.template.reminder        = $instance.children(".stec-layout-event-preview-reminder-template").html();
            
            glob.options.view = glob.options.general_settings.view;
            
            var now = new Date();
            
            // Go to user specified date on init
            if (typeof glob.options.start_date !== 'undefined') {
                now = new Date(glob.options.start_date);
            }
            
            glob.options.day   = now.getDate();
            glob.options.month = now.getMonth();
            glob.options.year  = now.getFullYear();
            
            if (typeof window.stecAnimate !== 'undefined') {
                helper.animate = new stecAnimate($instance);
            }
            
            preloader.add();
            
            top.init();
            layout.init();
            events.init();
            
            helper.extendBind("stachethemes_ec_extend");
            
        };
        
        /**
         * Calendar pre-init preloader 
         */
        var preloader = {

            add: function() {
                $(glob.template.preloader).addClass('stec-init-preloader stec-init-preloader-id-'+glob.options.id).insertBefore($instance);
            },
            
            destroy: function(){
                $('.stec-init-preloader-id-'+glob.options.id).remove();
            }
            
        };
      
        /**
         * handles top bar
         */
        var top = {
            
            dropDownScrollSpeed: 450,
            
            init: function () {
                this.bindControls();
                this.bindMobile();
            },
            
            bindMobile: function(){
                
                if (!helper.isMobile()) {
                    return;
                }
                
                $(document).on(helper.clickHandle(), function(){
                    
                    $instance.$top.find('.mobile-hover').removeClass('mobile-hover');
                    
                });
                
                $instance.$top.find('.stec-top-dropmenu-layouts').children('li').on(helper.clickHandle(), function (e) {
                    e.preventDefault();
                    e.stopPropagation();
                    $(this).toggleClass('mobile-hover');
                });

                $instance.$top.find('.stec-top-menu-date').children('li').on(helper.clickHandle(), function (e) {
                    e.preventDefault();
                    
                    $(this).toggleClass('mobile-hover');
                    
                    // on active; fill dropdowns
                    if ($(this).hasClass('mobile-hover')) {
                        e.stopPropagation();
                        // dropdown day display
                        if ($(this).hasClass('stec-top-menu-date-day')) {

                            $(this).attr("data-hovering", true);

                            $(this).find(".stec-top-menu-date-dropdown ul").remove();

                            var d = glob.options.day;

                            var html = '<ul>';

                            var m = helper.getMonthInfo();
                            var maxD = m.monthLength;

                            // center current year
                            for (var j = 0; j < 3; j++) {
                                d = d - 1 < 1 ? maxD : d - 1;
                            }
                            

                            for (var i = 0; i < 5; i++) {

                                d = d + 1 > maxD ? 1 : d + 1;

                                html += '<li><p data-day="' + d + '">' + d + '</p></li>';
                            }
                            html += '</ul>';

                            $(this).find(".stec-top-menu-date-control-up").after(html);

                            top.dateDropdownSetActive();
                        }

                        // Dropdown week display
                        if ($(this).hasClass('stec-top-menu-date-week')) {

                            $(this).find(".stec-top-menu-date-dropdown ul").remove();

                            var w = new Date(glob.options.year, glob.options.month, glob.options.day);
                            w.setDate(w.getDate() - 3 * 7);

                            var format = '';

                            switch (glob.options.general_settings.date_format) {
                                case 'dd-mm-yy' :
                                    format = 'sday smonth - eday emonth eyear';
                                    break;
                                case 'mm-dd-yy' :
                                    format = 'smonth sday - emonth eday eyear';
                                    break;
                                case 'yy-mm-dd' :
                                    format = 'smonth sday - eyear emonth eday';
                                    break;
                            }

                            var html = '<ul>';
                            for (var i = 0; i < 5; i++) {

                                w.setDate(w.getDate() + 7);

                                var week = helper.getWeekInfo(w);

                                var label = helper.getWeekLabel(format, week);

                                html += '<li><p data-week="' + week.week + '" data-date="' + week.start.year + "-" + week.start.month + "-" + week.start.day + '">' + label + '</p></li>';
                            }
                            html += '</ul>';

                            $(this).find(".stec-top-menu-date-control-up").after(html);

                            top.dateDropdownSetActive();
                        }

                        // Dropdown month display
                        if ($(this).hasClass('stec-top-menu-date-month')) {

                            $(this).find(".stec-top-menu-date-dropdown ul").remove();

                            var m = glob.options.month;

                            // center current month
                            for (var i = 0; i < 3; i++) {
                                m = m - 1 < 0 ? 11 : m - 1;
                            }

                            var html = '<ul>';
                            for (var i = 0; i < 5; i++) {
                                m = m + 1 > 11 ? 0 : m + 1;
                                html += '<li><p data-month="' + m + '">' + glob.options.monthLabels[m] + '</p></li>';
                            }
                            html += '</ul>';

                            $(this).find(".stec-top-menu-date-control-up").after(html);

                            top.dateDropdownSetActive();
                        }
                        

                        // Dropdown year display
                        if ($(this).hasClass('stec-top-menu-date-year')) {

                            $(this).find(".stec-top-menu-date-dropdown ul").remove();

                            var y = glob.options.year;

                            var html = '<ul>';

                            // center current year
                            y = y - 3;

                            for (var i = 0; i < 5; i++) {
                                y++;
                                html += '<li><p data-year="' + y + '">' + y + '</p></li>';
                            }
                            html += '</ul>';

                            $(this).find(".stec-top-menu-date-control-up").after(html);

                            top.dateDropdownSetActive();
                        }
                
                    }
                    
                });

                $instance.$top.find('.stec-top-menu-date-control-up, .stec-top-menu-date-control-down').on(helper.clickHandle(), function (e) {
                    e.stopPropagation();
                });
                    
            },
            
            bindControls: function () {
                
                var parent = this;
                
                // Click handle for top view buttons
                $instance.$top.find('[data-view]').on(helper.clickHandle(), function(){
                    glob.options.view = $(this).attr("data-view");
                    layout.set();
                });
                
                // Mousewheel for year dropdown
                $instance.$top.find(".stec-top-menu-date-year").on('DOMMouseScroll mousewheel', function (e) {

                    e.preventDefault();

                    if (e.originalEvent.wheelDelta > 0 || e.originalEvent.detail < 0) {
                        parent.dateYearScrollUp();
                    } else {
                        parent.dateYearScrollDown();
                    }
                });
                
                // Mousewheel for month dropdown
                $instance.$top.find(".stec-top-menu-date-month").on('DOMMouseScroll mousewheel', function (e) {

                    e.preventDefault();

                    if (e.originalEvent.wheelDelta > 0 || e.originalEvent.detail < 0) {
                        parent.dateMonthScrollUp();
                    } else {
                        parent.dateMonthScrollDown();
                    }
                });
                
                // Mousewheel for week dropdown
                $instance.$top.find(".stec-top-menu-date-week").on('DOMMouseScroll mousewheel', function (e) {

                    e.preventDefault();

                    if (e.originalEvent.wheelDelta > 0 || e.originalEvent.detail < 0) {
                        parent.dateWeekScrollUp();
                    } else {
                        parent.dateWeekScrollDown();
                    }
                });
                
                // Mousewheel for day dropdown
                $instance.$top.find(".stec-top-menu-date-day").on('DOMMouseScroll mousewheel', function (e) {

                    e.preventDefault();

                    if (e.originalEvent.wheelDelta > 0 || e.originalEvent.detail < 0) {
                        parent.dateDayScrollUp();
                    } else {
                        parent.dateDayScrollDown();
                    }
                });
                
                // Remove data-hovering from dropdown menu on mouseout
                $instance.$top.find(".stec-top-menu-date-year, .stec-top-menu-date-month, .stec-top-menu-date-week, .stec-top-menu-date-day").on("mouseleave", function(){
                    $(this).removeAttr("data-hovering");
                });
                
                // Dropdown day mouseenter display
                $instance.$top.find(".stec-top-menu-date-day").on("mouseenter", function(){
                    
                    if ($(this).attr("data-hovering")) return;
                    
                    $(this).attr("data-hovering", true);
                    
                    $(this).find(".stec-top-menu-date-dropdown ul").remove();
                    
                    var d = glob.options.day;
                    
                    var html = '<ul>';
                    
                        var m = helper.getMonthInfo();
                        var maxD = m.monthLength;
                        
                        // center current year
                        for (var j = 0; j < 3; j++) {
                            d = d - 1 < 1 ? maxD : d - 1;
                        };
                    
                        for (var i = 0; i < 5; i++) {
                            
                            d = d + 1 > maxD ? 1 : d + 1;
                            
                            html += '<li><p data-day="'+d+'">'+d+'</p></li>';
                        }
                    html += '</ul>';
                    
                    $(this).find(".stec-top-menu-date-control-up").after(html);
                    
                    top.dateDropdownSetActive();
                });
                
                // Dropdown week mouseenter display
                $instance.$top.find(".stec-top-menu-date-week").on("mouseenter", function(){
                    
                    if ($(this).attr("data-hovering")){ 
                        return;
                    }
                    
                    $(this).attr("data-hovering", true);
                    
                    $(this).find(".stec-top-menu-date-dropdown ul").remove();
                    
                    
                    var w = new Date(glob.options.year, glob.options.month, glob.options.day);
                        w.setDate(w.getDate() - 3*7);
                    
                    var format = '';
                    
                    switch(glob.options.general_settings.date_format) {
                        case 'dd-mm-yy' :
                            format = 'sday smonth - eday emonth eyear';
                        break;
                        case 'mm-dd-yy' :
                            format = 'smonth sday - emonth eday eyear';
                        break;
                        case 'yy-mm-dd' :
                            format = 'smonth sday - eyear emonth eday';
                        break;
                    }
                        
                    var html = '<ul>';
                        for (var i = 0; i < 5; i++) {
                            
                            w.setDate(w.getDate() + 7);
                            
                            var week = helper.getWeekInfo(w);

                            var label = helper.getWeekLabel(format, week);
                        
                            html += '<li><p data-week="'+week.week+'" data-date="'+ week.start.year + "-" + week.start.month + "-" + week.start.day +'">'+label+'</p></li>';
                        }
                    html += '</ul>';
                    
                    $(this).find(".stec-top-menu-date-control-up").after(html);
                    
                    top.dateDropdownSetActive();
                });
                
                // Dropdown month mouseenter display
                $instance.$top.find(".stec-top-menu-date-month").on("mouseenter", function(){
                    
                    if ($(this).attr("data-hovering")) {
                        return;
                    }
                    
                    $(this).attr("data-hovering", true);
                    
                    $(this).find(".stec-top-menu-date-dropdown ul").remove();
                    
                    var m = glob.options.month;
                    
                    // center current month
                    for (var i = 0; i < 3; i++) {
                        m = m - 1 < 0 ? 11 : m - 1;
                    }
                    
                    var html = '<ul>';
                        for (var i = 0; i < 5; i++) {
                            m = m + 1 > 11 ? 0 : m + 1;
                            html += '<li><p data-month="'+m+'">'+glob.options.monthLabels[m]+'</p></li>';
                        }
                    html += '</ul>';
                    
                    $(this).find(".stec-top-menu-date-control-up").after(html);
                    
                    top.dateDropdownSetActive();
                });
                
                // Dropdown year mouseenter display
                $instance.$top.find(".stec-top-menu-date-year").on("mouseenter", function(){
                    
                    if ($(this).attr("data-hovering")) {
                        return;
                    }
                    
                    $(this).attr("data-hovering", true);
                    
                    $(this).find(".stec-top-menu-date-dropdown ul").remove();
                    
                    var y = glob.options.year;
                    
                    var html = '<ul>';
                    
                        // center current year
                        y = y - 3;
                    
                        for (var i = 0; i < 5; i++) {
                            y++;
                            html += '<li><p data-year="'+y+'">'+y+'</p></li>';
                        }
                    html += '</ul>';
                    
                    $(this).find(".stec-top-menu-date-control-up").after(html);
                    
                    top.dateDropdownSetActive();
                });
                
                // Dropdown week control up
                $instance.$top.find(".stec-top-menu-date-week .stec-top-menu-date-control-up").on(helper.clickHandle(), function(e){
                    e.preventDefault();
                    parent.dateWeekScrollUp();
                });
                
                // Dropdown week control down
                $instance.$top.find(".stec-top-menu-date-week .stec-top-menu-date-control-down").on(helper.clickHandle(), function(e){
                    e.preventDefault();
                    parent.dateWeekScrollDown();
                });
                
                // Dropdown year control up
                $instance.$top.find(".stec-top-menu-date-year .stec-top-menu-date-control-up").on(helper.clickHandle(), function(e){
                    e.preventDefault();
                    parent.dateYearScrollUp();
                });
                
                // Dropdown year control down
                $instance.$top.find(".stec-top-menu-date-year .stec-top-menu-date-control-down").on(helper.clickHandle(), function(e){
                    e.preventDefault();
                    parent.dateYearScrollDown();
                });
                
                // Dropdown month control up
                $instance.$top.find(".stec-top-menu-date-month .stec-top-menu-date-control-up").on(helper.clickHandle(), function(e){
                    e.preventDefault();
                    parent.dateMonthScrollUp();
                });
                
                // Dropdown month control down
                $instance.$top.find(".stec-top-menu-date-month .stec-top-menu-date-control-down").on(helper.clickHandle(), function(e){
                    e.preventDefault();
                    parent.dateMonthScrollDown();
                });
                
                // Dropdown day control up
                $instance.$top.find(".stec-top-menu-date-day .stec-top-menu-date-control-up").on(helper.clickHandle(), function(e){
                    e.preventDefault();
                    parent.dateDayScrollUp();
                });
                
                // Dropdown day control down
                $instance.$top.find(".stec-top-menu-date-day .stec-top-menu-date-control-down").on(helper.clickHandle(), function(e){
                    e.preventDefault();
                    parent.dateDayScrollDown();
                });
                
                // Dropdown month li pick
                $(document).on(helper.clickHandle(), $instance.$top.path + ".stec-top-menu-date-month ul li", function(e){
                    
                    e.preventDefault();
                    
                    var month = $(this).find("[data-month]").attr("data-month");
                    
                    glob.options.month = parseInt(month, 10);
                    
                    var m = helper.getMonthInfo();
                    
                    if (glob.options.day > m.monthLength) {
                        glob.options.day = parseInt(m.monthLength, 10);
                    }
                    
                    layout.set();
                    
                });
                
                // Dropdown year li pick
                $(document).on(helper.clickHandle(), $instance.$top.path + ".stec-top-menu-date-year ul li", function(e){
                    
                    e.preventDefault();
                    
                    var year = $(this).find("[data-year]").attr("data-year");
                    
                    glob.options.year = parseInt(year, 10);
                    
                    layout.set();
                    
                });
                
                // Dropdown week li pick
                $(document).on(helper.clickHandle(), $instance.$top.path + ".stec-top-menu-date-week ul li", function(e){
                    
                    e.preventDefault();
                    
                    var d = helper.getDateFromData($(this).find("[data-date]").attr("data-date"));
                    
                    glob.options.year  = d.getFullYear();
                    glob.options.month = d.getMonth();
                    glob.options.day   = d.getDate();
                    
                    layout.set();
                    
                });
                
                // Dropdown day li pick
                $(document).on(helper.clickHandle(), $instance.$top.path + ".stec-top-menu-date-day ul li", function(e){
                    
                    e.preventDefault();
                    
                    glob.options.day = parseInt($(this).find("[data-day]").attr("data-day"), 10);
                    
                    layout.set();
                    
                });
                
                // Previous date depending on view layout
                $instance.$top.find("[data-action='previous']").on(helper.clickHandle(), function (e) {
                    
                    e.preventDefault();
                    
                    switch (glob.options.view) {
                        
                        case "agenda" :

                            glob.options.month = glob.options.month - 1;

                            if (glob.options.month < 0) {
                                glob.options.month = 11;
                                glob.options.year = glob.options.year - 1;
                            }
                            
                            glob.options.day = 1;

                            layout.set();
                            break;
                            
                        case "month" :

                            glob.options.month = glob.options.month - 1;

                            if (glob.options.month < 0) {
                                glob.options.month = 11;
                                glob.options.year = glob.options.year - 1;
                            }

                            layout.set();
                            break;
                            
                        case "week" :
                            
                            var week = helper.getWeekInfo();
                            
                            var next = new Date(week.start.year, week.start.month, week.start.day - 7);
                            
                            glob.options.year  = next.getFullYear();
                            glob.options.month = next.getMonth();
                            glob.options.day   = next.getDate();
                            
                            layout.set();

                        break
                        
                        case "day" :
                            
                            var m;
                            
                            if (glob.options.day - 1 < 1) {
                         
                                if (glob.options.month - 1 < 0) {
                                    
                                    glob.options.year = glob.options.year - 1;
                                    glob.options.month = 11;
                                    
                                    m = helper.getMonthInfo();
                                    glob.options.day = m.monthLength;
                                    
                                } else {
                                    
                                    glob.options.month = glob.options.month - 1;
                                    
                                    m = helper.getMonthInfo();
                                    glob.options.day = m.monthLength;
                                }
                                
                            } else {
                                glob.options.day = glob.options.day - 1;
                            }
                            
                            layout.set();
                        break;
                    }
                });
                
                // Next date depending on view layout
                $instance.$top.find("[data-action='next']").on(helper.clickHandle(), function (e) {
                    
                    e.preventDefault();
                    
                    switch (glob.options.view) {
                        
                        case "agenda" :

                            glob.options.month = glob.options.month + 1;

                            if (glob.options.month > 11) {
                                glob.options.month = 0;
                                glob.options.year = glob.options.year + 1;
                            }
                            
                            glob.options.day = 1;
                            
                            layout.set();
                        break;
                        
                        case "month" :

                            glob.options.month = glob.options.month + 1;

                            if (glob.options.month > 11) {
                                glob.options.month = 0;
                                glob.options.year = glob.options.year + 1;
                            }
                            
                            layout.set();
                        break;
                            
                        case "week" :
                            
                            var week = helper.getWeekInfo();
                            
                            var next = new Date(week.start.year, week.start.month, week.start.day + 7);
                            
                            glob.options.year  = next.getFullYear();
                            glob.options.month = next.getMonth();
                            glob.options.day   = next.getDate();
                            
                            layout.set();
                            
                        break;
                        
                        case "day" :
                            
                            var m = helper.getMonthInfo();
                            
                            if (glob.options.day + 1 > m.monthLength) {
                         
                                if (glob.options.month + 1 > 11) {
                                    
                                    glob.options.year = glob.options.year + 1;
                                    glob.options.month = 0;
                                    glob.options.day = 1;
                                    
                                } else {
                                    
                                    glob.options.month = glob.options.month + 1;
                                    glob.options.day = 1;
                                }
                                
                            } else {
                                glob.options.day = glob.options.day + 1;
                            }
                            
                            layout.set();
                        break;
                    }
                });
             
                // Today date depending on view layout
                $instance.$top.find("[data-action='today']").on(helper.clickHandle(), function (e) {
                    
                    e.preventDefault();
                    
                    glob.options.year  = new Date().getFullYear();
                    glob.options.month = new Date().getMonth();
                    glob.options.day   = new Date().getDate();
                    layout.set();
                });

            },
            
            /**
             * Set all top data
             */
            set: function(){
                
                // today events count
                var now = new Date();
                var events = calData.getEvents(now);
                
                if (events.length > 0) {
                    $instance.$top.find('.stec-top-menu-count').text(events.length);
                    $instance.$top.find('.stec-top-menu-count').show();
                } else {
                    $instance.$top.find('.stec-top-menu-count').hide();
                }
                
                
                // Set .active current view 
                $instance.$top.find("[data-view]").removeClass("active");
                $instance.$top.find("[data-view='"+glob.options.view+"']").addClass("active");
                
                // Hide date menu
                $instance.$top.find(".stec-top-menu-date-month").hide();
                $instance.$top.find(".stec-top-menu-date-year").hide();
                $instance.$top.find(".stec-top-menu-date-week").hide();
                $instance.$top.find(".stec-top-menu-date-day").hide();
                
                // Show date menu for the active view
                // Sets date label visible on small devices only
                switch(glob.options.view) {
                    
                    case "agenda" :
                        
                        var rad = $instance.$top.find(".stec-top-menu-date-year").css("border-top-right-radius");
                        
                        $instance.$top.find(".stec-top-menu-date-month, .stec-top-menu-date-month .stec-top-menu-date-dropdown").css({
                            borderTopLeftRadius: rad,
                            borderBottomLeftRadius: rad
                        });
                        
                        $instance.$top.find(".stec-top-menu-date-month").show();
                        $instance.$top.find(".stec-top-menu-date-year").show();
                        
                        $instance.$top.find(".stec-top-menu-date-month > [data-month]")
                                .attr("data-month", glob.options.month)
                                .text(glob.options.monthLabels[glob.options.month]);

                        $instance.find(".stec-top-menu-date-year > [data-year]")
                                .attr("data-year", glob.options.year)
                                .text(glob.options.year);
                        

                        switch (glob.options.general_settings.date_format) {
                            case 'dd-mm-yy' :
                                $instance.$top.find(".stec-top-menu-date-small")
                                    .text(glob.options.monthLabels[glob.options.month] + " " + glob.options.year);
                                break;
                            case 'mm-dd-yy' :
                                $instance.$top.find(".stec-top-menu-date-small")
                                    .text(glob.options.monthLabels[glob.options.month] + " " + glob.options.year);
                                break;
                            case 'yy-mm-dd' :
                                $instance.$top.find(".stec-top-menu-date-small")
                                    .text(glob.options.year + " " + glob.options.monthLabels[glob.options.month]);
                                break;
                        }
                        
                        break;
                        
                    case "month" :
                        
                        var rad = $instance.$top.find(".stec-top-menu-date-year").css("border-top-right-radius");
                        
                        $instance.$top.find(".stec-top-menu-date-month, .stec-top-menu-date-month .stec-top-menu-date-dropdown").css({
                            borderTopLeftRadius: rad,
                            borderBottomLeftRadius: rad
                        });
                        
                        $instance.$top.find(".stec-top-menu-date-month").show();
                        $instance.$top.find(".stec-top-menu-date-year").show();
                        
                        $instance.$top.find(".stec-top-menu-date-month > [data-month]")
                                .attr("data-month", glob.options.month)
                                .text(glob.options.monthLabels[glob.options.month]);

                        $instance.find(".stec-top-menu-date-year > [data-year]")
                                .attr("data-year", glob.options.year)
                                .text(glob.options.year);

                        
                        switch (glob.options.general_settings.date_format) {
                            case 'dd-mm-yy' :
                                $instance.$top.find(".stec-top-menu-date-small")
                                    .text(glob.options.monthLabels[glob.options.month] + " " + glob.options.year);
                                break;
                            case 'mm-dd-yy' :
                                $instance.$top.find(".stec-top-menu-date-small")
                                    .text(glob.options.monthLabels[glob.options.month] + " " + glob.options.year);
                                break;
                            case 'yy-mm-dd' :
                                $instance.$top.find(".stec-top-menu-date-small")
                                    .text(glob.options.year + " " + glob.options.monthLabels[glob.options.month]);
                                break;
                        }
                        
                        
                        break;
                        
                    case "week" :
                        
                        var week = helper.getWeekInfo();
                        var label;
                        
                        var format;
                        
                        if (week.start.year == week.end.year) {
                            if (week.start.month == week.end.month) {
                                
                                switch (glob.options.general_settings.date_format) {
                                    case 'dd-mm-yy' :
                                        format = 'sday - eday emonth eyear';
                                        break;
                                    case 'mm-dd-yy' :
                                        format = 'sday - emonth eday eyear';
                                        break;
                                    case 'yy-mm-dd' :
                                        format = 'sday - eyear emonth eday';
                                        break;
                                }
                                
                            } else {

                                switch (glob.options.general_settings.date_format) {
                                    case 'dd-mm-yy' :
                                        format = 'sday smonth - eday emonth eyear';
                                        break;
                                    case 'mm-dd-yy' :
                                        format = 'smonth sday - emonth eday eyear';
                                        break;
                                    case 'yy-mm-dd' :
                                        format = 'smonth sday - eyear emonth eday';
                                        break;
                                }
                                
                            }
                            
                        } else {

                            switch (glob.options.general_settings.date_format) {
                                case 'dd-mm-yy' :
                                    format = 'sday smonth syear - eday emonth eyear';
                                    break;
                                case 'mm-dd-yy' :
                                    format = 'smonth sday syear - emonth eday eyear';
                                    break;
                                case 'yy-mm-dd' :
                                    format = 'syear smonth sday - eyear emonth eday';
                                    break;
                            }
                            
                        }
                        
                        label = format;
                        
                        label = helper.getWeekLabel(label, week);
                        
                        $instance.$top.find(".stec-top-menu-date-week").show();
                        
                        $instance.$top.find(".stec-top-menu-date-week > [data-week]")
                                .attr("data-week", week.week)
                                .text(label);
                        
                        $instance.$top.find(".stec-top-menu-date-small").text(label);
                        
                    break;
                    
                    case "day" :
                        
                        $instance.$top.find(".stec-top-menu-date-month").css({
                            borderRadius: 0
                        }).find(".stec-top-menu-date-dropdown").css({
                            borderTopLeftRadius:0
                        });
                        
                        $instance.$top.find(".stec-top-menu-date-day").show();
                        $instance.$top.find(".stec-top-menu-date-month").show();
                        $instance.$top.find(".stec-top-menu-date-year").show();
                        
                        $instance.$top.find(".stec-top-menu-date-day > [data-day]")
                                .attr("data-day", glob.options.day)
                                .text(glob.options.day);
                        
                        $instance.$top.find(".stec-top-menu-date-month > [data-month]")
                                .attr("data-month", glob.options.month)
                                .text(glob.options.monthLabels[glob.options.month]);

                        $instance.$top.find(".stec-top-menu-date-year > [data-year]")
                                .attr("data-year", glob.options.year)
                                .text(glob.options.year);
                        
                        
                        switch (glob.options.general_settings.date_format) {
                            case 'dd-mm-yy' :
                                $instance.$top.find(".stec-top-menu-date-small")
                                    .text(glob.options.day + " " + glob.options.monthLabels[glob.options.month] + " " + glob.options.year);
                                break;
                            case 'mm-dd-yy' :
                                $instance.$top.find(".stec-top-menu-date-small")
                                    .text(glob.options.monthLabels[glob.options.month] + " " + glob.options.day + " " + glob.options.year);
                                break;
                            case 'yy-mm-dd' :
                                $instance.$top.find(".stec-top-menu-date-small")
                                    .text(glob.options.year + " " + glob.options.monthLabels[glob.options.month] + " " + glob.options.day);
                                break;
                        }
                        
                        break;
                }
                
                // Add active class for the given year,month,week,day for menu dropdown
                this.dateDropdownSetActive();
            },
            
            /**
             * Add active class for the given year,month,week,day for menu dropdown
             */
            dateDropdownSetActive: function(){
                
                $instance.$top
                        .find(".stec-top-menu-date-dropdown .active").removeClass("active");
                
                $instance.$top
                        .find(".stec-top-menu-date-dropdown")
                        .find('[data-day="'+glob.options.day+'"]')
                        .parent()
                        .addClass('active');
                
                $instance.$top
                        .find(".stec-top-menu-date-dropdown")
                        .find('[data-month="'+glob.options.month+'"]')
                        .parent()
                        .addClass('active');
                
                $instance.$top
                        .find(".stec-top-menu-date-dropdown")
                        .find('[data-year="'+glob.options.year+'"]')
                        .parent()
                        .addClass('active');
                
                var week = helper.getWeekInfo();
                var weekDate = week.start.year + "-" + week.start.month + "-" + week.start.day;    
                    
                $instance.$top
                        .find(".stec-top-menu-date-dropdown")
                        .find('[data-date="'+weekDate+'"]')
                        .parent()
                        .addClass('active');
                
            },
            
            /**
             * Month scrolldown action
             */
            dateMonthScrollDown: function(){
                
                var parent = this;
                
                $instance.$top.find(".stec-top-menu-date-month").find("ul").stop(true, true);
                
                var m = $instance.$top.find(".stec-top-menu-date-month").find("ul:first").find("li:last [data-month]").attr("data-month");
                m = parseInt(m, 10);

                var html = '';

                for (var i = 0; i <= 5; i++) {
                    m = m + 1 > 11 ? 0 : m + 1;
                    html += '<li><p data-month="' + m + '">' + glob.options.monthLabels[m] + '</p></li>';
                }

                $instance.$top.find(".stec-top-menu-date-month ul li:last").after(html);
                
                $instance.$top.find(".stec-top-menu-date-month").find("ul").css({
                    top: 45
                }).stop(true, true).animate({
                    top: -1 * 4 * 45
                }, {
                    duration: parent.dropDownScrollSpeed,
                    easing: "stecOutExpo",
                    complete: function () {
                        $(this).css("top", 45).find("li:lt(5)").remove();
                    }
                });
                
                this.dateDropdownSetActive();
            },
            
            /**
             * Month scrollup action
             */
            dateMonthScrollUp: function(){
                
                var parent = this;
                
                var m = $instance.$top.find(".stec-top-menu-date-month").find("ul:first").find("li:first [data-month]").attr("data-month");

                var html = '';
                var mArr = [];

                for (var i = 0; i <= 4; i++) {
                    m = m - 1 < 0 ? 11 : m - 1;
                    mArr[i] = '<li><p data-month="' + m + '">' + glob.options.monthLabels[m] + '</p></li>';
                }

                html += mArr.reverse().join('');

                $instance.$top.find(".stec-top-menu-date-month ul li:first").before(html);
                
                $instance.$top.find(".stec-top-menu-date-month").find("ul").css({
                    top: -1 * 4 * 45
                }).stop().animate({
                    top: 45
                }, {
                    duration: parent.dropDownScrollSpeed,
                    easing: "stecOutExpo",
                    complete: function(){
                        $(this).css("top",45).find("li:gt(5)").remove();
                    }
                });
                
                this.dateDropdownSetActive();
               
            },
            
            /**
             * Year scrolldown action
             */
            dateYearScrollDown: function(){
                
                var parent = this;
                
                $instance.$top.find(".stec-top-menu-date-year").find("ul").stop(true, true);
                
                var m = $instance.$top.find(".stec-top-menu-date-year").find("ul:first").find("li:last [data-year]").attr("data-year");
                m = parseInt(m, 10);

                var html = '';

                for (var i = 0; i <= 5; i++) {
                    m = m + 1;
                    html += '<li><p data-year="' + m + '">' + m + '</p></li>';
                }

                $instance.$top.find(".stec-top-menu-date-year ul li:last").after(html);
                $instance.$top.find(".stec-top-menu-date-year").find("ul").css({
                    top: 45
                }).stop(true, true).animate({
                    top: -1 * 4 * 45
                }, {
                    duration: parent.dropDownScrollSpeed,
                    easing: "stecOutExpo",
                    complete: function () {
                        $(this).css("top", 45).find("li:lt(5)").remove();
                    }
                });
                
                this.dateDropdownSetActive();
                
            },
            
            /**
             * Year scrollup action
             */
            dateYearScrollUp: function(){
                
                var parent = this;
                
                var m = $instance.$top.find(".stec-top-menu-date-year").find("ul:first").find("li:first [data-year]").attr("data-year");

                var html = '';
                var mArr = [];

                for (var i = 0; i <= 4; i++) {
                    m = m - 1;
                    mArr[i] = '<li><p data-year="' + m + '">' + m + '</p></li>';
                }

                html += mArr.reverse().join('');

                $instance.$top.find(".stec-top-menu-date-year ul li:first").before(html);
                
                $instance.$top.find(".stec-top-menu-date-year").find("ul").css({
                    top: -1 * 4 * 45
                }).stop().animate({
                    top: 45
                }, {
                    duration: parent.dropDownScrollSpeed,
                    easing: "stecOutExpo",
                    complete: function(){
                        $(this).css("top", 45).find("li:gt(5)").remove();
                    }
                });
                
                this.dateDropdownSetActive();
            },
            
            /**
             * Week scrolldown action
             */
            dateWeekScrollDown: function(){
                
                var parent = this;
                
                $instance.$top.find(".stec-top-menu-date-week").find("ul").stop(true, true);
                
                var lastWeek = $instance.$top.find(".stec-top-menu-date-week").find("ul:last").find("li:last [data-date]").attr("data-date");
                    
                var html = '', week ,label, w;
                
                var format;
                
                switch (glob.options.general_settings.date_format) {
                    case 'dd-mm-yy' :
                        format = 'sday smonth - eday emonth eyear';
                        break;
                    case 'mm-dd-yy' :
                        format = 'smonth sday - emonth eday eyear';
                        break;
                    case 'yy-mm-dd' :
                        format = 'smonth sday - eyear emonth eday';
                        break;
                }

                for (var i = 1; i <= 6; i++) {

                    w = helper.getDateFromData(lastWeek);
                    
                    w.setDate(w.getDate() + i * 7);

                    week = helper.getWeekInfo(w);

                    label = helper.getWeekLabel(format, week);

                    var date = week.start.year + "-" + week.start.month + "-" + week.start.day;

                    html += '<li><p data-week="' + week.week + '" data-date="' + date + '">' + label + '</p></li>';

                }

                $instance.$top.find(".stec-top-menu-date-week ul li:last").after(html);
                
                $instance.$top.find(".stec-top-menu-date-week").find("ul").css({
                    top: 45
                }).stop(true, true).animate({
                    top: -1 * 4 * 45
                }, {
                    duration: parent.dropDownScrollSpeed,
                    easing: "stecOutExpo",
                    complete: function () {
                        $(this).css("top", 45).find("li:lt(5)").remove();
                    }
                });
                
                this.dateDropdownSetActive();
                
            },
            
            dateWeekScrollUp: function(){
                
                var parent = this;
                
                var firstWeek = $instance.$top.find(".stec-top-menu-date-week").find("ul:first").find("li:first [data-date]").attr("data-date");

                var html = '', week ,label, w, mArr = [];
                
                var format;
                
                switch (glob.options.general_settings.date_format) {
                    case 'dd-mm-yy' :
                        format = 'sday smonth - eday emonth eyear';
                        break;
                    case 'mm-dd-yy' :
                        format = 'smonth sday - emonth eday eyear';
                        break;
                    case 'yy-mm-dd' :
                        format = 'smonth sday - eyear emonth eday';
                        break;
                }

                for (var i = 0; i <= 5; i++) {

                    w = helper.getDateFromData(firstWeek);
                    
                    w.setDate(w.getDate() - i * 7);

                    week = helper.getWeekInfo(w);

                    label = helper.getWeekLabel(format, week);

                    var date = week.start.year + "-" + week.start.month + "-" + week.start.day;

                    mArr[i] = '<li><p data-week="' + week.week + '" data-date="' + date + '">' + label + '</p></li>';

                }
                
                html = mArr.reverse().join('');

                $instance.$top.find(".stec-top-menu-date-week ul li:first").before(html);
                
                $instance.$top.find(".stec-top-menu-date-week").find("ul").css({
                    top: -1 * 4 * 45
                }).stop().animate({
                    top: 45
                }, {
                    duration: parent.dropDownScrollSpeed,
                    easing: "stecOutExpo",
                    complete: function(){
                        $(this).css("top", 45).find("li:gt(5)").remove();
                    }
                });
                
                this.dateDropdownSetActive();
                
            },
            
            dateDayScrollDown: function(){
                
                var parent = this;
                
                $instance.$top.find(".stec-top-menu-date-day").find("ul").stop(true, true);
                
                var d = $instance.$top.find(".stec-top-menu-date-day").find("ul:first").find("li:last [data-day]").attr("data-day");
                d = parseInt(d, 10);
                
                var m    = helper.getMonthInfo();
                var maxD = m.monthLength;
                
                var html = '';

                for (var i = 0; i <= 5; i++) {
                    d = d + 1 > maxD ? 1 : d + 1;
                    html += '<li><p data-day="' + d + '">' + d + '</p></li>';
                }

                $instance.$top.find(".stec-top-menu-date-day ul li:last").after(html);
                
                $instance.$top.find(".stec-top-menu-date-day").find("ul").css({
                    top: 45
                }).stop(true, true).animate({
                    top: -1 * 4 * 45
                }, {
                    duration: parent.dropDownScrollSpeed,
                    easing: "stecOutExpo",
                    complete: function () {
                        $(this).css("top", 45).find("li:lt(5)").remove();
                    }
                });
                
                this.dateDropdownSetActive();
                
            },
            
            dateDayScrollUp: function(){
                
                var parent = this;
                
                var d = $instance.$top.find(".stec-top-menu-date-day").find("ul:first").find("li:first [data-day]").attr("data-day");

                var m    = helper.getMonthInfo();
                var maxD = m.monthLength;

                var html = '';
                var mArr = [];

                for (var i = 0; i <= 4; i++) {
                    d = d - 1 < 1 ? maxD : d - 1;
                    mArr[i] = '<li><p data-day="' + d + '">' + d + '</p></li>';
                }

                html += mArr.reverse().join('');

                $instance.$top.find(".stec-top-menu-date-day ul li:first").before(html);
                
                $instance.$top.find(".stec-top-menu-date-day").find("ul").css({
                    top: -1 * 4 * 45
                }).stop().animate({
                    top: 45
                }, {
                    duration: parent.dropDownScrollSpeed,
                    easing: "stecOutExpo",
                    complete: function(){
                        $(this).css("top", 45).find("li:gt(5)").remove();
                    }
                });
                
                this.dateDropdownSetActive();
            }
        };
      
        var layout = {
            init: function () {
                
                this.agenda.bindControls();
                this.month.bindControls();
                this.week.bindControls();
                this.day.bindControls();
                
                calData.pullEvents(function(){
                    
                    preloader.destroy();
                    $instance.show();
                    layout.set();
                    
                });
            },
            
            set: function () {
                
                $instance.$agenda.hide();
                $instance.$month.hide();
                $instance.$week.hide();
                $instance.$day.hide();
                
                top.set();
                
                switch (glob.options.view) {
                    case "agenda" :
                        this.agenda.set();
                        break;
                        
                    case "month" :
                        this.month.set();
                        break;
                        
                    case "week" :
                        this.week.set();
                        break;
                        
                    case "day" :
                        this.day.set();
                        break;
                }
                
                // after layout set
                helper.extendBind("stachethemes_ec_extend", "onLayoutSet");
            },
            
            /**
             * AGENDA
             */
            agenda: {
                
                cache: {
                    getNfutureEvents: false
                },
                
                bindControls: function(){
                    
                    var parent = this;
                    
                    // Agenda layout needs readjusting on window resize
                    
                    helper.onResizeEnd(function(){
                        if ($instance.$agenda.is(":visible")) {
                            parent.set(true);
                        }
                    }, 50);
                    
                    $instance.$agenda.find('.stec-layout-agenda-events-all-load-more').on(helper.clickHandle(), function(e){
                        e.preventDefault();
                        parent.fillAgendaAllList();
                    });
                    
                    
                    // Click handle for cell click
                    $(document).on(helper.clickHandle(), $instance.$agenda.path + ' .stec-layout-agenda-daycell', function(e){
                        
                        e.preventDefault();
                        
                        if ($(this).hasClass("active")) {
                            // Close active cell
                            events.eventHolder.close();
                            $(this).removeClass("active");
                            return;
                        }
                        
                        var date = helper.getDateFromData($(this).attr('data-date'));

                        glob.options.day   = date.getDate();
                        glob.options.month = date.getMonth();
                        glob.options.year  = date.getFullYear();
                        top.set();

                        parent.setActiveCell();
                        
                    });
                    
                    // Instant click handle for cell click. Used for drag
                    $(document).on(helper.instaClickHandle(), $instance.$agenda.path + ' .stec-layout-agenda-daycell', function(e){
                       
                        e.preventDefault();
                        
                        var date = helper.getDateFromData($(this).attr('data-date'));
                        var curr = new Date(glob.options.year, glob.options.month, glob.options.day);
                        
                        if (date.getTime() != curr.getTime()) {
                            
                            glob.options.day   = date.getDate();
                            glob.options.month = date.getMonth();
                            glob.options.year  = date.getFullYear();
                            top.set();
                        }
                        
                    });
                    
                    // Draggable slider
                    $instance.$agenda.find(".stec-layout-agenda-list").draggable({
                        
                        axis: "x",
                        
                        start: function(event, ui){
                            
                            $instance.$agenda.find(".stec-layout-agenda-list").stop();
                            this.previousPosition = ui.position;
                            this.time = new Date().getTime();
                            
                        },
                        
                        stop: function(event, ui){
                             
                             var time = new Date().getTime() - this.time;
                             var moved = Math.abs(ui.position.left - this.previousPosition.left);
                             
                             parent.dragFill($(this), ui.position.left);
                             parent.innertia($(this), this.previousPosition.left > ui.position.left ? 1 : -1, time, moved);
                             
                        },
                        
                        drag: function(event, ui){
                            parent.dragFill($(this), ui.position.left);
                        }
                        
                    });
                },
                
                // Set agenda layout
                set: function(resizeOnly){
                    
                    
                    // Check if Agenda Slider is set to show; else remove it
                    if (glob.options.general_settings.agenda_cal_display != 0) {
                        
                        var DIM = this.getSlideDimensions(true);

                        $instance.$agenda.find(".stec-layout-agenda-list")
                                .stop()
                                .css({
                                    left: 0,
                                    width: DIM.width
                                });

                        var cells = this.getCells(false, true, 1, true);

                        $instance.$agenda.find(".stec-layout-agenda-list-b").empty().css('left',
                                -1 * $instance.$agenda.find(".stec-layout-agenda-list-a").width()
                                );

                        this.fillHTML($instance.$agenda.find(".stec-layout-agenda-list-a"), cells);

                    } else {
                        
                        $instance.$agenda.find('.stec-layout-agenda-list-wrap').remove();
                        
                    }
                    
                    if (resizeOnly !== true) {
                        events.eventHolder.close();
                        this.clearAgendaAllList();
                        this.fillAgendaAllList();
                    }
                    
                    $instance.$agenda.show();
                    
                },
                
                setActiveCell: function() {
                    
                    var activeCell = glob.options.year + "-" + glob.options.month + "-" + glob.options.day;

                    $instance.$agenda
                            .find(".stec-layout-agenda-daycell")
                            .removeClass("active");

                    $instance.$agenda
                            .find(".stec-layout-agenda-daycell[data-date='" + activeCell + "']")
                            .addClass("active");
                    
                    events.eventHolder.open();
                    
                },
                
                getSlideDimensions: function(refresh){
                    
                    if (refresh !== true && this.getSlideDimensions.cache) {
                        return this.getSlideDimensions.cache;
                    }
                    
                    var windowWidth = $(window).width() < 2000 ? 2000 : $(window).width();
                    var innerMaxCells = Math.floor($instance.width() / 80);
                    var cellWidth = Math.floor($instance.width() / innerMaxCells);
                    var maxCells = Math.round(windowWidth / cellWidth);
                    var width = maxCells * cellWidth;

                    var DIM = {
                        width: width,
                        maxCells: maxCells,
                        cellWidth: cellWidth
                    };
                    
                    this.getSlideDimensions.cache = DIM;

                    return DIM;
                },
                
                /**
                 * Return cells data for active date
                 * @param {Date} date Alternative date
                 * @param {bool} centerOnDate Center on active date
                 * @param {int} direction -1 backwards 1 forwards
                 * @param {bool} borderMonthCell prevents el2 slide monthcell overlap
                 * @returns {array} returns cells data 
                 */
                getCells: function(date, centerOnDate, direction, borderMonthCell) {
                    
                    if (!date) {
                        date = new Date(glob.options.year, glob.options.month, glob.options.day);
                    }
                    
                    var DIM = this.getSlideDimensions();
                    
                    var d = date.getDate();
                    var m = helper.getMonthInfo(date.getMonth());
                    var y = date.getFullYear();
                    
                    if (centerOnDate === true) {
                        
                        for (var j = 0; j < Math.round(DIM.maxCells / ((DIM.width / $instance.width()) * 2)); j++) {
                            
                            d = d - 1;

                            if (d <= 0) {

                                m = m.month - 1;

                                if (m < 0) {
                                    m = 11;
                                    y = y - 1;
                                }

                                m = helper.getMonthInfo(m, y);
                                d = m.monthLength;
                            }
                        }
                    }
                    
                    var cellArray = [];
                    var count = 0;
                    
                    // Fill cells
                    if (direction === 1) {
                        
                        for (var i = 0; i < DIM.maxCells; i++) {

                            d = d + 1;

                            if (d > m.monthLength) {

                                m = m.month + 1;

                                if (m > 11) {
                                    y = y + 1;
                                    m = 0;
                                }

                                m = helper.getMonthInfo(m, y);
                                d = 1;
                                
                                if (count != 0 || borderMonthCell === true) {
                                    cellArray[count] = {
                                        dataDate: false,
                                        dayNum: false,
                                        day: false,
                                        year: y,
                                        month: m.month,
                                        monthStartCell: true,
                                        hasEvents: false
                                    };

                                    count++;
                                }
                                

                            }

                            var date = new Date(y, m.month, d);
                            
                            cellArray[count] = {
                                dataDate: y + "-" + m.month + "-" + d,
                                dayNum: date.getDay(),
                                day: d,
                                year: y,
                                month: m.month,
                                monthStartCell: false,
                                hasEvents: false
                            };
                            
                            count++;
                        }
                        
                        cellArray = cellArray.slice(0, DIM.maxCells);
                    
                    } else {
                                
                        for (var i = 0; i < DIM.maxCells; i++) {

                            d = d - 1;

                            if (d <= 0) {
                                
                                if (count != 0 || borderMonthCell === true) {
                                    cellArray[count] = {
                                        dataDate: false,
                                        dayNum: false,
                                        day: false,
                                        year: y,
                                        month: m.month,
                                        monthStartCell: true,
                                        hasEvents: false
                                    };
                                    
                                    count++;
                                }

                                m = m.month - 1;

                                if (m < 0) {
                                    y = y - 1;
                                    m = 11;
                                }

                                m = helper.getMonthInfo(m, y);
                                d = m.monthLength;

                            } 
                            
                            
                            var date = new Date(y, m.month, d);

                            cellArray[count] = {
                                dataDate: y + "-" + m.month + "-" + d,
                                dayNum: date.getDay(),
                                day: d,
                                year: y,
                                month: m.month,
                                monthStartCell: false,
                                hasEvents: false
                            };

                            count++;
                            
                        }
                        
                        cellArray = cellArray.slice(0, DIM.maxCells);
                        
                        cellArray.reverse();
                    }
                    
                    return cellArray;
                    
                },
                
                /**
                 * Create and append html for given cells
                 * @param {object} $el Element to append to
                 * @param {array} cells array
                 */
                fillHTML: function($el, cells) {
                     
                    var DIM = this.getSlideDimensions();
                    
                    $el.empty();
                    
                    var html = "";
                    
                    $(cells).each(function(){
                        
                        var cell = this;
                        
                        if (cell.monthStartCell === true) {

                            html += '<li style="width: '+DIM.cellWidth+'px" class="stec-layout-agenda-monthstart" data-year="'+cell.year+'" data-month="'+cell.month+'" >';
                                html += '<div class="stec-layout-agenda-monthstart-wrap">';
                                html += '<p class="stec-layout-agenda-monthstart-year">' + cell.year + '</p>';
                                html += '<p class="stec-layout-agenda-monthstart-month">' + glob.options.monthLabelsShort[cell.month] + '</p>';
                                html += '</div>';
                            html += '</li>';

                        } else {

                            html += '<li style="width: '+DIM.cellWidth+'px" class="stec-layout-agenda-daycell" data-date="' + cell.dataDate + '">';
                                html += '<div class="stec-layout-agenda-daycell-wrap">';
                                html += '<p class="stec-layout-agenda-daycell-label">' + glob.options.dayLabelsShort[cell.dayNum] + '</p>';
                                html += '<p class="stec-layout-agenda-daycell-num">' + cell.day + '</p>';
                                html += '<div class="stec-layout-agenda-daycell-events">';
//                                    html += '<div class="stec-layout-agenda-daycell-event"></div>';
                                html += '</div>';
                                html += '</div>';
                            html += '</li>';
                        }
                            
                    });
                    
                    $(html).appendTo($el);
                    
                    // Set Today 
                    var today = new Date();
                    var date = today.getFullYear() + "-" + today.getMonth() + "-" + today.getDate();
                    
                    $instance.$agenda
                        .find(".stec-layout-agenda-daycell[data-date='" + date + "']")
                        .addClass("stec-layout-agenda-daycell-today");
                
                    this.fillEvents();
                    
                },
                
                fillEvents: function(){
                    
                    var $a = $instance.$agenda.find(".stec-layout-agenda-list-a");
                    var $b = $instance.$agenda.find(".stec-layout-agenda-list-b");
                    
                    var start, end;
                    
                    if ($b.children().length <= 0) {
                        // b is empty (init start)
                        
                        start = $a.children('.stec-layout-agenda-daycell').first().attr('data-date');
                        end   = $a.children('.stec-layout-agenda-daycell').last().attr('data-date');
                        
                    } else {
                        
                        if ($a[0].offsetLeft > $b[0].offsetLeft) {
                            // b is behind
                            
                            start = $b.children('.stec-layout-agenda-daycell').first().attr('data-date');
                            end   = $a.children('.stec-layout-agenda-daycell').last().attr('data-date');
                        } else {
                            
                            // b is ahead
                            end = $b.children('.stec-layout-agenda-daycell').last().attr('data-date');
                            start = $a.children('.stec-layout-agenda-daycell').first().attr('data-date');
                        }
                    }
                    
                    $instance.$agenda
                            .children('.stec-layout-agenda-list-wrap')
                            .find('.stec-layout-agenda-daycell-events').empty();
                    
                    // Populate cells with events
                    
                    var startDate = helper.getDateFromData(start);
                    var endDate   = helper.getDateFromData(end);
       
                    var events = calData.getEvents(startDate, endDate);
                    
                    if (events.length <= 0) {
                        // no events
                        return;
                    }
                    
                    $(events).each(function(i) {
                        
                        var startDate = new Date(this.start_date_timestamp * 1000);
                        var endDate   = new Date(this.end_date_timestamp * 1000);
                        
                        var d1, d2, days = 0;
                        
                        // we care for number of difference dates not per 24 hours
                        d1 = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate());
                        d2 = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate());
                        
                        days = helper.diffDays(d1, d2);
                        
                        for (var day = 0; day <= days; day++) {
                            
                            var stamp = moment(this.start_date).add(day,'days').unix();
                            
                            var dataDate = helper.getDataFromDate(new Date(stamp * 1000));
                            
                            if ($instance.$agenda
                                    .children('.stec-layout-agenda-list-wrap')
                                    .find('.stec-layout-agenda-daycell[data-date="' + dataDate + '"]')
                                    .find('.stec-layout-agenda-daycell-event').length > 2) {

                                // cells are full

                            } else {
                                
                                var extraClass = '';
                                
                                var calNow = helper.getCalNow(this.timezone_utc_offset / 3600);
                                
                                if (calNow > endDate) {
                                    extraClass = 'stec-layout-agenda-daycell-event-expired';
                                }
                                
                                var html = '<div class="stec-layout-agenda-daycell-event '+extraClass+'" data-id="'+this.id+'" style="background:' + this.color + '"></div>';

                                $(html).appendTo($instance.$agenda
                                        .children('.stec-layout-agenda-list-wrap')
                                        .find('.stec-layout-agenda-daycell[data-date="' + dataDate + '"]')
                                        .find('.stec-layout-agenda-daycell-events'));

                            }
                            
                        }
                        
                        
                    });
                        
                },
                
                /**
                 * Build cells on the run while dragging if required
                 * @param {object} $el Dragged element
                 * @param {Number} pos current position
                 */
                dragFill: function($el, pos){
                    
                    var $el2 = $el.parent().children(".stec-layout-agenda-list").not($el);

                    $el2.css('left', pos + (pos < 0 ? 1 : -1) * $el.width());
                    
                    if ($el2[0].offsetLeft > $el[0].offsetLeft) {
                        // increment el2
                        
                        var rebuild = false;
                        
                        var d1 = helper.getDateFromData($el.children('.stec-layout-agenda-daycell').last().attr('data-date'));
                        var d2 = $el2.children('.stec-layout-agenda-daycell').first().attr('data-date');
                        
                        if (!d2) {
                            rebuild = true;
                        } else {
                            d2 = helper.getDateFromData(d2);
                            d2.setDate(d2.getDate() - 1);
                            if (d1.getTime() != d2.getTime()) {
                                rebuild = true;
                            }
                        }
                        
                        if (rebuild === true) {
                            
                            var borderMonthCell = true;
                            
                            if ($el.children("li").last().hasClass("stec-layout-agenda-monthstart")) {
                                borderMonthCell = false;
                            }
                            
                            d1.setDate(d1.getDate());
                            var cells = this.getCells(d1, false, 1, borderMonthCell);
                            this.fillHTML($el2, cells);
                        }
                        
                    } else {
                        // decrement el2
                        
                        var rebuild = false;
                        
                        var d1 = helper.getDateFromData($el.children('.stec-layout-agenda-daycell').first().attr('data-date'));
                        var d2 = $el2.children('.stec-layout-agenda-daycell').last().attr('data-date');
                        
                        if (!d2) {
                            rebuild = true;
                        } else {
                            d2 = helper.getDateFromData(d2);
                            d2.setDate(d2.getDate() + 1);
                            if (d1.getTime() != d2.getTime()) {
                                rebuild = true;
                            }
                        }
                        
                        if (rebuild === true) {
                            
                            var borderMonthCell = true;
                            
                            if ($el.children("li").first().hasClass("stec-layout-agenda-monthstart")) {
                                borderMonthCell = false;
                            }
                            
                            var cells = this.getCells(d1, false, -1, borderMonthCell);
                            this.fillHTML($el2, cells);
                        }
                        
                    }
                },
                
                innertia: function($el, dir, time, moved) {
                    
                    var parent = this;
                    var x = 0;
                    
                    x =  moved/time * 100;
                    
                    x = x > $el.width() ? $el.width() / 4 : x;
                    
                    $instance.$agenda.find(".stec-layout-agenda-list").stop();
                    
                    switch (dir) {
                        
                        case 1:
                            $el.animate({
                                left: $el.position().left - x
                            }, {
                                easing: "stecOutExpo",
                                duration: 1000,
                                step:function(a,b) {
                                    parent.dragFill($el, b.now);
                                }
                            });
                        break;
                        
                        case -1:
                            $el.animate({
                                left: $el.position().left + x
                            }, {
                                easing: "stecOutExpo",
                                duration: 1000,
                                step:function(a,b) {
                                    parent.dragFill($el, b.now);
                                }
                            });
                        break;
                        
                    }
                    
                },
                
                /**
                 * Reset agenda all-list
                 */
                clearAgendaAllList: function(){
                    this.cache.getNfutureEvents = false;
                    $instance.$agenda.find('.stec-layout-agenda-events-all-control').show();
                    $instance.$agenda.find('.stec-layout-agenda-events-all ul').remove();
                    $instance.$agenda.find('.stec-layout-agenda-events-all-datetext').remove();
                },
                
                /**
                 * Caches all future eventis initially
                 * Each call pulls N events from the cache array
                 * @return (object) events list
                 */
                getNfutureEvents: function(){
                    
                    if (!this.cache.getNfutureEvents) {
                        // Load cache
                        
                        this.getNfutureEvents.n = parseInt(glob.options.general_settings.agenda_get_n, 10);
                        this.cache.getNfutureEvents = calData.getFutureEvents();
                        this.getNfutureEvents.i = 0;
                    }
                    
                    var x = this.getNfutureEvents.i++ * this.getNfutureEvents.n;
                    var y = x + ++this.getNfutureEvents.n;
                    
                    return this.cache.getNfutureEvents.slice(x , y);
                     
                },
                
                /**
                 * Builds agenda all list events html
                 */
                fillAgendaAllList: function() {
                    
                    if (glob.options.general_settings.agenda_list_display == '0') {
                        return;
                    }
                    
                    var events = this.getNfutureEvents();
                    
                    if (!events || events.length <= 0) {
                        
                        // no events
                        $instance.$agenda.find('.stec-layout-agenda-events-all-control').hide();
                        
                        return;
                    }
                    
                    var lastLabel = $instance.$agenda.find('.stec-layout-agenda-events-all-datetext').last();
                        lastLabel.month = lastLabel.attr('data-month');
                        lastLabel.year = lastLabel.attr('data-year');
                    
                    var now = new Date();
                    
                    $(events).each(function (i) {
                        
                        var event = this;
                        
                        var d = helper.dbDateTimeToDate(this.start_date);
                        
                        if (now > d) {
                            var noReminder = true;
                        }
                        
                        if (lastLabel.month != d.getMonth() || lastLabel.year != d.getFullYear()) {
                            // Add new label
                            lastLabel.month = d.getMonth();
                            lastLabel.year  = d.getFullYear();
                            
                            $('<p data-year="'+d.getFullYear()+'" data-month="'+d.getMonth()+'" class="stec-layout-agenda-events-all-datetext">'+ glob.options.monthLabels[d.getMonth()] + ' ' + d.getFullYear() +'</p>')
                                    .insertBefore($instance.$agenda.find('.stec-layout-agenda-events-all-control'));
                            
                            $('<ul class="stec-layout-agenda-events-all-list"></ul>')
                                    .insertAfter($instance.$agenda.find('.stec-layout-agenda-events-all-datetext').last());
                        }
                        
                        var featured_class = '';
                        
                        switch(parseInt(this.featured, 10)) {
                            case 1: 
                                featured_class = ' stec-event-featured ';
                            break;
                            
                            case 2: 
                                featured_class = ' stec-event-featured stec-event-featured-bg ';
                            break;
                            
                            default:
                            featured_class = '';
                        }
                        
                        var additional_class = "";

                        if (event.icon == 'fa') {
                            additional_class += ' stec-no-icon ';
                        }
                        
                        $(glob.template.event)
                                .addClass(featured_class)
                                .addClass(additional_class)
                                .addClass(noReminder ? 'stec-layout-event-no-reminder' : '')
                                .attr('data-id', event.id)
                                .attr('data-repeat-time-offset', event.repeat_time_offset ? event.repeat_time_offset : 0)
                                .html(function (index, html) {

                            var date = helper.beautifyTimespan(event.start_date, event.end_date, event.all_day);
                            
                            var gmtutc_offset = parseInt(event.timezone_utc_offset, 10) / 3600;
                            gmtutc_offset = gmtutc_offset > 0 ? '+' + gmtutc_offset : gmtutc_offset;
                            
                            if (gmtutc_offset == 0) {
                                gmtutc_offset = '';
                            }
                            
                            var timezoneOffsetLabel = glob.options.general_settings.date_label_gmtutc == 0 ? '' : 'UTC/GMT ' + gmtutc_offset;;
                            
                            html += '<a class="stec-layout-event-single-page-link" href="'+glob.options.single_page_url + event.alias + (event.repeat_time_offset > 0 ? '/' + event.repeat_time_offset : '')+'">'+event.summary+'</a>';
                            
                            return html
                                    .replace('stec_replace_summary', event.summary)
                                    .replace('stec_replace_date', date + ' ' + timezoneOffsetLabel)
                                    .replace('stec_replace_event_background', 'style="background:'+event.color+'"') // edge is retarded
                                    .replace('stec_replace_icon_class', event.icon);
                            
                            
                        }).appendTo($instance.find('.stec-layout-agenda-events-all-list').last());

                    });

                    // Remove + when single pages
                    if (glob.options.general_settings.open_event_in == 'single') {
                        $instance
                                .find('.stec-layout-agenda-events-all')
                                .find('.stec-layout-event-preview-right-event-toggle')
                                .remove();
                    }

                    if (helper.animate !== false) {
                        helper.animate.agenda.fillList($instance.$agenda);
                    } 
                    
                    
                }
                 
            },
            
            /**
             * MONTH LAYOUT
             */
            month: {
                bindControls: function () {

                    var parent = this;
                    
                    // Day cell click handle
                    $instance.$month.find(".stec-layout-month-daycell").on(helper.clickHandle(), function (e) {
                        
                        e.preventDefault();
                        
                        if ($(this).hasClass("active")) {
                            // Close active cell
                            events.eventHolder.close();
                            $(this).removeClass("active");
                            return;
                        }
                        
                        var reset = false;

                        var date = helper.getDateFromData($(this).attr("data-date"));

                        if (glob.options.year != date.getFullYear() || glob.options.month != date.getMonth()) {
                            reset = true;
                        }

                        glob.options.year = date.getFullYear();
                        glob.options.month = date.getMonth();
                        glob.options.day = date.getDate();
                        
                        if (reset === true) {
                            layout.set();
                            parent.setActiveCell();
                        } else {
                            parent.setActiveCell();
                        }
                        
                    });
                
                },
                
                // Set to month layout
                set: function () {
                    $instance.$month.show();
                    this.setDayLabels();
                    this.fillGridDays();
                    this.fillEvents();
                },
                
                setDayLabels: function() {
                    
                    var offset = 0;
                    
                    switch (glob.options.general_settings.first_day_of_the_week) {
                        case 'mon' :
                            offset = 1;
                            break;

                        case 'sat' :
                            offset = 6;
                            break;

                        case 'sun' :
                            offset = 0;
                            break;
                    }
                    
                    var a = offset;
                    
                    $instance.$month.find('.stec-layout-month-daylabel td').each(function(i){
                        
                        var label = helper.capitalizeFirstLetter(glob.options.dayLabels[a]);
                        var labelShort = helper.capitalizeFirstLetter(glob.options.dayLabelsShort[a]);
                        
                        $(this).find('p').eq(0).text(label);
                        $(this).find('p').eq(1).text(labelShort);
                        $(this).find('p').eq(2).text(labelShort.charAt(0));
                        
                        a = a + 1 >= glob.options.dayLabels.length ? 0 : a + 1;
                        
                    });
                },
                
                setActiveCell: function () {
               
                    var parent = this;
                    
                    var activeCell = glob.options.year + "-" + glob.options.month + "-" + glob.options.day;

                    $instance.$month
                            .find(".stec-layout-month-daycell")
                            .removeClass("active");
                    
                    $instance.$month
                            .find(".stec-layout-month-daycell[data-date='" + activeCell + "']")
                            .addClass("active");
               
                    $instance.$month.find(".stec-layout-month-eventholder")
                            .insertAfter(
                                $instance.$month
                                .find(".stec-layout-month-daycell.active")
                                .parents("tr")
                            );
                    
                    events.eventHolder.open();
                },
                
                resetGridCells: function () {

                    var parent = this;

                    $instance.$month
                            .find(".stec-layout-month-daylabel td")
                            .removeClass("stec-layout-month-daylabel-today");

                    $instance.$month
                            .find(".stec-layout-month-daycell")
                            .removeAttr("data-date")
                            .removeClass("stec-layout-month-daycell-today stec-layout-month-daycell-inactive active");
                    
                    $instance.$month
                            .find(".stec-layout-month-daycell")
                            .removeClass("active");
                    
                    $instance.$month
                            .find('.stec-layout-month-daycell-events').empty();
                    
                    events.eventHolder.close();
                    
                },
                
                fillGridDays: function () {

                    var parent = this;

                    parent.resetGridCells();

                    // Active Month
                    var activeMonthInfo = helper.getMonthInfo();

                    for (var i = 0; i < activeMonthInfo.monthLength; i++) {
                        var realDayNumber = i + 1;

                        $instance.$month
                                .find(".stec-layout-month-daycell")
                                .eq(activeMonthInfo.dayOffset + i)
                                .attr("data-date", activeMonthInfo.year + "-" + activeMonthInfo.month + "-" + realDayNumber)
                                .find(".stec-layout-month-daycell-num").text(realDayNumber);
                    }

                    // Prev Month 
                    var prevMonthInfo = helper.getMonthInfo(activeMonthInfo.month - 1 < 0 ? 11 : activeMonthInfo.month - 1, activeMonthInfo.month - 1 < 0 ? activeMonthInfo.year - 1 : activeMonthInfo.year);
                    for (var i = activeMonthInfo.dayOffset; i > 0; i--) {
                        var realDayNumber = prevMonthInfo.monthLength - activeMonthInfo.dayOffset + i;
                        $instance.$month
                                .find(".stec-layout-month-daycell").eq(i - 1)
                                .addClass("stec-layout-month-daycell-inactive")
                                .attr("data-date", prevMonthInfo.year + "-" + prevMonthInfo.month + "-" + realDayNumber)
                                .find(".stec-layout-month-daycell-num").text(realDayNumber);
                    }

                    // Next Month 
                    var nextMonthInfo = helper.getMonthInfo(activeMonthInfo.month + 1 > 11 ? 0 : activeMonthInfo.month + 1, activeMonthInfo.month + 1 > 11 ? activeMonthInfo.year + 1 : activeMonthInfo.year);
                    for (var i = 0; i < 6 * 7 - (activeMonthInfo.monthLength + activeMonthInfo.dayOffset); i++) {
                        var offset = activeMonthInfo.monthLength + activeMonthInfo.dayOffset + i;
                        var realDayNumber = i + 1;
                        $instance.$month
                                .find(".stec-layout-month-daycell").eq(offset)
                                .addClass("stec-layout-month-daycell-inactive")
                                .attr("data-date", nextMonthInfo.year + "-" + nextMonthInfo.month + "-" + realDayNumber)
                                .find(".stec-layout-month-daycell-num").text(realDayNumber);
                    }

                    // Set Today 
                    var today = new Date();
                    var date = today.getFullYear() + "-" + today.getMonth() + "-" + today.getDate();
                    
                    $instance.$month
                            .find(".stec-layout-month-daycell[data-date='" + date + "']")
                            .addClass("stec-layout-month-daycell-today");

                    if ($instance.$month.find(".stec-layout-month-daycell-today").length > 0) {
                        
                        var offset = $instance.$month
                                .find(".stec-layout-month-weekrow")
                                .find(".stec-layout-month-daycell[data-date='" + date + "']").index();

                        $instance.$month
                                .find(".stec-layout-month-daylabel td")
                                .eq(offset)
                                .addClass("stec-layout-month-daylabel-today");
                    }

                },
                
                fillEvents: function(){
                    
                    // Get layout date span
                    
                    var from = helper.getDateFromData($instance.$month.find('.stec-layout-month-daycell').first().attr('data-date'));
                    var to   = helper.getDateFromData($instance.$month.find('.stec-layout-month-daycell').last().attr('data-date'));
                   
                    // Get all events for this timespan
                    
                    var events = calData.getEvents(from, to);
                    
                    if (events.length <= 0) {
                        return;
                    }
                    
                    // Loop each event
                    
                    var hiddenEvents;
                    
                    $(events).each(function(){
                        
                        hiddenEvents = [];
                        
                        var startDate = helper.dbDateTimeToDate(this.start_date);
                        var endDate   = helper.dbDateTimeToDate(this.end_date);
                        
                        var d1, d2, days = 0;
                        
                        // we care for number of difference dates not per 24 hours
                        d1 = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate());
                        d2 = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate());
                        
                        days = helper.diffDays(d1, d2);
                        
                        for (var day = 0; day <= days; day++) {
                            
                            var stamp = moment(this.start_date).add(day,'days').unix();

                            var dataDate = helper.getDataFromDate(new Date(stamp * 1000));
                            
                            var $eventCont = $instance.$month
                                    .find('.stec-layout-month-daycell[data-date="' + dataDate + '"]')
                                    .find('.stec-layout-month-daycell-events');
                            
                            var html = '';
                            
                            if ($eventCont.find('.stec-layout-month-daycell-event').length > 2 || (hiddenEvents.indexOf(this.id) > -1) ) {
                                
                                // if container is full || event started from full container
                                
                                if ($eventCont.find('.stec-layout-month-daycell-eventmore').length > 0) {

                                    var text = $eventCont.find('.stec-layout-month-daycell-eventmore-count').text();
                                    var num = parseInt(text.match(/[0-9]+/), 10);

                                    $eventCont.find('.stec-layout-month-daycell-eventmore-count').text(text.replace(num, num + 1));

                                } else {

                                    html += '<li class="stec-layout-month-daycell-eventmore">';
                                        html += '<p class="stec-layout-month-daycell-eventmore-count">+1</p>';
                                        html += '<p class="stec-layout-month-daycell-eventmore-count-dot"></p>';
                                        html += '<p class="stec-layout-month-daycell-eventmore-count-dot"></p>';
                                        html += '<p class="stec-layout-month-daycell-eventmore-count-dot"></p>';
                                    html += '</li>';
                                }
                                
                                hiddenEvents.push(this.id);
                                
                            } else {
                                
                                // Add event cell

                                var extraClass = '';

                                var style = 'style="background-color:' + this.color + '"';

                                if (day == 0) {
                                    extraClass += ' stec-layout-month-daycell-event-start';
                                }

                                if (day == days) {
                                    extraClass += ' stec-layout-month-daycell-event-end';
                                }

                                var featured_class;

                                switch (parseInt(this.featured, 10)) {
                                    case 1:
                                        featured_class = ' stec-event-featured ';
                                        break;

                                    case 2:
                                        featured_class = ' stec-event-featured stec-event-featured-bg ';
                                        break;

                                    default:
                                        featured_class = '';
                                }

                                extraClass += featured_class;
                                   
                                // determine event position
                                var positions = [1,2,3];
                                var pos       = 0;
                                
                                // repeat instance acts like subid of the event
                                var repeat_time_offset = this.repeat_time_offset ? this.repeat_time_offset : 0;
                                var pos_id = this.id + '-' + repeat_time_offset;
                                
                                var $first = $instance.$month.find('.stec-layout-month-daycell-event[data-pos-id="' + pos_id + '"]').first();
                                
                                if ($first.length > 0) {
                                    
                                    pos = $first.attr('data-pos');
                                    
                                } else {
                                    
                                    $eventCont.find('.stec-layout-month-daycell-event').each(function(){
                                        
                                        var i = positions.indexOf(parseInt($(this).attr('data-pos'), 10));
                                        
                                        if (i > -1) {
                                            positions.splice(i, 1);
                                        }
                                    });
                                    
                                    pos = positions[0];
                                    
                                }
                                   
                                var brightness = helper.getColorBrightness(this.color);

                                if (brightness > 170) {
                                    extraClass += " stec-layout-month-daycell-event-bright";
                                }
                                
                                var calNow = helper.getCalNow(this.timezone_utc_offset / 3600);
                                
                                if (calNow > endDate) {
                                    extraClass += " stec-layout-month-daycell-event-expired";
                                }

                                html = '<li data-pos="'+pos+'" data-pos-id="'+pos_id+'" data-repeat-time-offset="'+ repeat_time_offset +'" data-id="'+this.id+'" class="stec-layout-month-daycell-event ' + extraClass + '" ' + style + '>';

                                if (day == 0 || glob.options.general_settings.show_event_title_all_cells != 0) {
                                    
                                    html += '<p class="stec-layout-month-daycell-event-name">' + this.summary + '</p>';
                                }

                                html += '</li>';

                            }
                            
                            $(html).appendTo($eventCont);
                        }
                    });
                
                }
            },
            
            /**
             * WEEK LAYOUT
             */
            week: {
                bindControls: function () {

                    var parent = this;
                    
                    // Week daycell click handle
                    $instance.$week.find(".stec-layout-week-daycell").on(helper.clickHandle(), function (e) {
                        
                        e.preventDefault();
                        
                        if ($(this).hasClass("active")) {
                            // Close active cell
                            events.eventHolder.close();
                            $(this).removeClass("active");
                            return;
                        }

                        var date = helper.getDateFromData($(this).attr("data-date"));
                        
                        glob.options.year = date.getFullYear();
                        glob.options.month = date.getMonth();
                        glob.options.day = date.getDate();
                        
                        parent.setActiveCell();
                            
                        
                    });
                },
                
                set: function () {
                    $instance.$week.show();
                    this.setDayLabels();
                    this.fillGridDays();
                    this.fillEvents();
                },
                
                setDayLabels: function() {
                    
                    var offset = 0;
                    
                    switch (glob.options.general_settings.first_day_of_the_week) {
                        case 'mon' :
                            offset = 1;
                            break;

                        case 'sat' :
                            offset = 6;
                            break;

                        case 'sun' :
                            offset = 0;
                            break;
                    }
                    
                    var a = offset;
                    
                    $instance.$week.find('.stec-layout-week-daylabel td').each(function(i){
                        
                        var label = helper.capitalizeFirstLetter(glob.options.dayLabels[a]);
                        var labelShort = helper.capitalizeFirstLetter(glob.options.dayLabelsShort[a]);
                        
                        $(this).find('p').eq(0).text(label);
                        $(this).find('p').eq(1).text(labelShort);
                        $(this).find('p').eq(2).text(labelShort.charAt(0));
                        
                        a = a + 1 >= glob.options.dayLabels.length ? 0 : a + 1;
                        
                    });
                },
                
                setActiveCell: function () {
               
                    var parent = this;

                    // Set Active Cell

                    var activeCell = glob.options.year + "-" + glob.options.month + "-" + glob.options.day;

                    $instance.$week
                            .find(".stec-layout-week-daycell")
                            .removeClass("active");

                    $instance.$week
                            .find(".stec-layout-week-daycell[data-date='" + activeCell + "']")
                            .addClass("active");
                    
                    events.eventHolder.open();
               
                },
                
                resetGridCells: function () {

                    // Reset data 

                    $instance.$week
                            .find(".stec-layout-week-daylabel td")
                            .removeClass("stec-layout-week-daylabel-today");

                    $instance.$week
                            .find(".stec-layout-week-daycell")
                            .removeAttr("data-date")
                            .removeClass("stec-layout-week-daycell-today stec-layout-week-daycell-inactive active");
                    
                    $instance.$week
                            .find(".stec-layout-week-daycell")
                            .removeClass("active");
                    
                    $instance.$week
                            .find('.stec-layout-week-daycell-events').empty();
                    
                    events.eventHolder.close();

                },
                
                fillGridDays: function () {

                    var parent = this;

                    parent.resetGridCells();
                    
                    var week = helper.getWeekInfo();
                    
                    // Active Week
                    $instance.$week
                            .find(".stec-layout-week-daycell").each(function(i){
                                
                            var cellDate = new Date(week.start.year, week.start.month, week.start.day);
                            var next     = i * 24 * 60 * 60 * 1000; 
                            
                            cellDate.setTime(cellDate.getTime() + next);
                            
                            $(this)
                                    .attr("data-date", cellDate.getFullYear() + "-" + cellDate.getMonth() + "-" + cellDate.getDate())
                                    .find(".stec-layout-week-daycell-num").text(cellDate.getDate());

                    });
                    

                    // Set Today 
                    var today = new Date();
                    var date = today.getFullYear() + "-" + today.getMonth() + "-" + today.getDate();
                    
                    $instance.$week
                            .find(".stec-layout-week-daycell[data-date='" + date + "']")
                            .addClass("stec-layout-week-daycell-today");

                    if ($instance.$week.find(".stec-layout-week-daycell-today").length > 0) {
                        
                        var offset = $instance.$week
                                .find(".stec-layout-week-weekrow")
                                .find(".stec-layout-week-daycell[data-date='" + date + "']").index();

                        $instance.$week
                                .find(".stec-layout-week-daylabel td")
                                .eq(offset)
                                .addClass("stec-layout-week-daylabel-today");
                    }
                },
                 
                  
                fillEvents: function(){
                    
                    // Get layout date span
                    
                    var from = helper.getDateFromData($instance.$week.find('.stec-layout-week-daycell').first().attr('data-date'));
                    var to   = helper.getDateFromData($instance.$week.find('.stec-layout-week-daycell').last().attr('data-date'));
                   
                    // Get all events for this timespan
                    
                    var events = calData.getEvents(from, to);
                    
                    if (events.length <= 0) {
                        return;
                    }
                    
                    // Loop each event
                    
                    var hiddenEvents;
                    
                    $(events).each(function(){
                        
                        hiddenEvents = [];
                        
                        var startDate = helper.dbDateTimeToDate(this.start_date);
                        var endDate   = helper.dbDateTimeToDate(this.end_date);
                        
                        var d1, d2, days = 0;
                        
                        // we care for number of difference dates not per 24 hours
                        d1 = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate());
                        d2 = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate());
                        
                        days = helper.diffDays(d1, d2);
                        
                        for (var day = 0; day <= days; day++) {
                            
                            var stamp = moment(this.start_date).add(day,'days').unix();

                            var dataDate = helper.getDataFromDate(new Date(stamp * 1000));
                            
                            var $eventCont = $instance.$week
                                    .find('.stec-layout-week-daycell[data-date="' + dataDate + '"]')
                                    .find('.stec-layout-week-daycell-events');
                            
                            var html = '';
                            
                            if ($eventCont.find('.stec-layout-week-daycell-event').length > 2 || (hiddenEvents.indexOf(this.id) > -1) ) {
                                
                                // if container is full || event started from full container
                                
                                if ($eventCont.find('.stec-layout-week-daycell-eventmore').length > 0) {

                                    var text = $eventCont.find('.stec-layout-week-daycell-eventmore-count').text();
                                    var num = parseInt(text.match(/[0-9]+/), 10);

                                    $eventCont.find('.stec-layout-week-daycell-eventmore-count').text(text.replace(num, num + 1));

                                } else {

                                    html += '<li class="stec-layout-week-daycell-eventmore">';
                                        html += '<p class="stec-layout-week-daycell-eventmore-count">+1</p>';
                                        html += '<p class="stec-layout-week-daycell-eventmore-count-dot"></p>';
                                        html += '<p class="stec-layout-week-daycell-eventmore-count-dot"></p>';
                                        html += '<p class="stec-layout-week-daycell-eventmore-count-dot"></p>';
                                    html += '</li>';
                                }
                                
                                hiddenEvents.push(this.id);
                                
                            } else {
                                
                                // Add event cell

                                var extraClass = '';

                                var style = 'style="background-color:' + this.color + '"';

                                if (day == 0) {
                                    extraClass += ' stec-layout-week-daycell-event-start';
                                }

                                if (day == days) {
                                    extraClass += ' stec-layout-week-daycell-event-end';
                                }
                                
                                var featured_class;

                                switch (parseInt(this.featured, 10)) {
                                    case 1:
                                        featured_class = ' stec-event-featured ';
                                        break;

                                    case 2:
                                        featured_class = ' stec-event-featured stec-event-featured-bg ';
                                        break;

                                    default:
                                        featured_class = '';
                                }
                                
                                extraClass += featured_class;
                                   
                                // determine event position
                                var positions = [1,2,3];
                                var pos       = 0;
                                
                                // repeat instance acts like subid of the event
                                var repeat_time_offset = this.repeat_time_offset ? this.repeat_time_offset : 0;
                                var pos_id = this.id + '-' + repeat_time_offset;
                                
                                var $first = $instance.$week.find('.stec-layout-week-daycell-event[data-pos-id="' + pos_id + '"]').first();
                                
                                if ($first.length > 0) {
                                    
                                    pos = $first.attr('data-pos');
                                    
                                } else {
                                    
                                    $eventCont.find('.stec-layout-week-daycell-event').each(function(){
                                        
                                        var i = positions.indexOf(parseInt($(this).attr('data-pos'), 10));
                                        
                                        if (i > -1) {
                                            positions.splice(i, 1);
                                        }
                                    });
                                    
                                    pos = positions[0];
                                    
                                }
                                   
                                var brightness = helper.getColorBrightness(this.color);

                                if (brightness > 170) {
                                    extraClass += " stec-layout-week-daycell-event-bright";
                                }
                                
                                var calNow = helper.getCalNow(this.timezone_utc_offset / 3600);
                                
                                if (calNow > endDate) {
                                    extraClass += " stec-layout-month-daycell-event-expired";
                                }

                                html = '<li data-pos="'+pos+'" data-pos-id="'+pos_id+'" data-repeat-time-offset="'+ repeat_time_offset +'" data-id="'+this.id+'" class="stec-layout-week-daycell-event ' + extraClass + '" ' + style + '>';

                                if (day == 0 || glob.options.general_settings.show_event_title_all_cells != 0) {
                                    html += '<p class="stec-layout-week-daycell-event-name">' + this.summary + '</p>';
                                }

                                html += '</li>';

                            }
                            
                            $(html).appendTo($eventCont);
                        }
                    });
                
                }
            },
            
            /**
             * DAY LAYOUT
             */
            day: {
                
                bindControls: function() {
                    
                },
                set: function(){
                    $instance.$day.show();
                    events.eventHolder.open();
                }
                
            }
        };
        
        /**
         * handles events
         */
        var events = {
            
            init: function(){
                this.bindControls();
            },
            
            bindControls: function(){
                
                var parent = this;
                
                // activate anchors for tabs content
                $(document).on(helper.clickHandle(), $instance.$events.path + (" a"), function(e){
                    e.stopPropagation();
                    return true;
                });
                
                // excludes .create-form toggle
                // .stec-event-create-form is handled by adds/event.create.js
                $(document).on(helper.clickHandle(), $instance.$events.path + (".stec-layout-event-preview-right-event-toggle:not('.stec-layout-event-create-form-preview-right-event-toggle')"), function(e){
                    
                    e.preventDefault();
                    e.stopPropagation();
                    
                    var $event   = $(this).parents(".stec-layout-event");
                    parent.eventToggle($event);
                    
                });
        
                // excludes .create-form toggle, .stec-layout-event-awaiting-approval
                // .stec-event-create-form is handled by adds/event.create.js
                $(document).on(helper.clickHandle(), $instance.$events.path + (".stec-layout-event:not('.stec-event-create-form, .stec-layout-event-awaiting-approval')"), function (e) {
                    e.preventDefault();
                   
                    var $event   = $(this);
                    parent.eventToggle($event);
                });
                
                // Prevent toggling from inner content
                $(document).on(helper.clickHandle(), $instance.$events.path + '.stec-layout-event-inner', function (e) {
                    e.stopPropagation();
                });
                
                $(document).on(helper.clickHandle(), $instance.$events.path + (".stec-layout-event-inner-top-tabs li"), function(e){
                    e.preventDefault();
                    parent.activateTab($(this));
                });
                
                $(document).on(helper.clickHandle(), $instance.$events.path + (".stec-layout-event-preview-left-reminder-toggle"), function(e){
                    e.preventDefault();
                    e.stopPropagation();
                    
                    parent.attachReminder(this);
                });
                
                $(document).on(helper.clickHandle(), $instance.$events.path + (".stec-layout-event-preview-reminder"), function(e){
                    e.stopPropagation();
                });
                
                $(document).on(helper.clickHandle(), $instance.$events.path + (".stec-layout-event-preview-right-menu"), function(e){
                    e.preventDefault();
                    e.stopPropagation();
                    
                    parent.attachReminder(this);
                });
                
                $(document).on(helper.clickHandle(), $instance.$events.path + (" .stec-layout-event-preview-reminder input"), function(e){
                    e.stopPropagation();
                });

                $(document).on(helper.clickHandle(), $instance.$events.path + (".stec-layout-event-preview-reminder-units-selector li"), function(e){
                    e.preventDefault();
                   
                    var value = $(this).attr('data-value');
                    var text  = $(this).text();
                    
                    $(this).parents('.stec-layout-event-preview-reminder-units-selector')
                            .find('p')
                            .attr('data-value', value)
                            .text(text);
                });

                $(document).on(helper.clickHandle(), $instance.$events.path + (".stec-layout-event-preview-remind-button"), function(e){
                    
                    e.preventDefault();
                    
                    var $event = $(this).parents('.stec-layout-event');
                    var $form  = $(this).parents('ul:first');
                    
                    var eventId        = $event.attr('data-id');
                    var repeat_offset  = $event.attr('data-repeat-time-offset');
                    var email          = $form.find('input[name="email"]').val();
                    var number         = $form.find('input[name="number"]').val();
                    var units          = $form.find('p[data-value]').attr('data-value');
                    
                    if (helper.isEmail(email) && number != '') {
                        reminder.remindEvent(eventId, repeat_offset, email, number, units);
                    }
                     
                });
                
            },
            
            /**
             * Attached the reminder template to (this) element
             */
            attachReminder: function(th){
                
                var leftSided = false;
                
                if ($instance.hasClass('stec-media-small')) {
                    leftSided = true;
                }
                
                $instance.$events.find(".stec-layout-event-preview-left-reminder-toggle").not(th).removeClass("active");
                $instance.$events.find(".stec-layout-event-preview-right-menu").not(th).removeClass("active");
                $(th).toggleClass("active");

                $(window).unbind('resize.' + 'reminder-' + glob.options.id);
                $instance.find('.stec-layout-event-preview-reminder').remove();

                function position() {
                
                    // remove if button not visible anymore 
                    if (!$(th).is(":visible")) {
                        $(th).removeClass('active');
                        $(window).unbind('resize.' + 'reminder-' + glob.options.id);
                        $instance.find('.stec-layout-event-preview-reminder').remove();
                        
                        return;
                    }
                    
                    $instance.find('.stec-layout-event-preview-reminder').css({
                        
                        left: function(){
                            
                            if (leftSided === true) {
                                
                                return 'initial'; // should be 0 but iPhone is ...
                                
                            } else {
                                
                                return $(th).position().left - $instance.find('.stec-layout-event-preview-reminder').width() + $(th).width() / 2 + 3;
                            
                            }
                            
                        },
                        top: function() {
                            
                            if (leftSided === true) {
                                
                                return $(th).position().top - $(th).height() - 12 - $instance.find('.stec-layout-event-preview-reminder').height();
                                
                            } else {
                                
                               return $(th).position().top - $instance.find('.stec-layout-event-preview-reminder').height() - 10;
                                
                            }
                            
                        }
                    });
                    
                    if (leftSided === true) {
                        // sets the bottom arrow to the left side
                        $instance.find('.stec-layout-event-preview-reminder').addClass('stec-layout-event-preview-reminder-left');
                    
                    } 
                }

                if ($(th).hasClass('active')) {
                    $(glob.template.reminder).appendTo($(th).parents('.stec-layout-event').first());

                    helper.onResizeEnd(function () {
                        position();
                    }, 10, 'reminder-' + glob.options.id);

                    position();
                }
                
            },
            
            /**
             * Hides tab if event has no data for this tab
             * @param {type} $event the event jquery html object
             * @todo automate
             */
            setEventTabs: function($event){
                
                // Remove unused tabs
                var event = calData.getEventById($event.attr('data-id'));
                var tabs  = 0;
                
                // comments
                if (event.tabs.comments != 1) {
                    $event.find('.stec-layout-event-inner-top-tabs [data-tab="stec-layout-event-inner-comments"]').hide();
                } else {
                    tabs++;
                }

                // location
                if (event.tabs.location != 1) {
                    $event.find('.stec-layout-event-inner-top-tabs [data-tab="stec-layout-event-inner-location"]').hide();
                } else {
                    tabs++;
                }

                // forecast
                if (event.tabs.forecast != 1) {
                    $event.find('.stec-layout-event-inner-top-tabs [data-tab="stec-layout-event-inner-forecast"]').hide();
                } else {
                    tabs++;
                }

                // schedule
                if (event.tabs.schedule != 1) {
                    $event.find('.stec-layout-event-inner-top-tabs [data-tab="stec-layout-event-inner-schedule"]').hide();
                } else {
                    tabs++;
                }

                // guests
                if (event.tabs.guests != 1) {
                    $event.find('.stec-layout-event-inner-top-tabs [data-tab="stec-layout-event-inner-guests"]').hide();
                } else {
                    tabs++;
                }

                // attendance
                if (event.tabs.attendance != 1) {
                    $event.find('.stec-layout-event-inner-top-tabs [data-tab="stec-layout-event-inner-attendance"]').hide();
                } else {
                    tabs++;
                }

                // woocommerce
                if (event.tabs.woocommerce != 1) {
                    $event.find('.stec-layout-event-inner-top-tabs [data-tab="stec-layout-event-inner-woocommerce"]').hide();
                } else {
                    tabs++;
                }
               
                if (tabs < 1) {
                    $event.find('.stec-layout-event-inner-top-tabs').hide();
                }
            },
            
            eventToggle: function($event) {
				
				var event = calData.getEventById($event.attr('data-id'));

if (event.link != '') {
    window.location.href = event.link;
} else if (glob.options.general_settings.open_event_in == 'single') {
                    window.location.href = $event.find('.stec-layout-event-single-page-link').attr('href');
                    return false;
                }
            
                if (!$event.hasClass("active")) {
                    
                    var requireData = false;
                    
                    // Add inner content
                    if ($event.find(".stec-layout-event-inner").length <= 0) {
                        $(glob.template.eventInner).appendTo($event);
                        requireData = true;
                    }

                    // Set active 
                    $event
                        .addClass("active")
                        .find(".stec-layout-event-preview-right-event-toggle").addClass("active");

                    var $siblings = $instance.$events.find(".stec-layout-event").not($event);

                    $siblings
                            .removeClass("active")
                            .find(".stec-layout-event-preview-right-event-toggle")
                            .removeClass("active");
                    
                    
                    this.setEventTabs($event);
                    

                    // Load first tab if no tab is active
                    if ($event.find('.stec-layout-event-inner-top-tabs').children('li.active').length <= 0) {
                        $event.find('.stec-layout-event-inner-top-tabs').children('li').first().trigger(helper.clickHandle());
                    }
                    
                    
                    if (requireData === true) {
                        
                        // pulls data only when necessary, do not override same data
                        calData.pullEventData($event.attr('data-id'), $event.attr('data-repeat-time-offset'), false);
                    }
                    
                    // Focus on event
                    helper.focus($event);
                    
                    
                } else {

                    $event
                        .removeClass("active")
                        .find(".stec-layout-event-preview-right-event-toggle").removeClass("active");
                }
                
            },
            
            activateTab: function($tab){
                
                if ($tab.hasClass("active")) {
                    return;
                }
                    
                $tab.addClass("active")
                        .siblings()
                        .removeClass("active");
                
                // remove only children active
                $tab
                    .parents(".stec-layout-event-inner")
                    .find(".stec-layout-event-inner-top-tabs-content")
                    .children('.active')
                    .removeClass("active");

                    
                var tabClass = "." + $tab.attr("data-tab");
                
                $tab
                    .parents(".stec-layout-event-inner")
                    .find(tabClass)
                    .addClass("active");
            
                $(document).trigger('stec-tab-click-'+glob.options.id);
                
            },
            
            eventHolder: {
                
                getEventHolder: function() {
                    
                    var $eventHolder = "";
                    
                    switch (glob.options.view) {
                        
                        case "agenda":
                            $eventHolder = $instance.$agenda.find(".stec-event-holder");
                            break;
                            
                        case "month":
                            $eventHolder = $instance.$month.find(".stec-event-holder");
                            break;
                            
                        case "week":
                            $eventHolder = $instance.$week.find(".stec-event-holder");
                            break;
                            
                        case "day":
                            $eventHolder = $instance.$day.find(".stec-event-holder");
                            break;
                    }
                    
                    return $eventHolder;
                },
                
                removeEvents: function() {
                    
                    // prevents duplicate triggers  
                    $(document).unbind('stec-tab-click-'+glob.options.id);
                    
                    // resize.stec-unbind-window-resize-on-event-close
                    // prevents duplicate triggers 
                    $(window).unbind('resize.stec-unbind-window-resize-on-event-close-'+glob.options.id);
                    
                    $instance.$events.not('.stec-layout-agenda-events-all').children().remove();
                },
                
                /**
                 * Displays events for active date
                 * @returns bool true of false if no events
                 */
                displayEvents: function(){
                    
                    var d = new Date(glob.options.year, glob.options.month, glob.options.day);
                    
                    var events = calData.getEvents(d, false);
                    
                    if (events.length <= 0) {
                        // no events
                        return false;
                    }
                    
                    var now = new Date();
                    
                    var format = 'd m y';

                    switch (glob.options.general_settings.date_format) {

                        case 'dd-mm-yy' :
                            format = 'd m y';
                            break;

                        case 'yy-mm-dd' :
                            format = 'y m d';
                            break;

                        case 'mm-dd-yy' :
                            format = 'm d y';
                            break;

                    }
                    
                    events.sort(calData.sortByFeatured);
                    
                    $(events).each(function(){
                        
                        var event = this;
                        
                        // stec-layout-event-preview-right-menu
                        
                        var startDate = new Date(event.start_date_timestamp * 1000);
                        
                        if (now > startDate) {
                            var noReminder = true;
                        }
                        
                        var date = helper.beautifyTimespan(event.start_date, event.end_date, event.all_day);
                        
                        var gmtutc_offset = parseInt(event.timezone_utc_offset, 10) / 3600;
                            gmtutc_offset = gmtutc_offset > 0 ? '+' + gmtutc_offset : gmtutc_offset;
                            
                            if (gmtutc_offset == 0) {
                                gmtutc_offset = '';
                            }
                            
                        var timezoneOffsetLabel = glob.options.general_settings.date_label_gmtutc == 0 ? '' : 'UTC/GMT ' + gmtutc_offset;;
                        
                        var featured_class = '';
                        
                        switch(parseInt(this.featured, 10)) {
                            case 1: 
                                featured_class = ' stec-event-featured ';
                            break;
                            
                            case 2: 
                                featured_class = ' stec-event-featured stec-event-featured-bg ';
                            break;
                            
                            default:
                            featured_class = '';
                        }
                        
                        var additional_class = "";
                        
                        if (event.icon == 'fa') {
                            additional_class += ' stec-no-icon ';
                        }
                        
                        $(glob.template.event)
                            .addClass(featured_class)
                            .addClass(additional_class)
                            .addClass(noReminder ? 'stec-layout-event-no-reminder' : '')
                            .attr('data-id', event.id)
                            .attr('data-repeat-time-offset', event.repeat_time_offset ? event.repeat_time_offset : 0)
                            .html(function(index, html){
                            
                            html += '<a class="stec-layout-event-single-page-link" href="'+glob.options.single_page_url + event.alias + (event.repeat_time_offset > 0 ? '/' + event.repeat_time_offset : '')+'">'+event.summary+'</a>';
                            
                            return html
                                    .replace('stec_replace_summary', event.summary)
                                    .replace('stec_replace_date', date + ' ' + timezoneOffsetLabel)
                                    .replace('stec_replace_event_background', ' style="background:'+event.color+'" ') // edge is retarded
                                    .replace('stec_replace_icon_class', event.icon);
                            
                        }).appendTo($instance.$events.not('.stec-layout-agenda-events-all'));
                        
                    });
                    
                    // Remove + when single pages
                    if (glob.options.general_settings.open_event_in == 'single') {
                        $instance.$events
                                .not('.stec-layout-agenda-events-all')
                                .find('.stec-layout-event-preview-right-event-toggle')
                                .remove();
                    }
                    
                    return true;
                },
                
                close: function(){
                   
                    $instance.$events
                            .not('.stec-layout-agenda-events-all')
                            .find(".active")
                            .removeClass("active");
                    
                    this.getEventHolder().hide();
                    
                    // last visible children fix for border-radius
                    if (glob.options.view == "month") {
                        $instance.$month.find(".stec-layout-month-weekrow").last().addClass("stec-layout-month-weekrow-last");
                    }
                    
                    if (glob.options.view == "week") {
                        $instance.$week.find(".stec-layout-week-weekrow").addClass("stec-layout-week-weekrow-last");
                    }
                    
                    helper.extendBind("stachethemes_ec_extend", "onEventHolderClose");
                    
                    // Remove inner content
                    this.removeEvents();
                },
                
                open: function(){
                    
                    this.close();
                    
                    var result = this.displayEvents();
                 
                    // Day layout specifics
                    if (glob.options.view == 'day') {
                        
                        if (result === false) {
                            $instance.$day.find('.stec-layout-day-noevents').show();
                        } else {
                            $instance.$day.find('.stec-layout-day-noevents').hide();
                        }
                        
                    }
                    
                    // If create form is disabled and there are no events do not open the event holder
                    if (result === false && glob.options.general_settings.show_create_event_form == '0') {
                        return;
                    }
                    
                    // If there is event holder...
                    
                    // Month layout specifics
                    if (glob.options.view == "month") {
                        
                        // last visible children fix...
                        
                        if ($instance.$month.find(".stec-layout-month-eventholder").is(":last-child")) {
                            $instance.$month.find(".stec-layout-month-weekrow-last").removeClass("stec-layout-month-weekrow-last");
                        } else {
                            $instance.$month.find("tr").last().addClass("stec-layout-month-weekrow-last");
                        }
                        
                        // focus on event
                        helper.focus($instance.$month.find('.stec-layout-month-daycell.active'));
                    }
                    
                    // Week layout specifics
                    if (glob.options.view == "week") {
                        $instance.$week.find(".stec-layout-week-weekrow-last").removeClass("stec-layout-week-weekrow-last");
                    }
                    
                    helper.extendBind("stachethemes_ec_extend", "onEventHolderOpen");
                    
                    if (helper.animate) {
                        helper.animate.eventHolder.open(this.getEventHolder());
                    } else {
                        this.getEventHolder().show();
                    }
                        
                    
                }
            }
        };
       
        var calData = {
            
            featuredOnly: false,
            calendarFilter: [],
            calendarsPool: [],
            eventsPool: [],
            
            
            
            /**
             * Returns calendar by id
             * 
             * @param {int} calendar_id
             * @returns calendar object or empty object
             */
            getCalendarById: function(calendar_id) {
                
                var cal = [];
                
                $(glob.options.calendars).each(function(){
                    if (this.id == calendar_id) {
                        cal = this;
                        return false;
                    }
                });
                
                return cal;
            },
            
            
            /**
             * Returns event by id
             * 
             * @param {int} event_id
             * @returns event object
             * @todo add paramenets for time offset
             */
            getEventById: function(event_id) {
                
                var event = [];
                
                $(calData.eventsPool).each(function(){
                    if (this.id == event_id) {
                        event = this;
                        return false; // break;
                    }
                });
                
                return event;
            },
            
            // sort by featured
            sortByFeatured: function (a, b) {
                if (a.featured == b.featured) {
                    return a.start_date_timestamp - b.start_date_timestamp;
                } else {
                    return b.featured - a.featured;
                }
            },
            
            // sort by timestamp oldest -> newest
            sortByTimestamp: function (a, b) {
                if (a.start_date_timestamp < b.start_date_timestamp)
                    return -1;
                else if (a.start_date_timestamp > b.start_date_timestamp)
                    return 1;
                else
                    return 0;
            },
            
            removeFromEventsPool: function(eventId) {
                
                var newPool = []; // probably the safest way to do it...
                
                $(this.eventsPool).each(function(i){
                   
                   if (this.id != eventId) {
                    
                        newPool.push(this);
                   }
                    
                });
                
                this.eventsPool = newPool;
            },
            
            addToEventsPool: function(events){
                
                var parent = this;
                
                $(events).each(function(i){
                   this.start_date_timestamp = helper.dateToUnixStamp(helper.dbDateTimeToDate(this.start_date));
                   this.end_date_timestamp   = helper.dateToUnixStamp(helper.dbDateTimeToDate(this.end_date));
                });
                
                events.sort(parent.sortByTimestamp);
                
                /*
                 * @todo keep/delete?
                 */
                events.sort(parent.sortByFeatured);
                
                this.eventsPool = this.eventsPool.concat(events);
                
                helper.extendBind("stachethemes_ec_extend", "onAddToEventsPool", this.eventsPool);
            },
            
            addDataToEvent: function(data){
                
                var parent = this;
                
                $(parent.eventsPool).each(function(i){
                    if (this.id == data.general.id) {
                        this.data = data;
                    }
                });
            },
            
            pullEvents: function(callback){
                
                var parent = this;
                
                glob.ajax = $.ajax({
                    dataType: "json",
                    type: 'POST',
                    url: window.ajaxurl,
                    data: {
                        action: 'stec_public_ajax_action',
                        cal: glob.options.cal ? glob.options.cal : '',
                        min_date: glob.options.min_date ? glob.options.min_date : null,
                        max_date: glob.options.max_date ? glob.options.max_date : null,
                        task: 'get_events'
                    },
                    
                    beforeSend: function(){
                        if (glob.ajax !== null) {
                            glob.ajax.abort();
                        }
                    },
                    
                    success: function(data) {
                        if (data) {
                            parent.addToEventsPool(data);
                        }
                    },
                    
                    error: function (xhr, status, thrown) {
                        console.log(xhr + " " + status + " " + thrown);
                    },
                    
                    complete: function() {
                        glob.ajax = null;
                        
                        if (typeof callback === "function") {
                            callback();
                        }
                    }
                });
                
            },
            
            /**
             * @param {int} event_id Real event id
             * @param {int} offset Repeater time offset in unixtime (works as unique event sub id for the db)
             * @param {fn} callback
             */
            pullEventData: function(event_id, offset, callback){
                
                var hasCache = false;
                    offset   = parseInt(offset, 10);
                
                $(this.eventsPool).each(function(){
                    if (this.id == event_id && typeof this.data !== 'undefined') {
                        
                        hasCache = true;
                        
                        this.data.repeat_time_offset = parseInt(offset, 10);
                        
                        if (typeof callback === "function") {
                            callback(this.data);
                        }
                        
                        helper.extendBind("stachethemes_ec_extend", "onEventDataReady", this.data);
                    } 
                });
                
                if (hasCache === true)  {
                    return;
                }
                
                glob.ajax = $.ajax({
                    dataType: "json",
                    type: 'POST',
                    url: window.ajaxurl,
                    data: {
                        action: 'stec_public_ajax_action',
                        task: 'get_event_data',
                        event_id: event_id
                    },
                    
                    beforeSend: function(){
                        if (glob.ajax !== null) {
                            glob.ajax.abort();
                        }
                        
                        helper.extendBind("stachethemes_ec_extend", "onBeforeEventDataAjax");
                    },
                    
                    success: function(data) {
                        
                        if (data) {
                            
                            data.repeat_time_offset = parseInt(offset, 10);
                            
                            calData.addDataToEvent(data);
                        }
                        
                        if (typeof callback === "function") {
                            callback(data);
                        }
                        
                        helper.extendBind("stachethemes_ec_extend", "onEventDataReady", data);
                        
                    },
                    error: function (xhr, status, thrown) {
                        console.log(xhr + " " + status + " " + thrown);
                    },
                    complete: function() {
                        glob.ajax = null;
                    }
                });
                
            },
            
            /**
             * Pulls all events from now up to 6 months in the future, including repeated events
             */
            getFutureEvents: function(){
                
                var now     = new Date();
                var date    = new Date(glob.options.year, glob.options.month, 1);
                
                var a = date > now ? date : now;
                var b = new Date(a);
                    b.setMonth(b.getMonth() + 6);
            
                var events = calData.getEvents(a,b);
                
                return events;
            },
            
            /**
             * 
             * Return all events for given timespan
             * 
             * @param {date} startDate
             * @param {date} endDate
             * @returns {array}
             */
            getEvents: function(startDate, endDate, incAapproval) {
                
                var parent = this;
                
                if (!incAapproval) {
                    incAapproval = false;
                }
                
                if (!startDate) {
                    startDate = new Date(glob.options.year, glob.options.month, glob.options.day);
                }
                
                startDate.setHours(0);
                startDate.setMinutes(0);
                startDate.setSeconds(0);
                startDate.setMilliseconds(0);
                
                if (endDate) {
                    endDate.setHours(0);
                    endDate.setMinutes(0);
                    endDate.setSeconds(0);
                    endDate.setMilliseconds(0);
                } else {
                    endDate = new Date(startDate);
                }
                
                endDate.setHours(24);
                
                var a = helper.dateToUnixStamp(startDate);
                var b = helper.dateToUnixStamp(endDate);
                
                var pick = [];
                
                parent.filterGetEvents = [];
                
                parent.filterGetEvents = calData.eventsPool;
                
                helper.extendBind("stachethemes_ec_extend", "beforeProccessGetEvents");
                
                $(parent.filterGetEvents).each(function() {
                    
                    var event_loop = this;
                    
                    if (incAapproval !== true && this.approved == '0') {
                        return true;
                    }
                    
                    //  If repeating event get repeater
                    if (this.rrule != '') {
                        var event_loop = parent.repeater.get(this,a,b);
                    }
                    
                    // Picker
                    $(event_loop).each(function () {
                        
                        var start = this.start_date_timestamp;
                        var end   = this.end_date_timestamp;
                        
                        if (b > start && end >= a) {
                            pick.push(this);
                        }
                    });
                    
                });
                
                // reorder full events by timestamp
                parent.filterGetEvents = pick.sort(parent.sortByTimestamp);
                
                helper.extendBind("stachethemes_ec_extend", "beforeReturnGetEvents");
                
                return parent.filterGetEvents;
            },
            
              
            repeater: {
                
                get: function(event, rangeStart, rangeEnd) {
                    
                    var eventStartDate = new Date((event.start_date_timestamp * 1000));
                    var rangeStartDate = new Date(rangeStart * 1000);
                    var rangeEndDate   = new Date(rangeEnd * 1000);
                    
                    var dtstartRFC = helper.dateToRFC(eventStartDate);
                    
                    var rfcString = event.rrule + ';DTSTART=' + dtstartRFC;
                           
                    var result = new window.RRule
                    
                                .fromString(rfcString)
                        
                                .between(eventStartDate, rangeEndDate, true);
 
                    var r_events = [];

                    if (result.length <= 0) {
                        return r_events;
                    }
                    
                    $(result).each(function () {

                        var offset = helper.dateToUnixStamp(this) - event.start_date_timestamp;

                        // not by reference! need fresh copy
                        var r_event = JSON.parse(JSON.stringify(event));

                        r_event.start_date_timestamp = r_event.start_date_timestamp + offset;
                        r_event.end_date_timestamp   = r_event.end_date_timestamp + offset;

                        r_event.start_date = helper.dateToDbDateTime(new Date(r_event.start_date_timestamp * 1000));
                        r_event.end_date   = helper.dateToDbDateTime(new Date(r_event.end_date_timestamp * 1000));
                        
                        r_event.repeat_time_offset = r_event.start_date_timestamp - event.start_date_timestamp;
                        
                        if (r_event.end_date_timestamp < rangeStart) {
                            return true;
                        }

                        r_events.push(r_event);

                    });
                    
                    return r_events;
                    
                }
            
            }
            
        };
        
        var reminder = {
            
            blockAction: false,
            ajax: null,
            
            remindEvent: function(eventId, repeat_offset, email, number, units) {
                
                if (this.blockAction === true) {
                    return;
                }
                
                var parent = this;
                
                var event = calData.getEventById(eventId);
                var remindDate = helper.dbDateTimeToDate(helper.dbDateOffset(event.start_date, repeat_offset));
                
                if (isNaN(number)) {
                    return;
                }
                
                switch(units) {
                    
                    case 'hours' :
                       
                       remindDate.setHours(remindDate.getHours() - number);
                       
                    break;
                    
                    case 'days' :
                        
                        remindDate.setDate(remindDate.getDate() - number);
                        
                    break;
                    
                    case 'weeks' :
                        
                        remindDate.setDate(remindDate.getDate() - number*7);
                       
                    break;
                }
                
                remindDate = helper.dateToDbDateTime(remindDate);
                
                var $menu = $instance.$events.find('.stec-layout-event-preview-right-menu.active');
                
                var $mini = $instance.$events.find('.stec-layout-event-preview-left-reminder-toggle.active');
                
                reminder.ajax = $.ajax({
                    dataType: "json",
                    type: 'POST',
                    url: window.ajaxurl,
                    data: {
                        action: 'stec_public_ajax_action',
                        task: 'add_reminder',
                        event_id: eventId,
                        repeat_offset: repeat_offset,
                        email: email,
                        date: remindDate
                    },
                    beforeSend: function () {
                        if (reminder.ajax !== null) {
                            reminder.ajax.abort();
                        }
                        
                        $menu.find('> i').hide();
                        $(glob.template.preloader).appendTo($menu);
                        
                        $mini.text(stecLang.setting);
                        
                        parent.blockAction = true;
                        
                    },
                    success: function (data) {
                        
                        $menu.find('> i').show();
                        
                        if (data && data.error != 1) {
                            $menu.find('> i').removeClass('fa-bell').addClass('fa-check');
                            $mini.text(stecLang.remindrset);
                            $mini.addClass('stec-layout-event-preview-left-reminder-success');

                            setTimeout(function(){
                                $menu.find('> i').removeClass('fa-check').addClass('fa-bell');
                                $mini.text(stecLang.reminder);
                                $mini.removeClass('stec-layout-event-preview-left-reminder-success');
                            }, 3000);
                            
                        } else {
                            
                            $menu.find('> i').removeClass('fa-bell').addClass('fa-times');
                            $mini.text(stecLang.error);
                            
                            setTimeout(function () {
                                $menu.find('> i').removeClass('fa-times').addClass('fa-bell');
                                $mini.text(stecLang.reminder);
                            }, 3000);
                            
                        }
                        
                    },
                    error: function (xhr, status, thrown) {
                        
                        $menu.find('> i').removeClass('fa-bell').addClass('fa-times');

                        setTimeout(function () {
                            $menu.find('> i').removeClass('fa-times').addClass('fa-bell');
                        }, 3000);
                        
                        console.log(xhr + " " + status + " " + thrown);
                    },
                    complete: function () {
                        
                        reminder.ajax = null;
                        
                        $menu.find('.stec-preloader').remove();
                        
                        setTimeout(function () {
                            parent.blockAction = false;
                        }, 3000);

                    }
                });

            }
            
        };
        
    }
    
    $(document).ready(function () {
        
        $(document).on('click', '.stec-fixed-message a', function (e) {
            e.preventDefault();

            $(this).parents('.stec-fixed-message').remove();
        });
        
        if (typeof window.stachethemes_ec_instance !== "undefined") {
            $(window.stachethemes_ec_instance).each(function () {
                
                var stec = new stachethemesEventCalendar();
                    stec.init(this);
                
            });
        }
    });

})(jQuery);
// source --> http://www.kolarac.rs/wp-content/plugins/stachethemes_event_calendar/stachethemes/../front/js/stec-extend.js?ver=4.8.25 
(function ($) {

    "use strict";
    
    /**
     * Helper function allows binding to certain listeners
     * Used by adds/...
     */
    
    $.stecExtend = function(fn, sub){
        
        if (typeof stachethemes_ec_extend === "undefined") {
            window.stachethemes_ec_extend = [];
        }
        
        if (sub) {
            
            if (typeof stachethemes_ec_extend[sub] === "undefined") {
                window.stachethemes_ec_extend[sub] = [];
            }
            
            stachethemes_ec_extend[sub].push(fn);
            
        } else {
            stachethemes_ec_extend.push(fn);
        }
        
    };
    

})(jQuery);
// source --> http://www.kolarac.rs/wp-content/plugins/stachethemes_event_calendar/stachethemes/../front/js/adds/search.js?ver=4.8.25 
(function ($) {

    "use strict";

    $.stecExtend(function (master) {
        
        var $instance = master.$instance;
        var helper    = master.helper;
        var glob      = master.glob;
        var layout    = master.layout;
        var calData   = master.calData;

        /**
         * Top Search form handling
         */
        var search = {
            
            init: function () {
                this.bindControls();
            },
            
            bindControls: function () {

                var parent = this;

                var suggestionTimeout;

                $instance.$top.find(".stec-top-search-dropdown").on("keyup", function (e) {

                    clearTimeout(suggestionTimeout);

                    var value = $instance.$top.find(".stec-top-search-form input").val();
                    var $lis = $instance.$top.find(".stec-top-search-results li");

                    switch (e.which) {

                        // esc
                        case 27 :
                            parent.closeSearch();
                            break;

                        // enter 
                        case 13 :

                            if ($lis.filter(".active").length <= 0) {
                                parent.getResults(value);
                                return;
                            }

                            var $selected = $lis.filter(".active");

                            // Jump date check
                            if (typeof $selected.attr("data-jumpdate") !== "undefined") {
                                parent.jumpToDate($selected);
                                parent.closeSearch();
                            }

                            break;

                        // up arrow
                        case 38 :
                            if ($lis.filter(".active").length > 0) {
                                $lis.filter(".active")
                                        .removeClass("active")
                                        .prev()
                                        .addClass("active");
                            } else {
                                $lis.filter(":last").addClass("active");
                            }
                            break;

                        // down arrow
                        case 40 :
                            if ($lis.filter(".active").length > 0) {
                                $lis.filter(".active")
                                        .removeClass("active")
                                        .next()
                                        .addClass("active");
                            } else {
                                $lis.filter(":first").addClass("active");
                            }
                            break;

                        default:
                            suggestionTimeout = setTimeout(function () {
                                parent.getResults(value);
                            }, 250);

                    }

                });

                // Result list click handle
                $(document).on(helper.clickHandle(), $instance.$top.path + " .stec-top-search-results li", function (e) {

                    e.preventDefault();

                    var $lis = $instance.$top.find(".stec-top-search-results li");

                    $lis.removeClass("active");
                    $(this).addClass("active");

                    var $selected = $lis.filter(".active");

                    // Jump date check
                    if (typeof $selected.attr("data-jumpdate") !== "undefined") {
                        parent.jumpToDate($selected);
                        parent.closeSearch();
                    }

                });

                // Search button click handle
                $instance.$top.find(".stec-top-search-form a").on(helper.clickHandle(), function (e) {

                    e.preventDefault();

                    var value = $instance.$top.find("input").val();
                    parent.getResults(value);
                });

                // Search main button toggle show/hide
                $(document).on(helper.clickHandle(), $instance.$top.path + " .stec-top-menu-search", function (e) {
                    e.preventDefault();
                    
                    $instance.$top.find('.stec-top-menu-filter-calendar').removeClass('active');
                    
                    // fix for left offset since today button is not fixed width
                    var $dropdown = $(this).find('.stec-top-search-dropdown');
                    
                    $dropdown.css({
                        left: -1 * Math.round($(this).position().left)
                    });
                    
                    $(this).toggleClass("active");
                });

                // Block search toggle for inner content
                $(document).on(helper.clickHandle(), $instance.$top.path + " .stec-top-search-dropdown", function (e) {
                    // preventDefault blocks mobile keyboard
                    e.stopPropagation();
                });

            },

            /**
             * jump to $selected data-jumpdate attribute
             * data-jumpdate="yyyy-mm-dd"
             * @param {object} $selected $(element)
             */
            jumpToDate: function ($selected) {

                var date = helper.getDateFromData($selected.attr("data-jumpdate"));

                glob.options.year = date.getFullYear();
                glob.options.month = date.getMonth();
                glob.options.day = date.getDate();

                layout.set();

            },
            
            closeSearch: function () {
                this.resetResults();
                $instance.$top.find(".stec-top-menu-search").removeClass("active");
            },
            
            resetResults: function () {
                $instance.$top.find('.stec-top-search-dropdown-noresult').hide();
                $instance.$top.find(".stec-top-search-results").empty();
            },
            
            escapeHtml: function (string) {

                var entityMap = {
                    "&": "&amp;",
                    "<": "&lt;",
                    ">": "&gt;",
                    '"': '&quot;',
                    "'": '&#39;',
                    "/": '&#x2F;'
                };

                return String(string).replace(/[&<>"'\/]/g, function (s) {
                    return entityMap[s];
                });
            },
            
            getResults: function (keyword) {

                var parent = this;

                parent.resetResults();

                keyword = $.trim(keyword);

                if (keyword == "") {
                    return;
                }

                var keywordArray = keyword.split(" ");

                var WORD = {
                    generic: false,
                    date: {
                        year: false,
                        month: false,
                        day: false
                    }
                };

                $(keywordArray).each(function () {

                    // Start as Generic word
                    var generic = true;

                    if (parent.isYear(this)) {
                        WORD.date.year = this;
                        generic = false;
                    }

                    if (parent.isMonthString(this)) {
                        var monthName = this;

                        $(glob.options.monthLabels).each(function (monthNumber) {
                            if (this.toLowerCase() == monthName.toLowerCase()) {
                                WORD.date.month = monthNumber;
                                generic = false;
                            }
                        });

                        if (WORD.date.month === false) {
                            // check shortname
                            $(glob.options.monthLabelsShort).each(function (monthNumber) {
                                if (this.toLowerCase() == monthName.toLowerCase()) {
                                    WORD.date.month = monthNumber;
                                    generic = false;
                                }
                            });
                        }
                    }

                    if (parent.isDay(this)) {
                        WORD.date.day = this;
                        generic = false;
                    }

                    // NO Func Match Found
                    if (generic === true) {
                        WORD.generic = true;
                    }

                });

                // Not a generic word
                if (WORD.generic === false) {
                    if (WORD.date.year !== false || WORD.date.month !== false || WORD.date.day !== false) {

                        if (WORD.date.year === false) {
                            WORD.date.year = glob.options.year;
                        }
                        if (WORD.date.month === false) {
                            WORD.date.month = glob.options.month;
                        }
                        if (WORD.date.day === false) {
                            WORD.date.day = glob.options.day;
                        }

                        // Suggest navigate to Date

                        var dateData = WORD.date.year + "-" + WORD.date.month + "-" + WORD.date.day;
                        var searchDate = new Date(WORD.date.year,WORD.date.month,WORD.date.day);
                        
                        var format = 'd m y';
                        switch(glob.options.general_settings.date_format) {
                            case 'dd-mm-yy' :
                                format = 'd m y';
                            break;
                            case 'yy-mm-dd' :
                                format = 'y m d';
                            break;
                            case 'mm-dd-yy' :
                                format = 'm d y';
                            break;
                        }
                        
                        var dateString = helper.dateToFormat(format, searchDate);

                        var html = '<li data-jumpDate="' + dateData + '"><i class="fa fa-calendar-check-o"></i> <p>' + dateString + '</p></li>';
                        $(html).appendTo($instance.$top.find(".stec-top-search-results"));
                        
                    }

                } else {
                    // Generic
                    // Search for keywords
                    
                    var result = [];
                    
                    $(keywordArray).each(function(){
                        
                        var word = this;
                        
                        if (word.length <= 2) {
                            return true;
                        }
                        
                        word = word.toLowerCase();
                        
                        var eventsPool = [];
                        
                        eventsPool = calData.eventsPool;
                        
                        $(eventsPool).each(function() {
                            
                            if (calData.calendarFilter.indexOf(this.calid) === -1) {
                                return; // continue loop
                            }
                            
                            var keywords = this.keywords.toLowerCase();
                            var summary  = this.summary.toLowerCase();
                            
                            if (keywords.indexOf(word) > -1 || summary.indexOf(word) > -1) {
                                result.push(this);
                            }
                        });
                        
                    });
                    
                    if (result.length > 0) {
                        // found match
                        
                        var html = '';

                        $(result).each(function () {
                            
                            var jumpDate = helper.getDataFromDate(helper.dbDateTimeToDate(this.start_date));
                            
                            html += '<li data-jumpDate="' + jumpDate + '"><i class="'+this.icon+'"></i><p>'+this.summary+'</p></li>';
                        });

                        $(html).appendTo($instance.$top.find(".stec-top-search-results"));

                    } else {
                        // no match found
                        $instance.$top.find('.stec-top-search-dropdown-noresult').show();
                    }
                   
                }
                
                


            },
            
            isMonthString: function (keyword) {
                var found = false;
                if (isNaN(keyword)) {

                    if ($.inArray(keyword.toLowerCase(), glob.options.monthLabels) !== -1) {
                        found = true;
                    }

                    if ($.inArray(keyword.toLowerCase(), glob.options.monthLabelsShort) !== -1) {
                        found = true;
                    }

                }

                return found;
            },
            
            isDay: function (keyword) {
                var found = false;
                if (!isNaN(keyword)) {
                    // numbers
                    if (keyword.length <= 2) {
                        if (keyword <= 31 && keyword > 0) {
                            // use as day
                            found = true;
                        }
                    }
                }
                return found;
            },
            
            isYear: function (keyword) {
                var found = false;
                if (!isNaN(keyword)) {
                    // numbers
                    if (keyword.length == 4 && keyword >= 1800 && keyword <= 2200) {
                        // use as year
                        found = true;
                    }
                }
                return found;
            }
        };

        search.init();

    });

})(jQuery);
// source --> http://www.kolarac.rs/wp-content/plugins/stachethemes_event_calendar/stachethemes/../front/js/adds/top.calfilter.js?ver=4.8.25 
(function ($) {

    "use strict";
    
    $.stecExtend(function (master, events) {
        
        var filtered = [];
      
        $(master.calData.filterGetEvents).each(function(){
            
            if (master.calData.featuredOnly === true) {
                if (parseInt(this.featured, 10) <= 0 ) {
                    return true;
                }
            }
            
            if (master.calData.calendarFilter.indexOf(this.calid) != -1) {
                filtered.push(this);
            }
            
        });
        
        master.calData.filterGetEvents = filtered;
        
    }, 'beforeProccessGetEvents');

    $.stecExtend(function (master, eventsPool) {
        
        var calendars = [];
        
        /**
         * @todo better implementation of sort by unique key value ?
         */
        $(eventsPool).each(function(){
            
            var event  = this;
            var pushed = false;
            
            $(calendars).each(function(){
                if (this.id == event.calid) {
                    pushed = true;
                }
            });
            
            if (pushed === false) {
                calendars.push({
                    id: event.calid,
                    title: event.cal_title,
                    color: event.cal_color
                });
            }
        });
        
        master.calData.calendarsPool = calendars;

        // build HTML for calendar filter list
        var html = '';
        
         html += '<li data-featured="1" data-calid="0"><p><span></span>'+window.stecLang.featured_events+'</p></li>';
         
        if (master.calData.calendarsPool.length > 3) {
            html += '<li class="stec-select-all-calendars active"><p><span></span>' + window.stecLang.select_all + '</p></li>';
        }
         
        $(master.calData.calendarsPool).each(function () {

            // add to filter by default
            master.calData.calendarFilter.push(this.id);
            $.uniqueSort(master.calData.calendarFilter);

            html += '<li class="active" data-calid="' + this.id + '"><p><span style="background:' + this.color + '"></span>' + this.title + '</p></li>';
        });

        master.$instance.$top.find('.stec-top-menu-filter-calendar-dropdown').children('li').remove();

        $(html).appendTo(master.$instance.$top.find('.stec-top-menu-filter-calendar-dropdown'));
            
        
    }, 'onAddToEventsPool');

    $.stecExtend(function (master) {
        
        var $instance = master.$instance;
        var helper    = master.helper;
        
        // Calendar filter button toggle show/hide
        $(document).on(helper.clickHandle(), $instance.$top.path + " .stec-top-menu-filter-calendar", function (e) {
            e.preventDefault();
            
            $instance.$top.find('.stec-top-menu-search').removeClass('active');

            // fix for left offset since today button is not fixed width
            var $dropdown = $(this).find('.stec-top-menu-filter-calendar-dropdown');

            $dropdown.css({
                left: -1 * Math.round($(this).position().left)
            });

            $(this).toggleClass("active");
        });

        // Block filter toggle for inner content
        $(document).on(helper.clickHandle(), $instance.$top.path + " .stec-top-menu-filter-calendar-dropdown", function (e) {
            // preventDefault blocks mobile keyboard
            e.stopPropagation();
        });
        
        // Toggle active calendars
        $(document).on(helper.clickHandle(), $instance.$top.path + " .stec-top-menu-filter-calendar-dropdown li:not(.stec-select-all-calendars)", function (e) {
            
            e.preventDefault();
            
            $(this).toggleClass('active');
            
            if ($(this).hasClass('active')) {
            
                // add to filter
                
                master.calData.calendarFilter.push($(this).attr('data-calid'));

                $.uniqueSort(master.calData.calendarFilter);

                if ($(this).attr('data-featured')) {
                    master.calData.featuredOnly = true;
                } 
                
            } else {
                
                // remove from filter
                
                if ($(this).attr('data-featured')) {
                    master.calData.featuredOnly = false;
                } 
                
                if (master.calData.calendarFilter !== false) {

                    var index = master.calData.calendarFilter.indexOf($(this).attr('data-calid'));

                    if (index > -1) {
                        master.calData.calendarFilter.splice(index, 1);
                    }

                }
                
            }
            
            master.layout.set();
            
            // fix for left offset since today button is not fixed width
            $instance.$top.find('.stec-top-menu-filter-calendar-dropdown').css({
                left: -1 * Math.round($instance.$top.find(" .stec-top-menu-filter-calendar").position().left)
            });
            
        });
        
        $(document).on(helper.clickHandle(), $instance.$top.path + " .stec-top-menu-filter-calendar-dropdown li.stec-select-all-calendars", function (e) {

            e.preventDefault();

            $(this).toggleClass('active');

            if ($(this).hasClass('active')) {

                // add to filter

                $(this).nextAll('li').addClass('active').each(function () {

                    master.calData.calendarFilter.push($(this).attr('data-calid'));

                    $.uniqueSort(master.calData.calendarFilter);

                });


            } else {

                // remove from filter

                $(this).nextAll('li').removeClass('active').each(function () {

                    master.calData.calendarFilter = [];

                });

            }

            master.layout.set();

            // fix for left offset since today button is not fixed width
            $instance.$top.find('.stec-top-menu-filter-calendar-dropdown').css({
                left: -1 * Math.round($instance.$top.find(" .stec-top-menu-filter-calendar").position().left)
            });

        });

        
    });

})(jQuery);
// source --> http://www.kolarac.rs/wp-content/plugins/stachethemes_event_calendar/stachethemes/../front/js/adds/tooltip.js?ver=4.8.25 
(function ($) {

    "use strict";

    $.stecExtend(function (master) {

        var helper    = master.helper;
        var glob      = master.glob;
        var instance  = master.instance;
        var $instance = master.$instance;
        var calData   = master.calData;

        var tooltip = {
            
            init: function () {
                
                if (parseInt(glob.options.general_settings.tooltip_display, 10) !== 1) {
                    return;
                }
                
                if (helper.isMobile() === true) {
                    // don't bind on mobile
                    return;
                }

                this.bindControls();
            },
            
            bindControls: function () {
                
                var parent = this;

                var event_class = instance + ' .stec-layout-month-daycell-event,' + instance + ' .stec-layout-week-daycell-event';

                $(document).on('mouseenter', event_class, function (e) {
                    
                    var th = this;

                    $('#tooltip-' + glob.options.id).remove();
                    
                    if (helper.animate !== false) {
                        helper.animate.tooltip.clear();
                    }

                    $(glob.template.tooltip).attr('id', 'tooltip-' + glob.options.id).appendTo('body');

                    var event = calData.getEventById($(th).attr('data-id'));
                    
                    var repeat_offset = parseInt($(th).attr('data-repeat-time-offset'), 10);
                    
                    event.repeat_offset = repeat_offset;
                    
                    parent.fillHTML(event);
                    
                    parent.position(th);
                    
                    if (helper.animate !== false) { 
                        
                        helper.animate.tooltip.show($('#tooltip-' + glob.options.id));
                        
                    } else {
                        
                        $('#tooltip-' + glob.options.id).fadeTo(0,1);
                        
                    }
                    

                });

                $(document).on('mouseleave', instance + event_class, function (e) {
                    
                    if (helper.animate !== false) {
                        helper.animate.tooltip.hide($('#tooltip-' + glob.options.id), function () {

                            $('#tooltip-' + glob.options.id).remove();

                        });
                        
                    } else {
                        
                        $('#tooltip-' + glob.options.id).fadeTo(0,0);
                        
                    }
                    
                    parent.clock.clear();
                });
            },
            
            position: function(th){
                
                var klass = '';
                
                var $tooltip = $('#tooltip-' + glob.options.id);
                
                $tooltip.css({
                    left: function () {

                        var x = 0;

                        if ($(th).parents('td').first().index() > 3) {
                            x = $(th).offset().left - $tooltip.width() - 5;
                            klass += ' stec-tooltip-pos-left';
                        } else {
                            x = $(th).width() + $(th).offset().left + 5;
                        }

                        return x;
                    },
                    top: function () {
                        
                        var y = 0;

                        if ($(th).parents('tr').first().index() > 3) {
                            
                            klass += ' stec-tooltip-pos-top';
                            
                            y = $instance.hasClass('stec-media-small') ? $(th).offset().top - $tooltip.height() + 29 : $(th).offset().top - $tooltip.height() + 40;
                            
                        } else {
                            
                            y = $instance.hasClass('stec-media-small') ? $(th).offset().top - 27 : $(th).offset().top - 15;
                            
                        }
                        
                        
                        return y;
                    }
                });

                $tooltip.addClass(klass);
            },
            
            fillHTML: function (event) {

                var $tooltip = $('#tooltip-' + glob.options.id);

                var iconHtml = '<div class="stec-tooltip-icon" style="background:' + event.color + ' "><i class="' + event.icon + '"></i></div>';
                
                // original date + the repeat offset
                var startDate       = helper.dbDateTimeToDate(helper.dbDateOffset(event.start_date, event.repeat_offset));

                // original date + the repeat offset
                var endDate       = helper.dbDateTimeToDate(helper.dbDateOffset(event.end_date, event.repeat_offset));
                
                var date = helper.beautifyTimespan(startDate, endDate, event.all_day);


                var imageHtml = '';

                if (event.images_meta.length > 0) {
                    imageHtml = '<div style="background-image: url(' + event.images_meta[0].src + ');"  ></div>';
                }

                $tooltip.html(function (index, html) {

                    return html
                            .replace(/stec_replace_image/g, imageHtml)
                            .replace(/stec_replace_summary/g, event.summary)
                            .replace(/stec_replace_desc_short/g, event.description_short)
                            .replace(/stec_replace_icon/g, iconHtml)
                            .replace(/stec_replace_location/g, event.location)
                            .replace(/stec_replace_timespan/g, date);

                });

                if (event.location == '') {
                    $tooltip.find('.stec-tooltip-location').hide();
                }

                if (imageHtml == '') {
                    $tooltip.find('.stec-tooltip-image').hide();
                    $tooltip.find('.stec-tooltip-icon').css({
                        top: 0,
                        position: 'static',
                        marginTop: 20
                    });
                }

                var calNow = helper.getCalNow(event.timezone_utc_offset / 3600);

                if (calNow > endDate) {
                    $tooltip.find('.stec-tooltip-expired').css('display', 'inline-block');
                }

                if (calNow > startDate && endDate > calNow) {
                    $tooltip.find('.stec-tooltip-progress').css('display', 'inline-block');
                }
                
                // Check counter
                if (event.counter != 0 && startDate > calNow) {
                    $tooltip.find('.stec-tooltip-counter').css('display', 'inline-block');
                    this.clock.init(startDate, calNow);
                }

            },
            
            clock: {
                days: 0,
                hours: 0,
                minutes: 0,
                seconds: 0,
                daysLabel: window.stecLang.DaysAbbr,
                hoursLabel: window.stecLang.HoursAbbr,
                minutesLabel: window.stecLang.MinutesAbbr,
                secondsLabel: window.stecLang.SecondsAbbr,
                interval: '',
                init: function (date, now) {
                    
                    this.clear();

                    var nowDate = now;
                    var startDate = date;

                    var timeLeft = Math.floor((startDate.getTime() - nowDate.getTime()) / 1000);
                    this.days = Math.floor(timeLeft / 86400);
                    this.hours = Math.floor(timeLeft % 86400 / 3600);
                    this.minutes = Math.floor(timeLeft % 86400 % 3600 / 60);
                    this.seconds = Math.floor(timeLeft % 86400 % 3600 % 60);

                    if (timeLeft < 0) {
                        this.complete();
                        return;
                    }

                    this.count();
                },
                setTimer: function () {
                    
                    var $tooltip = $('#tooltip-' + glob.options.id);
                    var countText = this.days + this.daysLabel + ' ' + this.hours + this.hoursLabel + ' ' + this.minutes + this.minutesLabel + ' ' + this.seconds + this.secondsLabel;
                    $tooltip.find('.stec-tooltip-counter span').text(countText);
                    
                },
                count: function () {

                    var parent = this;

                    parent.setTimer();

                    parent.interval = setInterval(function () {

                        parent.seconds--;

                        if (parent.seconds < 0) {
                            parent.seconds = 59;
                            parent.minutes--;
                            if (parent.minutes < 0) {
                                parent.minutes = 59;
                                parent.hours--;
                                if (parent.hours < 0) {
                                    parent.hours = 23;
                                    if (parent.days > 0) {
                                        parent.days--;
                                    }
                                }
                            }
                        }
                      
                        parent.setTimer();

                        if (parent.days == 0 && parent.hours == 0 && parent.minutes == 0 && parent.seconds == 0) {
                            parent.clear();
                            parent.complete();
                        }

                    }, 1000);
                },
                
                complete: function () {
                    this.clear();
                },
                
                clear: function() {
                    
                    clearInterval(this.interval);
                }

            }
        };
        
        tooltip.init();

    });


})(jQuery);
// source --> http://www.kolarac.rs/wp-content/plugins/stachethemes_event_calendar/stachethemes/../front/js/adds/media.js?ver=4.8.25 
(function ($) {

    "use strict";

    $.stecExtend(function (master) {
        
        var $instance = master.$instance;
        
        /**
         * Handles reponsive classes
         */
        var media = {
            
            init: function () {

                var parent = this;

                $(window).on("resize", function () {
                    parent.mediaTrigger();
                });

                parent.mediaTrigger();
            },
            
            mediaTrigger: function () {

                if ($instance.width() <= 600) {
                    $instance.removeClass("stec-media-med");
                    $instance.addClass("stec-media-small");
                }

                else if ($instance.width() <= 870) {
                    $instance.removeClass("stec-media-small");
                    $instance.addClass("stec-media-med");
                }

                else {
                    $instance.removeClass("stec-media-med stec-media-small");
                }
            }
        };
        
        media.init();
            

    }, 'onLayoutSet');


})(jQuery);
// source --> http://www.kolarac.rs/wp-content/plugins/stachethemes_event_calendar/stachethemes/../front/js/adds/intro.js?ver=4.8.25 
(function ($) {

    "use strict";
    
    $.stecExtend(function (master) {

        // add preloader
        var $tab = master.$instance.find('.stec-layout-event.active').find('.stec-layout-event-inner-intro');
        $tab.wrapInner('<div class="stec-layout-event-inner-preload-wrap" />');
        $(master.glob.template.preloader).appendTo($tab);

    }, 'onBeforeEventDataAjax');

    $.stecExtend(function (master, data) {

        var glob      = master.glob;
        var $instance = master.$instance;
        var helper    = master.helper;

        var $event = $instance.$events.find('.stec-layout-event.active');
        var $inner = $event.find('.stec-layout-event-inner-intro');
        
        var url = glob.options.single_page_url + data.general.alias;
        
        if (data.repeat_time_offset > 0) {
            url += '/' + data.repeat_time_offset + '/';
        }
        
        // add the repeat offset
        var start_date = helper.dbDateOffset(data.general.start_date, data.repeat_time_offset);
        var end_date   = helper.dbDateOffset(data.general.end_date, data.repeat_time_offset);

        var googleCalImportLink = helper.eventToGoogleCalImportLink(data.general.id, data.repeat_time_offset);
        
        $inner.html(function (index, html) {
            
            return html
            
                    .replace(/stec_replace_summary/g, data.general.summary)
                    .replace(/stec_replace_description/g, helper.nl2br(data.general.description))
                    .replace(/#stec_replace_link/g, data.general.link)
                    .replace(/#stec_replace_googlecal_import/g, googleCalImportLink)
                    .replace(/stec_replace_event_id/g, data.general.id)
                    .replace(/stec_replace_calendar_id/g, data.general.calid)
            
                    .replace(/stec_replace_event_single_url/g, url );
        });
        
        if (data.general.link == "") {
            $inner.find('.stec-layout-event-inner-intro-external-link').hide();
        }
        
        var slider = {
            
            cslide: 0,
            offset: 0,
            total: 0,
            blockAction: false,
            visCount: 0,
            visCountSmall: 3,
            visCountBig: 4,
            
            init: function () {

                var parent = this;
                
                if (!data.general.images_meta || data.general.images_meta.length <= 0) {
                    
                    $inner.find('.stec-layout-event-inner-intro-media').remove();
                    
                    // Remove tab preloaders
                    $inner.find('.stec-layout-event-inner-preload-wrap').children().first().unwrap();
                    $inner.find('.stec-layout-event-inner-preload-wrap').remove();
                    $inner.find('.stec-preloader').remove(); 
                    
                    return;
                }
                
                if (data.general.images_meta.length == 1) {
                    $inner.find('.stec-layout-event-inner-intro-media-controls').remove();
                } else {
                    if (data.general.images_meta.length < this.visCountBig) {
                        this.visCountBig = data.general.images_meta.length;
                    }

                    if (data.general.images_meta.length < this.visCountSmall) {
                        this.visCountSmall = data.general.images_meta.length;
                    }
                }
                
                this.html();
                
                helper.imgLoaded($inner.find('.stec-layout-event-inner-intro-media-content img'), function () {
                    
                    // Remove tab preloaders
                    $inner.find('.stec-layout-event-inner-preload-wrap').children().first().unwrap();
                    $inner.find('.stec-layout-event-inner-preload-wrap').remove();
                    $inner.find('.stec-preloader').remove(); 
                    
                    setTimeout(function(){
                        parent.controlsDimensions();
                        parent.showImage();
                        
                        $inner.find('.stec-layout-event-inner-intro-media').fadeTo(1000,1);
                    }, 100);
                    
                    
                });
                
                this.bindControls();
                
            },
            
            bindControls: function(){
                
                var parent = this;
                
                // resize on tab click
                $(document).on('stec-tab-click-'+glob.options.id, function(){
                    parent.controlsDimensions();
                });
                
                helper.onResizeEnd(function () {
                    parent.controlsDimensions();
                }, 100, 'stec-unbind-window-resize-on-event-close-'+glob.options.id);
                
                $inner.find('.stec-layout-event-inner-intro-media-controls-next').on(helper.clickHandle(), function(e){
                    e.preventDefault();
                    parent.slideNext();
                });
                
                $inner.find('.stec-layout-event-inner-intro-media-controls-prev').on(helper.clickHandle(), function(e){
                    e.preventDefault();
                    parent.slidePrev();
                });
                
                $inner.find('.stec-layout-event-inner-intro-media-controls li').on(helper.clickHandle(), function(e){
                    
                    e.preventDefault();
                    
                    if (parent.cslide == $(this).index()) {
                        return;
                    }
                    
                    parent.cslide = $(this).index();
                    
                    parent.showImage();
                    
                });
                
            },
            
            html: function(){
                
                var html = '';
                
                $(data.general.images_meta).each(function(){
                    
                    html += '<div style="background-image:url('+this.src+');">';
                    html += '   <img src="'+this.src+'" alt="'+this.alt+'">';
                    
                    if (this.caption != '' || this.description != '') {
                        html += '   <div>';
                        
                        if (this.caption != '') {
                            html += '       <p>' + this.caption + '</p>';
                        }
                        
                        if (this.description != '') {
                            html += '       <span>' + this.description + '</span>';
                        }
                        
                        html += '   </div>';
                    }
                    
                    html += '</div>';
                    
                });
                
                $(html).appendTo($inner.find('.stec-layout-event-inner-intro-media-content'));
                
                html = '';
                
                $(data.general.images_meta).each(function(){
                    html += '<li style="background-image:url('+this.thumb+')">';
                    html += '</li>';
                });
                
                $(html).appendTo($inner.find('.stec-layout-event-inner-intro-media-controls-list'));
                
            },
            
            controlsDimensions: function(){
                
                var parent = this;
                
                if (!$inner.is(':visible')) {
                    return;
                }
                
                if ($instance.hasClass('stec-media-small')) {
                    parent.visCount = parent.visCountSmall;
                } else {
                    parent.visCount = parent.visCountBig;
                }
                
                if ($inner.find('.stec-layout-event-inner-intro-media-controls-list li').length == parent.visCount) {
                    $inner.find('.stec-layout-event-inner-intro-media-controls').addClass('no-side-controls');
                } else {
                    $inner.find('.stec-layout-event-inner-intro-media-controls').removeClass('no-side-controls');
                }
                
                var maxWidth    = $inner.find('.stec-layout-event-inner-intro-media-controls-list-wrap').width();
                var $li         = $inner.find('.stec-layout-event-inner-intro-media-controls-list li');
                
                $inner.find('.stec-layout-event-inner-intro-media-content').height($inner.find('.stec-layout-event-inner-intro-media img').first().height());
                
                // ~'calc( (100% - 2*10px) / 3 )';
                var liWidth = (maxWidth - ((this.visCount - 1) * 10)) / this.visCount;
                
                var listWidth = ($li.length * liWidth) + ($li.length * 10) - 10;
                
                $inner.find('.stec-layout-event-inner-intro-media-controls-list').width(listWidth);
                $li.width(liWidth);
                
                
                this.offset = 0;
                
                var left  = -1 * ($li.first().width() * this.offset + this.offset * 10);
                
                $inner.find('.stec-layout-event-inner-intro-media-controls-list').stop().css({
                    left: left
                });
                
                
            },
            
            showImage: function(){
                
                $inner.find('.stec-layout-event-inner-intro-media-controls-list .active-thumb').removeClass('active-thumb');
                $inner.find('.stec-layout-event-inner-intro-media-controls-list li').eq(this.cslide).addClass('active-thumb');
                
                var $old = $inner.find('.stec-layout-event-inner-intro-media-content .active-image');
                var $new = $inner.find('.stec-layout-event-inner-intro-media-content > div').eq(this.cslide);
                

                var $textContent = $new.find('div');
                
                if ($textContent.length > 0) {
                    
                    
                    $inner.find('.stec-layout-event-inner-intro-media-content-subs div').fadeTo(250, 0, function () {
                        
                        var caption = $textContent.find('p').text();
                        var desc = $textContent.find('span').text();

                        $inner.find('.stec-layout-event-inner-intro-media-content-subs p').text(caption);
                        $inner.find('.stec-layout-event-inner-intro-media-content-subs span').text(desc);

                        var height = $inner.find('.stec-layout-event-inner-intro-media-content-subs p').height() + $inner.find('.stec-layout-event-inner-intro-media-content-subs span').height();

                        if (height > 0) {
                            height = height + 40;
                        }

                        $inner.find('.stec-layout-event-inner-intro-media-content-subs').stop().animate({
                            height: height
                        }, {
                            duration: 400,
                            easing: 'stecExpo',
                            complete: function () {
                                $inner.find('.stec-layout-event-inner-intro-media-content-subs div').fadeTo(250, 1);
                            }
                        });
                    });

                    
                } else {
                    
                    $inner.find('.stec-layout-event-inner-intro-media-content-subs div').fadeTo(250, 0, function () {

                        $inner.find('.stec-layout-event-inner-intro-media-content-subs').stop().animate({
                            height: 0
                        }, {
                            duration: 400,
                            easing: 'stecExpo'
                        });

                    });
                    
                }
                
                $new.addClass('fade-in');

                setTimeout(function () {

                    $old.removeClass('active-image');
                    $new.removeClass('fade-in').addClass('active-image');
                   
                }, 250);
            },
            
            slideNext: function() {
                
                var $li = $inner.find('.stec-layout-event-inner-intro-media-controls-list li');
             
                if (this.offset + this.visCount >= $li.length) {
                    this.offset = 0;
                } else {
                    this.offset = this.offset + this.visCount;

                    if (this.offset > $li.length - this.visCount) {
                        this.offset = $li.length - this.visCount;
                    }
                }
                
                
                var left  = -1 * ($li.first().width() * this.offset + this.offset * 10);
                
                $inner.find('.stec-layout-event-inner-intro-media-controls-list').stop().animate({
                    left: left
                }, {
                    duration: 750,
                    easing: 'stecExpo'
                });
                
            },
            
            slidePrev: function() {
                
                var $li = $inner.find('.stec-layout-event-inner-intro-media-controls-list li');
                
                if (this.offset <= 0) {
                    this.offset = $li.length - this.visCount;
                } else {
                    this.offset = this.offset - this.visCount;

                    if (this.offset < 0) {
                        this.offset = 0;
                    }
                }
                
                
                var left  = -1 * ($li.first().width() * this.offset + this.offset * 10);
                
                $inner.find('.stec-layout-event-inner-intro-media-controls-list').stop().animate({
                    left: left
                }, {
                    duration: 750,
                    easing: 'stecExpo'
                });
                
            }
        
        };

        slider.init();

        var clock = {
            days: 0,
            hours: 0,
            minutes: 0,
            seconds: 0,
            daysLabel: '',
            hoursLabel: '',
            mionutesLabel: '',
            secondsLabel: '',
            interval: '',
            
            init: function () {
                
                // Check counter disabled
                if (data.general.counter != 1) {
                    $inner.find('.stec-layout-event-inner-intro-counter').hide();
                    return;
                }

                var nowDate   = helper.getCalNow(parseInt(data.general.timezone_utc_offset, 10)/3600);
                var startDate = helper.dbDateTimeToDate(start_date);
                
                var timeLeft = Math.floor((startDate.getTime() - nowDate.getTime()) / 1000);
                
                this.days    = Math.floor(timeLeft / 86400);
                this.hours   = Math.floor(timeLeft % 86400 / 3600);
                this.minutes = Math.floor(timeLeft % 86400 % 3600 / 60);
                this.seconds = Math.floor(timeLeft % 86400 % 3600 % 60);

                $inner.find('.stec-layout-event-inner-intro-counter-num').eq(0).text(this.days);
                $inner.find('.stec-layout-event-inner-intro-counter-num').eq(1).text(this.hours);
                $inner.find('.stec-layout-event-inner-intro-counter-num').eq(2).text(this.minutes);
                $inner.find('.stec-layout-event-inner-intro-counter-num').eq(3).text(this.seconds);

                this.daysLabel = $inner.find('.stec-layout-event-inner-intro-counter-label').eq(0);
                this.hoursLabel = $inner.find('.stec-layout-event-inner-intro-counter-label').eq(1);
                this.minutesLabel = $inner.find('.stec-layout-event-inner-intro-counter-label').eq(2);
                this.secondsLabel = $inner.find('.stec-layout-event-inner-intro-counter-label').eq(3);

                this.daysLabel.text(this.days == 1 ? this.daysLabel.attr('data-singular-label') : this.daysLabel.attr('data-plural-label'));
                this.hoursLabel.text(this.hours == 1 ? this.hoursLabel.attr('data-singular-label') : this.hoursLabel.attr('data-plural-label'));
                this.minutesLabel.text(this.minutes == 1 ? this.minutesLabel.attr('data-singular-label') : this.minutesLabel.attr('data-plural-label'));
                this.secondsLabel.text(this.seconds == 1 ? this.secondsLabel.attr('data-singular-label') : this.secondsLabel.attr('data-plural-label'));
                
                if (timeLeft < 0) {
                    this.complete();
                    return;
                }
                
                this.count();
            },
            count: function () {

                var parent = this;

                parent.interval = setInterval(function () {

                    parent.seconds--;

                    if (parent.seconds < 0) {
                        parent.seconds = 59;
                        parent.minutes--;
                        if (parent.minutes < 0) {
                            parent.minutes = 59;
                            parent.hours--;
                            if (parent.hours < 0) {
                                parent.hours = 23;
                                if (parent.days > 0) {
                                    parent.days--;
                                }
                                $inner.find('.stec-layout-event-inner-intro-counter-num').eq(0).text(parent.days);
                                parent.daysLabel.text(parent.days == 1 ? parent.daysLabel.attr('data-singular-label') : parent.daysLabel.attr('data-plural-label'));
                            }
                            $inner.find('.stec-layout-event-inner-intro-counter-num').eq(1).text(parent.hours);
                            parent.hoursLabel.text(parent.hours == 1 ? parent.hoursLabel.attr('data-singular-label') : parent.hoursLabel.attr('data-plural-label'));
                        }
                        $inner.find('.stec-layout-event-inner-intro-counter-num').eq(2).text(parent.minutes);
                        parent.minutesLabel.text(parent.minutes == 1 ? parent.minutesLabel.attr('data-singular-label') : parent.minutesLabel.attr('data-plural-label'));
                    }
                    $inner.find('.stec-layout-event-inner-intro-counter-num').eq(3).text(parent.seconds);
                    parent.secondsLabel.text(parent.seconds == 1 ? parent.secondsLabel.attr('data-singular-label') : parent.secondsLabel.attr('data-plural-label'));


                    if (parent.days == 0 && parent.hours == 0 && parent.minutes == 0 && parent.seconds == 0) {
                        clearInterval(parent.interval);
                        parent.complete();
                    }

                }, 1000);
            },
            complete: function () {

                $inner.find('.stec-layout-event-inner-intro-counter-num').eq(0).text(0);
                $inner.find('.stec-layout-event-inner-intro-counter-num').eq(1).text(0);
                $inner.find('.stec-layout-event-inner-intro-counter-num').eq(2).text(0);
                $inner.find('.stec-layout-event-inner-intro-counter-num').eq(3).text(0);

                this.daysLabel.text(this.days == 1 ? this.daysLabel.attr('data-singular-label') : this.daysLabel.attr('data-plural-label'));
                this.hoursLabel.text(this.hours == 1 ? this.hoursLabel.attr('data-singular-label') : this.hoursLabel.attr('data-plural-label'));
                this.minutesLabel.text(this.minutes == 1 ? this.minutesLabel.attr('data-singular-label') : this.minutesLabel.attr('data-plural-label'));
                this.secondsLabel.text(this.seconds == 1 ? this.secondsLabel.attr('data-singular-label') : this.secondsLabel.attr('data-plural-label'));
                
                $inner.find('.stec-layout-event-inner-intro-counter').hide();
                
                var now     = helper.getCalNow(parseInt(data.general.timezone_utc_offset, 10)/3600);
                var endDate = helper.dbDateTimeToDate(end_date);
                
                if (now >= endDate) {
                    $inner.find('.stec-layout-event-inner-intro-event-status-text.event-expired').show();
                } else {
                    $inner.find('.stec-layout-event-inner-intro-event-status-text.event-inprogress').show();
                }
            }

        };

        clock.init();

        // Attend / Decline

        function ajaxAttendance(status) {
            
            // status
            // 0 - no decision
            // 1 - accept 
            // 2 - decline
            
            glob.ajax = $.ajax({
                dataType: "json",
                type: 'POST',
                url: window.ajaxurl,
                data: {
                    action: 'stec_public_ajax_action',
                    task: 'set_user_event_attendance',
                    event_id: data.general.id,
                    repeat_offset: data.repeat_time_offset,
                    status: status
                },
                beforeSend: function () {
                    if (glob.ajax !== null) {
                        glob.ajax.abort();
                    }
                    
                    $inner.find('.stec-layout-event-inner-intro-attendance').children().hide();
                    
                    $('<li>' + glob.template.preloader + '</li>').addClass('intro-attendance')
                            .appendTo($inner.find('.stec-layout-event-inner-intro-attendance'));
                },
                success: function (rtrn) {
                    
                    var status = parseInt(rtrn.status, 10);
                    var id     = parseInt(rtrn.id, 10);
                    
                    $inner.find('.stec-layout-event-inner-intro-attendance li').removeClass('active');
                    $event.find('.stec-layout-event-inner-attendance-invited-buttons li').removeClass('active');

                    var $avatar = $event.find('.stec-layout-event-inner-attendance-attendee-avatar')
                            .filter('[data-userid="' + glob.options.userid + '"]');

                    switch (status) {
                        case 1 :
                            $inner.find('.stec-layout-event-inner-intro-attendance-attend').addClass('active');
                            $event.find('.stec-layout-event-inner-attendance-invited-buttons-accept').addClass('active');
                            $avatar.find('li i').attr('class', 'fa fa-check');
                            break;
                        case 2 :
                            $inner.find('.stec-layout-event-inner-intro-attendance-decline').addClass('active');
                            $event.find('.stec-layout-event-inner-attendance-invited-buttons-decline').addClass('active');
                            $avatar.find('li i').attr('class', 'fa fa-times');
                            break;
                        default:
                            $avatar.find('li i').attr('class', 'fa fa-question');

                    }

                    var hasData = false;
                    $(data.attendance).each(function(){
                        
                        if (this.id == id) {
                            
                            this.status = status;
                            
                            hasData = true;
                            
                            return false; // break
                        }
                    });
                    
                    if (!hasData) {
                        // no data copy original with new status and id
                        
                        $(data.attendance).each(function(){
                            
                            if (this.userid == glob.options.userid) {
                                
                                // make fresh copy
                                var copy = JSON.parse(JSON.stringify(this));
                                
                                copy.repeat_offset = data.repeat_time_offset;
                                copy.status        = status;
                                copy.id            = id;
                                
                                data.attendance.push(copy);
                                
                                return false; // break
                                
                            }
                            
                        });
                        
                    }
                },
                error: function (xhr, status, thrown) {
                    console.log(xhr + " " + status + " " + thrown);
                },
                complete: function () {
                    glob.ajax = null;
                    
                    $inner.find('.stec-layout-event-inner-intro-attendance').children().show();
                    $inner.find('.stec-layout-event-inner-intro-attendance').children().last().remove();
                }
            });


        }

        $inner.find('.stec-layout-event-inner-intro-attendance-attend').on(helper.clickHandle(), function (e) {
            e.preventDefault();
            var status = $(this).hasClass('active') ? 0 : 1;
            ajaxAttendance(status);
        });

        $inner.find('.stec-layout-event-inner-intro-attendance-decline').on(helper.clickHandle(), function (e) {
            e.preventDefault();
            var status = $(this).hasClass('active') ? 0 : 2;
            ajaxAttendance(status);
        });
        
        var invited_user = false;
        
        if (!isNaN(glob.options.userid)) {
            
            // check if user is invited
            $(data.attendance).each(function () {
                if (this.userid == glob.options.userid) {
                    invited_user = true;
                    return false; // break
                }
            });
            
        } 
        
        if (invited_user !== false) {
            
            var status = 0;
            
            $(data.attendance).each(function () {
                if (this.userid == glob.options.userid && this.repeat_offset == data.repeat_time_offset) {
                    status = parseInt(this.status, 10);
                    return false; // break
                }
            });
            
            switch (status) {
                case 1:
                    $inner.find('.stec-layout-event-inner-intro-attendance-attend').addClass('active');
                    $inner.find('.stec-layout-event-inner-intro-attendance-decline').removeClass('active');
                    break;

                case 2:
                    $inner.find('.stec-layout-event-inner-intro-attendance-attend').removeClass('active');
                    $inner.find('.stec-layout-event-inner-intro-attendance-decline').addClass('active');
                    break;
            }
        } else {
            $inner.find('.stec-layout-event-inner-intro-attendance').hide();
        }
        
        // Check if event is in progress
        var nowDate   = helper.getCalNow(parseInt(data.general.timezone_utc_offset, 10)/3600);
        var startDate = helper.dbDateTimeToDate(helper.dbDateOffset(data.general.start_date, data.repeat_time_offset));
        
        if (nowDate >= startDate) {
            $inner.find('.stec-layout-event-inner-intro-attendance').hide();
        }
        
        // Attachments
        if (data.attachments.length > 0) {
            var attachments_template = $inner.find('.stec-layout-event-inner-intro-attachment-template')[0].outerHTML;
            $inner.find('.stec-layout-event-inner-intro-attachment-template').remove();

            $(data.attachments).each(function () {

                var th = this;

                $(attachments_template).html(function (index, html) {
                    return html
                            .replace(/stec_replace_filename/g, th.filename)
                            .replace(/stec_replace_desc/g, th.description)
                            .replace(/stec_replace_url/g, th.link)
                            .replace(/stec_replace_size/g, th.size);

                }).appendTo($inner.find('.stec-layout-event-inner-intro-attachments-list'));
            });

            $inner.find('.stec-layout-event-inner-intro-attachments-toggle').on(helper.clickHandle(), function (e) {

                e.preventDefault();

                $(this).toggleClass('active');

                $inner.find('.stec-layout-event-inner-intro-attachments-list').toggleClass('active');

            });
        } else {
            $inner.find('.stec-layout-event-inner-intro-attachments').remove();
        }
        
        
        $inner.find('.stec-layout-event-inner-intro-exports-toggle').on(helper.clickHandle(), function (e) {

            e.preventDefault();

            $(this).toggleClass('active');

            $inner.find('.stec-layout-event-inner-intro-exports-options').toggleClass('active');

        });

// inside slider init
//        helper.imgLoaded($inner.find('img'), function(){
//            // Remove tab preloaders
//            $inner.find('.stec-layout-event-inner-preload-wrap').children().first().unwrap();
//            $inner.find('.stec-layout-event-inner-preload-wrap').remove();
//            $inner.find('.stec-preloader').remove(); 
//        });

    }, 'onEventDataReady');

})(jQuery);
// source --> http://www.kolarac.rs/wp-content/plugins/stachethemes_event_calendar/stachethemes/../front/js/adds/location.js?ver=4.8.25 
(function ($) {

    "use strict";
    
    $.stecExtend(function (master) {

        // add preloader
        var $tab = master.$instance.find('.stec-layout-event.active').find('.stec-layout-event-inner-location');
        $tab.wrapInner('<div class="stec-layout-event-inner-preload-wrap" />');
        $(master.glob.template.preloader).appendTo($tab);

    }, 'onBeforeEventDataAjax');
    
    $.stecExtend(function (master, data) {
    
        if (data.general.location == '') {
            return;
        }
        
        var glob      = master.glob;
        var $instance = master.$instance;
        var helper    = master.helper;

        var $event = $instance.$events.find('.stec-layout-event.active');
        var $inner = $event.find('.stec-layout-event-inner-location');
        
        $inner.html(function (index, html) {
            
            return html
                    .replace(/stec_replace_location/g, data.general.location)
                    .replace(/stec_replace_details/g, data.general.location_details);
        });
        
        if ($.trim($inner.find('.stec-layout-event-inner-location-details').text()) == "") {
            $inner.find('.stec-layout-event-inner-location-optional-details').hide();
        }

        /**
         * @todo Instance or Single?
         */
        var gmap = function () {

            this.$tabCont = "";
            this.directionsService = "";
            this.directionsDisplay = "";
            this.map = "";
            this.geocoder = "";
            this.mapDiv = "";
            this.marker = "";
            this.address = "";

            this.init = function ($el) {

                var parent = this;

                parent.mapDiv = $el.get(0);

                parent.map = new window.google.maps.Map(parent.mapDiv, {
                    zoom: 15
                });

                parent.geocoder = new window.google.maps.Geocoder();

                parent.directionsService = new window.google.maps.DirectionsService;
                parent.directionsDisplay = new window.google.maps.DirectionsRenderer;

                parent.directionsDisplay.setMap(parent.map);

                parent.$tabCont = $el.parents(".stec-layout-event-inner-location");

                parent.address = parent.$tabCont.find(".stec-layout-event-inner-location-address").text();

                parent.setLocation(parent.address);

                // start end directions
                var $start = parent.$tabCont.find('input[name="start"]');

                var $end = parent.$tabCont.find('input[name="end"]');

                if ($.trim($end.val()) == "") {
                    $end.val(parent.$tabCont.find(".stec-layout-event-inner-location-address").text());
                }

                if ($.trim($start.val()) == "") {
                    parent.fillMyLocation($start);
                }

                this.bindControls();
                
                // Remove tab preloaders
                $inner.find('.stec-layout-event-inner-preload-wrap').children().first().unwrap();
                $inner.find('.stec-layout-event-inner-preload-wrap').remove();
                $inner.find('.stec-preloader').remove();

            };

            this.bindControls = function () {

                var parent = this;

                helper.onResizeEnd(function () {
                    parent.refresh();
                }, 150, 'stec-unbind-window-resize-on-event-close-'+glob.options.id);

                parent.$tabCont
                        .parents('.stec-layout-event-inner')
                        .find('[data-tab="stec-layout-event-inner-location"]')
                        .on(helper.clickHandle(), function (e) {

                            parent.refresh(false);
                        });


                parent.$tabCont.find(".stec-layout-event-inner-location-left-button").on(helper.clickHandle(), function (e) {
                    e.preventDefault();

                    var $tabCont = $(this).parents(".stec-layout-event-inner-location");

                    var $start = $tabCont.find('input[name="start"]');
                    var $end = $tabCont.find('input[name="end"]');

                    if ($.trim($start.val() != "") && $.trim($end.val() != "")) {
                        parent.getDirection($start.val(), $end.val());
                    }
                });

            },
                    
            this.refresh = function (centerOnLocation) {

                var parent = this;
                
                setTimeout(function(){
                    window.google.maps.event.trigger(parent.mapDiv, 'resize');

                    if (centerOnLocation === true) {
                        parent.setLocation(parent.address);
                    }
                }, 10); // timeout fixes resize bug
                
            };

            this.fillMyLocation = function ($el) {

                var parent = this;

                if (glob.options.myLocation) {
                    $el.val(glob.options.myLocation);
                    return;
                }

                if (navigator.geolocation) {

                    navigator.geolocation.getCurrentPosition(
                            function (position) {

                                var pos = position.coords.latitude + " " + position.coords.longitude;
                                parent.geocoder.geocode({'address': pos}, function (results, status) {
                                    glob.options.myLocation = (results[0].formatted_address);
                                    $el.val(glob.options.myLocation);
                                });
                            },
                            function (a,b,c) {
                                console.log('Navigator Geolocation Error');
                            }
                    );
                }
            };

            this.setLocation = function (address) {

                var parent = this;

                if (data.general.location_use_coord == 1) {
                    
                    var latlng = data.general.location_forecast.split(',');
                                 
                    var pos = {
                        lat:parseFloat($.trim(latlng[0])), 
                        lng:parseFloat($.trim(latlng[1]))
                    };
                    
                    parent.map.setCenter(pos);
                    parent.marker = new window.google.maps.Marker({
                        map: parent.map,
                        position: pos,
                        title: address
                    });
                    
                } else {
                    parent.geocoder.geocode({'address': address}, function (results, status) {
                        if (status === window.google.maps.GeocoderStatus.OK) {
                            parent.map.setCenter(results[0].geometry.location);
                            parent.marker = new window.google.maps.Marker({
                                map: parent.map,
                                position: results[0].geometry.location,
                                title: address
                            });

                        } else {
                            console.log("Geocoder error: " + status);
                        }
                    });
                }


                parent.refresh();
            };

            this.getDirection = function (a, b) {

                var parent = this;

                parent.directionsService.route({
                    origin: a,
                    destination: b ? b : parent.marker.position,
                    travelMode: window.google.maps.TravelMode.DRIVING
                }, function (response, status) {

                    if (status === window.google.maps.DirectionsStatus.OK) {
                        parent.directionsDisplay.setDirections(response);
                    } else {
                        console.log("Direction Service Error");
                        
                        $inner.find('.stec-layout-event-inner-location-direction-error').stop().fadeTo(250,1, function(){
                            
                            setTimeout(function(){
                                
                                $inner.find('.stec-layout-event-inner-location-direction-error').fadeTo(250,0);
                                
                            }, 3000);
                            
                        });
                    }

                });
            };
        };

        function loadMap($event) {

            var $mapCont = $event.find(".stec-layout-event-inner-location-right-gmap");
            
            // init once
            if ($mapCont.children().length <= 0) {
                new gmap().init($mapCont);
            }
        }
        
        
        $(document).on('stec-tab-click-' + glob.options.id, function () {
            if ($inner.is(':visible')) {
                var $event = $inner.parents('.stec-layout-event');
                loadMap($event);
            }
        });

        
    }, 'onEventDataReady');

})(jQuery);
// source --> http://www.kolarac.rs/wp-content/plugins/stachethemes_event_calendar/stachethemes/../front/js/adds/schedule.js?ver=4.8.25 
(function ($) {

    "use strict";
    
    $.stecExtend(function (master) {
        
        // add preloader
        var $tab = master.$instance.find('.stec-layout-event.active').find('.stec-layout-event-inner-schedule');
        $tab.wrapInner('<div class="stec-layout-event-inner-preload-wrap" />');
        $(master.glob.template.preloader).appendTo($tab);
        
    }, 'onBeforeEventDataAjax');
    
    $.stecExtend(function (master, data) {
        
        if (data.schedule.length <= 0) {
            return;
        }
        
        var $instance = master.$instance;
        var helper    = master.helper;
        
        var $event = $instance.$events.find('.stec-layout-event.active');
        var $inner = $event.find('.stec-layout-event-inner-schedule');

        var template = $inner.find('.stec-layout-event-inner-schedule-tab-template')[0].outerHTML;
        $inner.find('.stec-layout-event-inner-schedule-tab-template').remove();
        
        if (data.schedule.length > 0) {
            
            $(data.schedule).each(function(){
                
                var th = this;
                
                var customKlass = '';
                
                if (th.description == '') {
                    customKlass += ' stec-layout-event-inner-schedule-tab-no-desc ';
                }
                
                
                if (th.icon == "" || th.icon == "fa") {
                    customKlass += ' stec-layout-event-inner-schedule-tab-no-icon ';
                }
                
                
                $(template)
                        .addClass(customKlass)
                        .html(function(index, html){
                    
                    // add the repeat offset
                    var start = helper.dbDateTimeToDate(helper.dbDateOffset(th.start_date, data.repeat_time_offset));
                    
                    var format = 'd m y';
                    switch (master.glob.options.general_settings.date_format) {
                        case 'dd-mm-yy' :
                            format = 'd M';
                            break;
                        case 'yy-mm-dd' :
                            format = 'M d';
                            break;
                        case 'mm-dd-yy' :
                            format = 'M d';
                            break;
                    }
                    
                    return html
                            .replace(/stec_replace_date/g, helper.dateToFormat(format,start))
                            .replace(/stec_replace_time/g, helper.dateToFormat('h:i',start))
                            .replace(/stec_replace_icon/g, th.icon)
                            .replace(/stec_replace_color/g, 'style="color:'+th.icon_color+'"') 
                            .replace(/stec_replace_title/g, th.title)
                            .replace(/stec_replace_desc/g, helper.nl2br(th.description));
                    
                })
                .removeClass('stec-layout-event-inner-schedule-tab-template')
                .appendTo($inner);
                
            });
            
            $inner.find('.stec-layout-event-inner-schedule-isempty').remove();
            $inner.find('.stec-layout-event-inner-schedule-tab').first().addClass('open');
            
        } 
        
        $inner.find('.stec-layout-event-inner-schedule-tab-preview')
                .off(helper.clickHandle('open'))
                .on(helper.clickHandle('open'), function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    $(this).parents(".stec-layout-event-inner-schedule-tab").not('.stec-layout-event-inner-schedule-tab-no-desc').toggleClass("open");
        });
        
        // Remove tab preloaders
        $inner.find('.stec-layout-event-inner-preload-wrap').children().first().unwrap();
        $inner.find('.stec-layout-event-inner-preload-wrap').remove();
        $inner.find('.stec-preloader').remove();

    }, 'onEventDataReady');


})(jQuery);
// source --> http://www.kolarac.rs/wp-content/plugins/stachethemes_event_calendar/stachethemes/../front/js/adds/guests.js?ver=4.8.25 
(function ($) {

    "use strict";
    
    $.stecExtend(function (master) {

        // add preloader
        var $tab = master.$instance.find('.stec-layout-event.active').find('.stec-layout-event-inner-guests');
        $tab.wrapInner('<div class="stec-layout-event-inner-preload-wrap" />');
        $(master.glob.template.preloader).appendTo($tab);

    }, 'onBeforeEventDataAjax');

    $.stecExtend(function (master, data) {
        
        if (data.guests.length <= 0) {
            return;
        }
        
        var $instance = master.$instance;
        
        var $event = $instance.$events.find('.stec-layout-event.active');
        var $inner = $event.find('.stec-layout-event-inner-guests');

        var template = $inner.find('.stec-layout-event-inner-guests-guest-template')[0].outerHTML;
        $inner.find('.stec-layout-event-inner-guests-guest-template').remove();
        
        if (data.guests.length > 0) {
            
            $(data.guests).each(function(i){
                
                var th = this;
                
                $(template).html(function(index, html){
                    
                    var links = th.links.split('||');
                    
                    var lis = [];
                    
                    $(links).each(function(pos){
                        var link = this.split('::');
                        lis[pos] = '<li class="stec-layout-event-inner-guests-guest-left-avatar-icon-position-'+pos+'"><a href="'+link[1]+'"><i class="'+link[0]+'"></i></a></li>';
                    });
                    
                    var avatar;
                    
                    if (!th.photo_full) {
                        avatar = '<div class="stec-layout-event-inner-guests-guest-left-avatar-default"></div>';
                    } else {
                        avatar = '<img src="'+th.photo_full+'" alt="stec_replace_name" >';
                    }
                    
                    return html
                            .replace(/stec_replace_ico_position/g, i)
                            .replace(/stec_replace_avatar/g, avatar)
                            .replace(/stec_replace_social/g, lis.join(''))
                            .replace(/stec_replace_name/g, th.name)
                            .replace(/stec_replace_about/g, th.about);
                    
                })
                .removeClass('stec-layout-event-inner-guests-guest-template')
                .appendTo($inner);
                
            });
            
        } 
        
        // Remove tab preloaders
        $inner.find('.stec-layout-event-inner-preload-wrap').children().first().unwrap();
        $inner.find('.stec-layout-event-inner-preload-wrap').remove();
        $inner.find('.stec-preloader').remove();

    }, 'onEventDataReady');


})(jQuery);
// source --> http://www.kolarac.rs/wp-content/plugins/stachethemes_event_calendar/stachethemes/../front/js/adds/attendance.js?ver=4.8.25 
(function ($) {

    "use strict";
    
    $.stecExtend(function (master) {

        // add preloader
        var $tab = master.$instance.find('.stec-layout-event.active').find('.stec-layout-event-inner-attendance');
        $tab.wrapInner('<div class="stec-layout-event-inner-preload-wrap" />');
        $(master.glob.template.preloader).appendTo($tab);

    }, 'onBeforeEventDataAjax');

    $.stecExtend(function (master, data) {
        
        if (data.attendance.length <= 0) {
            return;
        }

        var $instance = master.$instance;
        var helper    = master.helper;
        var glob      = master.glob;

        var $event = $instance.$events.find('.stec-layout-event.active');
        var $inner = $event.find('.stec-layout-event-inner-attendance');

        var template = $inner.find('.stec-layout-event-inner-attendance-attendee-template')[0].outerHTML;
        $inner.find('.stec-layout-event-inner-attendance-attendee-template').remove();

        var attendees = [];
        
        $(data.attendance).each(function(){
            // initial event
            if (this.repeat_offset == 0) {
                attendees.push(this);
            }
        });
        
        attendees = jQuery.unique(attendees);

        if (attendees.length > 0) {

            $(attendees).each(function (i) {

                var th = this;

                $(template).html(function (index, html) {
                    
                    var statusKlass = '';
                    
                    switch (parseInt(th.status, 10)) {
                        case 1:
                            statusKlass = 'fa fa-check';
                            break;
                            
                        case 2:
                            statusKlass = 'fa fa-times';
                            break;
                            
                        default:
                            statusKlass = 'fa fa-question';
                    }
                    
                    return html
                            .replace(/stec_replace_name/g, th.name)
                            .replace(/#stec_replace_avatar/g, th.avatar)
                            .replace(/stec_replace_userid/g, th.userid ? th.userid : '')
                            .replace(/stec_replace_status/g, '<li class=""><i class="'+ statusKlass  +'"></i></li>');

                })
                    .removeClass('stec-layout-event-inner-attendance-attendee-template')
                    .appendTo($inner.find('.stec-layout-event-inner-attendance-attendees'));
            });

        }

        var invited_user = false;

        if (!isNaN(glob.options.userid)) {

            // check if user is invited
            $(data.attendance).each(function () {
                if (this.userid == glob.options.userid) {
                    invited_user = true;
                    return false; // break
                }
            });
        }

        if (invited_user !== false) {
            
            var status = 0;
            
            $(data.attendance).each(function () {
                if (this.userid == glob.options.userid && this.repeat_offset == data.repeat_time_offset) {
                    status = parseInt(this.status, 10);
                    return false; // break
                }
            });
            
            var $avatar = $inner.find('.stec-layout-event-inner-attendance-attendee-avatar')
                            .filter('[data-userid="' + glob.options.userid + '"]');
            
            switch (status) {
                case 1:
                    // accepted
                    $inner.find('.stec-layout-event-inner-attendance-invited-buttons-accept').addClass('active');
                    $inner.find('.stec-layout-event-inner-attendance-invited-buttons-decline').removeClass('active');
                    
                    $avatar.find('li i').attr('class', 'fa fa-check');
                    
                    break;

                case 2:
                    // declined
                    $inner.find('.stec-layout-event-inner-attendance-invited-buttons-accept').removeClass('active');
                    $inner.find('.stec-layout-event-inner-attendance-invited-buttons-decline').addClass('active');
                    
                    $avatar.find('li i').attr('class', 'fa fa-times');
                    
                    break;
            }
        } else {
            $inner.find('.stec-layout-event-inner-attendance-invited').remove();
        }

        // Attend / Decline

        function ajaxAttendance(status) {

            // status
            // 0 - no decision
            // 1 - accept 
            // 2 - decline

            glob.ajax = $.ajax({
                dataType: "json",
                type: 'POST',
                url: window.ajaxurl,
                data: {
                    action: 'stec_public_ajax_action',
                    task: 'set_user_event_attendance',
                    event_id: data.general.id,
                    repeat_offset: data.repeat_time_offset,
                    status: status
                },
                beforeSend: function () {
                    if (glob.ajax !== null) {
                        glob.ajax.abort();
                    }

                    $inner.find('.stec-layout-event-inner-attendance-invited-buttons').hide();
                    $(glob.template.preloader).appendTo($inner.find('.stec-layout-event-inner-attendance-invited'));
                },
                success: function (rtrn) {
                    
                    var status = parseInt(rtrn.status, 10);
                    var id     = parseInt(rtrn.id, 10);

                    $event.find('.stec-layout-event-inner-intro-attendance li').removeClass('active');
                    $inner.find('.stec-layout-event-inner-attendance-invited-buttons li').removeClass('active');

                    var $avatar = $inner.find('.stec-layout-event-inner-attendance-attendee-avatar')
                            .filter('[data-userid="' + glob.options.userid + '"]');

                    switch (parseInt(rtrn.status, 10)) {
                        case 1 :
                            $event.find('.stec-layout-event-inner-intro-attendance-attend').addClass('active');
                            $inner.find('.stec-layout-event-inner-attendance-invited-buttons-accept').addClass('active');
                            $avatar.find('li i').attr('class', 'fa fa-check');
                            break;
                        case 2 :
                            $event.find('.stec-layout-event-inner-intro-attendance-decline').addClass('active');
                            $inner.find('.stec-layout-event-inner-attendance-invited-buttons-decline').addClass('active');
                            $avatar.find('li i').attr('class', 'fa fa-times');
                            break;
                        default:
                            $avatar.find('li i').attr('class', 'fa fa-question');

                    }

                    var hasData = false;
                    $(data.attendance).each(function(){
                        
                        if (this.id == id) {
                            
                            this.status = status;
                            
                            hasData = true;
                            
                            return false; // break
                        }
                    });
                    
                    if (!hasData) {
                        // no data copy original with new status and id
                        
                        $(data.attendance).each(function(){
                            
                            if (this.userid == glob.options.userid) {
                                
                                // make fresh copy
                                var copy = JSON.parse(JSON.stringify(this));
                                
                                copy.repeat_offset = data.repeat_time_offset;
                                copy.status        = status;
                                copy.id            = id;
                                
                                data.attendance.push(copy);
                                
                                return false; // break
                                
                            }
                            
                        });
                        
                    }
                    

                },
                error: function (xhr, status, thrown) {
                    console.log(xhr + " " + status + " " + thrown);
                },
                complete: function () {
                    glob.ajax = null;

                    $inner.find('.stec-layout-event-inner-attendance-invited-buttons').css('display','flex');
                    $inner.find('.stec-layout-event-inner-attendance-invited').find('.stec-preloader').remove();

                }
            });

        }

        $inner.find('.stec-layout-event-inner-attendance-invited-buttons-accept').on(helper.clickHandle(), function (e) {
            e.preventDefault();
            var status = $(this).hasClass('active') ? 0 : 1;
            ajaxAttendance(status);
        });

        $inner.find('.stec-layout-event-inner-attendance-invited-buttons-decline').on(helper.clickHandle(), function (e) {
            e.preventDefault();
            var status = $(this).hasClass('active') ? 0 : 2;
            ajaxAttendance(status);
        });

        // Check if event is in progress
        var nowDate   = new Date();
        var startDate = helper.dbDateTimeToDate(helper.dbDateOffset(data.general.start_date, data.repeat_time_offset));

        if (nowDate >= startDate) {
            $inner.find('.stec-layout-event-inner-attendance-invited').hide();
        }
        
        // Remove tab preloaders
        $inner.find('.stec-layout-event-inner-preload-wrap').children().first().unwrap();
        $inner.find('.stec-layout-event-inner-preload-wrap').remove();
        $inner.find('.stec-preloader').remove();

    }, 'onEventDataReady');


})(jQuery);
// source --> http://www.kolarac.rs/wp-content/plugins/stachethemes_event_calendar/stachethemes/../front/js/adds/comments.js?ver=4.8.25 
(function ($) {

    "use strict";

    $.stecExtend(function (master) {
        
        var $instance = master.$instance;
        var helper    = master.helper;
        
        var disqus = {
            
            loadCommentsCount: function () {

                var disqus_shortname = master.glob.options.general_settings.disqus_shortname;

                $.ajax({
                    type: "GET",
                    url: "//" + disqus_shortname + ".disqus.com/count.js",
                    dataType: "script",
                    cache: true
                });
            },
            
            loadComments: function ($tabCont) {

                $instance.$events.find("#disqus_thread").remove();

                $('<div id="disqus_thread"></div>').appendTo($tabCont);
                
                var eventId          = $tabCont.parents('.stec-layout-event').attr('data-id');
                var disqus_shortname = master.glob.options.general_settings.disqus_shortname;
                var disqus_title     = $tabCont.parents('.stec-layout-event')
                                           .find('.stec-layout-event-preview-left-text-title')
                                           .text();

                window.disqus_url        = window.location.href + "#!stecEventDiscussion" + eventId;
                window.disqus_identifier = "stecEventID" + eventId;
                window.disqus_title      = disqus_title;

                if (typeof window.DISQUS === "undefined") {
                    $.ajax({
                        type: "GET",
                        url: "//" + disqus_shortname + ".disqus.com/embed.js",
                        dataType: "script",
                        cache: true
                    });
                } else {
                    window.DISQUS.reset({
                        reload: true
                    });
                }
            }
        };
        
        function tabToggle($event) {
            if ($event
                    .find('.stec-layout-event-inner-top-tabs')
                    .children('.active[data-tab="stec-layout-event-inner-comments"]')
                    .length > 0) {
                
                loadComments($event);
            }
        }
        
        function loadComments($event) {
            if ($event
                    .find('.stec-layout-event-inner-comments')
                    .find('#disqus_thread').length <= 0) {
                disqus.loadComments($event.find('.stec-layout-event-inner-comments'));
            }
        }
        
        $(document).on(helper.clickHandle(), $instance.$events.path + ' .stec-layout-event-inner-top-tabs li', function () {
            if ($(this).attr('data-tab') == "stec-layout-event-inner-comments") {
                var $event = $(this).parents('.stec-layout-event-inner');
                loadComments($event);
            }
        });
        
        $(document).on(helper.clickHandle(), $instance.$events.path + (".stec-layout-event-preview-right-event-toggle"), function (e) {
            e.preventDefault();
            e.stopPropagation();
            tabToggle($(this).parents('.stec-layout-event'));

        });

        $(document).on(helper.clickHandle(), $instance.$events.path + '.stec-layout-event', function (e) {
            e.preventDefault();
            tabToggle($(this));
            
        });
        
        

    });

})(jQuery);
// source --> http://www.kolarac.rs/wp-content/plugins/stachethemes_event_calendar/stachethemes/../front/js/adds/forecast.js?ver=4.8.25 
(function ($) {

    "use strict";

    $.stecExtend(function (master) {

        var $tab = master.$instance.find('.stec-layout-event.active').find('.stec-layout-event-inner-forecast');
        $tab.wrapInner('<div class="stec-layout-event-inner-preload-wrap" />');
        $(master.glob.template.preloader).appendTo($tab);

    }, 'onBeforeEventDataAjax');

    $.stecExtend(function (master, data) {

        if (data.general.location_forecast == '') {
            return;
        }

        var $instance = master.$instance;
        var helper = master.helper;
        var glob = master.glob;

        var $event = $instance.$events.find('.stec-layout-event.active');
        var $inner = $event.find('.stec-layout-event-inner-forecast');

        var template = $inner.find('.stec-layout-event-inner-forecast-details-left-forecast-day-template')[0].outerHTML;
        $inner.find('.stec-layout-event-inner-forecast-details-left-forecast-day-template').remove();

        function floorFigure(figure, decimals) {
            if (!decimals)
                decimals = 2;
            var d = Math.pow(10, decimals);
            return (parseInt(figure * d) / d).toFixed(decimals);
        }
        

        var getWeather = function () {

            if (data.forecast) {

                if (!data.forecast.error) {
                    fillData();
                } else {
                    fillError();
                }
                return;
            }

            var location = data.general.location_forecast;

            glob.ajax = $.ajax({
                type: 'POST',
                url: window.ajaxurl,
                data: {
                    action: 'stec_public_ajax_action',
                    task: 'get_weather_data',
                    location: function () {

                        location = location.split(',');

                        location[0] = floorFigure(location[0]);
                        location[1] = floorFigure(location[1]);

                        location = location.join(',');

                        return location;

                    }
                },
                beforeSend: function () {
                    if (glob.ajax !== null) {
                        glob.ajax.abort();
                    }
                },
                success: function (rtrn) {

                    if (rtrn) {

                        if (!data.forecast) {
                            data.forecast = rtrn;
                        }

                        // error ?
                        if (data.forecast.error || !data.forecast) {
                            fillError();
                            return;
                        }

                        fillData(rtrn);
                    } else {
                        fillError();
                    }

                },
                error: function (xhr, status, thrown) {
                    fillError();
                    console.log(xhr + " " + status + " " + thrown);
                },
                complete: function () {
                    glob.ajax = null;

                    // Remove tabs preloaders
                    $inner.find('.stec-layout-event-inner-preload-wrap').children().first().unwrap();
                    $inner.find('.stec-layout-event-inner-preload-wrap').remove();
                    $inner.find('.stec-preloader').remove();
                },
                dataType: "json"
            });
        };

        var fillData = function () {

            var fiveDays = [];

            var i = 0;

            var forecast = data.forecast;

            $(forecast.daily.data).each(function () {

                if (i > 4)
                    return false;

                var th = this;
                var icon = iconToiconHTML(th.icon, true);
                
                // Localtime
                var d = helper.treatAsUTC(new Date(this.time * 1000));
                d.setHours(d.getHours() + forecast.offset);
                
                var format = 'dd-mm';

                switch (glob.options.general_settings.date_format) {
                    case 'dd-mm-yy' :
                        format = 'd M';
                        break;
                    case 'mm-dd-yy' :
                        format = 'M d';
                        break;
                    case 'yy-mm-dd' :
                        format = 'M d';
                        break;
                }

                var niceday = helper.dateToFormat(format, d);

                fiveDays[i] = $(template).html(function (index, html) {

                    var tempFmin = Math.round(th.temperatureMin);
                    var tempCmin = Math.round((tempFmin - 32) * 5 / 9);

                    var tempFmax = Math.round(th.temperatureMax);
                    var tempCmax = Math.round((tempFmax - 32) * 5 / 9);

                    return html
                            .replace(/\bstec_replace_date\b/g, niceday)
                            .replace(/\bstec_replace_min\b/g, glob.options.general_settings.temp_units == "C" ? tempCmin : tempFmin)
                            .replace(/\bstec_replace_max\b/g, glob.options.general_settings.temp_units == "C" ? tempCmax : tempFmax)
                            .replace(/\bstec_replace_temp_units\b/g, glob.options.general_settings.temp_units == "C" ? "C" : "F")
                            .replace(/\bstec_replace_icon_div\b/g, icon);
                })[0].outerHTML;

                i++;
            });

            fiveDays = fiveDays.join('');

            $inner.html(function (index, html) {

                var icon = iconToiconHTML(forecast.currently.icon);

                var tempF = Math.round(forecast.currently.temperature);
                var tempC = Math.round((tempF - 32) * 5 / 9);

                var apTempF = Math.round(forecast.currently.apparentTemperature);
                var apTempC = Math.round((tempF - 32) * 5 / 9);

                var windMPH = Math.round(forecast.currently.windSpeed);
                var windKPH = Math.round(windMPH * 1.609344);
                
                // Local time
                var d = helper.treatAsUTC(new Date(forecast.currently.time * 1000));
                d.setHours(d.getHours() + forecast.offset);

                var niceday = helper.dateToFormat(false, d);

                return html
                        .replace(/\bstec_replace_current_summary_text\b/g, iconToText(forecast.currently.icon))
                        .replace(/\bstec_replace_today_date\b/g, niceday)
                        .replace(/\bstec_replace_location\b/g, helper.capitalizeFirstLetter(data.general.location))
                        .replace(/\bstec_replace_current_temp\b/g, glob.options.general_settings.temp_units == "C" ? tempC : tempF)
                        .replace(/\bstec_replace_current_feels_like\b/g, glob.options.general_settings.temp_units == "C" ? apTempC : apTempF)
                        .replace(/\bstec_replace_current_humidity\b/g, forecast.currently.humidity * 100)
                        .replace(/\bstec_replace_current_temp_units/g, glob.options.general_settings.temp_units == "C" ? "C" : "F")
                        .replace(/\bstec_replace_current_wind\b/g, glob.options.general_settings.wind_units == "MPH" ? windMPH : windKPH)
                        .replace(/\bstec_replace_current_wind_units\b/g, glob.options.general_settings.wind_units == "MPH" ? "MPH" : "KPH")
                        .replace(/\bstec_replace_current_wind_direction\b/g, getWindDir(forecast.currently.windBearing))
                        .replace(/\bstec_replace_today_icon_div\b/g, icon)
                        .replace(/\bstec_replace_5days\b/g, fiveDays);

            });

            // Chart instance
            setTimeout(function () {


                var humidity = [],
                        tempC = [],
                        tempF = [],
                        rain = [],
                        j = -1;


                var charTimeLabels = [];

                for (var i = 0; i < 8; i++) {

                    j = j + 3;

                    var th = forecast.hourly.data[j];

                    var tempf = Math.round(th.temperature);
                    var tempc = Math.round((tempf - 32) * 5 / 9);

                    tempC[i] = tempc;
                    tempF[i] = tempf;
                    humidity[i] = Math.round(th.humidity * 100);
                    rain[i] = th.precipProbability * 100;
                    
                    // Local time
                    var d = helper.treatAsUTC(new Date (th.time * 1000));
                    charTimeLabels.push(helper.dateToFormat('h:i', d));
                    
                }

                var ch = new chart();

                ch.setCanvas($inner.find('.stec-layout-event-inner-forecast-details-chart canvas'));

                ch.setChartData({
                    labels: charTimeLabels,
                    datasets: [
                        {
                            label: window.stecLang.humidity_percents,
                            data: humidity,
                            backgroundColor: "rgba(200,200,200,0.1)",
                            borderColor: "rgba(200,200,200,1)",
                            pointBackgroundColor: "rgba(200,200,200,1)",
                            fill: true,
                            lineTension: 0.3,
                            pointHoverRadius: 5,
                            pointHitRadius: 10,
                            borderWidth: 1
                        },
                        {
                            label: window.stecLang.rain_chance_percents,
                            data: rain,
                            backgroundColor: "rgba(70,129,195,0.1)",
                            borderColor: "rgba(70,129,195,1)",
                            pointBackgroundColor: "rgba(70,129,195,1)",
                            fill: true,
                            lineTension: 0.3,
                            pointHoverRadius: 5,
                            pointHitRadius: 10,
                            borderWidth: 1
                        },
                        {
                            label: window.stecLang.temperature + ' ' + '\u00B0' + (glob.options.general_settings.temp_units == "C" ? 'C' : 'F'),
                            data: glob.options.general_settings.temp_units == "C" ? tempC : tempF,
                            backgroundColor: "rgba(252,183,85,0.3)",
                            borderColor: "rgba(252,183,85,1)",
                            pointBackgroundColor: "rgba(252,183,85,1)",
                            fill: true,
                            lineTension: 0.3,
                            pointHoverRadius: 5,
                            pointHitRadius: 10,
                            borderWidth: 1
                        }
                    ]
                });

                ch.build();

                helper.onResizeEnd(function () {
                    
                    if ($instance.hasClass('stec-media-small')) {
                        ch.chart.options.legend.display = false;
                    } else {
                        ch.chart.options.legend.display = true;
                    }
                    
                    ch.chart.update();
                    
                }, 50, 'stec-unbind-window-resize-on-event-close-' + glob.options.id);

            }, 0);

        };

        function chart() {

            this.ctx,
                    this.chartData,
                    this.chart,
                    this.setCanvas = function ($canvas) {

                        var canvas = $canvas.get(0);

                        var w = parseInt($inner.find('.stec-layout-event-inner-forecast-details-chart').width(), 10);
                        var h = parseInt($inner.find('.stec-layout-event-inner-forecast-details-chart').height(), 10);

                        canvas.width = w;
                        canvas.height = h;

                        this.ctx = $canvas.get(0).getContext("2d");

                    },
                    this.setChartData = function (chartData) {
                        this.chartData = chartData;
                    },
                    this.destroy = function () {
                        this.chart.destroy();
                    },
                    this.build = function () {

                        var parent = this;

                        if (this.chart) {
                            this.destroy();
                        }

                        var generalTextColor = $inner.find('.stec-layout-event-inner-forecast-details-left-forecast-top p').css('color');
                        var generalFontFamily = $inner.find('.stec-layout-event-inner-forecast-details-left-forecast-top p').css('font-family');
                        var displayLegend     = true;
                        
                        if ($instance.hasClass('stec-media-small')) {
                            displayLegend = false;
                        } 
                        
                        this.chart = window.Chart(this.ctx, {
                            type: 'line',
                            data: parent.chartData,
                            options: {
                                maintainAspectRatio: false,
                                responsive: true,
                                defaultFontFamily: generalFontFamily,
                                defaultFontColor: generalTextColor,
                                legend: {
                                    display: displayLegend,
                                    labels: {
                                        fontFamily: generalFontFamily,
                                        fontColor: generalTextColor,
                                        fontSize: 12
                                    }
                                },
                                scales: {
                                    xAxes: [{
                                            ticks: {
                                                fontFamily: generalFontFamily,
                                                fontSize: 11,
                                                fontColor: generalTextColor
                                            },
                                            gridLines: {
                                                color: 'rgba(0,0,0,0.1)',
                                                zeroLineColor: 'rgba(0,0,0,0)'
                                            }
                                        }],
                                    yAxes: [{
                                            ticks: {
                                                fontFamily: generalFontFamily,
                                                fontSize: 11,
                                                fontColor: generalTextColor
                                            },
                                            gridLines: {
                                                color: 'rgba(0,0,0,0.1)',
                                                zeroLineColor: 'rgba(0,0,0,0)'
                                            }
                                        }]
                                },
                                tooltips: {
                                    titleFontColor: '#fff',
                                    titleFontStyle: generalFontFamily,
                                    bodyFontFamily: generalFontFamily,
                                    bodyFontColor: '#fff'
                                }

                            }
                        });

                    };

        }

        function getWindDir(bearing) {

            while (bearing < 0)
                bearing += 360;
            while (bearing >= 360)
                bearing -= 360;
            var val = Math.round((bearing - 11.25) / 22.5);
            var arr = [
                window.stecLang.N,
                window.stecLang.NNE,
                window.stecLang.NE,
                window.stecLang.ENE,
                window.stecLang.E,
                window.stecLang.ESE,
                window.stecLang.SE,
                window.stecLang.SSE,
                window.stecLang.S,
                window.stecLang.SSW,
                window.stecLang.SW,
                window.stecLang.WSW,
                window.stecLang.W,
                window.stecLang.WNW,
                window.stecLang.NW,
                window.stecLang.NNW
            ];
            return arr[ Math.abs(val) ];

        }

        var fillError = function () {
            $inner.find('.stec-layout-event-inner-forecast-content').remove();
            $inner.find('.errorna').show();
        };

        function iconToText(icon) {

            switch (icon) {

                case ('clear-day') :
                case ('clear-night') :
                    return window.stecLang.clear_sky;
                    break;

                case ('partly-cloudy-day') :
                case ('partly-cloudy-night') :
                    return window.stecLang.partly_cloudy;
                    break;

                case ('cloudy') :
                    return window.stecLang.cloudy;
                    break;

                case ('fog') :
                    return window.stecLang.fog;
                    break;

                case ('rain') :
                    return window.stecLang.rain;
                    break;

                case ('sleet') :
                    return window.stecLang.sleet;
                    break;

                case ('snow') :
                    return window.stecLang.snow;
                    break;

                case ('wind') :
                    return window.stecLang.wind;
                    break;

            }
        }

        function iconToiconHTML(icon, forceday) {

//          clear-day, clear-night, rain, snow, sleet, wind, fog, cloudy, partly-cloudy-day, or partly-cloudy-night

            switch (icon) {

                case ('clear-day') :
                    return '<div class="stec-forecast-icon-clear-day"></div>';
                    break;

                case ('clear-night') :
                    return forceday ? '<div class="stec-forecast-icon-clear-day"></div>' : '<div class="stec-forecast-icon-clear-night"></div>';
                    break;

                case ('partly-cloudy-day') :
                    return '<div class="stec-forecast-icon-cloudy-day"></div>';
                    break;

                case ('partly-cloudy-night') :
                    return forceday ? '<div class="stec-forecast-icon-cloudy-day"></div>' : '<div class="stec-forecast-icon-cloudy-night"></div>';
                    break;

                case ('cloudy') :
                    return '<div class="stec-forecast-icon-cloudy"></div>';
                    break;

                case ('fog') :
                    return '<div class="stec-forecast-icon-mist"></div>';
                    break;

                case ('rain') :
                    return  '<div class="stec-forecast-icon-rain"></div>';
                    break;

                case ('sleet') :
                    return '<div class="stec-forecast-icon-sleet"></div>';
                    break;

                case ('snow') :
                    return '<div class="stec-forecast-icon-snow"></div>';
                    break;

                case ('wind') :
                    return '<div class="stec-forecast-icon-cloudy"></div>';
                    break;

            }
        }

        var isLoaded = false;

        $(window).on('stec-tab-click-' + glob.options.id, function () {
            if (!$(this).hasClass('active') && isLoaded === false) {
                getWeather();
                isLoaded = true;
            }
        });

        if ($inner.hasClass('active')) {
            getWeather();
            isLoaded = true;
        }

    }, 'onEventDataReady');

})(jQuery);
// source --> http://www.kolarac.rs/wp-content/plugins/stachethemes_event_calendar/stachethemes/../front/js/libs/colorpicker/colorpicker.js?ver=4.8.25 
/**
 *
 * Color picker
 * Author: Stefan Petre www.eyecon.ro
 * 
 * Dual licensed under the MIT and GPL licenses
 * 
 * Modified by stachethemes to allow custom params
 * options.id
 * options.klass
 * 
 */
(function ($) {
	var ColorPicker = function () {
		var
			ids = {},
			inAction,
			charMin = 65,
			visible,
			tpl = '<div class="stec-colorpicker colorpicker"><div class="colorpicker_color"><div><div></div></div></div><div class="colorpicker_hue"><div></div></div><div class="colorpicker_new_color"></div><div class="colorpicker_current_color"></div><div class="colorpicker_hex"><input type="text" maxlength="6" size="6" /></div><div class="colorpicker_rgb_r colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_g colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_h colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_s colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_submit"></div></div>',
			defaults = {
				eventName: 'click',
				onShow: function () {},
				onBeforeShow: function(){},
				onHide: function () {},
				onChange: function () {},
				onSubmit: function () {},
				color: 'ff0000',
				livePreview: true,
				flat: false
			},
			fillRGBFields = function  (hsb, cal) {
				var rgb = HSBToRGB(hsb);
				$(cal).data('colorpicker').fields
					.eq(1).val(rgb.r).end()
					.eq(2).val(rgb.g).end()
					.eq(3).val(rgb.b).end();
			},
			fillHSBFields = function  (hsb, cal) {
				$(cal).data('colorpicker').fields
					.eq(4).val(hsb.h).end()
					.eq(5).val(hsb.s).end()
					.eq(6).val(hsb.b).end();
			},
			fillHexFields = function (hsb, cal) {
				$(cal).data('colorpicker').fields
					.eq(0).val(HSBToHex(hsb)).end();
			},
			setSelector = function (hsb, cal) {
				$(cal).data('colorpicker').selector.css('backgroundColor', '#' + HSBToHex({h: hsb.h, s: 100, b: 100}));
				$(cal).data('colorpicker').selectorIndic.css({
					left: parseInt(150 * hsb.s/100, 10),
					top: parseInt(150 * (100-hsb.b)/100, 10)
				});
			},
			setHue = function (hsb, cal) {
				$(cal).data('colorpicker').hue.css('top', parseInt(150 - 150 * hsb.h/360, 10));
			},
			setCurrentColor = function (hsb, cal) {
				$(cal).data('colorpicker').currentColor.css('backgroundColor', '#' + HSBToHex(hsb));
			},
			setNewColor = function (hsb, cal) {
				$(cal).data('colorpicker').newColor.css('backgroundColor', '#' + HSBToHex(hsb));
			},
			keyDown = function (ev) {
				var pressedKey = ev.charCode || ev.keyCode || -1;
				if ((pressedKey > charMin && pressedKey <= 90) || pressedKey == 32) {
					return false;
				}
				var cal = $(this).parent().parent();
				if (cal.data('colorpicker').livePreview === true) {
					change.apply(this);
				}
			},
			change = function (ev) {
				var cal = $(this).parent().parent(), col;
				if (this.parentNode.className.indexOf('_hex') > 0) {
					cal.data('colorpicker').color = col = HexToHSB(fixHex(this.value));
				} else if (this.parentNode.className.indexOf('_hsb') > 0) {
					cal.data('colorpicker').color = col = fixHSB({
						h: parseInt(cal.data('colorpicker').fields.eq(4).val(), 10),
						s: parseInt(cal.data('colorpicker').fields.eq(5).val(), 10),
						b: parseInt(cal.data('colorpicker').fields.eq(6).val(), 10)
					});
				} else {
					cal.data('colorpicker').color = col = RGBToHSB(fixRGB({
						r: parseInt(cal.data('colorpicker').fields.eq(1).val(), 10),
						g: parseInt(cal.data('colorpicker').fields.eq(2).val(), 10),
						b: parseInt(cal.data('colorpicker').fields.eq(3).val(), 10)
					}));
				}
				if (ev) {
					fillRGBFields(col, cal.get(0));
					fillHexFields(col, cal.get(0));
					fillHSBFields(col, cal.get(0));
				}
				setSelector(col, cal.get(0));
				setHue(col, cal.get(0));
				setNewColor(col, cal.get(0));
				cal.data('colorpicker').onChange.apply(cal, [col, HSBToHex(col), HSBToRGB(col)]);
			},
			blur = function (ev) {
				var cal = $(this).parent().parent();
				cal.data('colorpicker').fields.parent().removeClass('colorpicker_focus');
			},
			focus = function () {
				charMin = this.parentNode.className.indexOf('_hex') > 0 ? 70 : 65;
				$(this).parent().parent().data('colorpicker').fields.parent().removeClass('colorpicker_focus');
				$(this).parent().addClass('colorpicker_focus');
			},
			downIncrement = function (ev) {
				var field = $(this).parent().find('input').focus();
				var current = {
					el: $(this).parent().addClass('colorpicker_slider'),
					max: this.parentNode.className.indexOf('_hsb_h') > 0 ? 360 : (this.parentNode.className.indexOf('_hsb') > 0 ? 100 : 255),
					y: ev.pageY,
					field: field,
					val: parseInt(field.val(), 10),
					preview: $(this).parent().parent().data('colorpicker').livePreview					
				};
				$(document).bind('mouseup', current, upIncrement);
				$(document).bind('mousemove', current, moveIncrement);
			},
			moveIncrement = function (ev) {
				ev.data.field.val(Math.max(0, Math.min(ev.data.max, parseInt(ev.data.val + ev.pageY - ev.data.y, 10))));
				if (ev.data.preview) {
					change.apply(ev.data.field.get(0), [true]);
				}
				return false;
			},
			upIncrement = function (ev) {
				change.apply(ev.data.field.get(0), [true]);
				ev.data.el.removeClass('colorpicker_slider').find('input').focus();
				$(document).unbind('mouseup', upIncrement);
				$(document).unbind('mousemove', moveIncrement);
				return false;
			},
			downHue = function (ev) {
				var current = {
					cal: $(this).parent(),
					y: $(this).offset().top
				};
				current.preview = current.cal.data('colorpicker').livePreview;
				$(document).bind('mouseup', current, upHue);
				$(document).bind('mousemove', current, moveHue);
			},
			moveHue = function (ev) {
				change.apply(
					ev.data.cal.data('colorpicker')
						.fields
						.eq(4)
						.val(parseInt(360*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.y))))/150, 10))
						.get(0),
					[ev.data.preview]
				);
				return false;
			},
			upHue = function (ev) {
				fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
				fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
				$(document).unbind('mouseup', upHue);
				$(document).unbind('mousemove', moveHue);
				return false;
			},
			downSelector = function (ev) {
				var current = {
					cal: $(this).parent(),
					pos: $(this).offset()
				};
				current.preview = current.cal.data('colorpicker').livePreview;
				$(document).bind('mouseup', current, upSelector);
				$(document).bind('mousemove', current, moveSelector);
			},
			moveSelector = function (ev) {
				change.apply(
					ev.data.cal.data('colorpicker')
						.fields
						.eq(6)
						.val(parseInt(100*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.pos.top))))/150, 10))
						.end()
						.eq(5)
						.val(parseInt(100*(Math.max(0,Math.min(150,(ev.pageX - ev.data.pos.left))))/150, 10))
						.get(0),
					[ev.data.preview]
				);
				return false;
			},
			upSelector = function (ev) {
				fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
				fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
				$(document).unbind('mouseup', upSelector);
				$(document).unbind('mousemove', moveSelector);
				return false;
			},
			enterSubmit = function (ev) {
				$(this).addClass('colorpicker_focus');
			},
			leaveSubmit = function (ev) {
				$(this).removeClass('colorpicker_focus');
			},
			clickSubmit = function (ev) {
				var cal = $(this).parent();
				var col = cal.data('colorpicker').color;
				cal.data('colorpicker').origColor = col;
				setCurrentColor(col, cal.get(0));
				cal.data('colorpicker').onSubmit(col, HSBToHex(col), HSBToRGB(col), cal.data('colorpicker').el);
			},
			show = function (ev) {
				var cal = $('#' + $(this).data('colorpickerid'));
				cal.data('colorpicker').onBeforeShow.apply(this, [cal.get(0)]);
				var pos = $(this).offset();
				var viewPort = getViewport();
				var top = pos.top + this.offsetHeight;
				var left = pos.left;
				if (top + 176 > viewPort.t + viewPort.h) {
					top -= this.offsetHeight + 176;
				}
				if (left + 356 > viewPort.l + viewPort.w) {
					left -= 356;
				}
				cal.css({left: left + 'px', top: top + 'px'});
				if (cal.data('colorpicker').onShow.apply(this, [cal.get(0)]) != false) {
					cal.show();
				}
				$(document).bind('mousedown', {cal: cal}, hide);
				return false;
			},
			hide = function (ev) {
				if (!isChildOf(ev.data.cal.get(0), ev.target, ev.data.cal.get(0))) {
					if (ev.data.cal.data('colorpicker').onHide.apply(this, [ev.data.cal.get(0)]) != false) {
						ev.data.cal.hide();
					}
					$(document).unbind('mousedown', hide);
				}
			},
			isChildOf = function(parentEl, el, container) {
				if (parentEl == el) {
					return true;
				}
				if (parentEl.contains) {
					return parentEl.contains(el);
				}
				if ( parentEl.compareDocumentPosition ) {
					return !!(parentEl.compareDocumentPosition(el) & 16);
				}
				var prEl = el.parentNode;
				while(prEl && prEl != container) {
					if (prEl == parentEl)
						return true;
					prEl = prEl.parentNode;
				}
				return false;
			},
			getViewport = function () {
				var m = document.compatMode == 'CSS1Compat';
				return {
					l : window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft),
					t : window.pageYOffset || (m ? document.documentElement.scrollTop : document.body.scrollTop),
					w : window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth),
					h : window.innerHeight || (m ? document.documentElement.clientHeight : document.body.clientHeight)
				};
			},
			fixHSB = function (hsb) {
				return {
					h: Math.min(360, Math.max(0, hsb.h)),
					s: Math.min(100, Math.max(0, hsb.s)),
					b: Math.min(100, Math.max(0, hsb.b))
				};
			}, 
			fixRGB = function (rgb) {
				return {
					r: Math.min(255, Math.max(0, rgb.r)),
					g: Math.min(255, Math.max(0, rgb.g)),
					b: Math.min(255, Math.max(0, rgb.b))
				};
			},
			fixHex = function (hex) {
				var len = 6 - hex.length;
				if (len > 0) {
					var o = [];
					for (var i=0; i<len; i++) {
						o.push('0');
					}
					o.push(hex);
					hex = o.join('');
				}
				return hex;
			}, 
			HexToRGB = function (hex) {
				var hex = parseInt(((hex.indexOf('#') > -1) ? hex.substring(1) : hex), 16);
				return {r: hex >> 16, g: (hex & 0x00FF00) >> 8, b: (hex & 0x0000FF)};
			},
			HexToHSB = function (hex) {
				return RGBToHSB(HexToRGB(hex));
			},
			RGBToHSB = function (rgb) {
				var hsb = {
					h: 0,
					s: 0,
					b: 0
				};
				var min = Math.min(rgb.r, rgb.g, rgb.b);
				var max = Math.max(rgb.r, rgb.g, rgb.b);
				var delta = max - min;
				hsb.b = max;
				if (max != 0) {
					
				}
				hsb.s = max != 0 ? 255 * delta / max : 0;
				if (hsb.s != 0) {
					if (rgb.r == max) {
						hsb.h = (rgb.g - rgb.b) / delta;
					} else if (rgb.g == max) {
						hsb.h = 2 + (rgb.b - rgb.r) / delta;
					} else {
						hsb.h = 4 + (rgb.r - rgb.g) / delta;
					}
				} else {
					hsb.h = -1;
				}
				hsb.h *= 60;
				if (hsb.h < 0) {
					hsb.h += 360;
				}
				hsb.s *= 100/255;
				hsb.b *= 100/255;
				return hsb;
			},
			HSBToRGB = function (hsb) {
				var rgb = {};
				var h = Math.round(hsb.h);
				var s = Math.round(hsb.s*255/100);
				var v = Math.round(hsb.b*255/100);
				if(s == 0) {
					rgb.r = rgb.g = rgb.b = v;
				} else {
					var t1 = v;
					var t2 = (255-s)*v/255;
					var t3 = (t1-t2)*(h%60)/60;
					if(h==360) h = 0;
					if(h<60) {rgb.r=t1;	rgb.b=t2; rgb.g=t2+t3}
					else if(h<120) {rgb.g=t1; rgb.b=t2;	rgb.r=t1-t3}
					else if(h<180) {rgb.g=t1; rgb.r=t2;	rgb.b=t2+t3}
					else if(h<240) {rgb.b=t1; rgb.r=t2;	rgb.g=t1-t3}
					else if(h<300) {rgb.b=t1; rgb.g=t2;	rgb.r=t2+t3}
					else if(h<360) {rgb.r=t1; rgb.g=t2;	rgb.b=t1-t3}
					else {rgb.r=0; rgb.g=0;	rgb.b=0}
				}
				return {r:Math.round(rgb.r), g:Math.round(rgb.g), b:Math.round(rgb.b)};
			},
			RGBToHex = function (rgb) {
				var hex = [
					rgb.r.toString(16),
					rgb.g.toString(16),
					rgb.b.toString(16)
				];
				$.each(hex, function (nr, val) {
					if (val.length == 1) {
						hex[nr] = '0' + val;
					}
				});
				return hex.join('');
			},
			HSBToHex = function (hsb) {
				return RGBToHex(HSBToRGB(hsb));
			},
			restoreOriginal = function () {
				var cal = $(this).parent();
				var col = cal.data('colorpicker').origColor;
				cal.data('colorpicker').color = col;
				fillRGBFields(col, cal.get(0));
				fillHexFields(col, cal.get(0));
				fillHSBFields(col, cal.get(0));
				setSelector(col, cal.get(0));
				setHue(col, cal.get(0));
				setNewColor(col, cal.get(0));
			};
		return {
			init: function (opt) {
				opt = $.extend({}, defaults, opt||{});
                                
                                if (opt.id !== 'undefined') {
                                    
                                    // prevent duplicate
                                    if ($('#'+opt.id).length > 0) {
                                        return false;
                                    }
                                    
                                }
                                
				if (typeof opt.color == 'string') {
					opt.color = HexToHSB(opt.color);
				} else if (opt.color.r != undefined && opt.color.g != undefined && opt.color.b != undefined) {
					opt.color = RGBToHSB(opt.color);
				} else if (opt.color.h != undefined && opt.color.s != undefined && opt.color.b != undefined) {
					opt.color = fixHSB(opt.color);
				} else {
					return this;
				}
				return this.each(function () {
                                    
					if (!$(this).data('colorpickerid')) {
						var options = $.extend({}, opt);
						options.origColor = opt.color;
						var id = typeof options.id !== 'undefined' ? options.id : 'colorpicker_' + parseInt(Math.random() * 1000);
						$(this).data('colorpickerid', id);
						var cal = $(tpl).attr('id', id);
                                                
                                                if (typeof options.klass !== 'undefined') {
                                                    cal.addClass(options.klass);
                                                }
                                                
						if (options.flat) {
							cal.appendTo(this).show();
						} else {
							cal.appendTo(document.body);
						}
						options.fields = cal
											.find('input')
												.bind('keyup', keyDown)
												.bind('change', change)
												.bind('blur', blur)
												.bind('focus', focus);
						cal
							.find('span').bind('mousedown', downIncrement).end()
							.find('>div.colorpicker_current_color').bind('click', restoreOriginal);
						options.selector = cal.find('div.colorpicker_color').bind('mousedown', downSelector);
						options.selectorIndic = options.selector.find('div div');
						options.el = this;
						options.hue = cal.find('div.colorpicker_hue div');
						cal.find('div.colorpicker_hue').bind('mousedown', downHue);
						options.newColor = cal.find('div.colorpicker_new_color');
						options.currentColor = cal.find('div.colorpicker_current_color');
						cal.data('colorpicker', options);
						cal.find('div.colorpicker_submit')
							.bind('mouseenter', enterSubmit)
							.bind('mouseleave', leaveSubmit)
							.bind('click', clickSubmit);
						fillRGBFields(options.color, cal.get(0));
						fillHSBFields(options.color, cal.get(0));
						fillHexFields(options.color, cal.get(0));
						setHue(options.color, cal.get(0));
						setSelector(options.color, cal.get(0));
						setCurrentColor(options.color, cal.get(0));
						setNewColor(options.color, cal.get(0));
						if (options.flat) {
							cal.css({
								position: 'relative',
								display: 'block'
							});
						} else {
							$(this).bind(options.eventName, show);
						}
					}
				});
			},
			showPicker: function() {
				return this.each( function () {
					if ($(this).data('colorpickerid')) {
						show.apply(this);
					}
				});
			},
			hidePicker: function() {
				return this.each( function () {
					if ($(this).data('colorpickerid')) {
						$('#' + $(this).data('colorpickerid')).hide();
					}
				});
			},
			setColor: function(col) {
				if (typeof col == 'string') {
					col = HexToHSB(col);
				} else if (col.r != undefined && col.g != undefined && col.b != undefined) {
					col = RGBToHSB(col);
				} else if (col.h != undefined && col.s != undefined && col.b != undefined) {
					col = fixHSB(col);
				} else {
					return this;
				}
				return this.each(function(){
					if ($(this).data('colorpickerid')) {
						var cal = $('#' + $(this).data('colorpickerid'));
						cal.data('colorpicker').color = col;
						cal.data('colorpicker').origColor = col;
						fillRGBFields(col, cal.get(0));
						fillHSBFields(col, cal.get(0));
						fillHexFields(col, cal.get(0));
						setHue(col, cal.get(0));
						setSelector(col, cal.get(0));
						setCurrentColor(col, cal.get(0));
						setNewColor(col, cal.get(0));
					}
				});
			}
		};
	}();
	$.fn.extend({
		ColorPicker: ColorPicker.init,
		ColorPickerHide: ColorPicker.hidePicker,
		ColorPickerShow: ColorPicker.showPicker,
		ColorPickerSetColor: ColorPicker.setColor
	});
})(jQuery);
// source --> http://www.kolarac.rs/wp-includes/js/jquery/ui/datepicker.min.js?ver=1.11.4 
/*!
 * jQuery UI Datepicker 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/datepicker/
 */
!function(e){"function"==typeof define&&define.amd?define(["jquery","./core"],e):e(jQuery)}(function(M){var n;function e(){this._curInst=null,this._keyEvent=!1,this._disabledInputs=[],this._datepickerShowing=!1,this._inDialog=!1,this._mainDivId="ui-datepicker-div",this._inlineClass="ui-datepicker-inline",this._appendClass="ui-datepicker-append",this._triggerClass="ui-datepicker-trigger",this._dialogClass="ui-datepicker-dialog",this._disableClass="ui-datepicker-disabled",this._unselectableClass="ui-datepicker-unselectable",this._currentClass="ui-datepicker-current-day",this._dayOverClass="ui-datepicker-days-cell-over",this.regional=[],this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:!1,hideIfNoPrevNext:!1,navigationAsDateFormat:!1,gotoCurrent:!1,changeMonth:!1,changeYear:!1,yearRange:"c-10:c+10",showOtherMonths:!1,selectOtherMonths:!1,showWeek:!1,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:!0,showButtonPanel:!1,autoSize:!1,disabled:!1},M.extend(this._defaults,this.regional[""]),this.regional.en=M.extend(!0,{},this.regional[""]),this.regional["en-US"]=M.extend(!0,{},this.regional.en),this.dpDiv=a(M("<div id='"+this._mainDivId+"' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"))}function a(e){var t="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return e.delegate(t,"mouseout",function(){M(this).removeClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&M(this).removeClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&M(this).removeClass("ui-datepicker-next-hover")}).delegate(t,"mouseover",r)}function r(){M.datepicker._isDisabledDatepicker((n.inline?n.dpDiv.parent():n.input)[0])||(M(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),M(this).addClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&M(this).addClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&M(this).addClass("ui-datepicker-next-hover"))}function c(e,t){for(var a in M.extend(e,t),t)null==t[a]&&(e[a]=t[a]);return e}return M.extend(M.ui,{datepicker:{version:"1.11.4"}}),M.extend(e.prototype,{markerClassName:"hasDatepicker",maxRows:4,_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(e){return c(this._defaults,e||{}),this},_attachDatepicker:function(e,t){var a,i=e.nodeName.toLowerCase(),s="div"===i||"span"===i;e.id||(this.uuid+=1,e.id="dp"+this.uuid),(a=this._newInst(M(e),s)).settings=M.extend({},t||{}),"input"===i?this._connectDatepicker(e,a):s&&this._inlineDatepicker(e,a)},_newInst:function(e,t){return{id:e[0].id.replace(/([^A-Za-z0-9_\-])/g,"\\\\$1"),input:e,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:t,dpDiv:t?a(M("<div class='"+this._inlineClass+" ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")):this.dpDiv}},_connectDatepicker:function(e,t){var a=M(e);t.append=M([]),t.trigger=M([]),a.hasClass(this.markerClassName)||(this._attachments(a,t),a.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp),this._autoSize(t),M.data(e,"datepicker",t),t.settings.disabled&&this._disableDatepicker(e))},_attachments:function(e,t){var a,i=this._get(t,"appendText"),s=this._get(t,"isRTL");t.append&&t.append.remove(),i&&(t.append=M("<span class='"+this._appendClass+"'>"+i+"</span>"),e[s?"before":"after"](t.append)),e.unbind("focus",this._showDatepicker),t.trigger&&t.trigger.remove(),"focus"!==(a=this._get(t,"showOn"))&&"both"!==a||e.focus(this._showDatepicker),"button"!==a&&"both"!==a||(i=this._get(t,"buttonText"),a=this._get(t,"buttonImage"),t.trigger=M(this._get(t,"buttonImageOnly")?M("<img/>").addClass(this._triggerClass).attr({src:a,alt:i,title:i}):M("<button type='button'></button>").addClass(this._triggerClass).html(a?M("<img/>").attr({src:a,alt:i,title:i}):i)),e[s?"before":"after"](t.trigger),t.trigger.click(function(){return M.datepicker._datepickerShowing&&M.datepicker._lastInput===e[0]?M.datepicker._hideDatepicker():(M.datepicker._datepickerShowing&&M.datepicker._lastInput!==e[0]&&M.datepicker._hideDatepicker(),M.datepicker._showDatepicker(e[0])),!1}))},_autoSize:function(e){var t,a,i,s,n,r;this._get(e,"autoSize")&&!e.inline&&(n=new Date(2009,11,20),(r=this._get(e,"dateFormat")).match(/[DM]/)&&(t=function(e){for(s=i=a=0;s<e.length;s++)e[s].length>a&&(a=e[s].length,i=s);return i},n.setMonth(t(this._get(e,r.match(/MM/)?"monthNames":"monthNamesShort"))),n.setDate(t(this._get(e,r.match(/DD/)?"dayNames":"dayNamesShort"))+20-n.getDay())),e.input.attr("size",this._formatDate(e,n).length))},_inlineDatepicker:function(e,t){var a=M(e);a.hasClass(this.markerClassName)||(a.addClass(this.markerClassName).append(t.dpDiv),M.data(e,"datepicker",t),this._setDate(t,this._getDefaultDate(t),!0),this._updateDatepicker(t),this._updateAlternate(t),t.settings.disabled&&this._disableDatepicker(e),t.dpDiv.css("display","block"))},_dialogDatepicker:function(e,t,a,i,s){var n,r=this._dialogInst;return r||(this.uuid+=1,n="dp"+this.uuid,this._dialogInput=M("<input type='text' id='"+n+"' style='position: absolute; top: -100px; width: 0px;'/>"),this._dialogInput.keydown(this._doKeyDown),M("body").append(this._dialogInput),(r=this._dialogInst=this._newInst(this._dialogInput,!1)).settings={},M.data(this._dialogInput[0],"datepicker",r)),c(r.settings,i||{}),t=t&&t.constructor===Date?this._formatDate(r,t):t,this._dialogInput.val(t),this._pos=s?s.length?s:[s.pageX,s.pageY]:null,this._pos||(n=document.documentElement.clientWidth,i=document.documentElement.clientHeight,t=document.documentElement.scrollLeft||document.body.scrollLeft,s=document.documentElement.scrollTop||document.body.scrollTop,this._pos=[n/2-100+t,i/2-150+s]),this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px"),r.settings.onSelect=a,this._inDialog=!0,this.dpDiv.addClass(this._dialogClass),this._showDatepicker(this._dialogInput[0]),M.blockUI&&M.blockUI(this.dpDiv),M.data(this._dialogInput[0],"datepicker",r),this},_destroyDatepicker:function(e){var t,a=M(e),i=M.data(e,"datepicker");a.hasClass(this.markerClassName)&&(t=e.nodeName.toLowerCase(),M.removeData(e,"datepicker"),"input"===t?(i.append.remove(),i.trigger.remove(),a.removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress).unbind("keyup",this._doKeyUp)):"div"!==t&&"span"!==t||a.removeClass(this.markerClassName).empty(),n===i&&(n=null))},_enableDatepicker:function(t){var e,a=M(t),i=M.data(t,"datepicker");a.hasClass(this.markerClassName)&&("input"===(e=t.nodeName.toLowerCase())?(t.disabled=!1,i.trigger.filter("button").each(function(){this.disabled=!1}).end().filter("img").css({opacity:"1.0",cursor:""})):"div"!==e&&"span"!==e||((a=a.children("."+this._inlineClass)).children().removeClass("ui-state-disabled"),a.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!1)),this._disabledInputs=M.map(this._disabledInputs,function(e){return e===t?null:e}))},_disableDatepicker:function(t){var e,a=M(t),i=M.data(t,"datepicker");a.hasClass(this.markerClassName)&&("input"===(e=t.nodeName.toLowerCase())?(t.disabled=!0,i.trigger.filter("button").each(function(){this.disabled=!0}).end().filter("img").css({opacity:"0.5",cursor:"default"})):"div"!==e&&"span"!==e||((a=a.children("."+this._inlineClass)).children().addClass("ui-state-disabled"),a.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!0)),this._disabledInputs=M.map(this._disabledInputs,function(e){return e===t?null:e}),this._disabledInputs[this._disabledInputs.length]=t)},_isDisabledDatepicker:function(e){if(!e)return!1;for(var t=0;t<this._disabledInputs.length;t++)if(this._disabledInputs[t]===e)return!0;return!1},_getInst:function(e){try{return M.data(e,"datepicker")}catch(e){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(e,t,a){var i,s,n,r,d=this._getInst(e);if(2===arguments.length&&"string"==typeof t)return"defaults"===t?M.extend({},M.datepicker._defaults):d?"all"===t?M.extend({},d.settings):this._get(d,t):null;i=t||{},"string"==typeof t&&((i={})[t]=a),d&&(this._curInst===d&&this._hideDatepicker(),s=this._getDateDatepicker(e,!0),n=this._getMinMaxDate(d,"min"),r=this._getMinMaxDate(d,"max"),c(d.settings,i),null!==n&&void 0!==i.dateFormat&&void 0===i.minDate&&(d.settings.minDate=this._formatDate(d,n)),null!==r&&void 0!==i.dateFormat&&void 0===i.maxDate&&(d.settings.maxDate=this._formatDate(d,r)),"disabled"in i&&(i.disabled?this._disableDatepicker(e):this._enableDatepicker(e)),this._attachments(M(e),d),this._autoSize(d),this._setDate(d,s),this._updateAlternate(d),this._updateDatepicker(d))},_changeDatepicker:function(e,t,a){this._optionDatepicker(e,t,a)},_refreshDatepicker:function(e){e=this._getInst(e);e&&this._updateDatepicker(e)},_setDateDatepicker:function(e,t){e=this._getInst(e);e&&(this._setDate(e,t),this._updateDatepicker(e),this._updateAlternate(e))},_getDateDatepicker:function(e,t){e=this._getInst(e);return e&&!e.inline&&this._setDateFromField(e,t),e?this._getDate(e):null},_doKeyDown:function(e){var t,a,i=M.datepicker._getInst(e.target),s=!0,n=i.dpDiv.is(".ui-datepicker-rtl");if(i._keyEvent=!0,M.datepicker._datepickerShowing)switch(e.keyCode){case 9:M.datepicker._hideDatepicker(),s=!1;break;case 13:return(a=M("td."+M.datepicker._dayOverClass+":not(."+M.datepicker._currentClass+")",i.dpDiv))[0]&&M.datepicker._selectDay(e.target,i.selectedMonth,i.selectedYear,a[0]),(t=M.datepicker._get(i,"onSelect"))?(a=M.datepicker._formatDate(i),t.apply(i.input?i.input[0]:null,[a,i])):M.datepicker._hideDatepicker(),!1;case 27:M.datepicker._hideDatepicker();break;case 33:M.datepicker._adjustDate(e.target,e.ctrlKey?-M.datepicker._get(i,"stepBigMonths"):-M.datepicker._get(i,"stepMonths"),"M");break;case 34:M.datepicker._adjustDate(e.target,e.ctrlKey?+M.datepicker._get(i,"stepBigMonths"):+M.datepicker._get(i,"stepMonths"),"M");break;case 35:(e.ctrlKey||e.metaKey)&&M.datepicker._clearDate(e.target),s=e.ctrlKey||e.metaKey;break;case 36:(e.ctrlKey||e.metaKey)&&M.datepicker._gotoToday(e.target),s=e.ctrlKey||e.metaKey;break;case 37:(e.ctrlKey||e.metaKey)&&M.datepicker._adjustDate(e.target,n?1:-1,"D"),s=e.ctrlKey||e.metaKey,e.originalEvent.altKey&&M.datepicker._adjustDate(e.target,e.ctrlKey?-M.datepicker._get(i,"stepBigMonths"):-M.datepicker._get(i,"stepMonths"),"M");break;case 38:(e.ctrlKey||e.metaKey)&&M.datepicker._adjustDate(e.target,-7,"D"),s=e.ctrlKey||e.metaKey;break;case 39:(e.ctrlKey||e.metaKey)&&M.datepicker._adjustDate(e.target,n?-1:1,"D"),s=e.ctrlKey||e.metaKey,e.originalEvent.altKey&&M.datepicker._adjustDate(e.target,e.ctrlKey?+M.datepicker._get(i,"stepBigMonths"):+M.datepicker._get(i,"stepMonths"),"M");break;case 40:(e.ctrlKey||e.metaKey)&&M.datepicker._adjustDate(e.target,7,"D"),s=e.ctrlKey||e.metaKey;break;default:s=!1}else 36===e.keyCode&&e.ctrlKey?M.datepicker._showDatepicker(this):s=!1;s&&(e.preventDefault(),e.stopPropagation())},_doKeyPress:function(e){var t,a=M.datepicker._getInst(e.target);if(M.datepicker._get(a,"constrainInput"))return t=M.datepicker._possibleChars(M.datepicker._get(a,"dateFormat")),a=String.fromCharCode(null==e.charCode?e.keyCode:e.charCode),e.ctrlKey||e.metaKey||a<" "||!t||-1<t.indexOf(a)},_doKeyUp:function(e){var t=M.datepicker._getInst(e.target);if(t.input.val()!==t.lastVal)try{M.datepicker.parseDate(M.datepicker._get(t,"dateFormat"),t.input?t.input.val():null,M.datepicker._getFormatConfig(t))&&(M.datepicker._setDateFromField(t),M.datepicker._updateAlternate(t),M.datepicker._updateDatepicker(t))}catch(e){}return!0},_showDatepicker:function(e){var t,a,i,s;"input"!==(e=e.target||e).nodeName.toLowerCase()&&(e=M("input",e.parentNode)[0]),M.datepicker._isDisabledDatepicker(e)||M.datepicker._lastInput===e||(s=M.datepicker._getInst(e),M.datepicker._curInst&&M.datepicker._curInst!==s&&(M.datepicker._curInst.dpDiv.stop(!0,!0),s&&M.datepicker._datepickerShowing&&M.datepicker._hideDatepicker(M.datepicker._curInst.input[0])),!1!==(a=(i=M.datepicker._get(s,"beforeShow"))?i.apply(e,[e,s]):{})&&(c(s.settings,a),s.lastVal=null,M.datepicker._lastInput=e,M.datepicker._setDateFromField(s),M.datepicker._inDialog&&(e.value=""),M.datepicker._pos||(M.datepicker._pos=M.datepicker._findPos(e),M.datepicker._pos[1]+=e.offsetHeight),t=!1,M(e).parents().each(function(){return!(t|="fixed"===M(this).css("position"))}),i={left:M.datepicker._pos[0],top:M.datepicker._pos[1]},M.datepicker._pos=null,s.dpDiv.empty(),s.dpDiv.css({position:"absolute",display:"block",top:"-1000px"}),M.datepicker._updateDatepicker(s),i=M.datepicker._checkOffset(s,i,t),s.dpDiv.css({position:M.datepicker._inDialog&&M.blockUI?"static":t?"fixed":"absolute",display:"none",left:i.left+"px",top:i.top+"px"}),s.inline||(a=M.datepicker._get(s,"showAnim"),i=M.datepicker._get(s,"duration"),s.dpDiv.css("z-index",function(e){for(var t,a;e.length&&e[0]!==document;){if(t=e.css("position"),("absolute"===t||"relative"===t||"fixed"===t)&&(a=parseInt(e.css("zIndex"),10),!isNaN(a)&&0!==a))return a;e=e.parent()}return 0}(M(e))+1),M.datepicker._datepickerShowing=!0,M.effects&&M.effects.effect[a]?s.dpDiv.show(a,M.datepicker._get(s,"showOptions"),i):s.dpDiv[a||"show"](a?i:null),M.datepicker._shouldFocusInput(s)&&s.input.focus(),M.datepicker._curInst=s)))},_updateDatepicker:function(e){this.maxRows=4,(n=e).dpDiv.empty().append(this._generateHTML(e)),this._attachHandlers(e);var t,a=this._getNumberOfMonths(e),i=a[1],s=e.dpDiv.find("."+this._dayOverClass+" a");0<s.length&&r.apply(s.get(0)),e.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""),1<i&&e.dpDiv.addClass("ui-datepicker-multi-"+i).css("width",17*i+"em"),e.dpDiv[(1!==a[0]||1!==a[1]?"add":"remove")+"Class"]("ui-datepicker-multi"),e.dpDiv[(this._get(e,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"),e===M.datepicker._curInst&&M.datepicker._datepickerShowing&&M.datepicker._shouldFocusInput(e)&&e.input.focus(),e.yearshtml&&(t=e.yearshtml,setTimeout(function(){t===e.yearshtml&&e.yearshtml&&e.dpDiv.find("select.ui-datepicker-year:first").replaceWith(e.yearshtml),t=e.yearshtml=null},0))},_shouldFocusInput:function(e){return e.input&&e.input.is(":visible")&&!e.input.is(":disabled")&&!e.input.is(":focus")},_checkOffset:function(e,t,a){var i=e.dpDiv.outerWidth(),s=e.dpDiv.outerHeight(),n=e.input?e.input.outerWidth():0,r=e.input?e.input.outerHeight():0,d=document.documentElement.clientWidth+(a?0:M(document).scrollLeft()),c=document.documentElement.clientHeight+(a?0:M(document).scrollTop());return t.left-=this._get(e,"isRTL")?i-n:0,t.left-=a&&t.left===e.input.offset().left?M(document).scrollLeft():0,t.top-=a&&t.top===e.input.offset().top+r?M(document).scrollTop():0,t.left-=Math.min(t.left,t.left+i>d&&i<d?Math.abs(t.left+i-d):0),t.top-=Math.min(t.top,t.top+s>c&&s<c?Math.abs(s+r):0),t},_findPos:function(e){for(var t=this._getInst(e),a=this._get(t,"isRTL");e&&("hidden"===e.type||1!==e.nodeType||M.expr.filters.hidden(e));)e=e[a?"previousSibling":"nextSibling"];return[(t=M(e).offset()).left,t.top]},_hideDatepicker:function(e){var t,a,i=this._curInst;!i||e&&i!==M.data(e,"datepicker")||this._datepickerShowing&&(t=this._get(i,"showAnim"),a=this._get(i,"duration"),e=function(){M.datepicker._tidyDialog(i)},M.effects&&(M.effects.effect[t]||M.effects[t])?i.dpDiv.hide(t,M.datepicker._get(i,"showOptions"),a,e):i.dpDiv["slideDown"===t?"slideUp":"fadeIn"===t?"fadeOut":"hide"](t?a:null,e),t||e(),this._datepickerShowing=!1,(e=this._get(i,"onClose"))&&e.apply(i.input?i.input[0]:null,[i.input?i.input.val():"",i]),this._lastInput=null,this._inDialog&&(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),M.blockUI&&(M.unblockUI(),M("body").append(this.dpDiv))),this._inDialog=!1)},_tidyDialog:function(e){e.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")},_checkExternalClick:function(e){var t;M.datepicker._curInst&&(t=M(e.target),e=M.datepicker._getInst(t[0]),(t[0].id===M.datepicker._mainDivId||0!==t.parents("#"+M.datepicker._mainDivId).length||t.hasClass(M.datepicker.markerClassName)||t.closest("."+M.datepicker._triggerClass).length||!M.datepicker._datepickerShowing||M.datepicker._inDialog&&M.blockUI)&&(!t.hasClass(M.datepicker.markerClassName)||M.datepicker._curInst===e)||M.datepicker._hideDatepicker())},_adjustDate:function(e,t,a){var i=M(e),e=this._getInst(i[0]);this._isDisabledDatepicker(i[0])||(this._adjustInstDate(e,t+("M"===a?this._get(e,"showCurrentAtPos"):0),a),this._updateDatepicker(e))},_gotoToday:function(e){var t=M(e),a=this._getInst(t[0]);this._get(a,"gotoCurrent")&&a.currentDay?(a.selectedDay=a.currentDay,a.drawMonth=a.selectedMonth=a.currentMonth,a.drawYear=a.selectedYear=a.currentYear):(e=new Date,a.selectedDay=e.getDate(),a.drawMonth=a.selectedMonth=e.getMonth(),a.drawYear=a.selectedYear=e.getFullYear()),this._notifyChange(a),this._adjustDate(t)},_selectMonthYear:function(e,t,a){var i=M(e),e=this._getInst(i[0]);e["selected"+("M"===a?"Month":"Year")]=e["draw"+("M"===a?"Month":"Year")]=parseInt(t.options[t.selectedIndex].value,10),this._notifyChange(e),this._adjustDate(i)},_selectDay:function(e,t,a,i){var s=M(e);M(i).hasClass(this._unselectableClass)||this._isDisabledDatepicker(s[0])||((s=this._getInst(s[0])).selectedDay=s.currentDay=M("a",i).html(),s.selectedMonth=s.currentMonth=t,s.selectedYear=s.currentYear=a,this._selectDate(e,this._formatDate(s,s.currentDay,s.currentMonth,s.currentYear)))},_clearDate:function(e){e=M(e);this._selectDate(e,"")},_selectDate:function(e,t){var a=M(e),e=this._getInst(a[0]);t=null!=t?t:this._formatDate(e),e.input&&e.input.val(t),this._updateAlternate(e),(a=this._get(e,"onSelect"))?a.apply(e.input?e.input[0]:null,[t,e]):e.input&&e.input.trigger("change"),e.inline?this._updateDatepicker(e):(this._hideDatepicker(),this._lastInput=e.input[0],"object"!=typeof e.input[0]&&e.input.focus(),this._lastInput=null)},_updateAlternate:function(e){var t,a,i,s=this._get(e,"altField");s&&(t=this._get(e,"altFormat")||this._get(e,"dateFormat"),a=this._getDate(e),i=this.formatDate(t,a,this._getFormatConfig(e)),M(s).each(function(){M(this).val(i)}))},noWeekends:function(e){e=e.getDay();return[0<e&&e<6,""]},iso8601Week:function(e){var t=new Date(e.getTime());return t.setDate(t.getDate()+4-(t.getDay()||7)),e=t.getTime(),t.setMonth(0),t.setDate(1),Math.floor(Math.round((e-t)/864e5)/7)+1},parseDate:function(t,s,e){if(null==t||null==s)throw"Invalid arguments";if(""===(s="object"==typeof s?s.toString():s+""))return null;function n(e){return(e=v+1<t.length&&t.charAt(v+1)===e)&&v++,e}function a(e){var t=n(e),t="@"===e?14:"!"===e?20:"y"===e&&t?4:"o"===e?3:2,t=new RegExp("^\\d{"+("y"===e?t:1)+","+t+"}");if(!(t=s.substring(l).match(t)))throw"Missing number at position "+l;return l+=t[0].length,parseInt(t[0],10)}function i(e,t,a){var i=-1,t=M.map(n(e)?a:t,function(e,t){return[[t,e]]}).sort(function(e,t){return-(e[1].length-t[1].length)});if(M.each(t,function(e,t){var a=t[1];if(s.substr(l,a.length).toLowerCase()===a.toLowerCase())return i=t[0],l+=a.length,!1}),-1!==i)return i+1;throw"Unknown name at position "+l}function r(){if(s.charAt(l)!==t.charAt(v))throw"Unexpected literal at position "+l;l++}for(var d,c,o,l=0,h=(e?e.shortYearCutoff:null)||this._defaults.shortYearCutoff,h="string"!=typeof h?h:(new Date).getFullYear()%100+parseInt(h,10),u=(e?e.dayNamesShort:null)||this._defaults.dayNamesShort,p=(e?e.dayNames:null)||this._defaults.dayNames,g=(e?e.monthNamesShort:null)||this._defaults.monthNamesShort,_=(e?e.monthNames:null)||this._defaults.monthNames,f=-1,k=-1,D=-1,m=-1,y=!1,v=0;v<t.length;v++)if(y)"'"!==t.charAt(v)||n("'")?r():y=!1;else switch(t.charAt(v)){case"d":D=a("d");break;case"D":i("D",u,p);break;case"o":m=a("o");break;case"m":k=a("m");break;case"M":k=i("M",g,_);break;case"y":f=a("y");break;case"@":f=(o=new Date(a("@"))).getFullYear(),k=o.getMonth()+1,D=o.getDate();break;case"!":f=(o=new Date((a("!")-this._ticksTo1970)/1e4)).getFullYear(),k=o.getMonth()+1,D=o.getDate();break;case"'":n("'")?r():y=!0;break;default:r()}if(l<s.length&&(c=s.substr(l),!/^\s+/.test(c)))throw"Extra/unparsed characters found in date: "+c;if(-1===f?f=(new Date).getFullYear():f<100&&(f+=(new Date).getFullYear()-(new Date).getFullYear()%100+(f<=h?0:-100)),-1<m)for(k=1,D=m;;){if(D<=(d=this._getDaysInMonth(f,k-1)))break;k++,D-=d}if((o=this._daylightSavingAdjust(new Date(f,k-1,D))).getFullYear()!==f||o.getMonth()+1!==k||o.getDate()!==D)throw"Invalid date";return o},ATOM:"yy-mm-dd",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",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:24*(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925))*60*60*1e7,formatDate:function(t,e,a){if(!e)return"";function s(e){return(e=r+1<t.length&&t.charAt(r+1)===e)&&r++,e}function i(e,t,a){var i=""+t;if(s(e))for(;i.length<a;)i="0"+i;return i}function n(e,t,a,i){return(s(e)?i:a)[t]}var r,d=(a?a.dayNamesShort:null)||this._defaults.dayNamesShort,c=(a?a.dayNames:null)||this._defaults.dayNames,o=(a?a.monthNamesShort:null)||this._defaults.monthNamesShort,l=(a?a.monthNames:null)||this._defaults.monthNames,h="",u=!1;if(e)for(r=0;r<t.length;r++)if(u)"'"!==t.charAt(r)||s("'")?h+=t.charAt(r):u=!1;else switch(t.charAt(r)){case"d":h+=i("d",e.getDate(),2);break;case"D":h+=n("D",e.getDay(),d,c);break;case"o":h+=i("o",Math.round((new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()-new Date(e.getFullYear(),0,0).getTime())/864e5),3);break;case"m":h+=i("m",e.getMonth()+1,2);break;case"M":h+=n("M",e.getMonth(),o,l);break;case"y":h+=s("y")?e.getFullYear():(e.getYear()%100<10?"0":"")+e.getYear()%100;break;case"@":h+=e.getTime();break;case"!":h+=1e4*e.getTime()+this._ticksTo1970;break;case"'":s("'")?h+="'":u=!0;break;default:h+=t.charAt(r)}return h},_possibleChars:function(t){function e(e){return(e=s+1<t.length&&t.charAt(s+1)===e)&&s++,e}for(var a="",i=!1,s=0;s<t.length;s++)if(i)"'"!==t.charAt(s)||e("'")?a+=t.charAt(s):i=!1;else switch(t.charAt(s)){case"d":case"m":case"y":case"@":a+="0123456789";break;case"D":case"M":return null;case"'":e("'")?a+="'":i=!0;break;default:a+=t.charAt(s)}return a},_get:function(e,t){return(void 0!==e.settings[t]?e.settings:this._defaults)[t]},_setDateFromField:function(e,t){if(e.input.val()!==e.lastVal){var a=this._get(e,"dateFormat"),i=e.lastVal=e.input?e.input.val():null,s=this._getDefaultDate(e),n=s,r=this._getFormatConfig(e);try{n=this.parseDate(a,i,r)||s}catch(e){i=t?"":i}e.selectedDay=n.getDate(),e.drawMonth=e.selectedMonth=n.getMonth(),e.drawYear=e.selectedYear=n.getFullYear(),e.currentDay=i?n.getDate():0,e.currentMonth=i?n.getMonth():0,e.currentYear=i?n.getFullYear():0,this._adjustInstDate(e)}},_getDefaultDate:function(e){return this._restrictMinMax(e,this._determineDate(e,this._get(e,"defaultDate"),new Date))},_determineDate:function(d,e,t){var a,i,e=null==e||""===e?t:"string"==typeof e?function(e){try{return M.datepicker.parseDate(M.datepicker._get(d,"dateFormat"),e,M.datepicker._getFormatConfig(d))}catch(e){}for(var t=(e.toLowerCase().match(/^c/)?M.datepicker._getDate(d):null)||new Date,a=t.getFullYear(),i=t.getMonth(),s=t.getDate(),n=/([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,r=n.exec(e);r;){switch(r[2]||"d"){case"d":case"D":s+=parseInt(r[1],10);break;case"w":case"W":s+=7*parseInt(r[1],10);break;case"m":case"M":i+=parseInt(r[1],10),s=Math.min(s,M.datepicker._getDaysInMonth(a,i));break;case"y":case"Y":a+=parseInt(r[1],10),s=Math.min(s,M.datepicker._getDaysInMonth(a,i))}r=n.exec(e)}return new Date(a,i,s)}(e):"number"==typeof e?isNaN(e)?t:(a=e,(i=new Date).setDate(i.getDate()+a),i):new Date(e.getTime());return(e=e&&"Invalid Date"===e.toString()?t:e)&&(e.setHours(0),e.setMinutes(0),e.setSeconds(0),e.setMilliseconds(0)),this._daylightSavingAdjust(e)},_daylightSavingAdjust:function(e){return e?(e.setHours(12<e.getHours()?e.getHours()+2:0),e):null},_setDate:function(e,t,a){var i=!t,s=e.selectedMonth,n=e.selectedYear,t=this._restrictMinMax(e,this._determineDate(e,t,new Date));e.selectedDay=e.currentDay=t.getDate(),e.drawMonth=e.selectedMonth=e.currentMonth=t.getMonth(),e.drawYear=e.selectedYear=e.currentYear=t.getFullYear(),s===e.selectedMonth&&n===e.selectedYear||a||this._notifyChange(e),this._adjustInstDate(e),e.input&&e.input.val(i?"":this._formatDate(e))},_getDate:function(e){return!e.currentYear||e.input&&""===e.input.val()?null:this._daylightSavingAdjust(new Date(e.currentYear,e.currentMonth,e.currentDay))},_attachHandlers:function(e){var t=this._get(e,"stepMonths"),a="#"+e.id.replace(/\\\\/g,"\\");e.dpDiv.find("[data-handler]").map(function(){var e={prev:function(){M.datepicker._adjustDate(a,-t,"M")},next:function(){M.datepicker._adjustDate(a,+t,"M")},hide:function(){M.datepicker._hideDatepicker()},today:function(){M.datepicker._gotoToday(a)},selectDay:function(){return M.datepicker._selectDay(a,+this.getAttribute("data-month"),+this.getAttribute("data-year"),this),!1},selectMonth:function(){return M.datepicker._selectMonthYear(a,this,"M"),!1},selectYear:function(){return M.datepicker._selectMonthYear(a,this,"Y"),!1}};M(this).bind(this.getAttribute("data-event"),e[this.getAttribute("data-handler")])})},_generateHTML:function(e){var t,a,i,s,n,r,d,c,o,l,h,u,p,g,_,f,k,D,m,y,v,M,b,w,C,I,x,Y,S,N,F,T,A=new Date,K=this._daylightSavingAdjust(new Date(A.getFullYear(),A.getMonth(),A.getDate())),j=this._get(e,"isRTL"),O=this._get(e,"showButtonPanel"),R=this._get(e,"hideIfNoPrevNext"),L=this._get(e,"navigationAsDateFormat"),W=this._getNumberOfMonths(e),E=this._get(e,"showCurrentAtPos"),A=this._get(e,"stepMonths"),H=1!==W[0]||1!==W[1],P=this._daylightSavingAdjust(e.currentDay?new Date(e.currentYear,e.currentMonth,e.currentDay):new Date(9999,9,9)),U=this._getMinMaxDate(e,"min"),z=this._getMinMaxDate(e,"max"),B=e.drawMonth-E,J=e.drawYear;if(B<0&&(B+=12,J--),z)for(t=this._daylightSavingAdjust(new Date(z.getFullYear(),z.getMonth()-W[0]*W[1]+1,z.getDate())),t=U&&t<U?U:t;this._daylightSavingAdjust(new Date(J,B,1))>t;)--B<0&&(B=11,J--);for(e.drawMonth=B,e.drawYear=J,E=this._get(e,"prevText"),E=L?this.formatDate(E,this._daylightSavingAdjust(new Date(J,B-A,1)),this._getFormatConfig(e)):E,a=this._canAdjustMonth(e,-1,J,B)?"<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click' title='"+E+"'><span class='ui-icon ui-icon-circle-triangle-"+(j?"e":"w")+"'>"+E+"</span></a>":R?"":"<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+E+"'><span class='ui-icon ui-icon-circle-triangle-"+(j?"e":"w")+"'>"+E+"</span></a>",E=this._get(e,"nextText"),E=L?this.formatDate(E,this._daylightSavingAdjust(new Date(J,B+A,1)),this._getFormatConfig(e)):E,i=this._canAdjustMonth(e,1,J,B)?"<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click' title='"+E+"'><span class='ui-icon ui-icon-circle-triangle-"+(j?"w":"e")+"'>"+E+"</span></a>":R?"":"<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+E+"'><span class='ui-icon ui-icon-circle-triangle-"+(j?"w":"e")+"'>"+E+"</span></a>",R=this._get(e,"currentText"),E=this._get(e,"gotoCurrent")&&e.currentDay?P:K,R=L?this.formatDate(R,E,this._getFormatConfig(e)):R,L=e.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(e,"closeText")+"</button>",L=O?"<div class='ui-datepicker-buttonpane ui-widget-content'>"+(j?L:"")+(this._isInRange(e,E)?"<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'>"+R+"</button>":"")+(j?"":L)+"</div>":"",s=parseInt(this._get(e,"firstDay"),10),s=isNaN(s)?0:s,n=this._get(e,"showWeek"),r=this._get(e,"dayNames"),d=this._get(e,"dayNamesMin"),c=this._get(e,"monthNames"),o=this._get(e,"monthNamesShort"),l=this._get(e,"beforeShowDay"),h=this._get(e,"showOtherMonths"),u=this._get(e,"selectOtherMonths"),p=this._getDefaultDate(e),g="",f=0;f<W[0];f++){for(k="",this.maxRows=4,D=0;D<W[1];D++){if(m=this._daylightSavingAdjust(new Date(J,B,e.selectedDay)),y=" ui-corner-all",v="",H){if(v+="<div class='ui-datepicker-group",1<W[1])switch(D){case 0:v+=" ui-datepicker-group-first",y=" ui-corner-"+(j?"right":"left");break;case W[1]-1:v+=" ui-datepicker-group-last",y=" ui-corner-"+(j?"left":"right");break;default:v+=" ui-datepicker-group-middle",y=""}v+="'>"}for(v+="<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix"+y+"'>"+(/all|left/.test(y)&&0===f?j?i:a:"")+(/all|right/.test(y)&&0===f?j?a:i:"")+this._generateMonthYearHeader(e,B,J,U,z,0<f||0<D,c,o)+"</div><table class='ui-datepicker-calendar'><thead><tr>",M=n?"<th class='ui-datepicker-week-col'>"+this._get(e,"weekHeader")+"</th>":"",_=0;_<7;_++)M+="<th scope='col'"+(5<=(_+s+6)%7?" class='ui-datepicker-week-end'":"")+"><span title='"+r[b=(_+s)%7]+"'>"+d[b]+"</span></th>";for(v+=M+"</tr></thead><tbody>",C=this._getDaysInMonth(J,B),J===e.selectedYear&&B===e.selectedMonth&&(e.selectedDay=Math.min(e.selectedDay,C)),w=(this._getFirstDayOfMonth(J,B)-s+7)%7,C=Math.ceil((w+C)/7),I=H&&this.maxRows>C?this.maxRows:C,this.maxRows=I,x=this._daylightSavingAdjust(new Date(J,B,1-w)),Y=0;Y<I;Y++){for(v+="<tr>",S=n?"<td class='ui-datepicker-week-col'>"+this._get(e,"calculateWeek")(x)+"</td>":"",_=0;_<7;_++)N=l?l.apply(e.input?e.input[0]:null,[x]):[!0,""],T=(F=x.getMonth()!==B)&&!u||!N[0]||U&&x<U||z&&z<x,S+="<td class='"+(5<=(_+s+6)%7?" ui-datepicker-week-end":"")+(F?" ui-datepicker-other-month":"")+(x.getTime()===m.getTime()&&B===e.selectedMonth&&e._keyEvent||p.getTime()===x.getTime()&&p.getTime()===m.getTime()?" "+this._dayOverClass:"")+(T?" "+this._unselectableClass+" ui-state-disabled":"")+(F&&!h?"":" "+N[1]+(x.getTime()===P.getTime()?" "+this._currentClass:"")+(x.getTime()===K.getTime()?" ui-datepicker-today":""))+"'"+(F&&!h||!N[2]?"":" title='"+N[2].replace(/'/g,"&#39;")+"'")+(T?"":" data-handler='selectDay' data-event='click' data-month='"+x.getMonth()+"' data-year='"+x.getFullYear()+"'")+">"+(F&&!h?"&#xa0;":T?"<span class='ui-state-default'>"+x.getDate()+"</span>":"<a class='ui-state-default"+(x.getTime()===K.getTime()?" ui-state-highlight":"")+(x.getTime()===P.getTime()?" ui-state-active":"")+(F?" ui-priority-secondary":"")+"' href='#'>"+x.getDate()+"</a>")+"</td>",x.setDate(x.getDate()+1),x=this._daylightSavingAdjust(x);v+=S+"</tr>"}11<++B&&(B=0,J++),k+=v+="</tbody></table>"+(H?"</div>"+(0<W[0]&&D===W[1]-1?"<div class='ui-datepicker-row-break'></div>":""):"")}g+=k}return g+=L,e._keyEvent=!1,g},_generateMonthYearHeader:function(e,t,a,i,s,n,r,d){var c,o,l,h,u,p,g,_=this._get(e,"changeMonth"),f=this._get(e,"changeYear"),k=this._get(e,"showMonthAfterYear"),D="<div class='ui-datepicker-title'>",m="";if(n||!_)m+="<span class='ui-datepicker-month'>"+r[t]+"</span>";else{for(c=i&&i.getFullYear()===a,o=s&&s.getFullYear()===a,m+="<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>",l=0;l<12;l++)(!c||l>=i.getMonth())&&(!o||l<=s.getMonth())&&(m+="<option value='"+l+"'"+(l===t?" selected='selected'":"")+">"+d[l]+"</option>");m+="</select>"}if(k||(D+=m+(!n&&_&&f?"":"&#xa0;")),!e.yearshtml)if(e.yearshtml="",n||!f)D+="<span class='ui-datepicker-year'>"+a+"</span>";else{for(h=this._get(e,"yearRange").split(":"),u=(new Date).getFullYear(),p=(r=function(e){e=e.match(/c[+\-].*/)?a+parseInt(e.substring(1),10):e.match(/[+\-].*/)?u+parseInt(e,10):parseInt(e,10);return isNaN(e)?u:e})(h[0]),g=Math.max(p,r(h[1]||"")),p=i?Math.max(p,i.getFullYear()):p,g=s?Math.min(g,s.getFullYear()):g,e.yearshtml+="<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";p<=g;p++)e.yearshtml+="<option value='"+p+"'"+(p===a?" selected='selected'":"")+">"+p+"</option>";e.yearshtml+="</select>",D+=e.yearshtml,e.yearshtml=null}return D+=this._get(e,"yearSuffix"),k&&(D+=(!n&&_&&f?"":"&#xa0;")+m),D+="</div>"},_adjustInstDate:function(e,t,a){var i=e.drawYear+("Y"===a?t:0),s=e.drawMonth+("M"===a?t:0),t=Math.min(e.selectedDay,this._getDaysInMonth(i,s))+("D"===a?t:0),t=this._restrictMinMax(e,this._daylightSavingAdjust(new Date(i,s,t)));e.selectedDay=t.getDate(),e.drawMonth=e.selectedMonth=t.getMonth(),e.drawYear=e.selectedYear=t.getFullYear(),"M"!==a&&"Y"!==a||this._notifyChange(e)},_restrictMinMax:function(e,t){var a=this._getMinMaxDate(e,"min"),e=this._getMinMaxDate(e,"max"),t=a&&t<a?a:t;return e&&e<t?e:t},_notifyChange:function(e){var t=this._get(e,"onChangeMonthYear");t&&t.apply(e.input?e.input[0]:null,[e.selectedYear,e.selectedMonth+1,e])},_getNumberOfMonths:function(e){e=this._get(e,"numberOfMonths");return null==e?[1,1]:"number"==typeof e?[1,e]:e},_getMinMaxDate:function(e,t){return this._determineDate(e,this._get(e,t+"Date"),null)},_getDaysInMonth:function(e,t){return 32-this._daylightSavingAdjust(new Date(e,t,32)).getDate()},_getFirstDayOfMonth:function(e,t){return new Date(e,t,1).getDay()},_canAdjustMonth:function(e,t,a,i){var s=this._getNumberOfMonths(e),s=this._daylightSavingAdjust(new Date(a,i+(t<0?t:s[0]*s[1]),1));return t<0&&s.setDate(this._getDaysInMonth(s.getFullYear(),s.getMonth())),this._isInRange(e,s)},_isInRange:function(e,t){var a=this._getMinMaxDate(e,"min"),i=this._getMinMaxDate(e,"max"),s=null,n=null,r=this._get(e,"yearRange");return r&&(e=r.split(":"),r=(new Date).getFullYear(),s=parseInt(e[0],10),n=parseInt(e[1],10),e[0].match(/[+\-].*/)&&(s+=r),e[1].match(/[+\-].*/)&&(n+=r)),(!a||t.getTime()>=a.getTime())&&(!i||t.getTime()<=i.getTime())&&(!s||t.getFullYear()>=s)&&(!n||t.getFullYear()<=n)},_getFormatConfig:function(e){var t=this._get(e,"shortYearCutoff");return{shortYearCutoff:t="string"!=typeof t?t:(new Date).getFullYear()%100+parseInt(t,10),dayNamesShort:this._get(e,"dayNamesShort"),dayNames:this._get(e,"dayNames"),monthNamesShort:this._get(e,"monthNamesShort"),monthNames:this._get(e,"monthNames")}},_formatDate:function(e,t,a,i){t||(e.currentDay=e.selectedDay,e.currentMonth=e.selectedMonth,e.currentYear=e.selectedYear);t=t?"object"==typeof t?t:this._daylightSavingAdjust(new Date(i,a,t)):this._daylightSavingAdjust(new Date(e.currentYear,e.currentMonth,e.currentDay));return this.formatDate(this._get(e,"dateFormat"),t,this._getFormatConfig(e))}}),M.fn.datepicker=function(e){if(!this.length)return this;M.datepicker.initialized||(M(document).mousedown(M.datepicker._checkExternalClick),M.datepicker.initialized=!0),0===M("#"+M.datepicker._mainDivId).length&&M("body").append(M.datepicker.dpDiv);var t=Array.prototype.slice.call(arguments,1);return"string"==typeof e&&("isDisabled"===e||"getDate"===e||"widget"===e)||"option"===e&&2===arguments.length&&"string"==typeof arguments[1]?M.datepicker["_"+e+"Datepicker"].apply(M.datepicker,[this[0]].concat(t)):this.each(function(){"string"==typeof e?M.datepicker["_"+e+"Datepicker"].apply(M.datepicker,[this].concat(t)):M.datepicker._attachDatepicker(this,e)})},M.datepicker=new e,M.datepicker.initialized=!1,M.datepicker.uuid=(new Date).getTime(),M.datepicker.version="1.11.4",M.datepicker});