/* Script on ready
---------------------------------*/
$(document).ready(function () {

    $('form select').on('change', function(){$(this).closest('form').submit();});


    if($('table').length > 0){
        $('table').each(function(index, el) {
            if(! $(this).hasClass('table')){
                $(this).addClass('table');
                $(this).parents('div:first').addClass('daily-average table-responsive');
                // $(this).children('th:first').parents('tr:first').addClass('');
            }
        });
    }

    //----- slider script ----- //
    if($('.banner-slider').length > 0){
        $(".banner-slider").slick({
            slidesToShow: 1,
            slidesToScroll: 1,
            dots: true,
            autoplay: true,
			autoplaySpeed: 6000,
            responsive: [
                {
                    breakpoint: 768,
                    settings: {
                        slidesToShow: 1,
                        slidesToScroll: 1
                    }
                },
                {
                    breakpoint: 480,
                    settings: {
                        adaptiveHeight: true
                    }
                }
            ]
        });

        $('.banner-slider').on('afterChange', function(event, slick, currentSlide, nextSlide){
            if($('.banner-content').hasClass('banner-video-content')){
            if ($("video").parents(".banner-slides").hasClass("slick-active")) {$('#startup-video').get(0).play();} else {$('#startup-video').get(0).pause();}
            }
        });
    }


    //----- matchheight script ----- //
    $('.main-menu li').each(function () {
        $(this).find('.match-height-nav').matchHeight({
            byRow: true,
            property: 'height',
            target: null,
            remove: false
        });
    })
    $('.match-height').matchHeight();

    $('.freeform-row .freeform-column .freeform-label').matchHeight({
        property: 'min-height',
    });

    //----- mobile-menu script ----- //
    $(".hamburger").click(function(){
        $("#wrapper").toggleClass("menu-open")
        $(".nav-content ul li ul").slideUp();
        $(".nav-content ul li em").parent().find('em').removeClass('active');
        $(".nav-content ul li").removeClass('active');
    });
    $(".nav-content ul li ul").before('<em class="arrow"></em>');
    $(".nav-content ul li em").click(function(){
        if($(this).parent().hasClass('active')){
            $(this).parent().find('li').removeClass('active');
            $(this).parent().find("ul").slideUp();
            $(this).parent().removeClass('active');
            $(this).parent().find('em').removeClass('active');
        }
        else{
            $(this).addClass('active');
            $(this).parent().addClass('active');
            $(this).next().slideDown();
        }
    });

    /*$(".nav-content ul li" ).focusin(function() {
        if($(this).parent().hasClass('active')){
            $(this).parent().find('li').removeClass('active');
            $(this).parent().find("ul").slideUp();
            $(this).parent().removeClass('active');
            $(this).parent().find('em').removeClass('active');
        }
        else{
            $(this).addClass('active');
            $(this).find('em:first').addClass('active');
            // $(this).parent().addClass('active');
            $(this).find('ul:first').slideDown();
        }
    });*/

    $(document).on('click', '.nav-content ul li a', function(event) {
        if ($(this).next('em.arrow').length) {
            event.preventDefault();

            $(this).next().click();
            /*if (! $(this).next().hasClass('active')) {}*/}
    });

    //----- selct-box script ----- //
    if ($('.select-box').length > 0) {$('.select-box').select2();}

    //----- accordion script ----- //
    $('#myCollapsible').collapse({
        toggle: false
    })
    $(".accordion-click").click(function () {
        if($(this).hasClass('new-back')){$(this).removeClass('new-back');}else{
            $(".accordion-click").removeClass('new-back');
            $(this).addClass('new-back');
        }
    });

    //----- slide-toggle script ----- //
    $(".open-list").click(function(){
        if($(this).hasClass('open')){
            $(this).removeClass('open');
            $(this).parent().find("ul:first").stop().slideUp("slow");
        }else{
            $(this).addClass('open');
            $(this).parent().find("ul:first").stop().slideDown("slow");
        }
    });

    //----- tab to accordion script ----- //
    var $graph = $('#graph');
    $graph.on('show.bs.collapse','.collapse', function() {$graph.find('.collapse.in').collapse('hide');});

    //----- IE browser hack ----- //
    if (document.documentMode || /Edge/.test(navigator.userAgent)) {
        $('body #wrapper').addClass('ie-hack')
    }

    //----- scroll to top ----- //
    $(".to-top").click(function(event) {
        $('html, body').animate({scrollTop: "0px"}, 800);

    });


    //------ Added By Developer ------//
    $(".sitemap ul li").find("ul").parents("li").append("<em>")
    $(".sitemap ul li ul").addClass("first-sub");
    $(".sitemap ul li ul").next("em").addClass("first-em");
    $(".sitemap ul li ul ul").removeClass("first-sub");
    $(".sitemap ul li ul ul").addClass("second-sub");
    $(".sitemap ul li ul ul").next("em").addClass("second-em");
    $(".sitemap ul li ul ul").next("em").removeClass("first-em");
    $(".sitemap ul li em.first-em").click(function(e) {
        if ($(this).parent("li").hasClass("active")) {
            $(this).parent("li").removeClass("active");
            $(this).prev("ul.first-sub").slideUp();
            $(".sitemap ul li ul.second-sub li").removeClass("active");
            $(".sitemap ul li ul.second-sub").slideUp();
        } else {
            $(".sitemap ul li").removeClass("active");
            $(this).parent("li").addClass("active");
            $(".sitemap ul li ul.first-sub").slideUp();
            $(this).prev("ul.first-sub").slideDown();
            $(".sitemap ul li ul.second-sub li").removeClass("active");
            $(".sitemap ul li ul.second-sub").slideUp();
        }
    });
    $(".sitemap ul li ul.first-sub li em.second-em").click(function(e) {
        if ($(this).parent("li").hasClass("active")) {
            $(this).parent("li").removeClass("active");
            $(this).prev("ul.second-sub").slideUp();
        } else {
            $(".sitemap ul li ul li").removeClass("active");
            $(this).parent("li").addClass("active");
            $(".sitemap ul li ul.second-sub").slideUp();
            $(this).prev("ul.second-sub").slideDown();
        }
    });

    /* touch friendly navigation */
    $( 'nav li:has(ul)' ).doubleTapToGo();

    $('.header-top-content').find('a.header-links').clone().appendTo("ul#nav-sub").wrap("<li></li>")

    if($("#adv_modal").length)
    {
        var showPopup = getCookie("ad_show");
        if(showPopup != "no")
        {$('#adv_modal').modal('show');}

        $('#adv_modal').on('hidden.bs.modal', function () {
            setCookie("ad_show", "no", 1);
        })

        $('#adv_modal').find('a').click(function(event) {
            setCookie("ad_show", "no", 1);
        });
    }

    setTimeout(function() {banner_vid_height();}, 100);

    $('.animal-stats-block').find('strong').addClass('count');
    $('.count').each(function () {
        if(! isNaN($(this).text()))
        {
            $(this).prop('Counter',0).animate({
                Counter: $(this).text()
            }, {
                duration: 2000,
                easing: 'swing',
                step: function (now) {$(this).text(Math.ceil(now));}
            });
        }
    });

    // $.datepicker.setDefaults({ dateFormat: 'dd-mm-yy' });
    if ($('#dateFrom').length)
    {
        $("#dateFrom").datepicker({
            dateFormat: 'dd-mm-yy',
            maxDate: 0,
            onSelect: function (selected) {
                if(selected != "")
                {
                    var dt = generateDateWithFormatChange(selected);
                    $("#dateTo").datepicker("option", "minDate", dt);
                    dateConvert(dt, '.range-from-date-hide');
                }
            },
            onClose: function (selected) {
                if(selected == '')
                {$('.range-from-date-hide').val(null);}
            }
        });

        $("#dateTo").datepicker({
            dateFormat: 'dd-mm-yy',
            maxDate: 0,
            onSelect: function (selected) {
                if(selected != "")
                {
                    var dt = generateDateWithFormatChange(selected);
                    $("#dateFrom").datepicker("option", "maxDate", dt);
                    dateConvert(dt, '.range-to-date-hide');
                }
            },
            onClose: function (selected) {
                if(selected == '')
                {$('.range-to-date-hide').val(null);}
            }
        });
    }

    $(document).on('change', 'select[name="collection"]', function(event) {
        event.preventDefault();
        changeEventOfChannel();
    });

    changeEventOfChannel(true);

});

function changeEventOfChannel(firstTime = false)
{
    var value = $('select[name="collection"]').val();
    if(firstTime)
    {$('select[name="category"]').find('optgroup').hide();}
    else
    {
        $('select[name="category"]').find('optgroup').hide().val("");
        $('select[name="category"]').find('option[value=""]').prop('selected', true);
    }

    $('select[name="category"]').find('optgroup[data-' + value + '="true"]').removeAttr('style');
}

function dateConvert(date, className) {
    _timestamp = (new Date(date).getTime() / 1000);
    $(className).val(_timestamp);
}

function generateDateWithFormatChange(selected)
{
    var tmp = selected.split('-');
    var newDate = tmp[1] + '/' + tmp[0] + "/" + tmp[2];
    return new Date(newDate);
}

function timeStampConvert(classNameFirst, classNameSecond) {
    var dateTimestamp = $(classNameFirst).val();
    if (dateTimestamp != null && dateTimestamp != '') {
        var date = new Date(dateTimestamp * 1000);
        var finalDate = date.getDate() + '-' + (date.getMonth()+1) + '-' + date.getFullYear();
        $(classNameSecond).val(finalDate);
    }
}

/* Script on load
----------------------------------*/
$(window).load(function () {
    timeStampConvert('.range-from-date-hide', '#dateFrom');
    timeStampConvert('.range-to-date-hide', '#dateTo');

    $('.panel-collapse').removeClass('in');
    graph();
    banner_vid_height();

    if ($('#startup-video').length > 0) {$('#startup-video').get(0).play();}


});

/* Script on resize
---------------------------------*/
$(window).resize(function () {
    setTimeout(function() {banner_vid_height();}, 100)
});

function graph(){
    var byt = $("body").width();
    if(byt < 768){tabToAcor("#graph");}
    function tabToAcor(id){
        var link="";
        var inn = "";
        var ic = "";
        var ic2 = "";
        $(id).removeClass();
        $(id).addClass("panel-group cf");
        $(id).find(".nav li").each(function(e){
            if(e < 1){
                inn = "in";
            }else{
                inn = "";
            }
            link = $(this).find("a").attr("href");
            ic2 = $(this).find("a").html();
            $(link).removeAttr("role");
            $(link).removeClass();
            $(link).css("padding","0");
            $(link).addClass("panel panel-default pull-left col-xs-12 nopadding");
            ic = $(link).html();
            $(link).html("");
            $(link).prepend('<div class="panel-heading"><h4 class="panel-title"><a data-toggle="collapse" data-parent="' + link + '" href="' + link + '1">' + ic2 +'</a></h4></div>');
            $(link).append('<div id="' + link.substring(1,link.length) + '1" class="panel-collapse collapse ' + inn + '"><div class="panel-body"> ' + ic + '</div></div>');
        });
        $(id).find(".nav").remove();
    }
}

/* Script all functions
----------------------------------*/
(function( $, window, document, undefined )
 {
    $.fn.doubleTapToGo = function( params )
    {
        if( !( 'ontouchstart' in window ) &&
           !navigator.msMaxTouchPoints &&
           !navigator.userAgent.toLowerCase().match( /windows phone os 7/i ) ) return false;


        this.each( function()
                  {
            var curItem = false;

            $( this ).on( 'click', function( e )
                         {

                var item = $( this );
                if( item[ 0 ] != curItem[ 0 ] )
                {
                    e.preventDefault();
                    curItem = item;
                }
            });

            $( document ).on( 'click touchstart MSPointerDown', function( e )
                             {
                var resetItem = true,
                    parents   = $( e.target ).parents();

                for( var i = 0; i < parents.length; i++ )
                    if( parents[ i ] == curItem[ 0 ] )
                        resetItem = false;

                if( resetItem )
                    curItem = false;
            });
        });
        return this;
    };
})( jQuery, window, document );

function banner_vid_height(){
    $('#startup-video').parents('.banner-content').addClass('banner-video-content');
    var vid_hight = $("#startup-video").height();
    $(".banner-content").not('.banner-video-content').height(vid_hight);
}

function setCookie(cname, cvalue, exhours) {
    var d = new Date();
    d.setTime(d.getTime() + (exhours * 1 * 60 * 60 * 1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

