( function ($) { 
    $(document).ready(function(){
        

        function api( data, rfn ) {
            $.ajax({
                url: '/ajax',
                type: 'POST',
                data: data,
                success: function(rdata){
                    if ((rdata.substr(0,1) == '{') || (rdata.substr(0,1) == '[')) rdata = JSON.parse(rdata);
                    if (rfn) {
                        rfn(rdata);
                    }
                },
                error: function(xhr, ajaxOptions, thrownError){
                    if (xhr.status == 0) { rfn({result:'timeout'}); }
                }
            });
        }


        /* Notifications */
        function notify( message, classes, msec ) {
            var el = $('<div class="'+classes+'">'+message+'</div>');
            $('.log-info-box').prepend(el);
            if ( msec )
            setTimeout(function(){
                $(el).fadeOut(msec, function(){
                    $(el).remove();
                });
            }, msec);
        }


        /* Translate */
        function __( str, context = 'admin.mod.php' ) {
            if (!cms) return str;
            if (!cms.locale) return str;
            if (!cms.lang[context]) return str;
            if (!cms.lang[context][cms.locale][str]) return str;
            return cms.lang[context][cms.locale][str];
        }
        
        
        /* Logout */
        $('[data-logout]').click(function(){
            api({fn:'logout'},function(){
                window.location.reload(true);
            });
            return false;
        });
        
        
        /* Navigation */
        $('[data-am-page]').click(link_to_page);
        function link_to_page(){
            var page = $(this).attr('data-am-page');
            if (page) {
                $('[data-am-page]').removeClass('active');
                $(this).addClass('active');
                $('#'+page+' .main-main').animate({ scrollTop: 0 }, 500);
                $('aside,.bg-reset').removeClass('openpanel');
                $('body').removeClass('mobile-menu-open');
                $('.button-mobimenu-container').removeClass('menu-open');
                // Close top right menu
                document.getElementsByClassName("contmenu-group")[0].classList.remove("open");
            }
        }
        
        
        /* Highlight active menu */
        var page = window.location.hash;
        if ( page ) {
            $('a[href="'+page+'"]').click();
        } else {
            window.location.hash = "start";
        }
        
        
        /* Login */
        $('[data-login-btn]').click(function(){
            var data = {
                fn:       'login',
                login:    $('.authorization input[name=login]').val(),
                password: $('.authorization input[name=password]').val()
            }
            api( data, function(r){

                /* Go to admin page */
                if ( r.link ) {
                    window.location = r.link;
                }

                if (r.info_text) {
                    notify( r.info_text, r.info_class, r.info_time );
                }

                if (r.result == 'timeout') {
                    notify( __("Connection lost"), 'info-error', 10000 );
                }

                if (r.result == 'ok') {
                    window.location.reload(true);
                }

            });
        });
        $('input[name=login],input[name=password]').keyup(function(e){
            if (e.key == "Enter") {
                $('[data-login-btn]').click();
            }
        });

        /* Theme switcher */
        $( '[data-theme]' ).click( function(){
            var n = $.cookie('theme');
            $('body').removeClass(admin_styles[n][0]);
            n = (+n+1) % admin_styles.length;
            $('body').addClass(admin_styles[n][0]);
            notify(admin_styles[n][0], 'info-success', 3000);
            $.cookie('theme', n);
            let event = new Event("theme");
            $('body')[0].dispatchEvent(event);
            return false;
        });
        var n = $.cookie('theme');
        if ( n == undefined ) {
            n = 3; // warm
            $.cookie('theme', n);
        }
        var theme = admin_styles[n][0];
        $('body').addClass(theme);
        $('body')[0].addEventListener("theme", function(event) {
            if (window.codemirror_editor) {
                var n = $.cookie('theme');
                window.codemirror_editor.setOption("theme", admin_styles[n][1]);
            }
        });

        /* Update Cache */
        $('[data-cache]').click(function(){
            api({fn:'recreate_cache'}, function(r){
                if (r.info_text) {
                    notify( r.info_text, r.info_class, r.info_time );
                    if (!window.prevent_reload) {
                        setTimeout(function(){
                            window.location.reload(true);
                        },1000);
                    }
                }
            });
            return false;
        });
        
        /* Call Mobile Menu (Admin Menu) */
        $('[data-menu-admin-menu]').click(function(){
            var id = $(this).attr('data-menu-admin-menu');
            $('[data-am-item='+id+'] .admincont-menu-button').addClass('open');
            $('[data-am-item='+id+'] .admin-menu-button').addClass('open');
        });
        
        /* Close Mobile Menu (Admin Menu) */
        $('[data-settings="admin_menu"] .admincont-menu-button,[data-settings="admin_menu"] .admin-menu-button').click(function(){
            $(this).removeClass('open');
        });
        
        /* Open properties */
        $('[data-am-prop-open]').click(function(){
            var item = $(this).attr('data-am-prop-open');
            $('[data-am-prop='+item+']').removeClass('hidden').addClass('openhot');
            $('[data-am-item='+item+']').addClass('hidden');
            // Hide mobile menu
            $('[data-am-item='+item+'] .admincont-menu-button').removeClass('open');
            $('[data-am-item='+item+'] .admin-menu-button').removeClass('open');
            return false;
        });

        /* Close properties */
        $('[data-am-cancel]').click(function(){
            var item = $(this).attr('data-am-cancel');
            $('[data-am-prop='+item+']').addClass('hidden').removeClass('openhot');
            $('[data-am-item='+item+']').removeClass('hidden');
            return false;
        });

        /* Set parents in select2 */
        $('[data-am-prop] select').each(function(i,el){
            var parent = $(el).attr('data-am-parent');
            $(el).val(parent);
            $(el).select2();
        });

        /* Save properties */
        $('[data-am-save],[data-am-reset]').click(function(){
            var item = $(this).attr('data-am-i');
            var fn   = $(this).attr('data-am-fn');
            var selector = '[data-am-prop='+item+']';
            var data = {
                fn:      fn,
                type:    $(selector).attr('data-type'),
                module:  $(selector).attr('data-module'),
                item:    item,
                title:   $(selector+' [name=title]').val(),
                sort:    $(selector+' [name=sort]').val(),
                section: $(selector+' [name=section]').val(),
            }
            api(data, function(r){
                if (r.info_text) {
                    notify( r.info_text, r.info_class, r.info_time );
                    if ( r.info_time )
                    setTimeout(function(){
                        window.location.reload(true);
                    },1000);
                }
            });
            return false;
        });

        /* Delete Container */
        $('[data-am-delete]').click(function(e){
            e.preventDefault();
            var item = $(this).attr('data-am-delete');
            var childs = $('[data-am-childs='+item+'] > div').length;
            if ( childs ) {
                notify( __("Not Empty Container"), 'info-error', 2000 );
                return;
            }
            if ( !confirm( __("Delete?") ) ) return;
            var data = {
                fn:      'admin_menu_del',
                item:    item,
            }
            api(data, function(r){
                if (r.info_text) {
                    notify( r.info_text, r.info_class, r.info_time );
                    if ( r.info_time )
                    setTimeout(function(){
                        window.location.reload(true);
                    },r.info_time);
                }
            });
        });

        /* Hide */
        $('[data-am-show],[data-am-hide]').click(function(){
            if ( $(this).attr('data-am-hide') ) {
                if ( $(this).attr('data-am-status') == 'hidden' ) {
                    return false;
                } else {
                    var item = $(this).attr('data-am-hide');
                    var hide = 'true';
                    // Hide mobile menu
                    $('[data-am-item='+item+'] .admincont-menu-button').removeClass('open');
                    $('[data-am-item='+item+'] .admin-menu-button').removeClass('open');
                }
            }
            if ( $(this).attr('data-am-show') ) {
                if ( $(this).attr('data-am-status') == 'showed' ) {
                    return false;
                } else {
                    var item = $(this).attr('data-am-show');
                    var hide = 'false';
                    // Hide mobile menu
                    $('[data-am-item='+item+'] .admincont-menu-button').removeClass('open');
                    $('[data-am-item='+item+'] .admin-menu-button').removeClass('open');
                }
            }
            var el   = $('[data-am-prop='+item+']');
            var data = {
                fn:      'admin_menu_hide',
                hide:    hide,
                item:    item,
                type:    $(el).attr('data-type'),
                module:  $(el).attr('data-module'),
            }
            if ( data.item == "admin_menu" ) {
                if ( !confirm(__("Hide Admin Menu?")) ) return false;
            }
            api(data, function(r){
                if (r.info_text) {
                    notify( r.info_text, r.info_class, r.info_time );
                    if (r.info_time)
                    setTimeout(function(){
                        window.location.reload(true);
                    },r.info_time);
                }
            });
            return false;
        });

        /* Add Section */
        $('[data-am-add-section]').click(function(){
            api({fn:'admin_menu_add_section'},function(r){
                if (r.result == 'timeout') {
                    notify( __("Connection lost"), 'info-error', 10000 );
                } else if (r.info_text) {
                    notify( r.info_text, r.info_class, r.info_time );
                    if (r.info_time)
                    setTimeout(function(){
                        window.location.reload(true);
                    },r.info_time);
                }
            });
            return false;
        });
        
        
        /* Call Mobile Menu (Modules) */
        $('[data-menu-module]').click(function(){
            var id = $(this).attr('data-menu-module');
            $('[data-module="'+id+'"] .module-buttons').addClass('open');
        });
        
        /* Close Mobile Menu (Modules) */
        $('[data-settings="modules"] .module-buttons').click(function(){
            $(this).removeClass('open');
        });

        /* Disable Modules */
        $('[data-module-enable],[data-module-disable').click(function(){
            if ( $(this).attr('data-module-enable') ) {
                if ( $(this).attr('data-module-status') == 'enabled' ) {
                    return false;
                } else {
                    var module = $(this).attr('data-module-enable');
                    var disable = 'false';
                    // Hide mobile menu
                    $('[data-module="'+module+'"] .module-buttons').removeClass('open');
                }
            }
            if ( $(this).attr('data-module-disable') ) {
                if ( $(this).attr('data-module-status') == 'disabled' ) {
                    return false;
                } else {
                    var module = $(this).attr('data-module-disable');
                    var disable = 'true';
                    // Hide mobile menu
                    $('[data-module="'+module+'"] .module-buttons').removeClass('open');
                }
                if ( !confirm(__("Disable Module?")) ) return false;
            }
            var data = {
                fn:      'module_disable',
                disable: disable,
                module:  module,
            }
            api(data, function(r){
                if (r.info_text) {
                    notify( r.info_text, r.info_class, r.info_time );
                    if (r.info_time)
                    setTimeout(function(){
                        window.location.reload(true);
                    },r.info_time);
                }
            });
            return false;
        });

        /* Delete Module */
        $('[data-module-del]').click(function(e){
            e.preventDefault();
            var module = $(this).attr('data-module-del');
            // Hide mobile menu
            $('[data-module="'+module+'"] .module-buttons').removeClass('open');
            if ( !confirm( __("Delete?") ) ) return;
            var data = {
                fn:      'module_del',
                module:  module,
            }
            api(data, function(r){
                if (r.info_text) {
                    notify( r.info_text, r.info_class, r.info_time );
                    if ( r.info_time )
                    setTimeout(function(){
                        window.location.reload(true);
                    },r.info_time);
                }
            });
        });
          

        /* Theme select */
        $('[data-settings=theme] select').select2();

        /* Logout */
        $('[data-logged] [data-login]').click(function(){
            if ( !confirm( __("Close this session?") ) ) return;
            var data = {
                fn:   'logout',
                sess: $(this).attr('data-login'),
            }

            api(data, function(r){
                if (r.info_text) {
                    notify( r.info_text, r.info_class, r.info_time );
                    if ( r.result == 'refresh' ) {
                        window.location.reload(true);
                    } else if ( r.result == 'ok' ) {
                        $('[data-login='+data.sess+']').parents('[data-logged]').remove();
                    }
                }
            });
        });

        $('.password-eye').click(function(){
            $(this).toggleClass('showed');
            var inp = $(this).prev();
            var t   = inp.attr('type');
            if ( t == 'password' ) {
                inp.attr( 'type', 'text' );
            } else {
                inp.attr( 'type', 'password' );
            }
        });
        
        
        $('.services-button').click(function(){
            $('.contmenu-group').toggleClass('open');
        });
        $('main').click(function(){
            $('.contmenu-group').removeClass('open');
        });
        
    }); 
 })( jQuery );

document.addEventListener("DOMContentLoaded", function(event) {
    //console.log("DOM fully loaded and parsed");
    
    // Right Menu
    var menu_button = document.getElementsByClassName("button-mobimenu-container");
    if ( menu_button[0] ) {
        menu_button[0].setAttribute('onclick', "toggle_menu()");
    }
    var milk = document.getElementsByClassName("bg-reset")
    if ( milk[0] ) {
        milk[0].setAttribute('onclick', "toggle_menu()");
    }
    
    var items = document.querySelectorAll(".contmenu-group a");
    items.forEach(function(item) {
        item.setAttribute('onclick', "close_service_menu('"+item.className+"')");
    });
    
});

function toggle_menu() {
    document.getElementsByTagName("body")[0].classList.toggle("mobile-menu-open");
    document.getElementsByClassName("button-mobimenu-container")[0].classList.toggle("menu-open");
    document.getElementsByTagName("aside")[0].classList.toggle("openpanel");
    document.getElementsByClassName("bg-reset")[0].classList.toggle("openpanel");
    // Close .contmenu-group
    document.getElementsByClassName("contmenu-group")[0].classList.remove("open");
}

function close_service_menu( className ) {
    if ( className != "theme-switcher" ) {
        document.getElementsByClassName("contmenu-group")[0].classList.remove("open");
    }
}
