// source --> https://junioreinsteinsscienceclub.com/wp-content/plugins/booking-events-system/assets/js/frontend.js?ver=6.7.5 
// BES Single Event Displayer

var besSingleEventDisplayer = {

    getSinglePage: function(id, occurrence, ajaxurl, layout)

    {

        if(jQuery('.bes-modal-result').length === 0) jQuery('.bes-wrap').append('<div class="bes-modal-result"></div>');

        jQuery('.bes-modal-result').addClass('bes-modal-preloader');



        jQuery.ajax(

        {

            url: ajaxurl,

            data: "action=bes_load_single_page&id="+id+(occurrence != null ? "&occurrence="+occurrence : "")+"&layout="+layout,

            type: "get",

            success: function(response)

            {

                jQuery('.bes-modal-result').removeClass("bes-modal-preloader");

                lity(response);

            },

            error: function()

            {

            }

        });

    }

};



// BES SEARCH FORM PLUGIN

(function($)

{

    $.fn.besSearchForm = function(options)

    {

        // Default Options

        var settings = $.extend(

        {

            // These are the defaults.

            id: 0,

            search_form_element: '',

            atts: '',

            callback: function()

            {

            }

        }, options);

        

        $("#bes_sf_category_"+settings.id).on('change', function(e)

        {

            search();

        });

        $("#bes_sf_location_country_"+settings.id).on('change', function(e)

        {
			var countryID = $(this).val();
			getState(countryID);
		});
		
		$("#bes_sf_location_state_"+settings.id).on('change', function(e)

        {
			search();
		});

        $("#bes_sf_location_"+settings.id).on('change', function(e)

        {

            search();

        });

        

        $("#bes_sf_organizer_"+settings.id).on('change', function(e)

        {

            search();

        });

        

        $("#bes_sf_label_"+settings.id).on('change', function(e)

        {

            search();

        });

        

        $("#bes_sf_s_"+settings.id).on('change', function(e)

        {

            search();

        });



        $("#bes_sf_month_"+settings.id).on('change', function(e)

        {

            search();

        });



        $("#bes_sf_year_"+settings.id).on('change', function(e)

        {

            // Change Month to January if it's set to ignore date and year changed

            if($("#bes_sf_month_"+settings.id).val() === 'ignore_date') $("#bes_sf_month_"+settings.id).val('01');

            

            search();

        });
		function getState(countryID,locationState=""){
			 jQuery.ajax({
				type: 'post',
				dataType: 'json',
				url: ajaxURL,
				data: {
                    action: "get_state_list",
                    countryID: countryID,
				},
				beforeSend: function(){
					jQuery("#bes_sf_location_state_"+settings.id).append("<option value=''>Loading...!!!</option>");
				},
				success: function(response){
					var len = response.length;
					jQuery("#bes_sf_location_state_"+settings.id).empty();
					jQuery("#bes_sf_location_state_"+settings.id).append("<option value=''>Location State</option>");
					for( var i = 0; i<len; i++){
						var id = response[i]['id'];
						var name = response[i]['name'];
						jQuery("#bes_sf_location_state_"+settings.id).append("<option value='"+id+"'>"+name+"</option>");
					}
					$("#bes_sf_location_state_"+settings.id +'[value='+locationState+']').attr('selected', 'true');
				},
				error: function()
				{
				}
			});
		}
        

        function search()

        {

            var s = $("#bes_sf_s_"+settings.id).length ? $("#bes_sf_s_"+settings.id).val() : '';

            var category = $("#bes_sf_category_"+settings.id).length ? $("#bes_sf_category_"+settings.id).val() : '';
			
			var location_country = $("#bes_sf_location_country_"+settings.id).length ? $("#bes_sf_location_country_"+settings.id).val() : '';
			
			var location_state = $("#bes_sf_location_state_"+settings.id).length ? $("#bes_sf_location_state_"+settings.id).val() : '';

            var location = $("#bes_sf_location_"+settings.id).length ? $("#bes_sf_location_"+settings.id).val() : '';

            var organizer = $("#bes_sf_organizer_"+settings.id).length ? $("#bes_sf_organizer_"+settings.id).val() : '';

            var label = $("#bes_sf_label_"+settings.id).length ? $("#bes_sf_label_"+settings.id).val() : '';

            var month = $("#bes_sf_month_"+settings.id).length ? $("#bes_sf_month_"+settings.id).val() : '';

            var year = $("#bes_sf_year_"+settings.id).length ? $("#bes_sf_year_"+settings.id).val() : '';

            var skip_date = false;

            

            if(month === 'ignore_date') skip_date = true;



            // Skip filter by date

            if(skip_date === true)

            {

                month = '';

                year = '';

            }

            

            var atts = settings.atts+'&sf[s]='+s+'&sf[month]='+month+'&sf[year]='+year+'&sf[category]='+category+'&sf[location_country]='+location_country+'&sf[location_state]='+location_state+'&sf[location]='+location+'&sf[organizer]='+organizer+'&sf[label]='+label;

            settings.callback(atts);
			$("#bes_sf_location_state_"+settings.id +'[value='+location_state+']').attr('selected', 'true');
			getState(location_country,locationState);
		}

    };

    

}(jQuery));



// BES GOOGLE MAPS PLUGIN

(function($)

{

    $.fn.besGoogleMaps = function(options)

    {

        // Default Options

        var settings = $.extend(

        {

            // These are the defaults.

            latitude: 0,

            longitude: 0,

            zoom: 14,

            icon: '../img/m-01.png',

            markers: {},

            sf: {},

            getDirection: 0,

            directionOptions:

            {

                form: '#bes_get_direction_form',

                reset: '.bes-map-get-direction-reset',

                addr: '#bes_get_direction_addr',

                destination: {},

            },

        }, options);

        

        // Search Widget

        if(settings.sf.container !== '')

        {

            $(settings.sf.container).besSearchForm(

            {

                id: settings.id,

                atts: settings.atts,

                callback: function(atts)

                {

                    settings.atts = atts;

                    getMarkers();

                }

            });

        }

            

        // Create the options

        var bounds = new google.maps.LatLngBounds();

        var center = new google.maps.LatLng(settings.latitude, settings.longitude);

        

        var canvas = this;

        var DOM = canvas[0];

        

	var mapOptions = {

            scrollwheel: false,

            mapTypeId: google.maps.MapTypeId.ROADMAP,

            center: center,

            zoom: settings.zoom,

            styles: settings.styles,

	};

        

	// Init map

	var map = new google.maps.Map(DOM, mapOptions);

        

        // Init Infowindow

        var infowindow = new google.maps.InfoWindow(

        {

            pixelOffset: new google.maps.Size(0, -37)

        });

        

        var loadedMarkers = new Array();

        

        // Load Markers

        loadMarkers(settings.markers);

        

        // Initialize get direction feature

        if(settings.getDirection === 1) initSimpleGetDirection();

        else if(settings.getDirection === 2) initAdvancedGetDirection();

        

        function loadMarkers(markers)

        {

            var f = 0;

            for(var i in markers)

            {

                f++;

                var dataMarker = markers[i];



                var marker = new RichMarker(

                {

                    position: new google.maps.LatLng(dataMarker.latitude, dataMarker.longitude),

                    map: map,

                    event_ids: dataMarker.event_ids,

                    infowindow: dataMarker.infowindow,

                    lightbox: dataMarker.lightbox,

                    icon: (dataMarker.icon ? dataMarker.icon : settings.icon),

                    content: '<div class="bes-marker-container"><span class="bes-marker-wrap"><span class="bes-marker">'+dataMarker.count+'</span><span class="bes-marker-pulse-wrap"><span class="bes-marker-pulse"></span></span></span></div>',

                    shadow: 'none'

                });



                // Marker Info-Window

                google.maps.event.addListener(marker, 'mouseover', function(event)

                {

                    infowindow.close();

                    infowindow.setContent(this.infowindow);

                    infowindow.open(map, this);

                });



                // Marker Lightbox

                google.maps.event.addListener(marker, 'click', function(event)

                {

                    lity(this.lightbox);

                });



                // extend the bounds to include each marker's position

                bounds.extend(marker.position);

                

                // Added to Markers

                loadedMarkers.push(marker);

            }

            

            if(f > 1) map.fitBounds(bounds);



            // Set map center if only 1 marker found

            if(f === 1)

            {

                map.setCenter(new google.maps.LatLng(dataMarker.latitude, dataMarker.longitude));

            }

        }

        

        function getMarkers()

        {

            // Add loader

            $("#bes_googlemap_canvas"+settings.id).addClass("bes-loading");

            

            $.ajax(

            {

                url: settings.ajax_url,

                data: "action=bes_map_get_markers&"+settings.atts,

                dataType: "json",

                type: "post",

                success: function(response)

                {

                    // Remove Markers

                    removeMarkers();

                    

                    // Load Markers

                    loadMarkers(response.markers);

                    

                    // Remove loader

                    $("#bes_googlemap_canvas"+settings.id).removeClass("bes-loading");

                },

                error: function()

                {

                    // Remove loader

                    $("#bes_googlemap_canvas"+settings.id).removeClass("bes-loading");

                }

            });

        }

        

        function removeMarkers()

        {

            bounds = new google.maps.LatLngBounds();

            

            if(loadedMarkers)

            {

                for(i=0; i < loadedMarkers.length; i++) loadedMarkers[i].setMap(null);

                loadedMarkers.length = 0;

            }

        }

        

        var directionsDisplay;

        var directionsService;

        var startMarker;

        var endMarker;



        function initSimpleGetDirection()

        {

            $(settings.directionOptions.form).on('submit', function(event)

            {

                event.preventDefault();



                var from = $(settings.directionOptions.addr).val();

                var dest = new google.maps.LatLng(settings.directionOptions.destination.latitude, settings.directionOptions.destination.longitude);



                // Reset the direction

                if(typeof directionsDisplay !== 'undefined')

                {

                    directionsDisplay.setMap(null);

                    startMarker.setMap(null);

                    endMarker.setMap(null);

                }



                // Fade Google Maps canvas

                $(canvas).fadeTo(300, .4);



                directionsDisplay = new google.maps.DirectionsRenderer({suppressMarkers: true});

                directionsService = new google.maps.DirectionsService();



                var request = {

                    origin: from, 

                    destination: dest,

                    travelMode: google.maps.DirectionsTravelMode.DRIVING

                };



                directionsService.route(request, function(response, status)

                {

                    if(status === google.maps.DirectionsStatus.OK)

                    {

                        directionsDisplay.setDirections(response);

                        directionsDisplay.setMap(map);



                        var leg = response.routes[0].legs[0];

                        startMarker = new google.maps.Marker(

                        {

                            position: leg.start_location,

                            map: map,

                            icon: settings.directionOptions.startMarker,

                        });



                        endMarker = new google.maps.Marker(

                        {

                            position: leg.end_location,

                            map: map,

                            icon: settings.directionOptions.endMarker,

                        });

                    }



                    // Fade Google Maps canvas

                    $(canvas).fadeTo(300, 1);

                });



                // Show reset button

                $(settings.directionOptions.reset).removeClass('bes-util-hidden');

            });



            $(settings.directionOptions.reset).on('click', function(event)

            {

                $(settings.directionOptions.addr).val('');

                $(settings.directionOptions.form).submit();



                // Hide reset button

                $(settings.directionOptions.reset).addClass('bes-util-hidden');

            });

        }



        function initAdvancedGetDirection()

        {

            $(settings.directionOptions.form).on('submit', function(event)

            {

                event.preventDefault();



                var from = $(settings.directionOptions.addr).val();

                var url = 'https://maps.google.com/?saddr='+encodeURIComponent(from)+'&daddr='+settings.directionOptions.destination.latitude+','+settings.directionOptions.destination.longitude;



                window.open(url);

            });

        }

    };

    

}(jQuery));



// BES FULL CALENDAR PLUGIN

(function($)

{

    $.fn.besFullCalendar = function(options)

    {

        // Default Options

        var settings = $.extend(

        {

            // These are the defaults.

            id: 0,

            atts: '',

            ajax_url: '',

            sf: {},

            skin: '',

        }, options);

        

        // Set onclick Listeners

        setListeners();

        

        var sf;

        function setListeners()

        {

            // Search Widget

            if(settings.sf.container !== '')

            {

                sf = $(settings.sf.container).besSearchForm(

                {

                    id: settings.id,

                    atts: settings.atts,

                    callback: function(atts)

                    {

                        settings.atts = atts;

                        search();

                    }

                });

            }

            

            // Add the onclick event

            $("#bes_skin_"+settings.id+" .bes-totalcal-box .bes-totalcal-view span").on('click', function(e)

            {

                e.preventDefault();

                var skin = $(this).data('skin');



                $(this).addClass('bes-totalcalview-selected').siblings().removeClass('bes-totalcalview-selected');

                

                loadSkin(skin);

            });

        }

        

        function loadSkin(skin)

        {

            // Set new Skin

            settings.skin = skin;

            

            // Add Loading Class

        if(jQuery('.bes-modal-result').length === 0) jQuery('.bes-wrap').append('<div class="bes-modal-result"></div>');

        jQuery('.bes-modal-result').addClass('bes-month-navigator-loading');



            $.ajax(

            {

                url: settings.ajax_url,

                data: "action=bes_full_calendar_switch_skin&skin="+skin+"&"+settings.atts+"&apply_sf_date=1&sed="+settings.sed_method,

                dataType: "json",

                type: "post",

                success: function(response)

                {

                    $("#bes_full_calendar_container_"+settings.id).html(response);

                    

                    // Remove loader

                    $('.bes-modal-result').removeClass("bes-month-navigator-loading");

                },

                error: function()

                {

                }

            });

        }

        

        function search()

        {

            // Add Loading Class

        if(jQuery('.bes-modal-result').length === 0) jQuery('.bes-wrap').append('<div class="bes-modal-result"></div>');

        jQuery('.bes-modal-result').addClass('bes-month-navigator-loading');

            

            $.ajax(

            {

                url: settings.ajax_url,

                data: "action=bes_full_calendar_switch_skin&skin="+settings.skin+"&"+settings.atts+"&apply_sf_date=1",

                dataType: "json",

                type: "post",

                success: function(response)

                {

                    $("#bes_full_calendar_container_"+settings.id).html(response);

                    

                    // Remove loader

                    $('.bes-modal-result').removeClass("bes-month-navigator-loading");

                },

                error: function()

                {

                }

            });

        }

    };

    

}(jQuery));



// BES YEARLY VIEW PLUGIN

(function($)

{

    $.fn.besYearlyView = function(options)

    {

        var active_year;



        // Default Options

        var settings = $.extend(

        {

            // These are the defaults.

            today: null,

            id: 0,

            events_label: 'Events',

            event_label: 'Event',

            year_navigator: 0,

            atts: '',

            next_year: {},

            sf: {},

            ajax_url: '',

        }, options);



        // Initialize Year Navigator

        if(settings.year_navigator) initYearNavigator();



        // Load Next Year in background

        if(settings.year_navigator) setYear(settings.next_year.year, true);



        // Set onclick Listeners

        setListeners();



        // load more

        $(document).on("click", "#bes_skin_events_"+settings.id+" .bes-load-more-button", function()

        {

            var year = $(this).parent().parent().parent().data('year-id');

            loadMoreButton(year);

        });



        // Search Widget

        if(settings.sf.container !== '')

        {

            sf = $(settings.sf.container).besSearchForm(

            {

                id: settings.id,

                atts: settings.atts,

                callback: function(atts)

                {

                    settings.atts = atts;

                    search(active_year);

                }

            });

        }



        function initYearNavigator()

        {

            // Remove the onclick event

            $("#bes_skin_"+settings.id+" .bes-load-year").off("click");



            // Add onclick event

            $("#bes_skin_"+settings.id+" .bes-load-year").on("click", function()

            {

                var year = $(this).data("bes-year");

                setYear(year);

            });

        }



        function search(year)

        {

            // Add Loading Class

            if(jQuery('.bes-modal-result').length === 0) jQuery('.bes-wrap').append('<div class="bes-modal-result"></div>');

            jQuery('.bes-modal-result').addClass('bes-month-navigator-loading');



            $.ajax(

            {

                url: settings.ajax_url,

                data: "action=bes_yearly_view_load_year&bes_year="+year+"&"+settings.atts+"&apply_sf_date=1",

                dataType: "json",

                type: "post",

                success: function(response)

                {

                    active_year = response.current_year.year;



                    // Append Year

                    $("#bes_skin_events_"+settings.id).html('<div class="bes-year-container" id="bes_yearly_view_year_'+settings.id+'_'+response.current_year.id+'" data-year-id="'+response.current_year.id+'">'+response.year+'</div>');



                    // Append Year Navigator

                    $("#bes_skin_"+settings.id+" .bes-yearly-title-sec").append('<div class="bes-year-navigator" id="bes_year_navigator_'+settings.id+'_'+response.current_year.id+'">'+response.navigator+'</div>');



                    // Re-initialize Year Navigator

                    initYearNavigator();



                    // Set onclick Listeners

                    setListeners();



                    // Toggle Year

                    toggleYear(response.current_year.id);



                    // Remove loading Class

                    $('.bes-modal-result').removeClass("bes-month-navigator-loading");

                        

                },

                error: function()

                {

                }

            });

        }



        function setYear(year, do_in_background)

        {

            if(typeof do_in_background === "undefined") do_in_background = false;



            var year_id = year;

            active_year = year;



            // Year exists so we just show it

            if($("#bes_yearly_view_year_"+settings.id+"_"+year_id).length)

            {

                // Toggle Year

                toggleYear(year_id);

            }

            else

            {

                if(!do_in_background)

                {

                    // Add Loading Class

                    if(jQuery('.bes-modal-result').length === 0) jQuery('.bes-wrap').append('<div class="bes-modal-result"></div>');

                    jQuery('.bes-modal-result').addClass('bes-month-navigator-loading');

                }



                $.ajax(

                {

                    url: settings.ajax_url,

                    data: "action=bes_yearly_view_load_year&bes_year="+year+"&"+settings.atts+"&apply_sf_date=0",

                    dataType: "json",

                    type: "post",

                    success: function(response)

                    {

                        // Append Year

                        $("#bes_skin_events_"+settings.id).append('<div class="bes-year-container" id="bes_yearly_view_year_'+settings.id+'_'+response.current_year.id+'" data-year-id="'+response.current_year.id+'">'+response.year+'</div>');



                        // Append Year Navigator

                        $("#bes_skin_"+settings.id+" .bes-yearly-title-sec").append('<div class="bes-year-navigator" id="bes_year_navigator_'+settings.id+'_'+response.current_year.id+'">'+response.navigator+'</div>');



                        // Re-initialize Year Navigator

                        initYearNavigator();



                        // Set onclick Listeners

                        setListeners();



                        if(!do_in_background)

                        {

                            // Toggle Year

                            toggleYear(response.current_year.id);



                            // Remove loading Class

                            $('.bes-modal-result').removeClass("bes-month-navigator-loading");



                            // Set Year Filter values in search widget

                            $("#bes_sf_year_"+settings.id).val(year);

                        }

                        else

                        {

                            $("#bes_yearly_view_year_"+settings.id+"_"+response.current_year.id).hide();

                            $("#bes_year_navigator_"+settings.id+"_"+response.current_year.id).hide();

                        }

                    },

                    error: function()

                    {

                    }

                });

            }

        }



        function toggleYear(year_id)

        {

            // Toggle Year Navigator

            $("#bes_skin_"+settings.id+" .bes-year-navigator").hide();

            $("#bes_year_navigator_"+settings.id+"_"+year_id).show();



            // Toggle Year

            $("#bes_skin_"+settings.id+" .bes-year-container").hide();

            $("#bes_yearly_view_year_"+settings.id+"_"+year_id).show();

        }



        var sf;

        function setListeners()

        {

            // Single Event Method

            if(settings.sed_method != '0')

            {

                sed();

            }

        }



        function sed()

        {

            // Single Event Display

            $("#bes_skin_"+settings.id+" .bes-agenda-event-title a").off('click').on('click', function(e)

            {

                e.preventDefault();

                var href = $(this).attr('href');



                var id = $(this).data('event-id');

                var occurrence = get_parameter_by_name('occurrence', href);

                besSingleEventDisplayer.getSinglePage(id, occurrence, settings.ajax_url, settings.sed_method);

            });

        }



        function loadMoreButton(year)

        {

            var $max_count, $current_count = 0;

            $max_count = $("#bes_yearly_view_year_"+settings.id+"_"+year+ " .bes-yearly-max").data('count');

            $current_count = $("#bes_yearly_view_year_"+settings.id+"_"+year+ " .bes-util-hidden").length;



            if($current_count > 10)

            {

                for(var i = 0; i < 10; i++)

                {

                    $("#bes_yearly_view_year_"+settings.id+"_"+year+ " .bes-util-hidden").slice(0, 2).each(function()

                    {

                        $(this).removeClass('bes-util-hidden');

                    });

                }

            }



            if($current_count < 10 && $current_count != 0)

            {

                for(var j = 0; j < $current_count; j++)

                {

                    $("#bes_yearly_view_year_"+settings.id+"_"+year+ " .bes-util-hidden").slice(0, 2).each(function()

                    {

                        $(this).removeClass('bes-util-hidden');

                        $("#bes_yearly_view_year_"+settings.id+"_"+year+ " .bes-load-more-wrap").css('display', 'none');

                    });

                }

            }

        }

    };



}(jQuery));



// BES MONTHLY VIEW PLUGIN

(function($)

{

    $.fn.besMonthlyView = function(options)

    {

        var active_month;

        var active_year;

        

        // Default Options

        var settings = $.extend(

        {

            // These are the defaults.

            today: null,

            id: 0,

            events_label: 'Events',

            event_label: 'Event',

            month_navigator: 0,

            atts: '',

            next_month: {},

            sf: {},

            ajax_url: '',

        }, options);



        // Initialize Month Navigator

        if(settings.month_navigator) initMonthNavigator();

        

        // Load Next Month in background

        setMonth(settings.next_month.year, settings.next_month.month, true);

        

        // Set onclick Listeners

        setListeners();

        

        // Search Widget

        if(settings.sf.container !== '')

        {

            sf = $(settings.sf.container).besSearchForm(

            {

                id: settings.id,

                atts: settings.atts,

                callback: function(atts)

                {

                    settings.atts = atts;

                    search(active_year, active_month);

                }

            });

        }

        

        function initMonthNavigator()

        {

            // Remove the onclick event

            $("#bes_skin_"+settings.id+" .bes-load-month").off("click");



            // Add onclick event

            $("#bes_skin_"+settings.id+" .bes-load-month").on("click", function()

            {

                var year = $(this).data("bes-year");

                var month = $(this).data("bes-month");



                setMonth(year, month);

            });

        }

        

        function search(year, month)

        {



            // Add Loading Class

            if(jQuery('.bes-modal-result').length === 0) jQuery('.bes-wrap').append('<div class="bes-modal-result"></div>');

            jQuery('.bes-modal-result').addClass('bes-month-navigator-loading');

            

            $.ajax(

            {

                url: settings.ajax_url,

                data: "action=bes_monthly_view_load_month&bes_year="+year+"&bes_month="+month+"&"+settings.atts+"&apply_sf_date=1",

                dataType: "json",

                type: "post",

                success: function(response)

                {

                    active_month = response.current_month.month;

                    active_year = response.current_month.year;

            

                    // Append Month

                    $("#bes_skin_events_"+settings.id).html('<div class="bes-month-container" id="bes_monthly_view_month_'+settings.id+'_'+response.current_month.id+'" data-month-id="'+response.current_month.id+'">'+response.month+'</div>');



                    // Append Month Navigator

                    $("#bes_skin_"+settings.id+" .bes-skin-monthly-view-month-navigator-container").html('<div class="bes-month-navigator" id="bes_month_navigator_'+settings.id+'_'+response.current_month.id+'">'+response.navigator+'</div>');



                    // Append Events Side

                    $("#bes_skin_"+settings.id+" .bes-calendar-events-side").html('<div class="bes-month-side" id="bes_month_side_'+settings.id+'_'+response.current_month.id+'">'+response.events_side+'</div>');



                    // Re-initialize Month Navigator

                    initMonthNavigator();



                    // Set onclick Listeners

                    setListeners();



                    // Toggle Month

                    toggleMonth(response.current_month.id);



                    // Remove loading Class

                    $('.bes-modal-result').removeClass("bes-month-navigator-loading");



                },

                error: function()

                {

                }

            });

        }

        

        function setMonth(year, month, do_in_background)

        {

            if(typeof do_in_background === "undefined") do_in_background = false;

            var month_id = year+""+month;

            

            active_month = month;

            active_year = year;

            

            // Month exists so we just show it

            if($("#bes_monthly_view_month_"+settings.id+"_"+month_id).length)

            {

                // Toggle Month

                toggleMonth(month_id);

            }

            else

            {

                if(!do_in_background)

                {



                // Add Loading Class

                if(jQuery('.bes-modal-result').length === 0) jQuery('.bes-wrap').append('<div class="bes-modal-result"></div>');

                jQuery('.bes-modal-result').addClass('bes-month-navigator-loading');

                }



                $.ajax(

                {

                    url: settings.ajax_url,

                    data: "action=bes_monthly_view_load_month&bes_year="+year+"&bes_month="+month+"&"+settings.atts+"&apply_sf_date=0",

                    dataType: "json",

                    type: "post",

                    success: function(response)

                    {

                        // Append Month

                        $("#bes_skin_events_"+settings.id).append('<div class="bes-month-container" id="bes_monthly_view_month_'+settings.id+'_'+response.current_month.id+'" data-month-id="'+response.current_month.id+'">'+response.month+'</div>');

                        

                        // Append Month Navigator

                        $("#bes_skin_"+settings.id+" .bes-skin-monthly-view-month-navigator-container").append('<div class="bes-month-navigator" id="bes_month_navigator_'+settings.id+'_'+response.current_month.id+'">'+response.navigator+'</div>');



                        // Append Events Side

                        $("#bes_skin_"+settings.id+" .bes-calendar-events-side").append('<div class="bes-month-side" id="bes_month_side_'+settings.id+'_'+response.current_month.id+'">'+response.events_side+'</div>');



                        // Re-initialize Month Navigator

                        initMonthNavigator();



                        // Set onclick Listeners

                        setListeners();



                        if(!do_in_background)

                        {

                            // Toggle Month

                            toggleMonth(response.current_month.id);



                            // Remove loading Class

                            $('.bes-modal-result').removeClass("bes-month-navigator-loading");



                            

                            // Set Month Filter values in search widget

                            $("#bes_sf_month_"+settings.id).val(month);

                            $("#bes_sf_year_"+settings.id).val(year);

                        }

                        else

                        {

                            $("#bes_monthly_view_month_"+settings.id+"_"+response.current_month.id).hide();

                            $("#bes_month_navigator_"+settings.id+"_"+response.current_month.id).hide();

                            $("#bes_month_side_"+settings.id+"_"+response.current_month.id).hide();

                        }

                    },

                    error: function()

                    {

                    }

                });

            }

        }



        function toggleMonth(month_id)

        {

            var active_month = $("#bes_skin_"+settings.id+" .bes-month-container-selected").data("month-id");

            var active_day = $("#bes_monthly_view_month_"+settings.id+"_"+active_month+" .bes-selected-day").data("day");



            if(active_day <= 9) active_day = "0"+active_day;



            // Toggle Month Navigator

            $("#bes_skin_"+settings.id+" .bes-month-navigator").hide();

            $("#bes_month_navigator_"+settings.id+"_"+month_id).show();



            // Toggle Month

            $("#bes_skin_"+settings.id+" .bes-month-container").hide();

            $("#bes_monthly_view_month_"+settings.id+"_"+month_id).show();



            // Add selected class

            $("#bes_skin_"+settings.id+" .bes-month-container").removeClass("bes-month-container-selected");

            $("#bes_monthly_view_month_"+settings.id+"_"+month_id).addClass("bes-month-container-selected");



            // Toggle Events Side

            $("#bes_skin_"+settings.id+" .bes-month-side").hide();

            $("#bes_month_side_"+settings.id+"_"+month_id).show();

        }

        

        var sf;

        function setListeners()

        {

            // Remove the onclick event

            $("#bes_skin_"+settings.id+" .bes-has-event").off("click");



            // Add the onclick event

            $("#bes_skin_"+settings.id+" .bes-has-event").on('click', function(e)

            {

                e.preventDefault();

                

                // define variables

                var $this = $(this), data_bes_cell = $this.data('bes-cell'), month_id = $this.data('month');



                $("#bes_monthly_view_month_"+settings.id+"_"+month_id+" .bes-calendar-day").removeClass('bes-selected-day');

                $this.addClass('bes-selected-day');



                $('#bes_month_side_'+settings.id+'_'+month_id+' .bes-calendar-events-sec:not([data-bes-cell=' + data_bes_cell + '])').slideUp();

                $('#bes_month_side_'+settings.id+'_'+month_id+' .bes-calendar-events-sec[data-bes-cell=' + data_bes_cell + ']').slideDown();



                $('#bes_monthly_view_month_'+settings.id+'_'+month_id+' .bes-calendar-events-sec:not([data-bes-cell=' + data_bes_cell + '])').slideUp();

                $('#bes_monthly_view_month_'+settings.id+'_'+month_id+' .bes-calendar-events-sec[data-bes-cell=' + data_bes_cell + ']').slideDown();

            });

            

            // Single Event Method

            if(settings.sed_method != '0')

            {

                sed();

            }

        }

        

        function sed()

        {

            // Single Event Display

            $("#bes_skin_"+settings.id+" .bes-event-title a").off('click').on('click', function(e)

            {

                e.preventDefault();

                var href = $(this).attr('href');



                var id = $(this).data('event-id');

                var occurrence = get_parameter_by_name('occurrence', href);

                besSingleEventDisplayer.getSinglePage(id, occurrence, settings.ajax_url, settings.sed_method);

            });

        }

    };



}(jQuery));



// BES WEEKLY VIEW PLUGIN

(function($)

{

    $.fn.besWeeklyView = function(options)

    {

        var active_year;

        var active_month;

        var active_week;

        var active_week_number;

        

        // Default Options

        var settings = $.extend(

        {

            // These are the defaults.

            today: null,

            week: 1,

            id: 0,

            changeWeekElement: '.bes-load-week',

            month_navigator: 0,

            atts: '',

            ajax_url: '',

            sf: {}

        }, options);

        

        // Search Widget

        if(settings.sf.container !== '')

        {

            $(settings.sf.container).besSearchForm(

            {

                id: settings.id,

                atts: settings.atts,

                callback: function(atts)

                {

                    settings.atts = atts;

                    search(active_year, active_month, active_week);

                }

            });

        }

            

        // Set The Week

        setThisWeek(settings.month_id+settings.week);

        

        // Set Listeners

        setListeners();

        

        // Initialize Month Navigator

        if(settings.month_navigator) initMonthNavigator(settings.month_id);

        

        function setListeners()

        {

            $(settings.changeWeekElement).off('click').on('click', function()

            {

                var week = $('#bes_skin_'+settings.id+' .bes-weekly-view-week-active').data('week-id');

                var max_weeks = $('#bes_skin_'+settings.id+' .bes-weekly-view-week-active').data('max-weeks');

                var new_week_number = active_week_number;

                

                if($(this).hasClass('bes-previous-month'))

                {

                    week = parseInt(week)-1;

                    new_week_number--;

                }

                else

                {

                    week = parseInt(week)+1;

                    new_week_number++;

                }

                

                if(new_week_number <= 1 || new_week_number >= max_weeks)

                {

                    // Disable Next/Previous Button

                    $(this).css({'opacity': .6, 'cursor': 'default'});

                    $(this).find('i').css({'opacity': .6, 'cursor': 'default'});

                }

                else

                {

                    // Enable Next/Previous Buttons

                    $('#bes_skin_'+settings.id+' .bes-load-week, #bes_skin_'+settings.id+' .bes-load-week i').css({'opacity': 1, 'cursor': 'pointer'});

                }

                

                // Week is not in valid range

                if(new_week_number === 0 || new_week_number > max_weeks)

                {

                }

                else

                {

                    setThisWeek(week);

                }

            });

            

            // Single Event Method

            if(settings.sed_method != '0')

            {

                sed();

            }

        }

        

        function setThisWeek(week)

        {

            // Week is not exists

            if(!$('#bes_weekly_view_week_'+settings.id+'_'+week).length)

            {

                return setThisWeek((parseInt(week)-1));

            }



            // Set week to active in week list

            $('#bes_skin_'+settings.id+' .bes-weekly-view-week').removeClass('bes-weekly-view-week-active');

            $('#bes_weekly_view_week_'+settings.id+'_'+week).addClass('bes-weekly-view-week-active');

            

            // Show related events

            $('#bes_skin_'+settings.id+' .bes-weekly-view-date-events').addClass('bes-util-hidden');

            $('.bes-weekly-view-week-'+settings.id+'-'+week).removeClass('bes-util-hidden');



            active_week = week;

            active_week_number = $('#bes_skin_'+settings.id+' .bes-weekly-view-week-active').data('week-number');



            $('#bes_skin_'+settings.id+' .bes-calendar-d-top').find('.bes-current-week').find('span').remove();

            $('#bes_skin_'+settings.id+' .bes-calendar-d-top').find('.bes-current-week').append('<span>'+active_week_number+'</span>');



            if(active_week_number === 1)

            {

                // Disable Previous Button

                $('#bes_skin_'+settings.id+' .bes-previous-month.bes-load-week').css({'opacity': .6, 'cursor': 'default'});

                $('#bes_skin_'+settings.id+' .bes-previous-month.bes-load-week').find('i').css({'opacity': .6, 'cursor': 'default'});

            }

        }



        function initMonthNavigator(month_id)

        {

            $('#bes_month_navigator'+settings.id+'_'+month_id+' .bes-load-month').off('click');

            $('#bes_month_navigator'+settings.id+'_'+month_id+' .bes-load-month').on('click', function()

            {

                var year = $(this).data('bes-year');

                var month = $(this).data('bes-month');



                setMonth(year, month, active_week);

            });

        }

        

        function search(year, month, week)

        {

            var week_number = (String(week).slice(-1));



                // Add Loading Class

            if(jQuery('.bes-modal-result').length === 0) jQuery('.bes-wrap').append('<div class="bes-modal-result"></div>');

            jQuery('.bes-modal-result').addClass('bes-month-navigator-loading');



            $.ajax(

            {

                url: settings.ajax_url,

                data: "action=bes_weekly_view_load_month&bes_year="+year+"&bes_month="+month+"&bes_week="+week_number+"&"+settings.atts+"&apply_sf_date=1",

                dataType: "json",

                type: "post",

                success: function(response)

                {

                    // Remove Loading Class

                    $('.bes-modal-result').removeClass("bes-month-navigator-loading");



                    // Append Month

                    $("#bes_skin_events_"+settings.id).html('<div class="bes-month-container" id="bes_weekly_view_month_'+settings.id+'_'+response.current_month.id+'">'+response.month+'</div>');



                    // Append Month Navigator

                    $("#bes_skin_"+settings.id+" .bes-skin-weekly-view-month-navigator-container").html('<div class="bes-month-navigator" id="bes_month_navigator'+settings.id+'_'+response.current_month.id+'">'+response.navigator+'</div>');



                    // Set Listeners

                    setListeners();



                    // Toggle Month

                    toggleMonth(response.current_month.id);



                    // Set active week

                    setThisWeek(response.week_id);

                },

                error: function()

                {

                }

            });

        }

        

        function setMonth(year, month, week)

        {

            var month_id = ''+year+month;

            var week_number = (String(week).slice(-1));

            

            active_month = month;

            active_year = year;



            // Month exists so we just show it

            if($("#bes_weekly_view_month_"+settings.id+"_"+month_id).length)

            {

                // Toggle Month

                toggleMonth(month_id);



                // Set active week

                setThisWeek(''+month_id+week_number);

            }

            else

            {

                // Add Loading Class

                if(jQuery('.bes-modal-result').length === 0) jQuery('.bes-wrap').append('<div class="bes-modal-result"></div>');

                jQuery('.bes-modal-result').addClass('bes-month-navigator-loading');



                $.ajax(

                {

                    url: settings.ajax_url,

                    data: "action=bes_weekly_view_load_month&bes_year="+year+"&bes_month="+month+"&bes_week="+week_number+"&"+settings.atts+"&apply_sf_date=0",

                    dataType: "json",

                    type: "post",

                    success: function(response)

                    {

                        // Remove Loading Class

                         $('.bes-modal-result').removeClass("bes-month-navigator-loading");



                        // Append Month

                        $("#bes_skin_events_"+settings.id).append('<div class="bes-month-container" id="bes_weekly_view_month_'+settings.id+'_'+response.current_month.id+'">'+response.month+'</div>');



                        // Append Month Navigator

                        $("#bes_skin_"+settings.id+" .bes-skin-weekly-view-month-navigator-container").append('<div class="bes-month-navigator" id="bes_month_navigator'+settings.id+'_'+response.current_month.id+'">'+response.navigator+'</div>');



                        // Set Listeners

                        setListeners();



                        // Toggle Month

                        toggleMonth(response.current_month.id);



                        // Set active week

                        setThisWeek(response.week_id);

                        

                        // Set Month Filter values in search widget

                        $("#bes_sf_month_"+settings.id).val(month);

                        $("#bes_sf_year_"+settings.id).val(year);

                    },

                    error: function()

                    {

                    }

                });

            }

        }



        function toggleMonth(month_id)

        {

            // Show related events

            $('#bes_skin_'+settings.id+' .bes-month-container').addClass('bes-util-hidden');

            $('#bes_weekly_view_month_'+settings.id+'_'+month_id).removeClass('bes-util-hidden');



            $('#bes_skin_'+settings.id+' .bes-month-navigator').addClass('bes-util-hidden');

            $('#bes_month_navigator'+settings.id+'_'+month_id).removeClass('bes-util-hidden');



            // Initialize Month Navigator

            if(settings.month_navigator) initMonthNavigator(month_id);

        }

        

        function sed()

        {

            // Single Event Display

            $("#bes_skin_"+settings.id+" .bes-event-title a").off('click').on('click', function(e)

            {

                e.preventDefault();

                var href = $(this).attr('href');



                var id = $(this).data('event-id');

                var occurrence = get_parameter_by_name('occurrence', href);



                besSingleEventDisplayer.getSinglePage(id, occurrence, settings.ajax_url, settings.sed_method);

            });

        }

    };

    

}(jQuery));



// BES DAILY VIEW PLUGIN

(function($)

{

    $.fn.besDailyView = function(options)

    {

        var active_month;

        var active_year;

        var active_day;

        

        // Default Options

        var settings = $.extend(

        {

            // These are the defaults.

            today: null,

            id: 0,

            changeDayElement: '.bes-daily-view-day',

            events_label: 'Events',

            event_label: 'Event',

            month_navigator: 0,

            atts: '',

            ajax_url: '',

            sf: {},

        }, options);

        

        active_month = settings.month;

        active_year = settings.year;

        active_day = settings.day;

            

        // Set Today

        setToday(settings.today);



        // Set Listeners

        setListeners();



        // Initialize Month Navigator

        if(settings.month_navigator) initMonthNavigator(settings.month_id);

        

        // Initialize Days Slider

        initDaysSlider(settings.month_id);

        

        // Search Widget

        if(settings.sf.container !== '')

        {

            $(settings.sf.container).besSearchForm(

            {

                id: settings.id,

                atts: settings.atts,

                callback: function(atts)

                {

                    settings.atts = atts;

                    search(active_year, active_month, active_day);

                }

            });

        }

        

        function setListeners()

        {

            $(settings.changeDayElement).on('click', function()

            {

                var today = $(this).data('day-id');

                setToday(today);

            });

            

            // Single Event Method

            if(settings.sed_method != '0')

            {

                sed();

            }

        }



        var current_monthday;

        function setToday(today)

        {

            // For caring about 31st, 30th and 29th of some months

            if(!$('#bes_daily_view_day'+settings.id+'_'+today).length)

            {

                setToday(parseInt(today)-1);

                return false;

            }



            // Set day to active in day list

            $('.bes-daily-view-day').removeClass('bes-daily-view-day-active bes-color');

            $('#bes_daily_view_day'+settings.id+'_'+today).addClass('bes-daily-view-day-active bes-color');



            // Show related events

            $('.bes-daily-view-date-events').addClass('bes-util-hidden');

            $('#bes_daily_view_date_events'+settings.id+'_'+today).removeClass('bes-util-hidden');



            // Set today label

            var weekday = $('#bes_daily_view_day'+settings.id+'_'+today).data('day-weekday');

            var monthday = $('#bes_daily_view_day'+settings.id+'_'+today).data('day-monthday');

            var count = $('#bes_daily_view_day'+settings.id+'_'+today).data('events-count');

            var month_id = $('#bes_daily_view_day'+settings.id+'_'+today).data('month-id');



            $('#bes_today_container'+settings.id+'_'+month_id).html('<h2>'+monthday+'</h2><h3>'+weekday+'</h3><div class="bes-today-count">'+count+' '+(count > 1 ? settings.events_label : settings.event_label)+'</div>');



            if(monthday <= 9) current_monthday = '0'+monthday;

            else current_monthday = monthday;

        }



        function initMonthNavigator(month_id)

        {

            $('#bes_month_navigator'+settings.id+'_'+month_id+' .bes-load-month').off('click');

            $('#bes_month_navigator'+settings.id+'_'+month_id+' .bes-load-month').on('click', function()

            {

                var year = $(this).data('bes-year');

                var month = $(this).data('bes-month');



                setMonth(year, month, current_monthday);

            });

        }



        function initDaysSlider(month_id, day_id)

        {

            // Init Days slider

            var owl = $("#bes-owl-calendar-d-table-"+settings.id+"-"+month_id);

            owl.owlCarousel(

            {

                items : 22, //22 items above 1000px browser width

                responsiveClass: true,

                responsive: {

                    479: {

                        items: 4,

                    },

                    767: {

                        items: 7,

                    },

                    960: {

                        items: 14,

                    },

                    1000: {

                        items: 19,

                    }

                },

                dots: false,

            });



            // Custom Navigation Events

            $("#bes_daily_view_month_"+settings.id+"_"+month_id+" .bes-table-d-next").click(function(e)

            {

                e.preventDefault();

                owl.trigger('owl.next');

            });



            $("#bes_daily_view_month_"+settings.id+"_"+month_id+" .bes-table-d-prev").click(function(e)

            {

                e.preventDefault();

                owl.trigger('owl.prev');

            });



            if(typeof day_id === 'undefined') day_id = $('.bes-daily-view-day-active').data('day-id');



            var today_str = day_id.toString().substring(6,8);

            var today_int = parseInt(today_str);



            owl.trigger('owl.goTo', [today_int]);

        }

        

        function search(year, month, day)

        {

            // Add Loading Class

            if(jQuery('.bes-modal-result').length === 0) jQuery('.bes-wrap').append('<div class="bes-modal-result"></div>');

            jQuery('.bes-modal-result').addClass('bes-month-navigator-loading');



            $.ajax(

            {

                url: settings.ajax_url,

                data: "action=bes_daily_view_load_month&bes_year="+year+"&bes_month="+month+"&bes_day="+day+"&"+settings.atts+"&apply_sf_date=1",

                dataType: "json",

                type: "post",

                success: function(response)

                {

                    // Remove Loading Class

                    $('.bes-modal-result').removeClass("bes-month-navigator-loading");



                    // Append Month

                    $("#bes_skin_events_"+settings.id).html('<div class="bes-month-container" id="bes_daily_view_month_'+settings.id+'_'+response.current_month.id+'">'+response.month+'</div>');



                    // Append Month Navigator

                    $("#bes_skin_"+settings.id+" .bes-calendar-a-month.bes-clear").html('<div class="bes-month-navigator" id="bes_month_navigator'+settings.id+'_'+response.current_month.id+'">'+response.navigator+'</div>');



                    // Set Listeners

                    setListeners();

                    

                    active_year = response.current_month.year;

                    active_month = response.current_month.month;

                    active_day = '01';

                    

                    // Toggle Month

                    toggleMonth(response.current_month.id, ''+active_year+active_month+active_day);



                    // Set Today

                    setToday(''+active_year+active_month+active_day);

                },

                error: function()

                {

                }

            });

        }

        

        function setMonth(year, month, day)

        {

            var month_id = '' + year + month;

            

            active_month = month;

            active_year = year;

            active_day = day;

            

            // Month exists so we just show it

            if($("#bes_daily_view_month_"+settings.id+"_"+month_id).length)

            {

                // Toggle Month

                toggleMonth(month_id);



                // Set Today

                setToday(''+month_id+day);

            }

            else

            {

                // Add Loading Class

                if(jQuery('.bes-modal-result').length === 0) jQuery('.bes-wrap').append('<div class="bes-modal-result"></div>');

                jQuery('.bes-modal-result').addClass('bes-month-navigator-loading');



                $.ajax(

                {

                    url: settings.ajax_url,

                    data: "action=bes_daily_view_load_month&bes_year="+year+"&bes_month="+month+"&bes_day="+day+"&"+settings.atts+"&apply_sf_date=0",

                    dataType: "json",

                    type: "post",

                    success: function(response)

                    {

                        // Remove Loading Class

                        $('.bes-modal-result').removeClass("bes-month-navigator-loading");



                        // Append Month

                        $("#bes_skin_events_"+settings.id).append('<div class="bes-month-container" id="bes_daily_view_month_'+settings.id+'_'+response.current_month.id+'">'+response.month+'</div>');



                        // Append Month Navigator

                        $("#bes_skin_"+settings.id+" .bes-calendar-a-month.bes-clear").append('<div class="bes-month-navigator" id="bes_month_navigator'+settings.id+'_'+response.current_month.id+'">'+response.navigator+'</div>');



                        // Set Listeners

                        setListeners();



                        // Toggle Month

                        toggleMonth(response.current_month.id, ''+year+month+'01');



                        // Set Today

                        setToday(''+year+month+'01');

                        

                        // Set Month Filter values in search widget

                        $("#bes_sf_month_"+settings.id).val(month);

                        $("#bes_sf_year_"+settings.id).val(year);

                    },

                    error: function()

                    {

                    }

                });

            }

        }



        function toggleMonth(month_id, day_id)

        {

            // Show related events

            $('#bes_skin_'+settings.id+' .bes-month-container').addClass('bes-util-hidden');

            $('#bes_daily_view_month_'+settings.id+'_'+month_id).removeClass('bes-util-hidden');



            $('#bes_skin_'+settings.id+' .bes-month-navigator').addClass('bes-util-hidden');

            $('#bes_month_navigator'+settings.id+'_'+month_id).removeClass('bes-util-hidden');



            // Initialize Month Navigator

            if(settings.month_navigator) initMonthNavigator(month_id);



            // Initialize Days Slider

            initDaysSlider(month_id, day_id);

        }

        

        function sed()

        {

            // Single Event Display

            $("#bes_skin_"+settings.id+" .bes-event-title a").off('click').on('click', function(e)

            {

                e.preventDefault();

                var href = $(this).attr('href');



                var id = $(this).data('event-id');

                var occurrence = get_parameter_by_name('occurrence', href);



                besSingleEventDisplayer.getSinglePage(id, occurrence, settings.ajax_url, settings.sed_method);

            });

        }

    };

    

}(jQuery));



// BES TIMETABLE PLUGIN

(function($)

{

    $.fn.besTimeTable = function(options)

    {

        var active_year;

        var active_month;

        var active_week;

        var active_week_number;

        var active_day;



        // Default Options

        var settings = $.extend(

        {

            // These are the defaults.

            today: null,

            week: 1,

            active_day: 1,

            id: 0,

            changeWeekElement: '.bes-load-week',

            month_navigator: 0,

            atts: '',

            ajax_url: '',

            sf: {}

        }, options);



        // Search Widget

        if(settings.sf.container !== '')

        {

            $(settings.sf.container).besSearchForm(

            {

                id: settings.id,

                atts: settings.atts,

                callback: function(atts)

                {

                    settings.atts = atts;

                    search(active_year, active_month, active_week, active_day);

                }

            });

        }



        // Set The Week

        setThisWeek(settings.month_id+settings.week, settings.active_day);



        // Set Listeners

        setListeners();



        // Initialize Month Navigator

        if(settings.month_navigator) initMonthNavigator(settings.month_id);



        function setListeners()

        {

            // Change Week Listener

            $(settings.changeWeekElement).off('click').on('click', function()

            {

                var week = $('#bes_skin_'+settings.id+' .bes-weekly-view-week-active').data('week-id');

                var max_weeks = $('#bes_skin_'+settings.id+' .bes-weekly-view-week-active').data('max-weeks');

                var new_week_number = active_week_number;



                if($(this).hasClass('bes-previous-month'))

                {

                    week = parseInt(week)-1;

                    new_week_number--;

                }

                else

                {

                    week = parseInt(week)+1;

                    new_week_number++;

                }



                if(new_week_number <= 1 || new_week_number >= max_weeks)

                {

                    // Disable Next/Previous Button

                    $(this).css({'opacity': .6, 'cursor': 'default'});

                    $(this).find('i').css({'opacity': .6, 'cursor': 'default'});

                }

                else

                {

                    // Enable Next/Previous Buttons

                    $('#bes_skin_'+settings.id+' .bes-load-week, #bes_skin_'+settings.id+' .bes-load-week i').css({'opacity': 1, 'cursor': 'pointer'});

                }



                // Week is not in valid range

                if(new_week_number === 0 || new_week_number > max_weeks)

                {

                }

                else

                {

                    setThisWeek(week);

                }

            });



            // Change Day Listener

            $('#bes_skin_'+settings.id+' .bes-weekly-view-week dt').not('.bes-timetable-has-no-event').off('click').on('click', function()

            {

                var day = $(this).data('date-id');

                setDay(day);

            });



            // Single Event Method

            if(settings.sed_method != '0')

            {

                sed();

            }

        }



        function setThisWeek(week, day)

        {

            // Week is not exists

            if(!$('#bes_weekly_view_week_'+settings.id+'_'+week).length)

            {

                return setThisWeek((parseInt(week)-1), day);

            }



            // Set week to active in week list

            $('#bes_skin_'+settings.id+' .bes-weekly-view-week').removeClass('bes-weekly-view-week-active');

            $('#bes_weekly_view_week_'+settings.id+'_'+week).addClass('bes-weekly-view-week-active');



            setDay(day);



            active_week = week;

            active_week_number = $('#bes_skin_'+settings.id+' .bes-weekly-view-week-active').data('week-number');



            $('#bes_skin_'+settings.id+' .bes-calendar-d-top').find('.bes-current-week').find('span').remove();

            $('#bes_skin_'+settings.id+' .bes-calendar-d-top').find('.bes-current-week').append('<span>'+active_week_number+'</span>');



            if(active_week_number === 1)

            {

                // Disable Previous Button

                $('#bes_skin_'+settings.id+' .bes-previous-month.bes-load-week').css({'opacity': .6, 'cursor': 'default'});

                $('#bes_skin_'+settings.id+' .bes-previous-month.bes-load-week').find('i').css({'opacity': .6, 'cursor': 'default'});

            }

        }



        function setDay(day)

        {

            // Find the date automatically

            if(typeof day === 'undefined')

            {

                day = $('#bes_skin_'+settings.id+' .bes-weekly-view-week-active dt').not('.bes-timetable-has-no-event').first().data('date-id');

            }



            // Activate the date element

            $('#bes_skin_'+settings.id+' dt').removeClass('bes-timetable-day-active');

            $('#bes_skin_'+settings.id+' .bes-weekly-view-week-active dt[data-date-id="'+day+'"]').addClass('bes-timetable-day-active');



            // Show related events

            $('#bes_skin_'+settings.id+' .bes-weekly-view-date-events').addClass('bes-util-hidden');

            $('#bes_weekly_view_date_events'+settings.id+'_'+day).removeClass('bes-util-hidden');

        }



        function initMonthNavigator(month_id)

        {

            $('#bes_month_navigator'+settings.id+'_'+month_id+' .bes-load-month').off('click').on('click', function()

            {

                var year = $(this).data('bes-year');

                var month = $(this).data('bes-month');



                setMonth(year, month, active_week);

            });

        }



        function search(year, month, week)

        {

            var week_number = (String(week).slice(-1));



            // Add Loading Class

            if(jQuery('.bes-modal-result').length === 0) jQuery('.bes-wrap').append('<div class="bes-modal-result"></div>');

            jQuery('.bes-modal-result').addClass('bes-month-navigator-loading');



            $.ajax(

            {

                url: settings.ajax_url,

                data: "action=bes_timetable_load_month&bes_year="+year+"&bes_month="+month+"&bes_week="+week_number+"&"+settings.atts+"&apply_sf_date=1",

                dataType: "json",

                type: "post",

                success: function(response)

                {

                    // Remove Loading Class

                    $('.bes-modal-result').removeClass("bes-month-navigator-loading");



                    // Append Month

                    $("#bes_skin_events_"+settings.id).html('<div class="bes-month-container" id="bes_timetable_month_'+settings.id+'_'+response.current_month.id+'">'+response.month+'</div>');



                    // Append Month Navigator

                    $("#bes_skin_"+settings.id+" .bes-skin-weekly-view-month-navigator-container").html('<div class="bes-month-navigator" id="bes_month_navigator'+settings.id+'_'+response.current_month.id+'">'+response.navigator+'</div>');



                    // Set Listeners

                    setListeners();



                    // Toggle Month

                    toggleMonth(response.current_month.id);



                    // Set active week

                    setThisWeek(response.week_id);

                },

                error: function()

                {

                }

            });

        }



        function setMonth(year, month, week)

        {

            var month_id = ''+year+month;

            var week_number = (String(week).slice(-1));



            active_month = month;

            active_year = year;



            // Month exists so we just show it

            if($("#bes_timetable_month_"+settings.id+"_"+month_id).length)

            {

                // Toggle Month

                toggleMonth(month_id);



                // Set active week

                setThisWeek(''+month_id+week_number);

            }

            else

            {

                // Add Loading Class

                if(jQuery('.bes-modal-result').length === 0) jQuery('.bes-wrap').append('<div class="bes-modal-result"></div>');

                jQuery('.bes-modal-result').addClass('bes-month-navigator-loading');



                $.ajax(

                {

                    url: settings.ajax_url,

                    data: "action=bes_timetable_load_month&bes_year="+year+"&bes_month="+month+"&bes_week="+week_number+"&"+settings.atts+"&apply_sf_date=0",

                    dataType: "json",

                    type: "post",

                    success: function(response)

                    {

                        // Remove Loading Class

                        $('.bes-modal-result').removeClass("bes-month-navigator-loading");



                        // Append Month

                        $("#bes_skin_events_"+settings.id).append('<div class="bes-month-container" id="bes_timetable_month_'+settings.id+'_'+response.current_month.id+'">'+response.month+'</div>');



                        // Append Month Navigator

                        $("#bes_skin_"+settings.id+" .bes-skin-weekly-view-month-navigator-container").append('<div class="bes-month-navigator" id="bes_month_navigator'+settings.id+'_'+response.current_month.id+'">'+response.navigator+'</div>');



                        // Set Listeners

                        setListeners();



                        // Toggle Month

                        toggleMonth(response.current_month.id);



                        // Set active week

                        setThisWeek(response.week_id);



                        // Set Month Filter values in search widget

                        $("#bes_sf_month_"+settings.id).val(month);

                        $("#bes_sf_year_"+settings.id).val(year);

                    },

                    error: function()

                    {

                    }

                });

            }

        }



        function toggleMonth(month_id)

        {

            // Show related events

            $('#bes_skin_'+settings.id+' .bes-month-container').addClass('bes-util-hidden');

            $('#bes_timetable_month_'+settings.id+'_'+month_id).removeClass('bes-util-hidden');



            $('#bes_skin_'+settings.id+' .bes-month-navigator').addClass('bes-util-hidden');

            $('#bes_month_navigator'+settings.id+'_'+month_id).removeClass('bes-util-hidden');



            // Initialize Month Navigator

            if(settings.month_navigator) initMonthNavigator(month_id);

        }



        function sed()

        {

            // Single Event Display

            $("#bes_skin_"+settings.id+" .bes-timetable-event-title a").off('click').on('click', function(e)

            {

                e.preventDefault();

                var href = $(this).attr('href');



                var id = $(this).data('event-id');

                var occurrence = get_parameter_by_name('occurrence', href);



                besSingleEventDisplayer.getSinglePage(id, occurrence, settings.ajax_url, settings.sed_method);

            });

        }

    };



}(jQuery));



// BES WEEKLY PROGRAM PLUGIN

(function($)

{

    $.fn.besWeeklyProgram = function(options)

    {

        // Default Options

        var settings = $.extend(

        {

            // These are the defaults.

            id: 0,

            sf: {}

        }, options);



        console.log(settings);



        // Set Listeners

        setListeners();



        function setListeners()

        {

            // Single Event Method

            if(settings.sed_method != '0')

            {

                sed();

            }

        }



        function sed()

        {

            // Single Event Display

            $("#bes_skin_"+settings.id+" .bes-event-title a").off('click').on('click', function(e)

            {

                e.preventDefault();

                var href = $(this).attr('href');



                var id = $(this).data('event-id');

                var occurrence = get_parameter_by_name('occurrence', href);



                besSingleEventDisplayer.getSinglePage(id, occurrence, settings.ajax_url, settings.sed_method);

            });

        }

    };



}(jQuery));



// BES MASONRY VIEW PLUGIN

(function($)

{

    $.fn.besMasonryView = function(options)

    {

        // Default Options

        var settings = $.extend(

        {

            // These are the defaults.

            id: 0,

            atts: '',

            ajax_url: '',

            sf: {},

            end_date: '',

            offset: 0,

            start_date: '',

        }, options);



        // Set onclick Listeners

        setListeners();



        // Init Masonry

        jQuery(window).load(function(){

            initMasonry();

        });

        function initMasonry()

        {

            var $container = $("#bes_skin_"+settings.id+" .bes-event-masonry");

            $container.isotope(

            {

                filter: '*',

                animationOptions: {

                    duration: 750,

                    easing: 'linear',

                    queue: false

                }

            });



            $("#bes_skin_"+settings.id+" .bes-events-masonry-cats a").click(function()

            {

                var selector = $(this).attr('data-filter');

                $container.isotope(

                {

                    filter: selector,

                    animationOptions: {

                        duration: 750,

                        easing: 'linear',

                        queue: false

                    }

                });



                return false;

            });



            var $optionSets = $("#bes_skin_"+settings.id+" .bes-events-masonry-cats"),

                $optionLinks = $optionSets.find('a');



            $optionLinks.click(function()

            {

                var $this = $(this);



                // don't proceed if already selected

                if($this.hasClass('selected')) return false;



                var $optionSet = $this.parents('.bes-events-masonry-cats');

                $optionSet.find('.bes-masonry-cat-selected').removeClass('bes-masonry-cat-selected');

                $this.addClass('bes-masonry-cat-selected');

            });

        }



        function setListeners()

        {

            // Single Event Method

            if(settings.sed_method != '0')

            {

                sed();

            }

        }



        function sed()

        {

            // Single Event Display

            $("#bes_skin_"+settings.id+" .bes-event-title a, #bes_skin_"+settings.id+" .bes-booking-button").off('click').on('click', function(e)

            {

                e.preventDefault();

                var href = $(this).attr('href');



                var id = $(this).data('event-id');

                var occurrence = get_parameter_by_name('occurrence', href);



                besSingleEventDisplayer.getSinglePage(id, occurrence, settings.ajax_url, settings.sed_method);

            });

        }

    };



}(jQuery));





// BES LIST VIEW PLUGIN

(function($)

{

    $.fn.besListView = function(options)

    {

        // Default Options

        var settings = $.extend(

        {

            // These are the defaults.

            id: 0,

            atts: '',

            ajax_url: '',

            sf: {},

            current_month_divider: '',

            end_date: '',

            offset: 0,

        }, options);

        

        // Set onclick Listeners

        setListeners();

        

        var sf;

        function setListeners()

        {

            // Search Widget

            if(settings.sf.container !== '')

            {

                sf = $(settings.sf.container).besSearchForm(

                {

                    id: settings.id,

                    atts: settings.atts,

                    callback: function(atts)

                    {

                        settings.atts = atts;

                        search();

                    }

                });

            }

            

            $("#bes_skin_"+settings.id+" .bes-load-more-button").on("click", function()

            {

                loadMore();

            });



            // Accordion Toggle

            $("#bes_skin_"+settings.id+" .bes-toggle-item-inner").on("click", function(event)

            {

                var $this = $(this);

                event.preventDefault();

                $(this).parent().find(".bes-content-toggle").slideToggle("fast", function()

                {

                    $this.children("i").toggleClass("bes-sl-arrow-down bes-sl-arrow-up");

                });

            });

            

            // Single Event Method

            if(settings.sed_method != '0')

            {

                sed();

            }

        }

        

        function sed()

        {

            // Single Event Display

            $("#bes_skin_"+settings.id+" .bes-event-title a, #bes_skin_"+settings.id+" .bes-booking-button, #bes_skin_"+settings.id+" .bes-detail-button").off('click').on('click', function(e)

            {

                e.preventDefault();

                var href = $(this).attr('href');



                var id = $(this).data('event-id');

                var occurrence = get_parameter_by_name('occurrence', href);



                besSingleEventDisplayer.getSinglePage(id, occurrence, settings.ajax_url, settings.sed_method);

            });

        }

        

        function loadMore()

        {

            // Add loading Class

            $("#bes_skin_"+settings.id+" .bes-load-more-button").addClass("bes-load-more-loading");



            $.ajax(

            {

                url: settings.ajax_url,

                data: "action=bes_list_load_more&bes_start_date="+settings.end_date+"&bes_offset="+settings.offset+"&"+settings.atts+"&current_month_divider="+settings.current_month_divider+"&apply_sf_date=0",

                dataType: "json",

                type: "post",

                success: function(response)

                {

                    if(response.count == "0")

                    {

                        // Remove loading Class

                        $("#bes_skin_"+settings.id+" .bes-load-more-button").removeClass("bes-load-more-loading");



                        // Hide load more button

                        $("#bes_skin_"+settings.id+" .bes-load-more-button").addClass("bes-util-hidden");

                    }

                    else

                    {

                        // Show load more button

                        $("#bes_skin_"+settings.id+" .bes-load-more-button").removeClass("bes-util-hidden");

                        

                        // Append Items

                        $("#bes_skin_events_"+settings.id).append(response.html);



                        // Remove loading Class

                        $("#bes_skin_"+settings.id+" .bes-load-more-button").removeClass("bes-load-more-loading");



                        // Update the variables

                        settings.end_date = response.end_date;

                        settings.offset = response.offset;

                        settings.current_month_divider = response.current_month_divider;

                        

                        // Single Event Method

                        if(settings.sed_method != '0')

                        {

                            sed();

                        }

                    }

                },

                error: function()

                {

                }

            });

        }

        

        function search()

        {

            // Hide no event message

            $("#bes_skin_no_events_"+settings.id).addClass("bes-util-hidden");

            

            // Add loading Class

            if(jQuery('.bes-modal-result').length === 0) jQuery('.bes-wrap').append('<div class="bes-modal-result"></div>');

            jQuery('.bes-modal-result').addClass('bes-month-navigator-loading');



            $.ajax(

            {

                url: settings.ajax_url,

                data: "action=bes_list_load_more&bes_start_date="+settings.start_date+"&"+settings.atts+"&current_month_divider=0&apply_sf_date=1",

                dataType: "json",

                type: "post",

                success: function(response)

                {

                    if(response.count == "0")

                    {

                        // Append Items

                        $("#bes_skin_events_"+settings.id).html('');

                        

                        // Remove loading Class

                        $('.bes-modal-result').removeClass("bes-month-navigator-loading");



                        // Hide it

                        $("#bes_skin_"+settings.id+" .bes-load-more-button").addClass("bes-util-hidden");

                        

                        // Show no event message

                        $("#bes_skin_no_events_"+settings.id).removeClass("bes-util-hidden");

                    }

                    else

                    {

                        // Append Items

                        $("#bes_skin_events_"+settings.id).html(response.html);



                        // Remove loading Class

                        $('.bes-modal-result').removeClass("bes-month-navigator-loading");



                        // Show load more button

                        if(response.count >= settings.limit) $("#bes_skin_"+settings.id+" .bes-load-more-button").removeClass("bes-util-hidden");

                        // Hide load more button

                        else $("#bes_skin_"+settings.id+" .bes-load-more-button").addClass("bes-util-hidden");



                        // Update the variables

                        settings.end_date = response.end_date;

            			settings.offset = response.offset;

                        settings.current_month_divider = response.current_month_divider;

                        

                        // Single Event Method

                        if(settings.sed_method != '0')

                        {

                            sed();

                        }

                    }

                },

                error: function()

                {

                }

            });

        }

    };

    

}(jQuery));



// BES GRID VIEW PLUGIN

(function($)

{

    $.fn.besGridView = function(options)

    {

        // Default Options

        var settings = $.extend(

        {

            // These are the defaults.

            id: 0,

            atts: '',

            ajax_url: '',

            sf: {},

            end_date: '',

            offset: 0,

            start_date: '',

        }, options);

        

        // Set onclick Listeners

        setListeners();

        

        var sf;

        function setListeners()

        {

            // Search Widget

            if(settings.sf.container !== '')

            {

                sf = $(settings.sf.container).besSearchForm(

                {

                    id: settings.id,

                    atts: settings.atts,

                    callback: function(atts)

                    {

                        settings.atts = atts;

                        search();

                    }

                });

            }

            

            $("#bes_skin_"+settings.id+" .bes-load-more-button").on("click", function()

            {

                loadMore();

            });

            

            // Single Event Method

            if(settings.sed_method != '0')

            {

                sed();

            }

        }

        

        function sed()

        {

            // Single Event Display

            $("#bes_skin_"+settings.id+" .bes-event-title a, #bes_skin_"+settings.id+" .bes-booking-button").off('click').on('click', function(e)

            {

                e.preventDefault();

                var href = $(this).attr('href');



                var id = $(this).data('event-id');

                var occurrence = get_parameter_by_name('occurrence', href);



                besSingleEventDisplayer.getSinglePage(id, occurrence, settings.ajax_url, settings.sed_method);

            });

        }

        

        function loadMore()

        {

            // Add loading Class

            $("#bes_skin_"+settings.id+" .bes-load-more-button").addClass("bes-load-more-loading");



            $.ajax(

            {

                url: settings.ajax_url,

                data: "action=bes_grid_load_more&bes_start_date="+settings.end_date+"&bes_offset="+settings.offset+"&"+settings.atts+"&apply_sf_date=0",

                dataType: "json",

                type: "post",

                success: function(response)

                {

                    if(response.count == "0")

                    {

                        // Remove loading Class

                        $("#bes_skin_"+settings.id+" .bes-load-more-button").removeClass("bes-load-more-loading");



                        // Hide load more button

                        $("#bes_skin_"+settings.id+" .bes-load-more-button").addClass("bes-util-hidden");

                    }

                    else

                    {

                        // Show load more button

                        $("#bes_skin_"+settings.id+" .bes-load-more-button").removeClass("bes-util-hidden");

                        

                        // Append Items

                        $("#bes_skin_events_"+settings.id).append(response.html);



                        // Remove loading Class

                        $("#bes_skin_"+settings.id+" .bes-load-more-button").removeClass("bes-load-more-loading");



                        // Update the variables

                        settings.end_date = response.end_date;

                        settings.offset = response.offset;

                        

                        // Single Event Method

                        if(settings.sed_method != '0')

                        {

                            sed();

                        }

                    }

                },

                error: function()

                {

                }

            });

        }

        

        function search()

        {

            // Hide no event message

            $("#bes_skin_no_events_"+settings.id).addClass("bes-util-hidden");

                        

            // Add loading Class

            if(jQuery('.bes-modal-result').length === 0) jQuery('.bes-wrap').append('<div class="bes-modal-result"></div>');

            jQuery('.bes-modal-result').addClass('bes-month-navigator-loading');



            $.ajax(

            {

                url: settings.ajax_url,

                data: "action=bes_grid_load_more&bes_start_date="+settings.start_date+"&"+settings.atts+"&apply_sf_date=1",

                dataType: "json",

                type: "post",

                success: function(response)

                {

                    if(response.count == "0")

                    {

                        // Append Items

                        $("#bes_skin_events_"+settings.id).html('');

                        

                        // Remove loading Class

                        $('.bes-modal-result').removeClass("bes-month-navigator-loading");



                        // Hide it

                        $("#bes_skin_"+settings.id+" .bes-load-more-button").addClass("bes-util-hidden");

                        

                        // Show no event message

                        $("#bes_skin_no_events_"+settings.id).removeClass("bes-util-hidden");

                    }

                    else

                    {

                        // Append Items

                        $("#bes_skin_events_"+settings.id).html(response.html);



                        // Remove loading Class

                        $('.bes-modal-result').removeClass("bes-month-navigator-loading");



                        // Show load more button

                        if(response.count >= settings.limit) $("#bes_skin_"+settings.id+" .bes-load-more-button").removeClass("bes-util-hidden");

                        // Hide load more button

                        else $("#bes_skin_"+settings.id+" .bes-load-more-button").addClass("bes-util-hidden");



                        // Update the variables

                        settings.end_date = response.end_date;

			            settings.offset = response.offset;

                        

                        // Single Event Method

                        if(settings.sed_method != '0')

                        {

                            sed();

                        }

                    }

                },

                error: function()

                {

                }

            });

        }

    };

    

}(jQuery));



// BES AGENDA VIEW PLUGIN

(function($)

{

    $.fn.besAgendaView = function(options)

    {

        // Default Options

        var settings = $.extend(

        {

            // These are the defaults.

            id: 0,

            atts: '',

            ajax_url: '',

            sf: {},

            current_month_divider: '',

            end_date: '',

            offset: 0,

        }, options);



        // Set onclick Listeners

        setListeners();



        var sf;

        function setListeners()

        {

            // Search Widget

            if(settings.sf.container !== '')

            {

                sf = $(settings.sf.container).besSearchForm(

                {

                    id: settings.id,

                    atts: settings.atts,

                    callback: function(atts)

                    {

                        settings.atts = atts;

                        search();

                    }

                });

            }



            $("#bes_skin_"+settings.id+" .bes-load-more-button").on("click", function()

            {

                loadMore();

            });



            // Single Event Method

            if(settings.sed_method != '0')

            {

                sed();

            }

        }



        function sed()

        {

            // Single Event Display

            $("#bes_skin_"+settings.id+" .bes-agenda-event-title a").off('click').on('click', function(e)

            {

                e.preventDefault();

                var href = $(this).attr('href');



                var id = $(this).data('event-id');

                var occurrence = get_parameter_by_name('occurrence', href);



                besSingleEventDisplayer.getSinglePage(id, occurrence, settings.ajax_url, settings.sed_method);

            });

        }



        function loadMore()

        {

            // Add loading Class

            $("#bes_skin_"+settings.id+" .bes-load-more-button").addClass("bes-load-more-loading");



            $.ajax(

            {

                url: settings.ajax_url,

                data: "action=bes_agenda_load_more&bes_start_date="+settings.end_date+"&bes_offset="+settings.offset+"&"+settings.atts+"&current_month_divider="+settings.current_month_divider+"&apply_sf_date=0",

                dataType: "json",

                type: "post",

                success: function(response)

                {

                    if(response.count == "0")

                    {

                        // Remove loading Class

                        $("#bes_skin_"+settings.id+" .bes-load-more-button").removeClass("bes-load-more-loading");



                        // Hide load more button

                        $("#bes_skin_"+settings.id+" .bes-load-more-button").addClass("bes-util-hidden");

                    }

                    else

                    {

                        // Show load more button

                        $("#bes_skin_"+settings.id+" .bes-load-more-button").removeClass("bes-util-hidden");



                        // Append Items

                        $("#bes_skin_events_"+settings.id+" .bes-events-agenda-container").append(response.html);



                        // Remove loading Class

                        $("#bes_skin_"+settings.id+" .bes-load-more-button").removeClass("bes-load-more-loading");



                        // Update the variables

                        settings.end_date = response.end_date;

                        settings.offset = response.offset;

                        settings.current_month_divider = response.current_month_divider;



                        // Single Event Method

                        if(settings.sed_method != '0')

                        {

                            sed();

                        }

                    }

                },

                error: function()

                {

                }

            });

        }



        function search()

        {

            // Hide no event message

            $("#bes_skin_no_events_"+settings.id).addClass("bes-util-hidden");



            // Add loading Class

            if(jQuery('.bes-modal-result').length === 0) jQuery('.bes-wrap').append('<div class="bes-modal-result"></div>');

            jQuery('.bes-modal-result').addClass('bes-month-navigator-loading');



            $.ajax(

            {

                url: settings.ajax_url,

                data: "action=bes_agenda_load_more&bes_start_date="+settings.start_date+"&"+settings.atts+"&current_month_divider=0&apply_sf_date=1",

                dataType: "json",

                type: "post",

                success: function(response)

                {

                    if(response.count == "0")

                    {

                        // Append Items

                        $("#bes_skin_events_"+settings.id+" .bes-events-agenda-container").html('');



                        // Remove loading Class

                        $('.bes-modal-result').removeClass("bes-month-navigator-loading");

                    

                        // Hide it

                        $("#bes_skin_"+settings.id+" .bes-load-more-button").addClass("bes-util-hidden");



                        // Show no event message

                        $("#bes_skin_no_events_"+settings.id).removeClass("bes-util-hidden");

                    }

                    else

                    {

                        // Append Items

                        $("#bes_skin_events_"+settings.id+" .bes-events-agenda-container").html(response.html);



                        // Remove loading Class

                        $('.bes-modal-result').removeClass("bes-month-navigator-loading");



                        // Show load more button

                        if(response.count >= settings.limit) $("#bes_skin_"+settings.id+" .bes-load-more-button").removeClass("bes-util-hidden");

                        // Hide load more button

                        else $("#bes_skin_"+settings.id+" .bes-load-more-button").addClass("bes-util-hidden");



                        // Update the variables

                        settings.end_date = response.end_date;

                        settings.offset = response.offset;

                        settings.current_month_divider = response.current_month_divider;



                        // Single Event Method

                        if(settings.sed_method != '0')

                        {

                            sed();

                        }

                    }

                },

                error: function()

                {

                }

            });

        }

    };

}(jQuery));



// BES CAROUSEL VIEW PLUGIN

(function($)

{

    $.fn.besCarouselView = function(options)

    {

        // Default Options

        var settings = $.extend(

        {

            // These are the defaults.

            id: 0,

            atts: '',

            ajax_url: '',

            sf: {},

            items: 3,

            autoplay:'',

            style: 'type1',

            start_date: ''

        }, options);

        

        // Init Sliders

        initSlider();

        

        function initSlider()

        {

            if(settings.style === 'type1')

            {

                // Start carousel skin

                var owl = $("#bes_skin_"+settings.id+" .bes-event-carousel-type1 .bes-owl-carousel");



                owl.owlCarousel(

                {

                    autoplay: true,

                    autoplayTimeout: settings.autoplay, // Set AutoPlay to 3 seconds

                    items: settings.items,

                    responsiveClass: true,

                    responsive: {

                        0: {

                            items: 1,

                        },

                        979: {

                            items: 2,

                        },

                        1199: {

                            items: settings.count,

                        }

                    },

                    dots: true,

                    nav: false,

                    autoplayHoverPause:true

                });

            }

            else

            {

                $("#bes_skin_"+settings.id+" .bes-owl-carousel").owlCarousel(

                {

                    autoplay: true,

                    autoplayTimeout: settings.autoplay,

                    items: settings.items,

                    dots: false,

                    nav: true,

                    responsiveClass: true,

                    responsive: {

                        0: {

                            items: 1,

                        },

                        979: {

                            items: 2,

                        },

                        1199: {

                            items: settings.count,

                        }

                    },

                    autoplayHoverPause:true,

                    navText: ["<i class='bes-sl-arrow-left'></i>"," <i class='bes-sl-arrow-right'></i>"],

                });

            }

        }

    };

    

}(jQuery));



// BES SLIDER VIEW PLUGIN

(function($)

{

    $.fn.besSliderView = function(options)

    {

        // Default Options

        var settings = $.extend(

        {

            // These are the defaults.

            id: 0,

            atts: '',

            autoplay: false,

            ajax_url: '',

            sf: {},

            start_date: ''

        }, options);



        // Init Sliders

        initSlider();

        function initSlider()

        {

            $("#bes_skin_"+settings.id+" .bes-owl-carousel").owlCarousel(

            {

                autoplay: true,

                autoplayTimeout: settings.autoplay,

                items: 1,

                responsiveClass: true,

                responsive: {

                    0: {

                        items: 1,

                    },

                    960: {

                        items: 1,

                    },

                    1200: {

                        items: 1,

                    }

                },

                dots: false,

                nav: true,

                autoplayHoverPause: true,

                navText: ["<i class='bes-sl-arrow-left'></i>", " <i class='bes-sl-arrow-right'></i>"],

            });

        }

    };



}(jQuery));



// BES COUNTDOWN MODULE

(function($)

{

    $.fn.besCountDown = function(options, callBack)

    {

        // Default Options

        var settings = $.extend(

        {

            // These are the defaults.

            date: null,

            format: null

        }, options);



        var callback = callBack;

        var selector = $(this);

        

        startCountdown();

        var interval = setInterval(startCountdown, 1000);

        

        function startCountdown()

        {

            var eventDate = Date.parse(settings.date) / 1000;

            var currentDate = Math.floor($.now() / 1000);



            if(eventDate <= currentDate)

            {

                callback.call(this);

                clearInterval(interval);

            }



            var seconds = eventDate - currentDate;



            var days = Math.floor(seconds / (60 * 60 * 24)); 

            seconds -= days * 60 * 60 * 24; 



            var hours = Math.floor(seconds / (60 * 60));

            seconds -= hours * 60 * 60; 



            var minutes = Math.floor(seconds / 60);

            seconds -= minutes * 60;

            

            if(days == 1) selector.find(".bes-timeRefDays").text(besdata.day);

            else selector.find(".bes-timeRefDays").text(besdata.days);

            

            if(hours == 1) selector.find(".bes-timeRefHours").text(besdata.hour);

            else selector.find(".bes-timeRefHours").text(besdata.hours);

            

            if(minutes == 1) selector.find(".bes-timeRefMinutes").text(besdata.minute);

            else selector.find(".bes-timeRefMinutes").text(besdata.minutes);

            

            if(seconds == 1) selector.find(".bes-timeRefSeconds").text(besdata.second);

            else selector.find(".bes-timeRefSeconds").text(besdata.seconds);



            if(settings.format === "on")

            {

                days = (String(days).length >= 2) ? days : "0" + days;

                hours = (String(hours).length >= 2) ? hours : "0" + hours;

                minutes = (String(minutes).length >= 2) ? minutes : "0" + minutes;

                seconds = (String(seconds).length >= 2) ? seconds : "0" + seconds;

            }



            if(!isNaN(eventDate))

            {

                selector.find(".bes-days").text(days);

                selector.find(".bes-hours").text(hours);

                selector.find(".bes-minutes").text(minutes);

                selector.find(".bes-seconds").text(seconds);

            }

            else

            {

                clearInterval(interval);

            }

        }

    };

    

}(jQuery));



function bes_gateway_selected(gateway_id)

{

    // Hide all gateway forms

    jQuery('.bes-book-form-gateway-checkout').addClass('bes-util-hidden');

    

    // Show selected gateway form

    jQuery('#bes_book_form_gateway_checkout'+gateway_id).removeClass('bes-util-hidden');

}



function bes_wrap_resize()

{

    var $bes_wrap = jQuery('.bes-wrap'), bes_width = $bes_wrap.width();

    if(bes_width < 959)

    {

        $bes_wrap.addClass('bes-sm959');

    }

    else

    {

        $bes_wrap.removeClass('bes-sm959');

    }

}



function get_parameter_by_name(name, url)

{

    if(!url)

    {

        url = window.location.href;

    }

    

    name = name.replace(/[\[\]]/g, "\\$&");

    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),

        results = regex.exec(url);



    if(!results) return null;

    if(!results[2]) return '';

    

    return decodeURIComponent(results[2].replace(/\+/g, " "));

}



// TODO must be cleaned JS codes

(function($)

{

    $(document).ready(function()

    {

        // BES WIDGET CAROUSEL

        $(".bes-widget .bes-event-grid-classic").addClass('bes-owl-carousel bes-owl-theme');

        $(".bes-widget .bes-event-grid-classic").owlCarousel(

        {

            autoplay: true,

            autoplayTimeout: 3000, // Set AutoPlay to 3 seconds

            autoplayHoverPause: true,

            dots: false,

            nav: true,

            navText: ["<i class='bes-sl-arrow-left'></i>", " <i class='bes-sl-arrow-right'></i>"],

            items: 1,

            autoHeight: true,

            responsiveClass: true,

        });

        

        // add bes-sm959 class if bes-wrap div size < 959

        bes_wrap_resize();

        

        jQuery(window).bind('resize', function()

        {

            bes_wrap_resize();

        });



        // Fixed: social hover in iphone

        $('.bes-event-sharing-wrap').hover(function()

        {

            $(this).find('.bes-event-sharing').show(0);

        },

        function()

        {

            $(this).find('.bes-event-sharing').hide(0);

        });



        // Register Booking Smooth Scroll

        $('a[href="#bes-events-meta-group-booking"]').click(function()

        {

            if(location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname)

            {

                var target = $(this.hash);

                target = target.length ? target : $('[name=' + this.hash.slice(1) +']');



                if(target.length)

                {

                    var scrollTopVal = target.offset().top - 30;



                    $('html, body').animate(

                    {

                        scrollTop: scrollTopVal

                    }, 600);



                    return false;

                }

            }

        });

    });

})(jQuery);
// source --> https://junioreinsteinsscienceclub.com/wp-content/plugins/booking-events-system/assets/js/events.js?ver=6.7.5 
jQuery(document).ready(function($)

{

    // Image picker on terms menu

    $('.bes_upload_image_button').click(function(event)

    {

        event.preventDefault();

        

        var frame;

        if(frame)

        {

            frame.open();

            return;

        }



        frame = wp.media();

        frame.on('select', function()

        {

            // Grab the selected attachment.

            var attachment = frame.state().get('selection').first();



            $('#bes_thumbnail_img').html('<img src="'+attachment.attributes.url+'" />');

            $('#bes_thumbnail').val(attachment.attributes.url);

            

            $('.bes_remove_image_button').toggleClass('bes-util-hidden');

            

            frame.close();

        });

        

        frame.open();

    });

    

    // Image remover on terms menu

    $('.bes_remove_image_button').click(function(event)

    {

        event.preventDefault();

        

        $('#bes_thumbnail_img').html('');

        $('#bes_thumbnail').val('');

        

        $('.bes_remove_image_button').toggleClass('bes-util-hidden');

    });

    

    // Image picker on add event menu for location

    $('.bes_location_upload_image_button').click(function(event)

    {

        event.preventDefault();

        

        var frame;

        if(frame)

        {

            frame.open();

            return;

        }



        frame = wp.media();

        frame.on('select', function()

        {

            // Grab the selected attachment.

            var attachment = frame.state().get('selection').first();



            $('#bes_location_thumbnail_img').html('<img src="'+attachment.attributes.url+'" />');

            $('#bes_location_thumbnail').val(attachment.attributes.url);

            

            $('.bes_location_remove_image_button').toggleClass('bes-util-hidden');

            

            frame.close();

        });

        

        frame.open();

    });

    

    // Image remover on add event menu for location

    $('.bes_location_remove_image_button').click(function(event)

    {

        event.preventDefault();

        

        $('#bes_location_thumbnail_img').html('');

        $('#bes_location_thumbnail').val('');

        

        $('.bes_location_remove_image_button').toggleClass('bes-util-hidden');

    });

    

    // Image picker on add event menu for organizer

    $('.bes_organizer_upload_image_button').click(function(event)

    {

        event.preventDefault();

        

        var frame;

        if(frame)

        {

            frame.open();

            return;

        }



        frame = wp.media();

        frame.on('select', function()

        {

            // Grab the selected attachment.

            var attachment = frame.state().get('selection').first();



            $('#bes_organizer_thumbnail_img').html('<img src="'+attachment.attributes.url+'" />');

            $('#bes_organizer_thumbnail').val(attachment.attributes.url);

            

            $('.bes_organizer_remove_image_button').toggleClass('bes-util-hidden');

            

            frame.close();

        });

        

        frame.open();

    });

    

    // Image remover on add event menu for organizer

    $('.bes_organizer_remove_image_button').click(function(event)

    {

        event.preventDefault();

        

        $('#bes_organizer_thumbnail_img').html('');

        $('#bes_organizer_thumbnail').val('');

        

        $('.bes_organizer_remove_image_button').toggleClass('bes-util-hidden');

    });

    

    // Image remover on frontend event submission menu

    $('#bes_fes_remove_image_button').click(function(event)

    {

        event.preventDefault();

        

        $('#bes_fes_thumbnail_img').html('');

        $('#bes_fes_thumbnail').val('');

        $('#bes_featured_image_file').val('');

        

        $('#bes_fes_remove_image_button').addClass('bes-util-hidden');

    });

    

    // Location Image remover on frontend event submission menu

    $('#bes_fes_location_remove_image_button').click(function(event)

    {

        event.preventDefault();

        

        $('#bes_fes_location_thumbnail_img').html('');

        $('#bes_fes_location_thumbnail').val('');

        $('#bes_fes_location_thumbnail_file').val('');

        

        $('#bes_fes_location_remove_image_button').addClass('bes-util-hidden');

    });

    

    // Organizer Image remover on frontend event submission menu

    $('#bes_fes_organizer_remove_image_button').click(function(event)

    {

        event.preventDefault();

        

        $('#bes_fes_organizer_thumbnail_img').html('');

        $('#bes_fes_organizer_thumbnail').val('');

        $('#bes_fes_organizer_thumbnail_file').val('');

        

        $('#bes_fes_organizer_remove_image_button').addClass('bes-util-hidden');

    });

    

    $('#bes_start_date').datepicker(

    {

        changeYear: true,

        changeMonth: true,

        dateFormat: 'yy-mm-dd',

        gotoCurrent: true,

        yearRange: 'c-3:c+5',

    });

    

    $('#bes_end_date').datepicker(

    {

        changeYear: true,

        changeMonth: true,

        dateFormat: 'yy-mm-dd',

        gotoCurrent: true,

        yearRange: 'c-3:c+5',

    });

    

    $('#bes_date_repeat_end_at_date').datepicker(

    {

        changeYear: true,

        changeMonth: true,

        dateFormat: 'yy-mm-dd',

        gotoCurrent: true,

        yearRange: 'c-3:c+5',

    });

    

    $('.bes_date_picker').datepicker(

    {

        changeYear: true,

        changeMonth: true,

        dateFormat: 'yy-mm-dd',

        gotoCurrent: true,

        yearRange: 'c-3:c+5',

    });

    

    $('#bes_location_id').on('change', function()

    {

        bes_location_toggle();

    });

    

    $('#bes_organizer_id').on('change', function()

    {

        bes_organizer_toggle();

    });

    

    bes_location_toggle();

    bes_organizer_toggle()

    

    $('#bes_repeat').on('change', function()

    {

        bes_repeat_toggle();

    });

    

    bes_repeat_toggle();

    

    $('#bes_repeat_type').on('change', function()

    {

        bes_repeat_type_toggle();

    });

    

    bes_repeat_type_toggle();

    

    $('#bes_bookings_limit_unlimited').on('change', function()

    {

        bes_bookings_unlimited_toggle();

    });

    

    $('#bes_add_in_days').on('click', function()

    {

        var date = $('#bes_exceptions_in_days_date').val();

        if(date === '') return false;

        

        var key = $('#bes_new_in_days_key').val();

        var html = $('#bes_new_in_days_raw').html().replace(/:i:/g, key).replace(/:val:/g, date);

        

        $('#bes_in_days').append(html);

        $('#bes_new_in_days_key').val(parseInt(key)+1);

    });

    

    $('#bes_add_not_in_days').on('click', function()

    {

        var date = $('#bes_exceptions_not_in_days_date').val();

        if(date === '') return false;

        

        var key = $('#bes_new_not_in_days_key').val();

        var html = $('#bes_new_not_in_days_raw').html().replace(/:i:/g, key).replace(/:val:/g, date);

        

        $('#bes_not_in_days').append(html);

        $('#bes_new_not_in_days_key').val(parseInt(key)+1);

    });

    

    $('#bes_add_ticket_button').on('click', function()

    {

        var key = $('#bes_new_ticket_key').val();

        var html = $('#bes_new_ticket_raw').html().replace(/:i:/g, key);

        

        $('#bes_tickets').append(html);

        $('#bes_new_ticket_key').val(parseInt(key)+1);

    });

    

    $('#bes_add_time_slot_button').on('click', function()

    {

        var key = $('#bes_new_timeslot_schedule_key').val();

        var html = $('#bes_new_timeslot_schedule_raw').html().replace(/:i:/g, key);

        

        $('#bes_timeslot_schedules').append(html);

        $('#bes_new_timeslot_schedule_key').val(parseInt(key)+1);

    });
	
	$('#bes_add_hourly_schedule_button').on('click', function()

    {

        var key = $('#bes_new_hourly_schedule_key').val();

        var html = $('#bes_new_hourly_schedule_raw').html().replace(/:i:/g, key);

        

        $('#bes_hourly_schedules').append(html);

        $('#bes_new_hourly_schedule_key').val(parseInt(key)+1);

    });

    

    $('#bes_add_fee_button').on('click', function()

    {

        var key = $('#bes_new_fee_key').val();

        var html = $('#bes_new_fee_raw').html().replace(/:i:/g, key);

        

        $('#bes_fees_list').append(html);

        $('#bes_new_fee_key').val(parseInt(key)+1);

    });

    

    $('.bes-form-row.bes-available-color-row span').on('click', function()

    {

        $('.bes-form-row.bes-available-color-row span').removeClass('color-selected');

        $(this).addClass('color-selected');

    });



    $('#bes_reg_form_field_types button').on('click', function()

    {

        var type = $(this).data('type');

        var key = $('#bes_new_reg_field_key').val();

        var html = $('#bes_reg_field_'+type).html().replace(/:i:/g, key);



        $('#bes_reg_form_fields').append(html);

        $('#bes_new_reg_field_key').val(parseInt(key)+1);



        // Set onclick listener for add option fields

        bes_reg_fields_option_listeners();

    });



    // Set onclick listener for add option fields

    bes_reg_fields_option_listeners();

});



function bes_location_toggle()

{

    if(jQuery('#bes_location_id').val() != '0') jQuery('#bes_location_new_container').hide();

    else jQuery('#bes_location_new_container').show();

}



function bes_organizer_toggle()

{

    if(jQuery('#bes_organizer_id').val() != '0') jQuery('#bes_organizer_new_container').hide();

    else jQuery('#bes_organizer_new_container').show();

}



function bes_repeat_toggle()

{

    if(jQuery('#bes_repeat').is(':checked')) jQuery('.bes-form-repeating-event-row').show();

    else jQuery('.bes-form-repeating-event-row').hide();

}



function bes_repeat_type_toggle()

{

    var repeat_type = jQuery('#bes_repeat_type').val();

    

    if(repeat_type == 'certain_weekdays')

    {

        jQuery('#bes_repeat_interval_container').hide();

        jQuery('#bes_repeat_certain_weekdays_container').show();

        jQuery('#bes_exceptions_in_days_container').hide();

    }

    else if(repeat_type == 'custom_days')

    {

        jQuery('#bes_repeat_interval_container').hide();

        jQuery('#bes_repeat_certain_weekdays_container').hide();

        jQuery('#bes_exceptions_in_days_container').show();

    }

    else if(repeat_type != 'daily' && repeat_type != 'weekly')

    {

        jQuery('#bes_repeat_interval_container').hide();

        jQuery('#bes_repeat_certain_weekdays_container').hide();

        jQuery('#bes_exceptions_in_days_container').hide();

    }

    else

    {

        jQuery('#bes_repeat_interval_container').show();

        jQuery('#bes_repeat_certain_weekdays_container').hide();

        jQuery('#bes_exceptions_in_days_container').hide();

    }

}



function bes_in_days_remove(i)

{

    jQuery('#bes_in_days_row'+i).remove();

}



function bes_not_in_days_remove(i)

{

    jQuery('#bes_not_in_days_row'+i).remove();

}



function bes_bookings_unlimited_toggle()

{

    jQuery('#bes_bookings_limit').toggleClass('bes-util-hidden');

}



function bes_hourly_schedule_remove(i)

{

    jQuery("#bes_hourly_schedule_row"+i).remove();

}

function bes_timeslot_schedule_remove(i)

{

    jQuery("#bes_timeslot_schedule_row"+i).remove();

}



function bes_ticket_remove(i)

{

    jQuery("#bes_ticket_row"+i).remove();

}



function bes_set_event_color(color)

{

    try

    {

        jQuery("#bes_event_color").wpColorPicker('color', '#'+color);

    }

    catch(e)

    {

        jQuery("#bes_event_color").val(color);

    }

}



function bes_remove_fee(key)

{

    jQuery("#bes_fee_row"+key).remove();

}



function bes_reg_fields_option_listeners()

{

    jQuery('button.bes-reg-field-add-option').on('click', function()

    {

        var field_id = jQuery(this).data('field-id');

        var key = jQuery('#bes_new_reg_field_option_key_'+field_id).val();

        var html = jQuery('#bes_reg_field_option').html().replace(/:i:/g, key).replace(/:fi:/g, field_id);



        jQuery('#bes_reg_fields_'+field_id+'_options_container').append(html);

        jQuery('#bes_new_reg_field_option_key_'+field_id).val(parseInt(key)+1);

    });



    if(typeof jQuery.fn.sortable !== 'undefined')

    {

        jQuery("#bes_reg_form_fields").sortable(

        {

            handle: '.bes_reg_field_sort'

        });



        jQuery(".bes_reg_fields_options_container").sortable(

        {

            handle: '.bes_reg_field_option_sort'

        });

    }

}



function bes_reg_fields_option_remove(field_key, key)

{

    jQuery("#bes_reg_fields_option_"+field_key+"_"+key).remove();

};
// source --> https://junioreinsteinsscienceclub.com/wp-content/plugins/booking-events-system/assets/packages/lity/lity.min.js?ver=6.7.5 
/*! Lity - v2.1.0 - 2016-09-19
* http://sorgalla.com/lity/
* Copyright (c) 2015-2016 Jan Sorgalla; Licensed MIT */
!function(a,b){"function"==typeof define&&define.amd?define(["jquery"],function(c){return b(a,c)}):"object"==typeof module&&"object"==typeof module.exports?module.exports=b(a,require("jquery")):a.lity=b(a,a.jQuery||a.Zepto)}("undefined"!=typeof window?window:this,function(a,b){"use strict";function c(a){var b=A();return L&&a.length?(a.one(L,b.resolve),setTimeout(b.resolve,500)):b.resolve(),b.promise()}function d(a,c,d){if(1===arguments.length)return b.extend({},a);if("string"==typeof c){if("undefined"==typeof d)return"undefined"==typeof a[c]?null:a[c];a[c]=d}else b.extend(a,c);return this}function e(a){for(var b,c=decodeURI(a.split("#")[0]).split("&"),d={},e=0,f=c.length;e<f;e++)c[e]&&(b=c[e].split("="),d[b[0]]=b[1]);return d}function f(a,c){return a+(a.indexOf("?")>-1?"&":"?")+b.param(c)}function g(a,b){var c=a.indexOf("#");return-1===c?b:(c>0&&(a=a.substr(c)),b+a)}function h(a){return b('<span class="lity-error"/>').append(a)}function i(a,c){var d=c.opener()&&c.opener().data("lity-desc")||"Image with no description",e=b('<img src="'+a+'" alt="'+d+'"/>'),f=A(),g=function(){f.reject(h("Failed loading image"))};return e.on("load",function(){return 0===this.naturalWidth?g():void f.resolve(e)}).on("error",g),f.promise()}function j(a,c){var d,e,f;try{d=b(a)}catch(a){return!1}return!!d.length&&(e=b('<i style="display:none !important"/>'),f=d.hasClass("lity-hide"),c.element().one("lity:remove",function(){e.before(d).remove(),f&&!d.closest(".lity-content").length&&d.addClass("lity-hide")}),d.removeClass("lity-hide").after(e))}function k(a){var c=I.exec(a);return!!c&&n(g(a,f("https://www.youtube"+(c[2]||"")+".com/embed/"+c[4],b.extend({autoplay:1},e(c[5]||"")))))}function l(a){var c=J.exec(a);return!!c&&n(g(a,f("https://player.vimeo.com/video/"+c[3],b.extend({autoplay:1},e(c[4]||"")))))}function m(a){var b=K.exec(a);return!!b&&n(g(a,f("https://www.google."+b[3]+"/maps?"+b[6],{output:b[6].indexOf("layer=c")>0?"svembed":"embed"})))}function n(a){return'<div class="lity-iframe-container"><iframe frameborder="0" allowfullscreen src="'+a+'"/></div>'}function o(){return y.documentElement.clientHeight?y.documentElement.clientHeight:Math.round(z.height())}function p(a){var b=u();b&&(27===a.keyCode&&b.close(),9===a.keyCode&&q(a,b))}function q(a,b){var c=b.element().find(F),d=c.index(y.activeElement);a.shiftKey&&d<=0?(c.get(c.length-1).focus(),a.preventDefault()):a.shiftKey||d!==c.length-1||(c.get(0).focus(),a.preventDefault())}function r(){b.each(C,function(a,b){b.resize()})}function s(a){1===C.unshift(a)&&(B.addClass("lity-active"),z.on({resize:r,keydown:p})),b("body > *").not(a.element()).addClass("lity-hidden").each(function(){var a=b(this);void 0===a.data(E)&&a.data(E,a.attr(D)||null)}).attr(D,"true")}function t(a){var c;a.element().attr(D,"true"),1===C.length&&(B.removeClass("lity-active"),z.off({resize:r,keydown:p})),C=b.grep(C,function(b){return a!==b}),c=C.length?C[0].element():b(".lity-hidden"),c.removeClass("lity-hidden").each(function(){var a=b(this),c=a.data(E);c?a.attr(D,c):a.removeAttr(D),a.removeData(E)})}function u(){return 0===C.length?null:C[0]}function v(a,c,d,e){var f,g="inline",h=b.extend({},d);return e&&h[e]?(f=h[e](a,c),g=e):(b.each(["inline","iframe"],function(a,b){delete h[b],h[b]=d[b]}),b.each(h,function(b,d){return!d||(!(!d.test||d.test(a,c))||(f=d(a,c),!1!==f?(g=b,!1):void 0))})),{handler:g,content:f||""}}function w(a,e,f,g){function h(a){k=b(a).css("max-height",o()+"px"),j.find(".lity-loader").each(function(){var a=b(this);c(a).always(function(){a.remove()})}),j.removeClass("lity-loading").find(".lity-content").empty().append(k),m=!0,k.trigger("lity:ready",[l])}var i,j,k,l=this,m=!1,n=!1;e=b.extend({},G,e),j=b(e.template),l.element=function(){return j},l.opener=function(){return f},l.options=b.proxy(d,l,e),l.handlers=b.proxy(d,l,e.handlers),l.resize=function(){m&&!n&&k.css("max-height",o()+"px").trigger("lity:resize",[l])},l.close=function(){if(m&&!n){n=!0,t(l);var a=A();return g&&b.contains(j,y.activeElement)&&g.focus(),k.trigger("lity:close",[l]),j.removeClass("lity-opened").addClass("lity-closed"),c(k.add(j)).always(function(){k.trigger("lity:remove",[l]),j.remove(),j=void 0,a.resolve()}),a.promise()}},i=v(a,l,e.handlers,e.handler),j.attr(D,"false").addClass("lity-loading lity-opened lity-"+i.handler).appendTo("body").focus().on("click","[data-lity-close]",function(a){b(a.target).is("[data-lity-close]")&&l.close()}).trigger("lity:open",[l]),s(l),b.when(i.content).always(h)}function x(a,c,d){a.preventDefault?(a.preventDefault(),d=b(this),a=d.data("lity-target")||d.attr("href")||d.attr("src")):d=b(d);var e=new w(a,b.extend({},d.data("lity-options")||d.data("lity"),c),d,y.activeElement);if(!a.preventDefault)return e}var y=a.document,z=b(a),A=b.Deferred,B=b("html"),C=[],D="aria-hidden",E="lity-"+D,F='a[href],area[href],input:not([disabled]),select:not([disabled]),textarea:not([disabled]),button:not([disabled]),iframe,object,embed,[contenteditable],[tabindex]:not([tabindex^="-"])',G={handler:null,handlers:{image:i,inline:j,youtube:k,vimeo:l,googlemaps:m,iframe:n},template:'<div class="lity" role="dialog" aria-label="Dialog Window (Press escape to close)" tabindex="-1"><div class="lity-wrap" data-lity-close role="document"><div class="lity-loader" aria-hidden="true">Loading...</div><div class="lity-container"><div class="lity-content"></div><button class="lity-close" type="button" aria-label="Close (Press escape to close)" data-lity-close>&times;</button></div></div></div>'},H=/(^data:image\/)|(\.(png|jpe?g|gif|svg|webp|bmp|ico|tiff?)(\?\S*)?$)/i,I=/(youtube(-nocookie)?\.com|youtu\.be)\/(watch\?v=|v\/|u\/|embed\/?)?([\w-]{11})(.*)?/i,J=/(vimeo(pro)?.com)\/(?:[^\d]+)?(\d+)\??(.*)?$/,K=/((maps|www)\.)?google\.([^\/\?]+)\/?((maps\/?)?\?)(.*)/i,L=function(){var a=y.createElement("div"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return b[c];return!1}();return i.test=function(a){return H.test(a)},x.version="2.1.0",x.options=b.proxy(d,x,G),x.handlers=b.proxy(d,x,G.handlers),x.current=u,b(y).on("click.lity","[data-lity]",x),x});
// source --> https://junioreinsteinsscienceclub.com/wp-content/plugins/booking-events-system/assets/packages/owl-carousel/owl.carousel.min.js?ver=6.7.5 
/**
 * Owl Carousel v2.2.1
 * Copyright 2013-2017 David Deutsch
 * Licensed under  ()
 */
/**
 * Owl carousel
 * @version 2.1.6
 * @author Bartosz Wojciechowski
 * @author David Deutsch
 * @license The MIT License (MIT)
 * @todo Lazy Load Icon
 * @todo prevent animationend bubling
 * @todo itemsScaleUp
 * @todo Test Zepto
 * @todo stagePadding calculate wrong active classes
 */
; (function ($, window, document, undefined) {

	/**
	 * Creates a carousel.
	 * @class The Owl Carousel.
	 * @public
	 * @param {HTMLElement|jQuery} element - The element to create the carousel for.
	 * @param {Object} [options] - The options
	 */
    function Owl(element, options) {

		/**
		 * Current settings for the carousel.
		 * @public
		 */
        this.settings = null;

		/**
		 * Current options set by the caller including defaults.
		 * @public
		 */
        this.options = $.extend({}, Owl.Defaults, options);

		/**
		 * Plugin element.
		 * @public
		 */
        this.$element = $(element);

		/**
		 * Proxied event handlers.
		 * @protected
		 */
        this._handlers = {};

		/**
		 * References to the running plugins of this carousel.
		 * @protected
		 */
        this._plugins = {};

		/**
		 * Currently suppressed events to prevent them from beeing retriggered.
		 * @protected
		 */
        this._supress = {};

		/**
		 * Absolute current position.
		 * @protected
		 */
        this._current = null;

		/**
		 * Animation speed in milliseconds.
		 * @protected
		 */
        this._speed = null;

		/**
		 * Coordinates of all items in pixel.
		 * @todo The name of this member is missleading.
		 * @protected
		 */
        this._coordinates = [];

		/**
		 * Current breakpoint.
		 * @todo Real media queries would be nice.
		 * @protected
		 */
        this._breakpoint = null;

		/**
		 * Current width of the plugin element.
		 */
        this._width = null;

		/**
		 * All real items.
		 * @protected
		 */
        this._items = [];

		/**
		 * All cloned items.
		 * @protected
		 */
        this._clones = [];

		/**
		 * Merge values of all items.
		 * @todo Maybe this could be part of a plugin.
		 * @protected
		 */
        this._mergers = [];

		/**
		 * Widths of all items.
		 */
        this._widths = [];

		/**
		 * Invalidated parts within the update process.
		 * @protected
		 */
        this._invalidated = {};

		/**
		 * Ordered list of workers for the update process.
		 * @protected
		 */
        this._pipe = [];

		/**
		 * Current state information for the drag operation.
		 * @todo #261
		 * @protected
		 */
        this._drag = {
            time: null,
            target: null,
            pointer: null,
            stage: {
                start: null,
                current: null
            },
            direction: null
        };

		/**
		 * Current state information and their tags.
		 * @type {Object}
		 * @protected
		 */
        this._states = {
            current: {},
            tags: {
                'initializing': ['busy'],
                'animating': ['busy'],
                'dragging': ['interacting']
            }
        };

        $.each(['onResize', 'onThrottledResize'], $.proxy(function (i, handler) {
            this._handlers[handler] = $.proxy(this[handler], this);
        }, this));

        $.each(Owl.Plugins, $.proxy(function (key, plugin) {
            this._plugins[key.charAt(0).toLowerCase() + key.slice(1)]
                = new plugin(this);
        }, this));

        $.each(Owl.Workers, $.proxy(function (priority, worker) {
            this._pipe.push({
                'filter': worker.filter,
                'run': $.proxy(worker.run, this)
            });
        }, this));

        this.setup();
        this.initialize();
    }

	/**
	 * Default options for the carousel.
	 * @public
	 */
    Owl.Defaults = {
        items: 3,
        loop: false,
        center: false,
        rewind: false,

        mouseDrag: true,
        touchDrag: true,
        pullDrag: true,
        freeDrag: false,

        margin: 0,
        stagePadding: 0,

        merge: false,
        mergeFit: true,
        autoWidth: false,

        startPosition: 0,
        rtl: false,

        smartSpeed: 250,
        fluidSpeed: false,
        dragEndSpeed: false,

        responsive: {},
        responsiveRefreshRate: 200,
        responsiveBaseElement: window,

        fallbackEasing: 'swing',

        info: false,

        nestedItemSelector: false,
        itemElement: 'div',
        stageElement: 'div',

        refreshClass: 'owl-refresh',
        loadedClass: 'owl-loaded',
        loadingClass: 'owl-loading',
        rtlClass: 'owl-rtl',
        responsiveClass: 'owl-responsive',
        dragClass: 'owl-drag',
        itemClass: 'owl-item',
        stageClass: 'owl-stage',
        stageOuterClass: 'owl-stage-outer',
        grabClass: 'owl-grab'
    };

	/**
	 * Enumeration for width.
	 * @public
	 * @readonly
	 * @enum {String}
	 */
    Owl.Width = {
        Default: 'default',
        Inner: 'inner',
        Outer: 'outer'
    };

	/**
	 * Enumeration for types.
	 * @public
	 * @readonly
	 * @enum {String}
	 */
    Owl.Type = {
        Event: 'event',
        State: 'state'
    };

	/**
	 * Contains all registered plugins.
	 * @public
	 */
    Owl.Plugins = {};

	/**
	 * List of workers involved in the update process.
	 */
    Owl.Workers = [{
        filter: ['width', 'settings'],
        run: function () {
            this._width = this.$element.width();
        }
    }, {
        filter: ['width', 'items', 'settings'],
        run: function (cache) {
            cache.current = this._items && this._items[this.relative(this._current)];
        }
    }, {
        filter: ['items', 'settings'],
        run: function () {
            this.$stage.children('.cloned').remove();
        }
    }, {
        filter: ['width', 'items', 'settings'],
        run: function (cache) {
            var margin = this.settings.margin || '',
                grid = !this.settings.autoWidth,
                rtl = this.settings.rtl,
                css = {
                    'width': 'auto',
                    'margin-left': rtl ? margin : '',
                    'margin-right': rtl ? '' : margin
                };

            !grid && this.$stage.children().css(css);

            cache.css = css;
        }
    }, {
        filter: ['width', 'items', 'settings'],
        run: function (cache) {
            var width = (this.width() / this.settings.items).toFixed(3) - this.settings.margin,
                merge = null,
                iterator = this._items.length,
                grid = !this.settings.autoWidth,
                widths = [];

            cache.items = {
                merge: false,
                width: width
            };

            while (iterator--) {
                merge = this._mergers[iterator];
                merge = this.settings.mergeFit && Math.min(merge, this.settings.items) || merge;

                cache.items.merge = merge > 1 || cache.items.merge;

                widths[iterator] = !grid ? this._items[iterator].width() : width * merge;
            }

            this._widths = widths;
        }
    }, {
        filter: ['items', 'settings'],
        run: function () {
            var clones = [],
                items = this._items,
                settings = this.settings,
                // TODO: Should be computed from number of min width items in stage
                view = Math.max(settings.items * 2, 4),
                size = Math.ceil(items.length / 2) * 2,
                repeat = settings.loop && items.length ? settings.rewind ? view : Math.max(view, size) : 0,
                append = '',
                prepend = '';

            repeat /= 2;

            while (repeat--) {
                // Switch to only using appended clones
                clones.push(this.normalize(clones.length / 2, true));
                append = append + items[clones[clones.length - 1]][0].outerHTML;
                clones.push(this.normalize(items.length - 1 - (clones.length - 1) / 2, true));
                prepend = items[clones[clones.length - 1]][0].outerHTML + prepend;
            }

            this._clones = clones;

            $(append).addClass('cloned').appendTo(this.$stage);
            $(prepend).addClass('cloned').prependTo(this.$stage);
        }
    }, {
        filter: ['width', 'items', 'settings'],
        run: function () {
            var rtl = this.settings.rtl ? 1 : -1,
                size = this._clones.length + this._items.length,
                iterator = -1,
                previous = 0,
                current = 0,
                coordinates = [];

            while (++iterator < size) {
                previous = coordinates[iterator - 1] || 0;
                current = this._widths[this.relative(iterator)] + this.settings.margin;
                coordinates.push(previous + current * rtl);
            }

            this._coordinates = coordinates;
        }
    }, {
        filter: ['width', 'items', 'settings'],
        run: function () {
            var padding = this.settings.stagePadding,
                coordinates = this._coordinates,
                css = {
                    'width': Math.ceil(Math.abs(coordinates[coordinates.length - 1])) + padding * 2,
                    'padding-left': padding || '',
                    'padding-right': padding || ''
                };

            this.$stage.css(css);
        }
    }, {
        filter: ['width', 'items', 'settings'],
        run: function (cache) {
            var iterator = this._coordinates.length,
                grid = !this.settings.autoWidth,
                items = this.$stage.children();

            if (grid && cache.items.merge) {
                while (iterator--) {
                    cache.css.width = this._widths[this.relative(iterator)];
                    items.eq(iterator).css(cache.css);
                }
            } else if (grid) {
                cache.css.width = cache.items.width;
                items.css(cache.css);
            }
        }
    }, {
        filter: ['items'],
        run: function () {
            this._coordinates.length < 1 && this.$stage.removeAttr('style');
        }
    }, {
        filter: ['width', 'items', 'settings'],
        run: function (cache) {
            cache.current = cache.current ? this.$stage.children().index(cache.current) : 0;
            cache.current = Math.max(this.minimum(), Math.min(this.maximum(), cache.current));
            this.reset(cache.current);
        }
    }, {
        filter: ['position'],
        run: function () {
            this.animate(this.coordinates(this._current));
        }
    }, {
        filter: ['width', 'position', 'items', 'settings'],
        run: function () {
            var rtl = this.settings.rtl ? 1 : -1,
                padding = this.settings.stagePadding * 2,
                begin = this.coordinates(this.current()) + padding,
                end = begin + this.width() * rtl,
                inner, outer, matches = [], i, n;

            for (i = 0, n = this._coordinates.length; i < n; i++) {
                inner = this._coordinates[i - 1] || 0;
                outer = Math.abs(this._coordinates[i]) + padding * rtl;

                if ((this.op(inner, '<=', begin) && (this.op(inner, '>', end)))
                    || (this.op(outer, '<', begin) && this.op(outer, '>', end))) {
                    matches.push(i);
                }
            }

            this.$stage.children('.active').removeClass('active');
            this.$stage.children(':eq(' + matches.join('), :eq(') + ')').addClass('active');

            if (this.settings.center) {
                this.$stage.children('.center').removeClass('center');
                this.$stage.children().eq(this.current()).addClass('center');
            }
        }
    }];

	/**
	 * Initializes the carousel.
	 * @protected
	 */
    Owl.prototype.initialize = function () {
        this.enter('initializing');
        this.trigger('initialize');

        this.$element.toggleClass(this.settings.rtlClass, this.settings.rtl);

        if (this.settings.autoWidth && !this.is('pre-loading')) {
            var imgs, nestedSelector, width;
            imgs = this.$element.find('img');
            nestedSelector = this.settings.nestedItemSelector ? '.' + this.settings.nestedItemSelector : undefined;
            width = this.$element.children(nestedSelector).width();

            if (imgs.length && width <= 0) {
                this.preloadAutoWidthImages(imgs);
            }
        }

        this.$element.addClass(this.options.loadingClass);

        // create stage
        this.$stage = $('<' + this.settings.stageElement + ' class="' + this.settings.stageClass + '"/>')
            .wrap('<div class="' + this.settings.stageOuterClass + '"/>');

        // append stage
        this.$element.append(this.$stage.parent());

        // append content
        this.replace(this.$element.children().not(this.$stage.parent()));

        // check visibility
        if (this.$element.is(':visible')) {
            // update view
            this.refresh();
        } else {
            // invalidate width
            this.invalidate('width');
        }

        this.$element
            .removeClass(this.options.loadingClass)
            .addClass(this.options.loadedClass);

        // register event handlers
        this.registerEventHandlers();

        this.leave('initializing');
        this.trigger('initialized');
    };

	/**
	 * Setups the current settings.
	 * @todo Remove responsive classes. Why should adaptive designs be brought into IE8?
	 * @todo Support for media queries by using `matchMedia` would be nice.
	 * @public
	 */
    Owl.prototype.setup = function () {
        var viewport = this.viewport(),
            overwrites = this.options.responsive,
            match = -1,
            settings = null;

        if (!overwrites) {
            settings = $.extend({}, this.options);
        } else {
            $.each(overwrites, function (breakpoint) {
                if (breakpoint <= viewport && breakpoint > match) {
                    match = Number(breakpoint);
                }
            });

            settings = $.extend({}, this.options, overwrites[match]);
            if (typeof settings.stagePadding === 'function') {
                settings.stagePadding = settings.stagePadding();
            }
            delete settings.responsive;

            // responsive class
            if (settings.responsiveClass) {
                this.$element.attr('class',
                    this.$element.attr('class').replace(new RegExp('(' + this.options.responsiveClass + '-)\\S+\\s', 'g'), '$1' + match)
                );
            }
        }

        this.trigger('change', { property: { name: 'settings', value: settings } });
        this._breakpoint = match;
        this.settings = settings;
        this.invalidate('settings');
        this.trigger('changed', { property: { name: 'settings', value: this.settings } });
    };

	/**
	 * Updates option logic if necessery.
	 * @protected
	 */
    Owl.prototype.optionsLogic = function () {
        if (this.settings.autoWidth) {
            this.settings.stagePadding = false;
            this.settings.merge = false;
        }
    };

	/**
	 * Prepares an item before add.
	 * @todo Rename event parameter `content` to `item`.
	 * @protected
	 * @returns {jQuery|HTMLElement} - The item container.
	 */
    Owl.prototype.prepare = function (item) {
        var event = this.trigger('prepare', { content: item });

        if (!event.data) {
            event.data = $('<' + this.settings.itemElement + '/>')
                .addClass(this.options.itemClass).append(item)
        }

        this.trigger('prepared', { content: event.data });

        return event.data;
    };

	/**
	 * Updates the view.
	 * @public
	 */
    Owl.prototype.update = function () {
        var i = 0,
            n = this._pipe.length,
            filter = $.proxy(function (p) { return this[p] }, this._invalidated),
            cache = {};

        while (i < n) {
            if (this._invalidated.all || $.grep(this._pipe[i].filter, filter).length > 0) {
                this._pipe[i].run(cache);
            }
            i++;
        }

        this._invalidated = {};

        !this.is('valid') && this.enter('valid');
    };

	/**
	 * Gets the width of the view.
	 * @public
	 * @param {Owl.Width} [dimension=Owl.Width.Default] - The dimension to return.
	 * @returns {Number} - The width of the view in pixel.
	 */
    Owl.prototype.width = function (dimension) {
        dimension = dimension || Owl.Width.Default;
        switch (dimension) {
            case Owl.Width.Inner:
            case Owl.Width.Outer:
                return this._width;
            default:
                return this._width - this.settings.stagePadding * 2 + this.settings.margin;
        }
    };

	/**
	 * Refreshes the carousel primarily for adaptive purposes.
	 * @public
	 */
    Owl.prototype.refresh = function () {
        this.enter('refreshing');
        this.trigger('refresh');

        this.setup();

        this.optionsLogic();

        this.$element.addClass(this.options.refreshClass);

        this.update();

        this.$element.removeClass(this.options.refreshClass);

        this.leave('refreshing');
        this.trigger('refreshed');
    };

	/**
	 * Checks window `resize` event.
	 * @protected
	 */
    Owl.prototype.onThrottledResize = function () {
        window.clearTimeout(this.resizeTimer);
        this.resizeTimer = window.setTimeout(this._handlers.onResize, this.settings.responsiveRefreshRate);
    };

	/**
	 * Checks window `resize` event.
	 * @protected
	 */
    Owl.prototype.onResize = function () {
        if (!this._items.length) {
            return false;
        }

        if (this._width === this.$element.width()) {
            return false;
        }

        if (!this.$element.is(':visible')) {
            return false;
        }

        this.enter('resizing');

        if (this.trigger('resize').isDefaultPrevented()) {
            this.leave('resizing');
            return false;
        }

        this.invalidate('width');

        this.refresh();

        this.leave('resizing');
        this.trigger('resized');
    };

	/**
	 * Registers event handlers.
	 * @todo Check `msPointerEnabled`
	 * @todo #261
	 * @protected
	 */
    Owl.prototype.registerEventHandlers = function () {
        if ($.support.transition) {
            this.$stage.on($.support.transition.end + '.owl.core', $.proxy(this.onTransitionEnd, this));
        }

        if (this.settings.responsive !== false) {
            this.on(window, 'resize', this._handlers.onThrottledResize);
        }

        if (this.settings.mouseDrag) {
            this.$element.addClass(this.options.dragClass);
            this.$stage.on('mousedown.owl.core', $.proxy(this.onDragStart, this));
            this.$stage.on('dragstart.owl.core selectstart.owl.core', function () { return false });
        }

        if (this.settings.touchDrag) {
            this.$stage.on('touchstart.owl.core', $.proxy(this.onDragStart, this));
            this.$stage.on('touchcancel.owl.core', $.proxy(this.onDragEnd, this));
        }
    };

	/**
	 * Handles `touchstart` and `mousedown` events.
	 * @todo Horizontal swipe threshold as option
	 * @todo #261
	 * @protected
	 * @param {Event} event - The event arguments.
	 */
    Owl.prototype.onDragStart = function (event) {
        var stage = null;

        if (event.which === 3) {
            return;
        }

        if ($.support.transform) {
            stage = this.$stage.css('transform').replace(/.*\(|\)| /g, '').split(',');
            stage = {
                x: stage[stage.length === 16 ? 12 : 4],
                y: stage[stage.length === 16 ? 13 : 5]
            };
        } else {
            stage = this.$stage.position();
            stage = {
                x: this.settings.rtl ?
                    stage.left + this.$stage.width() - this.width() + this.settings.margin :
                    stage.left,
                y: stage.top
            };
        }

        if (this.is('animating')) {
            $.support.transform ? this.animate(stage.x) : this.$stage.stop()
            this.invalidate('position');
        }

        this.$element.toggleClass(this.options.grabClass, event.type === 'mousedown');

        this.speed(0);

        this._drag.time = new Date().getTime();
        this._drag.target = $(event.target);
        this._drag.stage.start = stage;
        this._drag.stage.current = stage;
        this._drag.pointer = this.pointer(event);

        $(document).on('mouseup.owl.core touchend.owl.core', $.proxy(this.onDragEnd, this));

        $(document).one('mousemove.owl.core touchmove.owl.core', $.proxy(function (event) {
            var delta = this.difference(this._drag.pointer, this.pointer(event));

            $(document).on('mousemove.owl.core touchmove.owl.core', $.proxy(this.onDragMove, this));

            if (Math.abs(delta.x) < Math.abs(delta.y) && this.is('valid')) {
                return;
            }

            event.preventDefault();

            this.enter('dragging');
            this.trigger('drag');
        }, this));
    };

	/**
	 * Handles the `touchmove` and `mousemove` events.
	 * @todo #261
	 * @protected
	 * @param {Event} event - The event arguments.
	 */
    Owl.prototype.onDragMove = function (event) {
        var minimum = null,
            maximum = null,
            pull = null,
            delta = this.difference(this._drag.pointer, this.pointer(event)),
            stage = this.difference(this._drag.stage.start, delta);

        if (!this.is('dragging')) {
            return;
        }

        event.preventDefault();

        if (this.settings.loop) {
            minimum = this.coordinates(this.minimum());
            maximum = this.coordinates(this.maximum() + 1) - minimum;
            stage.x = (((stage.x - minimum) % maximum + maximum) % maximum) + minimum;
        } else {
            minimum = this.settings.rtl ? this.coordinates(this.maximum()) : this.coordinates(this.minimum());
            maximum = this.settings.rtl ? this.coordinates(this.minimum()) : this.coordinates(this.maximum());
            pull = this.settings.pullDrag ? -1 * delta.x / 5 : 0;
            stage.x = Math.max(Math.min(stage.x, minimum + pull), maximum + pull);
        }

        this._drag.stage.current = stage;

        this.animate(stage.x);
    };

	/**
	 * Handles the `touchend` and `mouseup` events.
	 * @todo #261
	 * @todo Threshold for click event
	 * @protected
	 * @param {Event} event - The event arguments.
	 */
    Owl.prototype.onDragEnd = function (event) {
        var delta = this.difference(this._drag.pointer, this.pointer(event)),
            stage = this._drag.stage.current,
            direction = delta.x > 0 ^ this.settings.rtl ? 'left' : 'right';

        $(document).off('.owl.core');

        this.$element.removeClass(this.options.grabClass);

        if (delta.x !== 0 && this.is('dragging') || !this.is('valid')) {
            this.speed(this.settings.dragEndSpeed || this.settings.smartSpeed);
            this.current(this.closest(stage.x, delta.x !== 0 ? direction : this._drag.direction));
            this.invalidate('position');
            this.update();

            this._drag.direction = direction;

            if (Math.abs(delta.x) > 3 || new Date().getTime() - this._drag.time > 300) {
                this._drag.target.one('click.owl.core', function () { return false; });
            }
        }

        if (!this.is('dragging')) {
            return;
        }

        this.leave('dragging');
        this.trigger('dragged');
    };

	/**
	 * Gets absolute position of the closest item for a coordinate.
	 * @todo Setting `freeDrag` makes `closest` not reusable. See #165.
	 * @protected
	 * @param {Number} coordinate - The coordinate in pixel.
	 * @param {String} direction - The direction to check for the closest item. Ether `left` or `right`.
	 * @return {Number} - The absolute position of the closest item.
	 */
    Owl.prototype.closest = function (coordinate, direction) {
        var position = -1,
            pull = 30,
            width = this.width(),
            coordinates = this.coordinates();

        if (!this.settings.freeDrag) {
            // check closest item
            $.each(coordinates, $.proxy(function (index, value) {
                // on a left pull, check on current index
                if (direction === 'left' && coordinate > value - pull && coordinate < value + pull) {
                    position = index;
                    // on a right pull, check on previous index
                    // to do so, subtract width from value and set position = index + 1
                } else if (direction === 'right' && coordinate > value - width - pull && coordinate < value - width + pull) {
                    position = index + 1;
                } else if (this.op(coordinate, '<', value)
                    && this.op(coordinate, '>', coordinates[index + 1] || value - width)) {
                    position = direction === 'left' ? index + 1 : index;
                }
                return position === -1;
            }, this));
        }

        if (!this.settings.loop) {
            // non loop boundries
            if (this.op(coordinate, '>', coordinates[this.minimum()])) {
                position = coordinate = this.minimum();
            } else if (this.op(coordinate, '<', coordinates[this.maximum()])) {
                position = coordinate = this.maximum();
            }
        }

        return position;
    };

	/**
	 * Animates the stage.
	 * @todo #270
	 * @public
	 * @param {Number} coordinate - The coordinate in pixels.
	 */
    Owl.prototype.animate = function (coordinate) {
        var animate = this.speed() > 0;

        this.is('animating') && this.onTransitionEnd();

        if (animate) {
            this.enter('animating');
            this.trigger('translate');
        }

        if ($.support.transform3d && $.support.transition) {
            this.$stage.css({
                transform: 'translate3d(' + coordinate + 'px,0px,0px)',
                transition: (this.speed() / 1000) + 's'
            });
        } else if (animate) {
            this.$stage.animate({
                left: coordinate + 'px'
            }, this.speed(), this.settings.fallbackEasing, $.proxy(this.onTransitionEnd, this));
        } else {
            this.$stage.css({
                left: coordinate + 'px'
            });
        }
    };

	/**
	 * Checks whether the carousel is in a specific state or not.
	 * @param {String} state - The state to check.
	 * @returns {Boolean} - The flag which indicates if the carousel is busy.
	 */
    Owl.prototype.is = function (state) {
        return this._states.current[state] && this._states.current[state] > 0;
    };

	/**
	 * Sets the absolute position of the current item.
	 * @public
	 * @param {Number} [position] - The new absolute position or nothing to leave it unchanged.
	 * @returns {Number} - The absolute position of the current item.
	 */
    Owl.prototype.current = function (position) {
        if (position === undefined) {
            return this._current;
        }

        if (this._items.length === 0) {
            return undefined;
        }

        position = this.normalize(position);

        if (this._current !== position) {
            var event = this.trigger('change', { property: { name: 'position', value: position } });

            if (event.data !== undefined) {
                position = this.normalize(event.data);
            }

            this._current = position;

            this.invalidate('position');

            this.trigger('changed', { property: { name: 'position', value: this._current } });
        }

        return this._current;
    };

	/**
	 * Invalidates the given part of the update routine.
	 * @param {String} [part] - The part to invalidate.
	 * @returns {Array.<String>} - The invalidated parts.
	 */
    Owl.prototype.invalidate = function (part) {
        if ($.type(part) === 'string') {
            this._invalidated[part] = true;
            this.is('valid') && this.leave('valid');
        }
        return $.map(this._invalidated, function (v, i) { return i });
    };

	/**
	 * Resets the absolute position of the current item.
	 * @public
	 * @param {Number} position - The absolute position of the new item.
	 */
    Owl.prototype.reset = function (position) {
        position = this.normalize(position);

        if (position === undefined) {
            return;
        }

        this._speed = 0;
        this._current = position;

        this.suppress(['translate', 'translated']);

        this.animate(this.coordinates(position));

        this.release(['translate', 'translated']);
    };

	/**
	 * Normalizes an absolute or a relative position of an item.
	 * @public
	 * @param {Number} position - The absolute or relative position to normalize.
	 * @param {Boolean} [relative=false] - Whether the given position is relative or not.
	 * @returns {Number} - The normalized position.
	 */
    Owl.prototype.normalize = function (position, relative) {
        var n = this._items.length,
            m = relative ? 0 : this._clones.length;

        if (!this.isNumeric(position) || n < 1) {
            position = undefined;
        } else if (position < 0 || position >= n + m) {
            position = ((position - m / 2) % n + n) % n + m / 2;
        }

        return position;
    };

	/**
	 * Converts an absolute position of an item into a relative one.
	 * @public
	 * @param {Number} position - The absolute position to convert.
	 * @returns {Number} - The converted position.
	 */
    Owl.prototype.relative = function (position) {
        position -= this._clones.length / 2;
        return this.normalize(position, true);
    };

	/**
	 * Gets the maximum position for the current item.
	 * @public
	 * @param {Boolean} [relative=false] - Whether to return an absolute position or a relative position.
	 * @returns {Number}
	 */
    Owl.prototype.maximum = function (relative) {
        var settings = this.settings,
            maximum = this._coordinates.length,
            iterator,
            reciprocalItemsWidth,
            elementWidth;

        if (settings.loop) {
            maximum = this._clones.length / 2 + this._items.length - 1;
        } else if (settings.autoWidth || settings.merge) {
            iterator = this._items.length;
            reciprocalItemsWidth = this._items[--iterator].width();
            elementWidth = this.$element.width();
            while (iterator--) {
                reciprocalItemsWidth += this._items[iterator].width() + this.settings.margin;
                if (reciprocalItemsWidth > elementWidth) {
                    break;
                }
            }
            maximum = iterator + 1;
        } else if (settings.center) {
            maximum = this._items.length - 1;
        } else {
            maximum = this._items.length - settings.items;
        }

        if (relative) {
            maximum -= this._clones.length / 2;
        }

        return Math.max(maximum, 0);
    };

	/**
	 * Gets the minimum position for the current item.
	 * @public
	 * @param {Boolean} [relative=false] - Whether to return an absolute position or a relative position.
	 * @returns {Number}
	 */
    Owl.prototype.minimum = function (relative) {
        return relative ? 0 : this._clones.length / 2;
    };

	/**
	 * Gets an item at the specified relative position.
	 * @public
	 * @param {Number} [position] - The relative position of the item.
	 * @return {jQuery|Array.<jQuery>} - The item at the given position or all items if no position was given.
	 */
    Owl.prototype.items = function (position) {
        if (position === undefined) {
            return this._items.slice();
        }

        position = this.normalize(position, true);
        return this._items[position];
    };

	/**
	 * Gets an item at the specified relative position.
	 * @public
	 * @param {Number} [position] - The relative position of the item.
	 * @return {jQuery|Array.<jQuery>} - The item at the given position or all items if no position was given.
	 */
    Owl.prototype.mergers = function (position) {
        if (position === undefined) {
            return this._mergers.slice();
        }

        position = this.normalize(position, true);
        return this._mergers[position];
    };

	/**
	 * Gets the absolute positions of clones for an item.
	 * @public
	 * @param {Number} [position] - The relative position of the item.
	 * @returns {Array.<Number>} - The absolute positions of clones for the item or all if no position was given.
	 */
    Owl.prototype.clones = function (position) {
        var odd = this._clones.length / 2,
            even = odd + this._items.length,
            map = function (index) { return index % 2 === 0 ? even + index / 2 : odd - (index + 1) / 2 };

        if (position === undefined) {
            return $.map(this._clones, function (v, i) { return map(i) });
        }

        return $.map(this._clones, function (v, i) { return v === position ? map(i) : null });
    };

	/**
	 * Sets the current animation speed.
	 * @public
	 * @param {Number} [speed] - The animation speed in milliseconds or nothing to leave it unchanged.
	 * @returns {Number} - The current animation speed in milliseconds.
	 */
    Owl.prototype.speed = function (speed) {
        if (speed !== undefined) {
            this._speed = speed;
        }

        return this._speed;
    };

	/**
	 * Gets the coordinate of an item.
	 * @todo The name of this method is missleanding.
	 * @public
	 * @param {Number} position - The absolute position of the item within `minimum()` and `maximum()`.
	 * @returns {Number|Array.<Number>} - The coordinate of the item in pixel or all coordinates.
	 */
    Owl.prototype.coordinates = function (position) {
        var multiplier = 1,
            newPosition = position - 1,
            coordinate;

        if (position === undefined) {
            return $.map(this._coordinates, $.proxy(function (coordinate, index) {
                return this.coordinates(index);
            }, this));
        }

        if (this.settings.center) {
            if (this.settings.rtl) {
                multiplier = -1;
                newPosition = position + 1;
            }

            coordinate = this._coordinates[position];
            coordinate += (this.width() - coordinate + (this._coordinates[newPosition] || 0)) / 2 * multiplier;
        } else {
            coordinate = this._coordinates[newPosition] || 0;
        }

        coordinate = Math.ceil(coordinate);

        return coordinate;
    };

	/**
	 * Calculates the speed for a translation.
	 * @protected
	 * @param {Number} from - The absolute position of the start item.
	 * @param {Number} to - The absolute position of the target item.
	 * @param {Number} [factor=undefined] - The time factor in milliseconds.
	 * @returns {Number} - The time in milliseconds for the translation.
	 */
    Owl.prototype.duration = function (from, to, factor) {
        if (factor === 0) {
            return 0;
        }

        return Math.min(Math.max(Math.abs(to - from), 1), 6) * Math.abs((factor || this.settings.smartSpeed));
    };

	/**
	 * Slides to the specified item.
	 * @public
	 * @param {Number} position - The position of the item.
	 * @param {Number} [speed] - The time in milliseconds for the transition.
	 */
    Owl.prototype.to = function (position, speed) {
        var current = this.current(),
            revert = null,
            distance = position - this.relative(current),
            direction = (distance > 0) - (distance < 0),
            items = this._items.length,
            minimum = this.minimum(),
            maximum = this.maximum();

        if (this.settings.loop) {
            if (!this.settings.rewind && Math.abs(distance) > items / 2) {
                distance += direction * -1 * items;
            }

            position = current + distance;
            revert = ((position - minimum) % items + items) % items + minimum;

            if (revert !== position && revert - distance <= maximum && revert - distance > 0) {
                current = revert - distance;
                position = revert;
                this.reset(current);
            }
        } else if (this.settings.rewind) {
            maximum += 1;
            position = (position % maximum + maximum) % maximum;
        } else {
            position = Math.max(minimum, Math.min(maximum, position));
        }

        this.speed(this.duration(current, position, speed));
        this.current(position);

        if (this.$element.is(':visible')) {
            this.update();
        }
    };

	/**
	 * Slides to the next item.
	 * @public
	 * @param {Number} [speed] - The time in milliseconds for the transition.
	 */
    Owl.prototype.next = function (speed) {
        speed = speed || false;
        this.to(this.relative(this.current()) + 1, speed);
    };

	/**
	 * Slides to the previous item.
	 * @public
	 * @param {Number} [speed] - The time in milliseconds for the transition.
	 */
    Owl.prototype.prev = function (speed) {
        speed = speed || false;
        this.to(this.relative(this.current()) - 1, speed);
    };

	/**
	 * Handles the end of an animation.
	 * @protected
	 * @param {Event} event - The event arguments.
	 */
    Owl.prototype.onTransitionEnd = function (event) {

        // if css2 animation then event object is undefined
        if (event !== undefined) {
            event.stopPropagation();

            // Catch only owl-stage transitionEnd event
            if ((event.target || event.srcElement || event.originalTarget) !== this.$stage.get(0)) {
                return false;
            }
        }

        this.leave('animating');
        this.trigger('translated');
    };

	/**
	 * Gets viewport width.
	 * @protected
	 * @return {Number} - The width in pixel.
	 */
    Owl.prototype.viewport = function () {
        var width;
        if (this.options.responsiveBaseElement !== window) {
            width = $(this.options.responsiveBaseElement).width();
        } else if (window.innerWidth) {
            width = window.innerWidth;
        } else if (document.documentElement && document.documentElement.clientWidth) {
            width = document.documentElement.clientWidth;
        } else {
            console.warn('Can not detect viewport width.');
        }
        return width;
    };

	/**
	 * Replaces the current content.
	 * @public
	 * @param {HTMLElement|jQuery|String} content - The new content.
	 */
    Owl.prototype.replace = function (content) {
        this.$stage.empty();
        this._items = [];

        if (content) {
            content = (content instanceof jQuery) ? content : $(content);
        }

        if (this.settings.nestedItemSelector) {
            content = content.find('.' + this.settings.nestedItemSelector);
        }

        content.filter(function () {
            return this.nodeType === 1;
        }).each($.proxy(function (index, item) {
            item = this.prepare(item);
            this.$stage.append(item);
            this._items.push(item);
            this._mergers.push(item.find('[data-merge]').addBack('[data-merge]').attr('data-merge') * 1 || 1);
        }, this));

        this.reset(this.isNumeric(this.settings.startPosition) ? this.settings.startPosition : 0);

        this.invalidate('items');
    };

	/**
	 * Adds an item.
	 * @todo Use `item` instead of `content` for the event arguments.
	 * @public
	 * @param {HTMLElement|jQuery|String} content - The item content to add.
	 * @param {Number} [position] - The relative position at which to insert the item otherwise the item will be added to the end.
	 */
    Owl.prototype.add = function (content, position) {
        var current = this.relative(this._current);

        position = position === undefined ? this._items.length : this.normalize(position, true);
        content = content instanceof jQuery ? content : $(content);

        this.trigger('add', { content: content, position: position });

        content = this.prepare(content);

        if (this._items.length === 0 || position === this._items.length) {
            this._items.length === 0 && this.$stage.append(content);
            this._items.length !== 0 && this._items[position - 1].after(content);
            this._items.push(content);
            this._mergers.push(content.find('[data-merge]').addBack('[data-merge]').attr('data-merge') * 1 || 1);
        } else {
            this._items[position].before(content);
            this._items.splice(position, 0, content);
            this._mergers.splice(position, 0, content.find('[data-merge]').addBack('[data-merge]').attr('data-merge') * 1 || 1);
        }

        this._items[current] && this.reset(this._items[current].index());

        this.invalidate('items');

        this.trigger('added', { content: content, position: position });
    };

	/**
	 * Removes an item by its position.
	 * @todo Use `item` instead of `content` for the event arguments.
	 * @public
	 * @param {Number} position - The relative position of the item to remove.
	 */
    Owl.prototype.remove = function (position) {
        position = this.normalize(position, true);

        if (position === undefined) {
            return;
        }

        this.trigger('remove', { content: this._items[position], position: position });

        this._items[position].remove();
        this._items.splice(position, 1);
        this._mergers.splice(position, 1);

        this.invalidate('items');

        this.trigger('removed', { content: null, position: position });
    };

	/**
	 * Preloads images with auto width.
	 * @todo Replace by a more generic approach
	 * @protected
	 */
    Owl.prototype.preloadAutoWidthImages = function (images) {
        images.each($.proxy(function (i, element) {
            this.enter('pre-loading');
            element = $(element);
            $(new Image()).one('load', $.proxy(function (e) {
                element.attr('src', e.target.src);
                element.css('opacity', 1);
                this.leave('pre-loading');
                !this.is('pre-loading') && !this.is('initializing') && this.refresh();
            }, this)).attr('src', element.attr('src') || element.attr('data-src') || element.attr('data-src-retina'));
        }, this));
    };

	/**
	 * Destroys the carousel.
	 * @public
	 */
    Owl.prototype.destroy = function () {

        this.$element.off('.owl.core');
        this.$stage.off('.owl.core');
        $(document).off('.owl.core');

        if (this.settings.responsive !== false) {
            window.clearTimeout(this.resizeTimer);
            this.off(window, 'resize', this._handlers.onThrottledResize);
        }

        for (var i in this._plugins) {
            this._plugins[i].destroy();
        }

        this.$stage.children('.cloned').remove();

        this.$stage.unwrap();
        this.$stage.children().contents().unwrap();
        this.$stage.children().unwrap();

        this.$element
            .removeClass(this.options.refreshClass)
            .removeClass(this.options.loadingClass)
            .removeClass(this.options.loadedClass)
            .removeClass(this.options.rtlClass)
            .removeClass(this.options.dragClass)
            .removeClass(this.options.grabClass)
            .attr('class', this.$element.attr('class').replace(new RegExp(this.options.responsiveClass + '-\\S+\\s', 'g'), ''))
            .removeData('owl.carousel');
    };

	/**
	 * Operators to calculate right-to-left and left-to-right.
	 * @protected
	 * @param {Number} [a] - The left side operand.
	 * @param {String} [o] - The operator.
	 * @param {Number} [b] - The right side operand.
	 */
    Owl.prototype.op = function (a, o, b) {
        var rtl = this.settings.rtl;
        switch (o) {
            case '<':
                return rtl ? a > b : a < b;
            case '>':
                return rtl ? a < b : a > b;
            case '>=':
                return rtl ? a <= b : a >= b;
            case '<=':
                return rtl ? a >= b : a <= b;
            default:
                break;
        }
    };

	/**
	 * Attaches to an internal event.
	 * @protected
	 * @param {HTMLElement} element - The event source.
	 * @param {String} event - The event name.
	 * @param {Function} listener - The event handler to attach.
	 * @param {Boolean} capture - Wether the event should be handled at the capturing phase or not.
	 */
    Owl.prototype.on = function (element, event, listener, capture) {
        if (element.addEventListener) {
            element.addEventListener(event, listener, capture);
        } else if (element.attachEvent) {
            element.attachEvent('on' + event, listener);
        }
    };

	/**
	 * Detaches from an internal event.
	 * @protected
	 * @param {HTMLElement} element - The event source.
	 * @param {String} event - The event name.
	 * @param {Function} listener - The attached event handler to detach.
	 * @param {Boolean} capture - Wether the attached event handler was registered as a capturing listener or not.
	 */
    Owl.prototype.off = function (element, event, listener, capture) {
        if (element.removeEventListener) {
            element.removeEventListener(event, listener, capture);
        } else if (element.detachEvent) {
            element.detachEvent('on' + event, listener);
        }
    };

	/**
	 * Triggers a public event.
	 * @todo Remove `status`, `relatedTarget` should be used instead.
	 * @protected
	 * @param {String} name - The event name.
	 * @param {*} [data=null] - The event data.
	 * @param {String} [namespace=carousel] - The event namespace.
	 * @param {String} [state] - The state which is associated with the event.
	 * @param {Boolean} [enter=false] - Indicates if the call enters the specified state or not.
	 * @returns {Event} - The event arguments.
	 */
    Owl.prototype.trigger = function (name, data, namespace, state, enter) {
        var status = {
            item: { count: this._items.length, index: this.current() }
        }, handler = $.camelCase(
            $.grep(['on', name, namespace], function (v) { return v })
                .join('-').toLowerCase()
        ), event = $.Event(
            [name, 'owl', namespace || 'carousel'].join('.').toLowerCase(),
            $.extend({ relatedTarget: this }, status, data)
        );

        if (!this._supress[name]) {
            $.each(this._plugins, function (name, plugin) {
                if (plugin.onTrigger) {
                    plugin.onTrigger(event);
                }
            });

            this.register({ type: Owl.Type.Event, name: name });
            this.$element.trigger(event);

            if (this.settings && typeof this.settings[handler] === 'function') {
                this.settings[handler].call(this, event);
            }
        }

        return event;
    };

	/**
	 * Enters a state.
	 * @param name - The state name.
	 */
    Owl.prototype.enter = function (name) {
        $.each([name].concat(this._states.tags[name] || []), $.proxy(function (i, name) {
            if (this._states.current[name] === undefined) {
                this._states.current[name] = 0;
            }

            this._states.current[name]++;
        }, this));
    };

	/**
	 * Leaves a state.
	 * @param name - The state name.
	 */
    Owl.prototype.leave = function (name) {
        $.each([name].concat(this._states.tags[name] || []), $.proxy(function (i, name) {
            this._states.current[name]--;
        }, this));
    };

	/**
	 * Registers an event or state.
	 * @public
	 * @param {Object} object - The event or state to register.
	 */
    Owl.prototype.register = function (object) {
        if (object.type === Owl.Type.Event) {
            if (!$.event.special[object.name]) {
                $.event.special[object.name] = {};
            }

            if (!$.event.special[object.name].owl) {
                var _default = $.event.special[object.name]._default;
                $.event.special[object.name]._default = function (e) {
                    if (_default && _default.apply && (!e.namespace || e.namespace.indexOf('owl') === -1)) {
                        return _default.apply(this, arguments);
                    }
                    return e.namespace && e.namespace.indexOf('owl') > -1;
                };
                $.event.special[object.name].owl = true;
            }
        } else if (object.type === Owl.Type.State) {
            if (!this._states.tags[object.name]) {
                this._states.tags[object.name] = object.tags;
            } else {
                this._states.tags[object.name] = this._states.tags[object.name].concat(object.tags);
            }

            this._states.tags[object.name] = $.grep(this._states.tags[object.name], $.proxy(function (tag, i) {
                return $.inArray(tag, this._states.tags[object.name]) === i;
            }, this));
        }
    };

	/**
	 * Suppresses events.
	 * @protected
	 * @param {Array.<String>} events - The events to suppress.
	 */
    Owl.prototype.suppress = function (events) {
        $.each(events, $.proxy(function (index, event) {
            this._supress[event] = true;
        }, this));
    };

	/**
	 * Releases suppressed events.
	 * @protected
	 * @param {Array.<String>} events - The events to release.
	 */
    Owl.prototype.release = function (events) {
        $.each(events, $.proxy(function (index, event) {
            delete this._supress[event];
        }, this));
    };

	/**
	 * Gets unified pointer coordinates from event.
	 * @todo #261
	 * @protected
	 * @param {Event} - The `mousedown` or `touchstart` event.
	 * @returns {Object} - Contains `x` and `y` coordinates of current pointer position.
	 */
    Owl.prototype.pointer = function (event) {
        var result = { x: null, y: null };

        event = event.originalEvent || event || window.event;

        event = event.touches && event.touches.length ?
            event.touches[0] : event.changedTouches && event.changedTouches.length ?
                event.changedTouches[0] : event;

        if (event.pageX) {
            result.x = event.pageX;
            result.y = event.pageY;
        } else {
            result.x = event.clientX;
            result.y = event.clientY;
        }

        return result;
    };

	/**
	 * Determines if the input is a Number or something that can be coerced to a Number
	 * @protected
	 * @param {Number|String|Object|Array|Boolean|RegExp|Function|Symbol} - The input to be tested
	 * @returns {Boolean} - An indication if the input is a Number or can be coerced to a Number
	 */
    Owl.prototype.isNumeric = function (number) {
        return !isNaN(parseFloat(number));
    };

	/**
	 * Gets the difference of two vectors.
	 * @todo #261
	 * @protected
	 * @param {Object} - The first vector.
	 * @param {Object} - The second vector.
	 * @returns {Object} - The difference.
	 */
    Owl.prototype.difference = function (first, second) {
        return {
            x: first.x - second.x,
            y: first.y - second.y
        };
    };

	/**
	 * The jQuery Plugin for the Owl Carousel
	 * @todo Navigation plugin `next` and `prev`
	 * @public
	 */
    $.fn.owlCarousel = function (option) {
        var args = Array.prototype.slice.call(arguments, 1);

        return this.each(function () {
            var $this = $(this),
                data = $this.data('owl.carousel');

            if (!data) {
                data = new Owl(this, typeof option == 'object' && option);
                $this.data('owl.carousel', data);

                $.each([
                    'next', 'prev', 'to', 'destroy', 'refresh', 'replace', 'add', 'remove'
                ], function (i, event) {
                    data.register({ type: Owl.Type.Event, name: event });
                    data.$element.on(event + '.owl.carousel.core', $.proxy(function (e) {
                        if (e.namespace && e.relatedTarget !== this) {
                            this.suppress([event]);
                            data[event].apply(this, [].slice.call(arguments, 1));
                            this.release([event]);
                        }
                    }, data));
                });
            }

            if (typeof option == 'string' && option.charAt(0) !== '_') {
                data[option].apply(data, args);
            }
        });
    };

	/**
	 * The constructor for the jQuery Plugin
	 * @public
	 */
    $.fn.owlCarousel.Constructor = Owl;

})(window.Zepto || window.jQuery, window, document);

/**
 * AutoRefresh Plugin
 * @version 2.1.0
 * @author Artus Kolanowski
 * @author David Deutsch
 * @license The MIT License (MIT)
 */
; (function ($, window, document, undefined) {

	/**
	 * Creates the auto refresh plugin.
	 * @class The Auto Refresh Plugin
	 * @param {Owl} carousel - The Owl Carousel
	 */
    var AutoRefresh = function (carousel) {
		/**
		 * Reference to the core.
		 * @protected
		 * @type {Owl}
		 */
        this._core = carousel;

		/**
		 * Refresh interval.
		 * @protected
		 * @type {number}
		 */
        this._interval = null;

		/**
		 * Whether the element is currently visible or not.
		 * @protected
		 * @type {Boolean}
		 */
        this._visible = null;

		/**
		 * All event handlers.
		 * @protected
		 * @type {Object}
		 */
        this._handlers = {
            'initialized.owl.carousel': $.proxy(function (e) {
                if (e.namespace && this._core.settings.autoRefresh) {
                    this.watch();
                }
            }, this)
        };

        // set default options
        this._core.options = $.extend({}, AutoRefresh.Defaults, this._core.options);

        // register event handlers
        this._core.$element.on(this._handlers);
    };

	/**
	 * Default options.
	 * @public
	 */
    AutoRefresh.Defaults = {
        autoRefresh: true,
        autoRefreshInterval: 500
    };

	/**
	 * Watches the element.
	 */
    AutoRefresh.prototype.watch = function () {
        if (this._interval) {
            return;
        }

        this._visible = this._core.$element.is(':visible');
        this._interval = window.setInterval($.proxy(this.refresh, this), this._core.settings.autoRefreshInterval);
    };

	/**
	 * Refreshes the element.
	 */
    AutoRefresh.prototype.refresh = function () {
        if (this._core.$element.is(':visible') === this._visible) {
            return;
        }

        this._visible = !this._visible;

        this._core.$element.toggleClass('owl-hidden', !this._visible);

        this._visible && (this._core.invalidate('width') && this._core.refresh());
    };

	/**
	 * Destroys the plugin.
	 */
    AutoRefresh.prototype.destroy = function () {
        var handler, property;

        window.clearInterval(this._interval);

        for (handler in this._handlers) {
            this._core.$element.off(handler, this._handlers[handler]);
        }
        for (property in Object.getOwnPropertyNames(this)) {
            typeof this[property] != 'function' && (this[property] = null);
        }
    };

    $.fn.owlCarousel.Constructor.Plugins.AutoRefresh = AutoRefresh;

})(window.Zepto || window.jQuery, window, document);

/**
 * Lazy Plugin
 * @version 2.1.0
 * @author Bartosz Wojciechowski
 * @author David Deutsch
 * @license The MIT License (MIT)
 */
; (function ($, window, document, undefined) {

	/**
	 * Creates the lazy plugin.
	 * @class The Lazy Plugin
	 * @param {Owl} carousel - The Owl Carousel
	 */
    var Lazy = function (carousel) {

		/**
		 * Reference to the core.
		 * @protected
		 * @type {Owl}
		 */
        this._core = carousel;

		/**
		 * Already loaded items.
		 * @protected
		 * @type {Array.<jQuery>}
		 */
        this._loaded = [];

		/**
		 * Event handlers.
		 * @protected
		 * @type {Object}
		 */
        this._handlers = {
            'initialized.owl.carousel change.owl.carousel resized.owl.carousel': $.proxy(function (e) {
                if (!e.namespace) {
                    return;
                }

                if (!this._core.settings || !this._core.settings.lazyLoad) {
                    return;
                }

                if ((e.property && e.property.name == 'position') || e.type == 'initialized') {
                    var settings = this._core.settings,
                        n = (settings.center && Math.ceil(settings.items / 2) || settings.items),
                        i = ((settings.center && n * -1) || 0),
                        position = (e.property && e.property.value !== undefined ? e.property.value : this._core.current()) + i,
                        clones = this._core.clones().length,
                        load = $.proxy(function (i, v) { this.load(v) }, this);

                    while (i++ < n) {
                        this.load(clones / 2 + this._core.relative(position));
                        clones && $.each(this._core.clones(this._core.relative(position)), load);
                        position++;
                    }
                }
            }, this)
        };

        // set the default options
        this._core.options = $.extend({}, Lazy.Defaults, this._core.options);

        // register event handler
        this._core.$element.on(this._handlers);
    };

	/**
	 * Default options.
	 * @public
	 */
    Lazy.Defaults = {
        lazyLoad: false
    };

	/**
	 * Loads all resources of an item at the specified position.
	 * @param {Number} position - The absolute position of the item.
	 * @protected
	 */
    Lazy.prototype.load = function (position) {
        var $item = this._core.$stage.children().eq(position),
            $elements = $item && $item.find('.owl-lazy');

        if (!$elements || $.inArray($item.get(0), this._loaded) > -1) {
            return;
        }

        $elements.each($.proxy(function (index, element) {
            var $element = $(element), image,
                url = (window.devicePixelRatio > 1 && $element.attr('data-src-retina')) || $element.attr('data-src');

            this._core.trigger('load', { element: $element, url: url }, 'lazy');

            if ($element.is('img')) {
                $element.one('load.owl.lazy', $.proxy(function () {
                    $element.css('opacity', 1);
                    this._core.trigger('loaded', { element: $element, url: url }, 'lazy');
                }, this)).attr('src', url);
            } else {
                image = new Image();
                image.onload = $.proxy(function () {
                    $element.css({
                        'background-image': 'url("' + url + '")',
                        'opacity': '1'
                    });
                    this._core.trigger('loaded', { element: $element, url: url }, 'lazy');
                }, this);
                image.src = url;
            }
        }, this));

        this._loaded.push($item.get(0));
    };

	/**
	 * Destroys the plugin.
	 * @public
	 */
    Lazy.prototype.destroy = function () {
        var handler, property;

        for (handler in this.handlers) {
            this._core.$element.off(handler, this.handlers[handler]);
        }
        for (property in Object.getOwnPropertyNames(this)) {
            typeof this[property] != 'function' && (this[property] = null);
        }
    };

    $.fn.owlCarousel.Constructor.Plugins.Lazy = Lazy;

})(window.Zepto || window.jQuery, window, document);

/**
 * AutoHeight Plugin
 * @version 2.1.0
 * @author Bartosz Wojciechowski
 * @author David Deutsch
 * @license The MIT License (MIT)
 */
; (function ($, window, document, undefined) {

	/**
	 * Creates the auto height plugin.
	 * @class The Auto Height Plugin
	 * @param {Owl} carousel - The Owl Carousel
	 */
    var AutoHeight = function (carousel) {
		/**
		 * Reference to the core.
		 * @protected
		 * @type {Owl}
		 */
        this._core = carousel;

		/**
		 * All event handlers.
		 * @protected
		 * @type {Object}
		 */
        this._handlers = {
            'initialized.owl.carousel refreshed.owl.carousel': $.proxy(function (e) {
                if (e.namespace && this._core.settings.autoHeight) {
                    this.update();
                }
            }, this),
            'changed.owl.carousel': $.proxy(function (e) {
                if (e.namespace && this._core.settings.autoHeight && e.property.name == 'position') {
                    this.update();
                }
            }, this),
            'loaded.owl.lazy': $.proxy(function (e) {
                if (e.namespace && this._core.settings.autoHeight
                    && e.element.closest('.' + this._core.settings.itemClass).index() === this._core.current()) {
                    this.update();
                }
            }, this)
        };

        // set default options
        this._core.options = $.extend({}, AutoHeight.Defaults, this._core.options);

        // register event handlers
        this._core.$element.on(this._handlers);
    };

	/**
	 * Default options.
	 * @public
	 */
    AutoHeight.Defaults = {
        autoHeight: false,
        autoHeightClass: 'owl-height'
    };

	/**
	 * Updates the view.
	 */
    AutoHeight.prototype.update = function () {
        var start = this._core._current,
            end = start + this._core.settings.items,
            visible = this._core.$stage.children().toArray().slice(start, end),
            heights = [],
            maxheight = 0;

        $.each(visible, function (index, item) {
            heights.push($(item).height());
        });

        maxheight = Math.max.apply(null, heights);

        this._core.$stage.parent()
            .height(maxheight)
            .addClass(this._core.settings.autoHeightClass);
    };

    AutoHeight.prototype.destroy = function () {
        var handler, property;

        for (handler in this._handlers) {
            this._core.$element.off(handler, this._handlers[handler]);
        }
        for (property in Object.getOwnPropertyNames(this)) {
            typeof this[property] != 'function' && (this[property] = null);
        }
    };

    $.fn.owlCarousel.Constructor.Plugins.AutoHeight = AutoHeight;

})(window.Zepto || window.jQuery, window, document);

/**
 * Video Plugin
 * @version 2.1.0
 * @author Bartosz Wojciechowski
 * @author David Deutsch
 * @license The MIT License (MIT)
 */
; (function ($, window, document, undefined) {

	/**
	 * Creates the video plugin.
	 * @class The Video Plugin
	 * @param {Owl} carousel - The Owl Carousel
	 */
    var Video = function (carousel) {
		/**
		 * Reference to the core.
		 * @protected
		 * @type {Owl}
		 */
        this._core = carousel;

		/**
		 * Cache all video URLs.
		 * @protected
		 * @type {Object}
		 */
        this._videos = {};

		/**
		 * Current playing item.
		 * @protected
		 * @type {jQuery}
		 */
        this._playing = null;

		/**
		 * All event handlers.
		 * @todo The cloned content removale is too late
		 * @protected
		 * @type {Object}
		 */
        this._handlers = {
            'initialized.owl.carousel': $.proxy(function (e) {
                if (e.namespace) {
                    this._core.register({ type: 'state', name: 'playing', tags: ['interacting'] });
                }
            }, this),
            'resize.owl.carousel': $.proxy(function (e) {
                if (e.namespace && this._core.settings.video && this.isInFullScreen()) {
                    e.preventDefault();
                }
            }, this),
            'refreshed.owl.carousel': $.proxy(function (e) {
                if (e.namespace && this._core.is('resizing')) {
                    this._core.$stage.find('.cloned .owl-video-frame').remove();
                }
            }, this),
            'changed.owl.carousel': $.proxy(function (e) {
                if (e.namespace && e.property.name === 'position' && this._playing) {
                    this.stop();
                }
            }, this),
            'prepared.owl.carousel': $.proxy(function (e) {
                if (!e.namespace) {
                    return;
                }

                var $element = $(e.content).find('.owl-video');

                if ($element.length) {
                    $element.css('display', 'none');
                    this.fetch($element, $(e.content));
                }
            }, this)
        };

        // set default options
        this._core.options = $.extend({}, Video.Defaults, this._core.options);

        // register event handlers
        this._core.$element.on(this._handlers);

        this._core.$element.on('click.owl.video', '.owl-video-play-icon', $.proxy(function (e) {
            this.play(e);
        }, this));
    };

	/**
	 * Default options.
	 * @public
	 */
    Video.Defaults = {
        video: false,
        videoHeight: false,
        videoWidth: false
    };

	/**
	 * Gets the video ID and the type (YouTube/Vimeo/vzaar only).
	 * @protected
	 * @param {jQuery} target - The target containing the video data.
	 * @param {jQuery} item - The item containing the video.
	 */
    Video.prototype.fetch = function (target, item) {
        var type = (function () {
            if (target.attr('data-vimeo-id')) {
                return 'vimeo';
            } else if (target.attr('data-vzaar-id')) {
                return 'vzaar'
            } else {
                return 'youtube';
            }
        })(),
            id = target.attr('data-vimeo-id') || target.attr('data-youtube-id') || target.attr('data-vzaar-id'),
            width = target.attr('data-width') || this._core.settings.videoWidth,
            height = target.attr('data-height') || this._core.settings.videoHeight,
            url = target.attr('href');

        if (url) {

			/*
					Parses the id's out of the following urls (and probably more):
					https://www.youtube.com/watch?v=:id
					https://youtu.be/:id
					https://vimeo.com/:id
					https://vimeo.com/channels/:channel/:id
					https://vimeo.com/groups/:group/videos/:id
					https://app.vzaar.com/videos/:id

					Visual example: https://regexper.com/#(http%3A%7Chttps%3A%7C)%5C%2F%5C%2F(player.%7Cwww.%7Capp.)%3F(vimeo%5C.com%7Cyoutu(be%5C.com%7C%5C.be%7Cbe%5C.googleapis%5C.com)%7Cvzaar%5C.com)%5C%2F(video%5C%2F%7Cvideos%5C%2F%7Cembed%5C%2F%7Cchannels%5C%2F.%2B%5C%2F%7Cgroups%5C%2F.%2B%5C%2F%7Cwatch%5C%3Fv%3D%7Cv%5C%2F)%3F(%5BA-Za-z0-9._%25-%5D*)(%5C%26%5CS%2B)%3F
			*/

            id = url.match(/(http:|https:|)\/\/(player.|www.|app.)?(vimeo\.com|youtu(be\.com|\.be|be\.googleapis\.com)|vzaar\.com)\/(video\/|videos\/|embed\/|channels\/.+\/|groups\/.+\/|watch\?v=|v\/)?([A-Za-z0-9._%-]*)(\&\S+)?/);

            if (id[3].indexOf('youtu') > -1) {
                type = 'youtube';
            } else if (id[3].indexOf('vimeo') > -1) {
                type = 'vimeo';
            } else if (id[3].indexOf('vzaar') > -1) {
                type = 'vzaar';
            } else {
                throw new Error('Video URL not supported.');
            }
            id = id[6];
        } else {
            throw new Error('Missing video URL.');
        }

        this._videos[url] = {
            type: type,
            id: id,
            width: width,
            height: height
        };

        item.attr('data-video', url);

        this.thumbnail(target, this._videos[url]);
    };

	/**
	 * Creates video thumbnail.
	 * @protected
	 * @param {jQuery} target - The target containing the video data.
	 * @param {Object} info - The video info object.
	 * @see `fetch`
	 */
    Video.prototype.thumbnail = function (target, video) {
        var tnLink,
            icon,
            path,
            dimensions = video.width && video.height ? 'style="width:' + video.width + 'px;height:' + video.height + 'px;"' : '',
            customTn = target.find('img'),
            srcType = 'src',
            lazyClass = '',
            settings = this._core.settings,
            create = function (path) {
                icon = '<div class="owl-video-play-icon"></div>';

                if (settings.lazyLoad) {
                    tnLink = '<div class="owl-video-tn ' + lazyClass + '" ' + srcType + '="' + path + '"></div>';
                } else {
                    tnLink = '<div class="owl-video-tn" style="opacity:1;background-image:url(' + path + ')"></div>';
                }
                target.after(tnLink);
                target.after(icon);
            };

        // wrap video content into owl-video-wrapper div
        target.wrap('<div class="owl-video-wrapper"' + dimensions + '></div>');

        if (this._core.settings.lazyLoad) {
            srcType = 'data-src';
            lazyClass = 'owl-lazy';
        }

        // custom thumbnail
        if (customTn.length) {
            create(customTn.attr(srcType));
            customTn.remove();
            return false;
        }

        if (video.type === 'youtube') {
            path = "//img.youtube.com/vi/" + video.id + "/hqdefault.jpg";
            create(path);
        } else if (video.type === 'vimeo') {
            $.ajax({
                type: 'GET',
                url: '//vimeo.com/api/v2/video/' + video.id + '.json',
                jsonp: 'callback',
                dataType: 'jsonp',
                success: function (data) {
                    path = data[0].thumbnail_large;
                    create(path);
                }
            });
        } else if (video.type === 'vzaar') {
            $.ajax({
                type: 'GET',
                url: '//vzaar.com/api/videos/' + video.id + '.json',
                jsonp: 'callback',
                dataType: 'jsonp',
                success: function (data) {
                    path = data.framegrab_url;
                    create(path);
                }
            });
        }
    };

	/**
	 * Stops the current video.
	 * @public
	 */
    Video.prototype.stop = function () {
        this._core.trigger('stop', null, 'video');
        this._playing.find('.owl-video-frame').remove();
        this._playing.removeClass('owl-video-playing');
        this._playing = null;
        this._core.leave('playing');
        this._core.trigger('stopped', null, 'video');
    };

	/**
	 * Starts the current video.
	 * @public
	 * @param {Event} event - The event arguments.
	 */
    Video.prototype.play = function (event) {
        var target = $(event.target),
            item = target.closest('.' + this._core.settings.itemClass),
            video = this._videos[item.attr('data-video')],
            width = video.width || '100%',
            height = video.height || this._core.$stage.height(),
            html;

        if (this._playing) {
            return;
        }

        this._core.enter('playing');
        this._core.trigger('play', null, 'video');

        item = this._core.items(this._core.relative(item.index()));

        this._core.reset(item.index());

        if (video.type === 'youtube') {
            html = '<iframe width="' + width + '" height="' + height + '" src="//www.youtube.com/embed/' +
                video.id + '?autoplay=1&rel=0&v=' + video.id + '" frameborder="0" allowfullscreen></iframe>';
        } else if (video.type === 'vimeo') {
            html = '<iframe src="//player.vimeo.com/video/' + video.id +
                '?autoplay=1" width="' + width + '" height="' + height +
                '" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>';
        } else if (video.type === 'vzaar') {
            html = '<iframe frameborder="0"' + 'height="' + height + '"' + 'width="' + width +
                '" allowfullscreen mozallowfullscreen webkitAllowFullScreen ' +
                'src="//view.vzaar.com/' + video.id + '/player?autoplay=true"></iframe>';
        }

        $('<div class="owl-video-frame">' + html + '</div>').insertAfter(item.find('.owl-video'));

        this._playing = item.addClass('owl-video-playing');
    };

	/**
	 * Checks whether an video is currently in full screen mode or not.
	 * @todo Bad style because looks like a readonly method but changes members.
	 * @protected
	 * @returns {Boolean}
	 */
    Video.prototype.isInFullScreen = function () {
        var element = document.fullscreenElement || document.mozFullScreenElement ||
            document.webkitFullscreenElement;

        return element && $(element).parent().hasClass('owl-video-frame');
    };

	/**
	 * Destroys the plugin.
	 */
    Video.prototype.destroy = function () {
        var handler, property;

        this._core.$element.off('click.owl.video');

        for (handler in this._handlers) {
            this._core.$element.off(handler, this._handlers[handler]);
        }
        for (property in Object.getOwnPropertyNames(this)) {
            typeof this[property] != 'function' && (this[property] = null);
        }
    };

    $.fn.owlCarousel.Constructor.Plugins.Video = Video;

})(window.Zepto || window.jQuery, window, document);

/**
 * Animate Plugin
 * @version 2.1.0
 * @author Bartosz Wojciechowski
 * @author David Deutsch
 * @license The MIT License (MIT)
 */
; (function ($, window, document, undefined) {

	/**
	 * Creates the animate plugin.
	 * @class The Navigation Plugin
	 * @param {Owl} scope - The Owl Carousel
	 */
    var Animate = function (scope) {
        this.core = scope;
        this.core.options = $.extend({}, Animate.Defaults, this.core.options);
        this.swapping = true;
        this.previous = undefined;
        this.next = undefined;

        this.handlers = {
            'change.owl.carousel': $.proxy(function (e) {
                if (e.namespace && e.property.name == 'position') {
                    this.previous = this.core.current();
                    this.next = e.property.value;
                }
            }, this),
            'drag.owl.carousel dragged.owl.carousel translated.owl.carousel': $.proxy(function (e) {
                if (e.namespace) {
                    this.swapping = e.type == 'translated';
                }
            }, this),
            'translate.owl.carousel': $.proxy(function (e) {
                if (e.namespace && this.swapping && (this.core.options.animateOut || this.core.options.animateIn)) {
                    this.swap();
                }
            }, this)
        };

        this.core.$element.on(this.handlers);
    };

	/**
	 * Default options.
	 * @public
	 */
    Animate.Defaults = {
        animateOut: false,
        animateIn: false
    };

	/**
	 * Toggles the animation classes whenever an translations starts.
	 * @protected
	 * @returns {Boolean|undefined}
	 */
    Animate.prototype.swap = function () {

        if (this.core.settings.items !== 1) {
            return;
        }

        if (!$.support.animation || !$.support.transition) {
            return;
        }

        this.core.speed(0);

        var left,
            clear = $.proxy(this.clear, this),
            previous = this.core.$stage.children().eq(this.previous),
            next = this.core.$stage.children().eq(this.next),
            incoming = this.core.settings.animateIn,
            outgoing = this.core.settings.animateOut;

        if (this.core.current() === this.previous) {
            return;
        }

        if (outgoing) {
            left = this.core.coordinates(this.previous) - this.core.coordinates(this.next);
            previous.one($.support.animation.end, clear)
                .css({ 'left': left + 'px' })
                .addClass('animated owl-animated-out')
                .addClass(outgoing);
        }

        if (incoming) {
            next.one($.support.animation.end, clear)
                .addClass('animated owl-animated-in')
                .addClass(incoming);
        }
    };

    Animate.prototype.clear = function (e) {
        $(e.target).css({ 'left': '' })
            .removeClass('animated owl-animated-out owl-animated-in')
            .removeClass(this.core.settings.animateIn)
            .removeClass(this.core.settings.animateOut);
        this.core.onTransitionEnd();
    };

	/**
	 * Destroys the plugin.
	 * @public
	 */
    Animate.prototype.destroy = function () {
        var handler, property;

        for (handler in this.handlers) {
            this.core.$element.off(handler, this.handlers[handler]);
        }
        for (property in Object.getOwnPropertyNames(this)) {
            typeof this[property] != 'function' && (this[property] = null);
        }
    };

    $.fn.owlCarousel.Constructor.Plugins.Animate = Animate;

})(window.Zepto || window.jQuery, window, document);

/**
 * Autoplay Plugin
 * @version 2.1.0
 * @author Bartosz Wojciechowski
 * @author Artus Kolanowski
 * @author David Deutsch
 * @license The MIT License (MIT)
 */
; (function ($, window, document, undefined) {

	/**
	 * Creates the autoplay plugin.
	 * @class The Autoplay Plugin
	 * @param {Owl} scope - The Owl Carousel
	 */
    var Autoplay = function (carousel) {
		/**
		 * Reference to the core.
		 * @protected
		 * @type {Owl}
		 */
        this._core = carousel;

		/**
		 * The autoplay timeout.
		 * @type {Timeout}
		 */
        this._timeout = null;

		/**
		 * Indicates whenever the autoplay is paused.
		 * @type {Boolean}
		 */
        this._paused = false;

		/**
		 * All event handlers.
		 * @protected
		 * @type {Object}
		 */
        this._handlers = {
            'changed.owl.carousel': $.proxy(function (e) {
                if (e.namespace && e.property.name === 'settings') {
                    if (this._core.settings.autoplay) {
                        this.play();
                    } else {
                        this.stop();
                    }
                } else if (e.namespace && e.property.name === 'position') {
                    //console.log('play?', e);
                    if (this._core.settings.autoplay) {
                        this._setAutoPlayInterval();
                    }
                }
            }, this),
            'initialized.owl.carousel': $.proxy(function (e) {
                if (e.namespace && this._core.settings.autoplay) {
                    this.play();
                }
            }, this),
            'play.owl.autoplay': $.proxy(function (e, t, s) {
                if (e.namespace) {
                    this.play(t, s);
                }
            }, this),
            'stop.owl.autoplay': $.proxy(function (e) {
                if (e.namespace) {
                    this.stop();
                }
            }, this),
            'mouseover.owl.autoplay': $.proxy(function () {
                if (this._core.settings.autoplayHoverPause && this._core.is('rotating')) {
                    this.pause();
                }
            }, this),
            'mouseleave.owl.autoplay': $.proxy(function () {
                if (this._core.settings.autoplayHoverPause && this._core.is('rotating')) {
                    this.play();
                }
            }, this),
            'touchstart.owl.core': $.proxy(function () {
                if (this._core.settings.autoplayHoverPause && this._core.is('rotating')) {
                    this.pause();
                }
            }, this),
            'touchend.owl.core': $.proxy(function () {
                if (this._core.settings.autoplayHoverPause) {
                    this.play();
                }
            }, this)
        };

        // register event handlers
        this._core.$element.on(this._handlers);

        // set default options
        this._core.options = $.extend({}, Autoplay.Defaults, this._core.options);
    };

	/**
	 * Default options.
	 * @public
	 */
    Autoplay.Defaults = {
        autoplay: false,
        autoplayTimeout: 5000,
        autoplayHoverPause: false,
        autoplaySpeed: false
    };

	/**
	 * Starts the autoplay.
	 * @public
	 * @param {Number} [timeout] - The interval before the next animation starts.
	 * @param {Number} [speed] - The animation speed for the animations.
	 */
    Autoplay.prototype.play = function (timeout, speed) {
        this._paused = false;

        if (this._core.is('rotating')) {
            return;
        }

        this._core.enter('rotating');

        this._setAutoPlayInterval();
    };

	/**
	 * Gets a new timeout
	 * @private
	 * @param {Number} [timeout] - The interval before the next animation starts.
	 * @param {Number} [speed] - The animation speed for the animations.
	 * @return {Timeout}
	 */
    Autoplay.prototype._getNextTimeout = function (timeout, speed) {
        if (this._timeout) {
            window.clearTimeout(this._timeout);
        }
        return window.setTimeout($.proxy(function () {
            if (this._paused || this._core.is('busy') || this._core.is('interacting') || document.hidden) {
                return;
            }
            this._core.next(speed || this._core.settings.autoplaySpeed);
        }, this), timeout || this._core.settings.autoplayTimeout);
    };

	/**
	 * Sets autoplay in motion.
	 * @private
	 */
    Autoplay.prototype._setAutoPlayInterval = function () {
        this._timeout = this._getNextTimeout();
    };

	/**
	 * Stops the autoplay.
	 * @public
	 */
    Autoplay.prototype.stop = function () {
        if (!this._core.is('rotating')) {
            return;
        }

        window.clearTimeout(this._timeout);
        this._core.leave('rotating');
    };

	/**
	 * Stops the autoplay.
	 * @public
	 */
    Autoplay.prototype.pause = function () {
        if (!this._core.is('rotating')) {
            return;
        }

        this._paused = true;
    };

	/**
	 * Destroys the plugin.
	 */
    Autoplay.prototype.destroy = function () {
        var handler, property;

        this.stop();

        for (handler in this._handlers) {
            this._core.$element.off(handler, this._handlers[handler]);
        }
        for (property in Object.getOwnPropertyNames(this)) {
            typeof this[property] != 'function' && (this[property] = null);
        }
    };

    $.fn.owlCarousel.Constructor.Plugins.autoplay = Autoplay;

})(window.Zepto || window.jQuery, window, document);

/**
 * Navigation Plugin
 * @version 2.1.0
 * @author Artus Kolanowski
 * @author David Deutsch
 * @license The MIT License (MIT)
 */
; (function ($, window, document, undefined) {
    'use strict';

	/**
	 * Creates the navigation plugin.
	 * @class The Navigation Plugin
	 * @param {Owl} carousel - The Owl Carousel.
	 */
    var Navigation = function (carousel) {
		/**
		 * Reference to the core.
		 * @protected
		 * @type {Owl}
		 */
        this._core = carousel;

		/**
		 * Indicates whether the plugin is initialized or not.
		 * @protected
		 * @type {Boolean}
		 */
        this._initialized = false;

		/**
		 * The current paging indexes.
		 * @protected
		 * @type {Array}
		 */
        this._pages = [];

		/**
		 * All DOM elements of the user interface.
		 * @protected
		 * @type {Object}
		 */
        this._controls = {};

		/**
		 * Markup for an indicator.
		 * @protected
		 * @type {Array.<String>}
		 */
        this._templates = [];

		/**
		 * The carousel element.
		 * @type {jQuery}
		 */
        this.$element = this._core.$element;

		/**
		 * Overridden methods of the carousel.
		 * @protected
		 * @type {Object}
		 */
        this._overrides = {
            next: this._core.next,
            prev: this._core.prev,
            to: this._core.to
        };

		/**
		 * All event handlers.
		 * @protected
		 * @type {Object}
		 */
        this._handlers = {
            'prepared.owl.carousel': $.proxy(function (e) {
                if (e.namespace && this._core.settings.dotsData) {
                    this._templates.push('<div class="' + this._core.settings.dotClass + '">' +
                        $(e.content).find('[data-dot]').addBack('[data-dot]').attr('data-dot') + '</div>');
                }
            }, this),
            'added.owl.carousel': $.proxy(function (e) {
                if (e.namespace && this._core.settings.dotsData) {
                    this._templates.splice(e.position, 0, this._templates.pop());
                }
            }, this),
            'remove.owl.carousel': $.proxy(function (e) {
                if (e.namespace && this._core.settings.dotsData) {
                    this._templates.splice(e.position, 1);
                }
            }, this),
            'changed.owl.carousel': $.proxy(function (e) {
                if (e.namespace && e.property.name == 'position') {
                    this.draw();
                }
            }, this),
            'initialized.owl.carousel': $.proxy(function (e) {
                if (e.namespace && !this._initialized) {
                    this._core.trigger('initialize', null, 'navigation');
                    this.initialize();
                    this.update();
                    this.draw();
                    this._initialized = true;
                    this._core.trigger('initialized', null, 'navigation');
                }
            }, this),
            'refreshed.owl.carousel': $.proxy(function (e) {
                if (e.namespace && this._initialized) {
                    this._core.trigger('refresh', null, 'navigation');
                    this.update();
                    this.draw();
                    this._core.trigger('refreshed', null, 'navigation');
                }
            }, this)
        };

        // set default options
        this._core.options = $.extend({}, Navigation.Defaults, this._core.options);

        // register event handlers
        this.$element.on(this._handlers);
    };

	/**
	 * Default options.
	 * @public
	 * @todo Rename `slideBy` to `navBy`
	 */
    Navigation.Defaults = {
        nav: false,
        navText: ['prev', 'next'],
        navSpeed: false,
        navElement: 'div',
        navContainer: false,
        navContainerClass: 'owl-nav',
        navClass: ['owl-prev', 'owl-next'],
        slideBy: 1,
        dotClass: 'owl-dot',
        dotsClass: 'owl-dots',
        dots: true,
        dotsEach: false,
        dotsData: false,
        dotsSpeed: false,
        dotsContainer: false
    };

	/**
	 * Initializes the layout of the plugin and extends the carousel.
	 * @protected
	 */
    Navigation.prototype.initialize = function () {
        var override,
            settings = this._core.settings;

        // create DOM structure for relative navigation
        this._controls.$relative = (settings.navContainer ? $(settings.navContainer)
            : $('<div>').addClass(settings.navContainerClass).appendTo(this.$element)).addClass('disabled');

        this._controls.$previous = $('<' + settings.navElement + '>')
            .addClass(settings.navClass[0])
            .html(settings.navText[0])
            .prependTo(this._controls.$relative)
            .on('click', $.proxy(function (e) {
                this.prev(settings.navSpeed);
            }, this));
        this._controls.$next = $('<' + settings.navElement + '>')
            .addClass(settings.navClass[1])
            .html(settings.navText[1])
            .appendTo(this._controls.$relative)
            .on('click', $.proxy(function (e) {
                this.next(settings.navSpeed);
            }, this));

        // create DOM structure for absolute navigation
        if (!settings.dotsData) {
            this._templates = [$('<div>')
                .addClass(settings.dotClass)
                .append($('<span>'))
                .prop('outerHTML')];
        }

        this._controls.$absolute = (settings.dotsContainer ? $(settings.dotsContainer)
            : $('<div>').addClass(settings.dotsClass).appendTo(this.$element)).addClass('disabled');

        this._controls.$absolute.on('click', 'div', $.proxy(function (e) {
            var index = $(e.target).parent().is(this._controls.$absolute)
                ? $(e.target).index() : $(e.target).parent().index();

            e.preventDefault();

            this.to(index, settings.dotsSpeed);
        }, this));

        // override public methods of the carousel
        for (override in this._overrides) {
            this._core[override] = $.proxy(this[override], this);
        }
    };

	/**
	 * Destroys the plugin.
	 * @protected
	 */
    Navigation.prototype.destroy = function () {
        var handler, control, property, override;

        for (handler in this._handlers) {
            this.$element.off(handler, this._handlers[handler]);
        }
        for (control in this._controls) {
            this._controls[control].remove();
        }
        for (override in this.overides) {
            this._core[override] = this._overrides[override];
        }
        for (property in Object.getOwnPropertyNames(this)) {
            typeof this[property] != 'function' && (this[property] = null);
        }
    };

	/**
	 * Updates the internal state.
	 * @protected
	 */
    Navigation.prototype.update = function () {
        var i, j, k,
            lower = this._core.clones().length / 2,
            upper = lower + this._core.items().length,
            maximum = this._core.maximum(true),
            settings = this._core.settings,
            size = settings.center || settings.autoWidth || settings.dotsData
                ? 1 : settings.dotsEach || settings.items;

        if (settings.slideBy !== 'page') {
            settings.slideBy = Math.min(settings.slideBy, settings.items);
        }

        if (settings.dots || settings.slideBy == 'page') {
            this._pages = [];

            for (i = lower, j = 0, k = 0; i < upper; i++) {
                if (j >= size || j === 0) {
                    this._pages.push({
                        start: Math.min(maximum, i - lower),
                        end: i - lower + size - 1
                    });
                    if (Math.min(maximum, i - lower) === maximum) {
                        break;
                    }
                    j = 0, ++k;
                }
                j += this._core.mergers(this._core.relative(i));
            }
        }
    };

	/**
	 * Draws the user interface.
	 * @todo The option `dotsData` wont work.
	 * @protected
	 */
    Navigation.prototype.draw = function () {
        var difference,
            settings = this._core.settings,
            disabled = this._core.items().length <= settings.items,
            index = this._core.relative(this._core.current()),
            loop = settings.loop || settings.rewind;

        this._controls.$relative.toggleClass('disabled', !settings.nav || disabled);

        if (settings.nav) {
            this._controls.$previous.toggleClass('disabled', !loop && index <= this._core.minimum(true));
            this._controls.$next.toggleClass('disabled', !loop && index >= this._core.maximum(true));
        }

        this._controls.$absolute.toggleClass('disabled', !settings.dots || disabled);

        if (settings.dots) {
            difference = this._pages.length - this._controls.$absolute.children().length;

            if (settings.dotsData && difference !== 0) {
                this._controls.$absolute.html(this._templates.join(''));
            } else if (difference > 0) {
                this._controls.$absolute.append(new Array(difference + 1).join(this._templates[0]));
            } else if (difference < 0) {
                this._controls.$absolute.children().slice(difference).remove();
            }

            this._controls.$absolute.find('.active').removeClass('active');
            this._controls.$absolute.children().eq($.inArray(this.current(), this._pages)).addClass('active');
        }
    };

	/**
	 * Extends event data.
	 * @protected
	 * @param {Event} event - The event object which gets thrown.
	 */
    Navigation.prototype.onTrigger = function (event) {
        var settings = this._core.settings;

        event.page = {
            index: $.inArray(this.current(), this._pages),
            count: this._pages.length,
            size: settings && (settings.center || settings.autoWidth || settings.dotsData
                ? 1 : settings.dotsEach || settings.items)
        };
    };

	/**
	 * Gets the current page position of the carousel.
	 * @protected
	 * @returns {Number}
	 */
    Navigation.prototype.current = function () {
        var current = this._core.relative(this._core.current());
        return $.grep(this._pages, $.proxy(function (page, index) {
            return page.start <= current && page.end >= current;
        }, this)).pop();
    };

	/**
	 * Gets the current succesor/predecessor position.
	 * @protected
	 * @returns {Number}
	 */
    Navigation.prototype.getPosition = function (successor) {
        var position, length,
            settings = this._core.settings;

        if (settings.slideBy == 'page') {
            position = $.inArray(this.current(), this._pages);
            length = this._pages.length;
            successor ? ++position : --position;
            position = this._pages[((position % length) + length) % length].start;
        } else {
            position = this._core.relative(this._core.current());
            length = this._core.items().length;
            successor ? position += settings.slideBy : position -= settings.slideBy;
        }

        return position;
    };

	/**
	 * Slides to the next item or page.
	 * @public
	 * @param {Number} [speed=false] - The time in milliseconds for the transition.
	 */
    Navigation.prototype.next = function (speed) {
        $.proxy(this._overrides.to, this._core)(this.getPosition(true), speed);
    };

	/**
	 * Slides to the previous item or page.
	 * @public
	 * @param {Number} [speed=false] - The time in milliseconds for the transition.
	 */
    Navigation.prototype.prev = function (speed) {
        $.proxy(this._overrides.to, this._core)(this.getPosition(false), speed);
    };

	/**
	 * Slides to the specified item or page.
	 * @public
	 * @param {Number} position - The position of the item or page.
	 * @param {Number} [speed] - The time in milliseconds for the transition.
	 * @param {Boolean} [standard=false] - Whether to use the standard behaviour or not.
	 */
    Navigation.prototype.to = function (position, speed, standard) {
        var length;

        if (!standard && this._pages.length) {
            length = this._pages.length;
            $.proxy(this._overrides.to, this._core)(this._pages[((position % length) + length) % length].start, speed);
        } else {
            $.proxy(this._overrides.to, this._core)(position, speed);
        }
    };

    $.fn.owlCarousel.Constructor.Plugins.Navigation = Navigation;

})(window.Zepto || window.jQuery, window, document);

/**
 * Hash Plugin
 * @version 2.1.0
 * @author Artus Kolanowski
 * @author David Deutsch
 * @license The MIT License (MIT)
 */
; (function ($, window, document, undefined) {
    'use strict';

	/**
	 * Creates the hash plugin.
	 * @class The Hash Plugin
	 * @param {Owl} carousel - The Owl Carousel
	 */
    var Hash = function (carousel) {
		/**
		 * Reference to the core.
		 * @protected
		 * @type {Owl}
		 */
        this._core = carousel;

		/**
		 * Hash index for the items.
		 * @protected
		 * @type {Object}
		 */
        this._hashes = {};

		/**
		 * The carousel element.
		 * @type {jQuery}
		 */
        this.$element = this._core.$element;

		/**
		 * All event handlers.
		 * @protected
		 * @type {Object}
		 */
        this._handlers = {
            'initialized.owl.carousel': $.proxy(function (e) {
                if (e.namespace && this._core.settings.startPosition === 'URLHash') {
                    $(window).trigger('hashchange.owl.navigation');
                }
            }, this),
            'prepared.owl.carousel': $.proxy(function (e) {
                if (e.namespace) {
                    var hash = $(e.content).find('[data-hash]').addBack('[data-hash]').attr('data-hash');

                    if (!hash) {
                        return;
                    }

                    this._hashes[hash] = e.content;
                }
            }, this),
            'changed.owl.carousel': $.proxy(function (e) {
                if (e.namespace && e.property.name === 'position') {
                    var current = this._core.items(this._core.relative(this._core.current())),
                        hash = $.map(this._hashes, function (item, hash) {
                            return item === current ? hash : null;
                        }).join();

                    if (!hash || window.location.hash.slice(1) === hash) {
                        return;
                    }

                    window.location.hash = hash;
                }
            }, this)
        };

        // set default options
        this._core.options = $.extend({}, Hash.Defaults, this._core.options);

        // register the event handlers
        this.$element.on(this._handlers);

        // register event listener for hash navigation
        $(window).on('hashchange.owl.navigation', $.proxy(function (e) {
            var hash = window.location.hash.substring(1),
                items = this._core.$stage.children(),
                position = this._hashes[hash] && items.index(this._hashes[hash]);

            if (position === undefined || position === this._core.current()) {
                return;
            }

            this._core.to(this._core.relative(position), false, true);
        }, this));
    };

	/**
	 * Default options.
	 * @public
	 */
    Hash.Defaults = {
        URLhashListener: false
    };

	/**
	 * Destroys the plugin.
	 * @public
	 */
    Hash.prototype.destroy = function () {
        var handler, property;

        $(window).off('hashchange.owl.navigation');

        for (handler in this._handlers) {
            this._core.$element.off(handler, this._handlers[handler]);
        }
        for (property in Object.getOwnPropertyNames(this)) {
            typeof this[property] != 'function' && (this[property] = null);
        }
    };

    $.fn.owlCarousel.Constructor.Plugins.Hash = Hash;

})(window.Zepto || window.jQuery, window, document);

/**
 * Support Plugin
 *
 * @version 2.1.0
 * @author Vivid Planet Software GmbH
 * @author Artus Kolanowski
 * @author David Deutsch
 * @license The MIT License (MIT)
 */
; (function ($, window, document, undefined) {

    var style = $('<support>').get(0).style,
        prefixes = 'Webkit Moz O ms'.split(' '),
        events = {
            transition: {
                end: {
                    WebkitTransition: 'webkitTransitionEnd',
                    MozTransition: 'transitionend',
                    OTransition: 'oTransitionEnd',
                    transition: 'transitionend'
                }
            },
            animation: {
                end: {
                    WebkitAnimation: 'webkitAnimationEnd',
                    MozAnimation: 'animationend',
                    OAnimation: 'oAnimationEnd',
                    animation: 'animationend'
                }
            }
        },
        tests = {
            csstransforms: function () {
                return !!test('transform');
            },
            csstransforms3d: function () {
                return !!test('perspective');
            },
            csstransitions: function () {
                return !!test('transition');
            },
            cssanimations: function () {
                return !!test('animation');
            }
        };

    function test(property, prefixed) {
        var result = false,
            upper = property.charAt(0).toUpperCase() + property.slice(1);

        $.each((property + ' ' + prefixes.join(upper + ' ') + upper).split(' '), function (i, property) {
            if (style[property] !== undefined) {
                result = prefixed ? property : true;
                return false;
            }
        });

        return result;
    }

    function prefixed(property) {
        return test(property, true);
    }

    if (tests.csstransitions()) {
        /* jshint -W053 */
        $.support.transition = new String(prefixed('transition'))
        $.support.transition.end = events.transition.end[$.support.transition];
    }

    if (tests.cssanimations()) {
        /* jshint -W053 */
        $.support.animation = new String(prefixed('animation'))
        $.support.animation.end = events.animation.end[$.support.animation];
    }

    if (tests.csstransforms()) {
        /* jshint -W053 */
        $.support.transform = new String(prefixed('transform'));
        $.support.transform3d = tests.csstransforms3d();
    }

})(window.Zepto || window.jQuery, window, document);