/* Usage:
   let $selects = pages.getElementsByClassName( "select-grid" );
   select3( $selects );
   searcher( $selects, ".list-search li", "" );
*/
function select3( $selects ) {
    Array.from($selects).forEach( function( $select ) {
        // show/hide dropdown list
        $select.getElementsByClassName( "field-select" )[0].addEventListener( "click", 
            function ( event ) {
                event.currentTarget.nextElementSibling.classList.toggle( "open" );
                let $input = $select.getElementsByTagName( "input" )[0].focus();
            }
        );
        // click on <li>
        let $lis = $select.getElementsByTagName( "li" );
        Array.from($lis).forEach( function( $li ) {
            $li.addEventListener( "click", 
                function ( event ) {
                    Array.from($lis).forEach( function( $li ) {
                        $li.classList.remove( "activex" );
                    } );
                    event.currentTarget.classList.add( "activex" );
                    let $value = event.currentTarget.textContent.replace(/^\s*/g, '');
                    let $id    = event.currentTarget.getAttribute( 'value' );
                    let $el    = $select.getElementsByClassName( "field-select" )[0];
                    $el.textContent = $value;
                    $el.setAttribute( 'data-value', $id );
                    $select.getElementsByClassName( "field-select" )[0].click();
                }
            );
        } );
        
    } );
}

/* Usage:
   let $selects = pages.getElementsByClassName( "select-grid" );
   select3( $selects );
   searcher( $selects, ".list-search li", "" );
*/
function searcher( $selects, $itemSelector, $textSelector ) {
    Array.from($selects).forEach( function( $select ) {
        $select.getElementsByClassName( "search-field" )[0].addEventListener( "keyup",
            function (event) {
                let $items         = $select.querySelectorAll( $itemSelector );
                let $search_string = event.currentTarget.value;
                let $regex   = new RegExp( $search_string, 'i' );
                $items.forEach( function( $el ) {
                    let $fields = [$el];
                    if ( $textSelector != '' ) {
                        $fields = $el.querySelectorAll( $textSelector );
                    }
                    $fields.forEach( function( $fi ) {
                        let $content = $fi.textContent;
                        let $finded  = $content.match( $regex );
                        if ( $finded ) {
                            $el.classList.remove( "searcher-hidden" );
                        } else {
                            $el.classList.add( "searcher-hidden" );
                        }
                    } );
                } );
            }
        );
    } );
}

function get_cookie( $name ) {
    var $cookie_lines = decodeURIComponent( document.cookie ).split( ';' );
    for ( var $line in $cookie_lines ) {
        var $cookie = $cookie_lines[$line].split( '=' );
        if ( $name == $cookie[0].trim() ) {
            return $cookie[1];
        }
    }
    return '';
}

function set_cookie( $name, $value ) {
    document.cookie = encodeURIComponent( $name ) + '=' + encodeURIComponent( $value );
}

function toggle_menu() {
    document.body.classList.toggle("mobile-menu-open");
    cms_mob_menu.classList.toggle("menu-open");
    aside.classList.toggle("openpanel");
    cms_mob_menu_milk.classList.toggle("openpanel");
    cms_right_menu.classList.remove("open");
}

function close_service_menu( className ) {
    if ( className != "theme-switcher" ) {
        cms_right_menu.classList.remove("open");
    }
}

/* Notifications */
function notify( $message, $classes, $msec ) {
    let $div = document.createElement( 'div' );
    let $bulb = document.createElement( 'div' );
    $bulb.className = $classes;
    $bulb.textContent = $message;
    $div.appendChild( $bulb );
    document.querySelectorAll( '.log-info-box' )[0].appendChild( $div );
    let $h = $div.clientHeight;
    $div.setAttribute( 'style', `height:${$h}px` );
    if ( $msec )
    setTimeout(function(){
        $div.classList.add( 'timeout' );
    }, $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];
}

async function api2( $data, $rfn ) {
    const $formData = new FormData();
    // push $data to $formData
    for ( var $key in $data ) {
        if ( !$data.hasOwnProperty( $key ) ) continue;
        $formData.append( $key, $data[$key] );
    }
    // send data
    let $response = await fetch( cms.api, {
        method: 'POST',
        body: $formData
    } );
    // get response and call callback function
    if ( $response.ok ) { // HTTP-status: 200-299
        let $rdata = await $response.json();
        if ( $rfn ) {
            $rfn( $rdata );
        }
    } else {
        alert( "Error HTTP: " + $response.status );
    }
}


document.addEventListener("DOMContentLoaded", function( event ) {
    
    // DOMAttrModified for Google Chrome
    var emulateDOMAttrModified = {
        isSupportedNatively: function () {
            var supported = false;
            function handler() {
                supported = true;
            }
            document.addEventListener('DOMAttrModified', handler);
            var attr = 'emulateDOMAttrModifiedTEST';
            document.body.setAttribute(attr, 'foo');
            document.removeEventListener('DOMAttrModified', handler);
            document.body.removeAttribute(attr);
            return supported;
        },
        install: function () {
            if (!this.isSupportedNatively() &&
                !Element.prototype._setAttribute_before_emulateDOMAttrModified) {
                Element.prototype._setAttribute_before_emulateDOMAttrModified = Element.prototype.setAttribute
                Element.prototype.setAttribute = function(name, val) {
                var prev = this.getAttribute(name);
                val = String(val);
                if (prev !== val) {
                    this._setAttribute_before_emulateDOMAttrModified(name, val);
                    var e = document.createEvent('MutationEvents');
                    e.initMutationEvent('DOMAttrModified', true, true, null, prev, val, name, 2);
                    this.dispatchEvent(e);
                }
                };
            }
        }
    };
    // Install this when loaded.  No other file needs to reference this; it will just make Chrome and Safari
    // support the standard same as Firefox does.
    emulateDOMAttrModified.install();

    // Mob Menu
    if ( window.cms_mob_menu ) { cms_mob_menu.onclick = toggle_menu; }
    if ( window.cms_mob_menu_milk ) { cms_mob_menu_milk.onclick = toggle_menu; }

    var items = document.querySelectorAll( ".contmenu-group a" );
    items.forEach(function(item) {
        if ( item != theme_switcher ) {
            item.addEventListener( 'onclick', close_service_menu(item.className) );
        }
    });

    /* Theme switcher */
    //theme_switcher.addEventListener( 'onclick', theme_switcher_fn ); -- почему так не работает?
    theme_switcher.onclick = theme_switcher_fn;
    function theme_switcher_fn( event ) {
        event.preventDefault();
        var n = get_cookie('theme');
        document.getElementsByTagName('body')[0].classList.remove(admin_styles[n][0]);
        n = (+n+1) % admin_styles.length;
        document.getElementsByTagName('body')[0].classList.add(admin_styles[n][0]);
        notify(admin_styles[n][0], 'info-success', 5000);
        set_cookie('theme', n);
        // switch theme in codemirror
        let theme_event = new Event("theme");
        document.getElementsByTagName('body')[0].dispatchEvent( theme_event );
    };
    var n = get_cookie('theme');
    if ( n == undefined || isNaN( n ) || n === "" ) {
        n = 1; /* dark */
        set_cookie('theme', n);
    }
    var theme = admin_styles[n][0];
    document.getElementsByTagName('body')[0].classList.add(theme);
    document.getElementsByTagName('body')[0].addEventListener("theme", function(event) {
        if (window.codemirror_editor) {
            var n = get_cookie('theme');
            window.codemirror_editor.setOption("theme", admin_styles[n][1]);
        }
    });

    /* Lang Selector */
    if ( window.lang_selector ) {
        let $loc = window.location.search.replace(/.*=/,"");
        if ( $loc == "" ) {
            if ( cms && cms.locale ) {
                $loc = cms.locale;
            } else {
                $loc = "en_US.UTF-8";
            }
        }
        lang_selector.value = $loc;
        lang_selector.onchange = function( e ) {
            window.location.search = "?locale=" + e.currentTarget.value;
        }
    }

    /* Logout */
    let logoutBtn = document.querySelector('[data-logout]');
    if ( logoutBtn ) {
        logoutBtn.addEventListener( "click", function(){
            api2({fn:'logout'},function(){
                window.location.reload(true);
            });
            return false;
        });
    }

    /* Navigation */
    let pages = Array.from( document.querySelectorAll( '[data-am-page]' ) );
    pages.forEach( function( page ) {
        page.addEventListener( "click", link_to_page );
    } );
    function link_to_page(){
        var page = this.getAttribute('data-am-page');
        if ( page ) {
            pages.forEach( function( page ) {
                page.classList.remove( 'active' );
            } );
            this.classList.add( 'active' );
            document.querySelector( 'aside' ).classList.remove( 'openpanel' );
            document.querySelector( '.bg-reset' ).classList.remove( 'openpanel' );
            document.querySelector( 'body' ).classList.remove( 'mobile-menu-open' );
            document.querySelector( '.button-mobimenu-container' ).classList.remove( 'menu-open' );
            // Close top right menu
            cms_right_menu.classList.remove("open");
        }
    }
    
    
    /* Highlight active menu */
    if ( document.querySelector( 'body' ).classList.contains( 'logged' ) ) {
        var page = window.location.hash;
        if ( page && page != "#start" ) {
            document.querySelector( 'a[href="'+page+'"]' ).click();
        } else {
            window.location.hash = "start";
        }
    }

    /* Login */
    let loginBtn = document.querySelector( '[data-login-btn]' );
    if ( loginBtn ) {
        loginBtn.addEventListener( "click", function(){
            let data = {
                fn:       'login',
                login:    document.querySelector( '.authorization input[name=login]' ).value,
                password: document.querySelector( '.authorization input[name=password]' ).value,
                url: window.location.pathname
            }
            if ( window.lang_selector ) {
                data.locale = lang_selector.value
            }
            api2( 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);
                }

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

    /* Update Cache */
    let clearCacheBtn = document.querySelector( '[data-cache]' );
    if ( clearCacheBtn ) {
        clearCacheBtn.addEventListener( "click", function( e ){
            e.preventDefault();
            api2( { fn: 'clear_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 );
                    }
                }
            });
        });
    }

    // insert

});

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

        function api( data, rfn ) {
            $.ajax({
                url:  cms.api,
                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'}); }
                }
            });
        }


        /* 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;
        });

        /* 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);
                }
            });
        });

        /* 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(){
            cms_right_menu.classList.toggle( "open" );
        });
        $('main').click(function(){
            cms_right_menu.classList.remove( "open" );
        });
        
    }); 
 })( jQuery );
