var t8 = window.toastr8;
var resizeWindow = function () {
    try {
        var evt = window.document.createEvent('UIEvents');
        evt.initUIEvent('resize', true, false, window, 0);
        window.dispatchEvent(evt);
    } catch (err) {
        console.log('Window Resize function not working on this browser')
        console.info('Please Switch/Update browser to better experience')
        console.error(err);
    }
};
function ajaxModal(url, title, smalldata) {
    var urldata = url;
    var titledata = title;
    var options = {
        url: urldata,
        title: titledata,
        size: eModal.size.lg,
        subtitle: smalldata,
        buttons: [
            {text: 'Ok', style: 'info', close: true},
            {text: 'Cancel', style: 'danger', close: true}
        ],
    };
    eModal.ajax(options);
}
function alertModal(alertData, alertTitle) {
    var options = {
        message: alertData,
        title: alertTitle,
        size: eModal.size.sm,
        subtitle: "",
        useBin: true,
    };
    eModal.alert(options);
}
function confirmModal(cData, cTitle) {
    var title = 'Confirm modal callback feedback';
    return eModal
            .confirm('It is simple enough?', 'Confirm modal')
            .then(
                    function ( /* DOM */ ) {
                        t8.success('Thank you for your OK pressed!', title);
                    },
                    function ( /*null*/ ) {
                        t8.error('Thank you for your Cancel pressed!', title)
                    }
            );
}
function promptModal() {
    var title = 'Prompt modal callback feedback';
    return eModal
            .prompt({size: eModal.size.sm, message: 'What\'s your name?', title: title})
            .then(
                    function (input) {
                        t8.github({message: 'Hi ' + input + '!', title: title, imgURI: 'https://conversational-itxdesign.netdna-ssl.com/wp-content/uploads/2014/08/slider-girl.png'})
                    },
                    function ( /**/ ) {
                        t8.android('Why don\'t you tell me your name?', title);
                    });
}
function iframeModal(url, title) {
    return eModal
            .iframe(url, title)
            .then(function () {
                t8.success('iFrame loaded!!!!', title)
            });
}
function countUp(divClass) {
    $('.' + divClass).each(function () {
        var c_this = $(this);
        var c_value = parseInt(c_this.html())
        var div_by = 100,
                speed = Math.round(c_value / div_by),
                $display = c_this,
                run_count = 1,
                int_speed = 24;
        var int = setInterval(function () {
            if (run_count < div_by) {
                $display.text(speed * run_count);
                run_count++;
            } else if (parseInt($display.text()) < c_value) {
                var curr_count = parseInt($display.text()) + 1;
                $display.text(curr_count);
            } else {
                clearInterval(int);
            }
        }, int_speed);
    });
}
$(function () {
    // Side Menu Settings
    if (!$('aside').hasClass('menu-2')) {
        $(".has-sub.l1>a").click(function () {
            var l1 = $(this).parent();
            if (!l1.hasClass("open")) {
                $(".has-sub.l1").removeClass("open");
                $(".has-sub.l1>ul , .has-sub.l2>ul , .has-sub.l3>ul").slideUp();
                l1.addClass("open");
                l1.children(".sub-l1").slideDown();
            }
        });
        $(".has-sub.l2>a").click(function () {
            var l2 = $(this).parent();
            if (!l2.hasClass("open")) {
                $(".has-sub.l2").removeClass("open");
                $(".has-sub.l2>ul , .has-sub.l3>ul").slideUp();
                l2.addClass("open");
                l2.children(".sub-l2").slideDown();
            }
        });
        $(".has-sub.l3>a").click(function () {
            var l3 = $(this).parent();
            if (!l3.hasClass("open")) {
                $(".has-sub.l3").removeClass("open");
                $(".has-sub.l3>ul").slideUp();
                l3.addClass("open");
                l3.children(".sub-l3").slideDown();
            }
        });
    } else {
        var menufunction = function(el){
            $('.menu-2>li').removeClass('active');
            if(el.hasClass('onActive')){
                return true;
            }
            el.addClass('onActive');
            el.parent('li').addClass('active');
            var target_id = el.attr('data-target');
            targetHtml = $(target_id).html();
            if(targetHtml){
                var $submenu = '<ul class="menu-2-sub">' + targetHtml + '</ul>';
            }
            if (!target_id) {
                $submenu = '<ul class="menu-2-sub"></ul>';
            }
            var menu_name = $(this).parent('li').attr("id");
            $('#submenu-holder').html($submenu);
            $('#submenu-holder>ul').fadeIn();
            setTimeout(function(){
                try{
                    $("#submenu-holder").getNiceScroll().resize();
                }catch(e){}
            }, 500);
        };
        $('#submenu-holder').niceScroll({
            cursorcolor: "#43943b",
            cursoropacitymin: "0.3",
            cursoropacitymax: "0.7",
            cursorwidth: "4px",
            cursorborder: "0",
            cursorborderradius: "0",
            mousescrollstep: "10",
            // touchbehavior:true,
            autohidemode: true,
            background: "#ccc"
        });
        $('.menu-2>li>a').hover(function(){
            var $el=$(this);
            setTimeout(function(){
                if($el.is(":hover")){
                    menufunction($el);
                }
            }, 1000);
        } );
        $('.menu-2>li>a').click(function(){
            var $el=$(this);
            menufunction($el);
        } );
        $('.menu-2>li>a').on('mouseleave',function(){
            $(this).removeClass('onActive');
        });
        $('#submenu-holder').on('mouseenter', '.menu-2-sub>li', function () {
            $('.submenu-top').remove();
            $('.menu-2-sub>li').removeClass('active');
            var el_data = $('ul', this).html();
            $(this).addClass('active');
            if (el_data) {
                var this_position = $(this).offset();
                var eTop = this_position.top;
                var el_top = eTop - $(window).scrollTop() + $(this).outerHeight();
                var $submenu_top = $('<ul class="submenu-top">' + el_data + '</ul>');
                $('body').append($submenu_top);
                $submenu_top.css({'position': 'fixed', 'z-index': '9999999', 'top': el_top, 'left': this_position.left});
                $submenu_top.on('mouseleave', function () {
                    $('.submenu-top').remove();
                    $('.menu-2-sub>li').removeClass('active');
                });
            }
        }).on('mouseleave', '.menu-2-sub>li', function () {
            if (!$('.submenu-top:hover')) {
                $('.submenu-top').remove();
                $('.menu-2-sub>li').removeClass('active');
            }
        });
        $('aside').find('ul.menu-2>li.active>a').click();
    }
    var aside_scroll = {
        cursorcolor: "#43943b",
        cursoropacitymin: "0.0",
        cursoropacitymax: "0.7",
        cursorwidth: "4px",
        cursorborder: "0",
        cursorborderradius: "0",
        mousescrollstep: "10",
        // touchbehavior:true,
        autohidemode: true,
        background: "#ccc",
        zindex: 11002
    };
    $("aside").niceScroll(aside_scroll);
    $("aside a").click(function () {
        setTimeout(function () {
            $("aside").getNiceScroll().resize();
        }, 500);
    })
    $("aside").hover(function () {
        setTimeout(function () {
            $("aside").getNiceScroll().resize();
        }, 600);
    }, function () {
        setTimeout(function () {
            $("aside").getNiceScroll().resize();
        }, 400);
    });
    $(".menu-ham").click(function () {
        $(this).toggleClass("open");
        $("body").toggleClass("menu-closed")
        setTimeout(function () {
            try {
                var evt = window.document.createEvent('UIEvents');
                evt.initUIEvent('resize', true, false, window, 0);
                window.dispatchEvent(evt);
            } catch (err) {
                console.log('Window Resize function not working on this browser')
                console.info('Please Switch/Update browser to better experience')
                console.error(err);
            }
        }, 500);
    });
    $('[data-toggle="popover"],.popovers').popover();
    $('[data-toggle="tooltip"],.tooltips').tooltip({html: true});
    $('[data-mask]').each(function () {
        var dm = $(this).attr('data-mask');
        $(this).mask(dm);
    });
    $('.clockpicker').clockpicker({autoclose: true});
    $('.clockpicker12').clockpicker({autoclose: true,twelvehour:true});
    $('.datepicker').datetimepicker({
        format: 'DD/MM/YYYY',
        // debug: true,
        tooltips: {
            today: 'Go to today',
            clear: 'Clear selection',
            close: 'Close the picker',
            selectMonth: 'Select Month',
            prevMonth: 'Previous Month',
            nextMonth: 'Next Month',
            selectYear: 'Select Year',
            prevYear: 'Previous Year',
            nextYear: 'Next Year',
            selectDecade: 'Select Decade',
            prevDecade: 'Previous Decade',
            nextDecade: 'Next Decade',
            prevCentury: 'Previous Century',
            nextCentury: 'Next Century'
        }
    });
    $('.datetimepicker').datetimepicker({
        format: 'DD/MM/YYYY hh:mm a',
        showClose: true,
        showTodayButton: true,
        toolbarPlacement: 'top',
        // debug: true,
        tooltips: {
            today: 'Go to today',
            clear: 'Clear selection',
            close: 'Close the picker',
            selectMonth: 'Select Month',
            prevMonth: 'Previous Month',
            nextMonth: 'Next Month',
            selectYear: 'Select Year',
            prevYear: 'Previous Year',
            nextYear: 'Next Year',
            selectDecade: 'Select Decade',
            prevDecade: 'Previous Decade',
            nextDecade: 'Next Decade',
            prevCentury: 'Previous Century',
            nextCentury: 'Next Century'
        }
    });
    countUp('count');
    $.formUtils.addValidator({
        name: 'phone',
        validatorFunction: function (value, $el, config, language, $form) {
            var filter = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
            if (filter.test(value)) {
                return true;
            } else {
                return false;
            }
        },
        errorMessage: 'You have not given a correct phone number',
        errorMessageKey: 'badPhoneNumber'
    });
    $.formUtils.addValidator({
        name: 'phone_null',
        validatorFunction: function (value, $el, config, language, $form) {
            var filter = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
            if (filter.test(value) || !value) {
                return true;
            } else {
                return false;
            }
        },
        errorMessage: 'You have not given a correct phone number',
        errorMessageKey: 'badPhoneNumber_null'
    });
    $.formUtils.addValidator({
        name: "email_null",
        validatorFunction: function (b) {
            var c = b.toLowerCase().split("@"),
                    d = c[0],
                    e = c[1];
            if (d && e) {
                if (0 === d.indexOf('"')) {
                    var f = d.length;
                    if (d = d.replace(/\"/g, ""), d.length !== f - 2)
                        return !1
                }
                return a.formUtils.validators.validate_domain.validatorFunction(c[1]) && 0 !== d.indexOf(".") && "." !== d.substring(d.length - 1, d.length) && -1 === d.indexOf("..") && !/[^\w\+\.\-\#\-\_\~\!\$\&\'\(\)\*\+\,\;\=\:]/.test(d)
            } else if (!b) {
                return true;
            }
            return !1
        },
        errorMessage: "You have not given a correct e-mail address",
        errorMessageKey: "badEmail_null"
    })
    $.validate({lang: 'en'});
    $(".custom-data-table .dataTables_scrollBody").niceScroll({
        cursorcolor: "#b7b6b6",
        cursoropacitymin: "0.3",
        cursoropacitymax: "0.9",
        cursorwidth: "5px",
        cursorborder: "0",
        cursorborderradius: "2px",
        mousescrollstep: "10",
        autohidemode: true,
        background: "#f1f1f1"
    });
    $(".custom-data-table .dataTables_scrollBody").hover(function () {
        $(this).getNiceScroll().resize();
    });
    resizeWindow();
    $('body').on('click', '.cst-btn', function (e){
        e.preventDefault();
        $(this).parent().toggleClass('expand');
        $(this).parent().children().toggleClass('expand');
    });
}); //End of document.ready
$(window).load(function () {
    $("#loader").fadeOut();
});
$(document).ajaxComplete(function () {
    $.validate({lang: 'en'});
    $('[data-toggle="popover"]').popover();
    $('.popovers').popover();
    $('[data-toggle="tooltip"],.tooltips').tooltip({html: true});
    $('[data-mask]').each(function () {
        var dm = $(this).attr('data-mask');
        $(this).mask(dm);
    });
    $('.clockpicker').clockpicker({autoclose: true});
    $('.clockpicker12').clockpicker({autoclose: true,twelvehour:true});
    $('.datepicker').datetimepicker({
        format: 'DD/MM/YYYY',
        // debug:true,
        tooltips: {
            today: 'Go to today',
            clear: 'Clear selection',
            close: 'Close the picker',
            selectMonth: 'Select Month',
            prevMonth: 'Previous Month',
            nextMonth: 'Next Month',
            selectYear: 'Select Year',
            prevYear: 'Previous Year',
            nextYear: 'Next Year',
            selectDecade: 'Select Decade',
            prevDecade: 'Previous Decade',
            nextDecade: 'Next Decade',
            prevCentury: 'Previous Century',
            nextCentury: 'Next Century'
        }
    });
    $('.datetimepicker').datetimepicker({
        format: 'DD/MM/YYYY hh:mm a',
        showClose: true,
        showTodayButton: true,
        toolbarPlacement: 'top',
        // debug:true,
        tooltips: {
            today: 'Go to today',
            clear: 'Clear selection',
            close: 'Close the picker',
            selectMonth: 'Select Month',
            prevMonth: 'Previous Month',
            nextMonth: 'Next Month',
            selectYear: 'Select Year',
            prevYear: 'Previous Year',
            nextYear: 'Next Year',
            selectDecade: 'Select Decade',
            prevDecade: 'Previous Decade',
            nextDecade: 'Next Decade',
            prevCentury: 'Previous Century',
            nextCentury: 'Next Century'
        }
    });
    // $('[data-toggle="tab"]').click(function () {
    //     setTimeout(function () {
    //         resizeWindow();
    //     }, 50);
    // });
    
});
function tableRefresh(id){
    setTimeout(function(){
        $(id).resize()
    },50)
}