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

/* Usage:
   let selects = document.querySelectorAll( "#pages .select-grid" );
   select3( selects );
   searcher( selects, ".list-search li", "" );
*/
function searcher( selects, itemSelector, textSelector ) {
    selects.forEach( function( select ) {
        select.querySelector( ".search-field" ).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 );
}

/* Notifications */
function notify( message, classes, msec ) {
    let div = document.createElement( 'div' );
    let bulb = document.createElement( 'div' );
    bulb.className = classes;
    bulb.innerHTML = message;
    div.appendChild( bulb );
    document.querySelector( '.log-info-box' ).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 ( let key in data ) {
        if ( !data.hasOwnProperty( key ) ) continue;
        if ( Array.isArray( data[key] ) ) {
            for ( let key2 in data[key] ) {
                formData.append( key+"[]", data[key][key2] );
            }
        } else {
            formData.append( key, data[key] );
        }
    }
    // send data
    try {
        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 );
        }
    } catch( error ) {
        throw error;
    }
}


document.addEventListener("DOMContentLoaded", function( event ) {

    function toggle_menu() {
        document.body.classList.toggle("mobile-menu-open");
        coffee_cms_mobile_menu.classList.toggle("menu-open");
        aside.classList.toggle("openpanel");
        coffee_cms_mobile_menu_milk.classList.toggle("openpanel");
        coffee_cms_top_right_menu.classList.remove("open");
    }
    
    function close_service_menu( className ) {
        if ( className != "theme-switcher" ) {
            coffee_cms_top_right_menu.classList.remove("open");
        }
    }
    
    // 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.coffee_cms_mobile_menu ) { coffee_cms_mobile_menu.onclick = toggle_menu; }
    if ( window.coffee_cms_mobile_menu_milk ) { coffee_cms_mobile_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( '.coffee-cms_dropdown-left-menu-mobile-button' ).classList.remove( 'menu-open' );
            // Close top right menu
            coffee_cms_top_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 );
                    }
                }
            });
        });
    }

    /* Call Mobile Menu in Admin Menu section */
    let amMobMenuBtns = document.querySelectorAll( '[data-menu-admin-menu]' );
    amMobMenuBtns.forEach( function( amMobMenuBtn ) {
        amMobMenuBtn.addEventListener( "click", function( e ){
            let id = this.getAttribute( 'data-menu-admin-menu' );
            let container = document.querySelector( '[data-am-item='+id+'] .admincont-menu-button' );
            if ( container ) {
                container.classList.add( 'open' );
            }
            let menu = document.querySelector( '[data-am-item='+id+'] .admin-menu-button' );
            if ( menu ) {
                menu.classList.add( 'open' );
            }
        } );
    } );

    /* Admin Menu section, Close Mobile Menu */
    let closeMobileMenuBtns = document.querySelectorAll( '[data-settings="admin_menu"] .admincont-menu-button,[data-settings="admin_menu"] .admin-menu-button' );
    closeMobileMenuBtns.forEach( function( closeBtn ) {
        closeBtn.addEventListener( "click", function() {
            this.classList.remove( 'open' );
        } );
    } );

    /* Admin Menu section, Open properties */
    let openPropBtns = document.querySelectorAll( '[data-am-prop-open]' );
    openPropBtns.forEach( function( openPropBtn ) {
        openPropBtn.addEventListener( "click", function( e ) {
            e.preventDefault();
            let item = openPropBtn.getAttribute( 'data-am-prop-open' );
            let panel = document.querySelector( '[data-am-prop='+item+']' );
            panel.classList.remove( 'hidden' );
            panel.classList.add( 'openhot' );
            let plashka = document.querySelector( '[data-am-item='+item+']' );
            plashka.classList.add( 'hidden' );
            // Hide mobile menu
            let mm = document.querySelector( '[data-am-item='+item+'] .admincont-menu-button, [data-am-item='+item+'] .admin-menu-button' );
            if ( mm ) {
                mm.classList.remove( 'open' );
            }
        } );
    } );

    /* Admin Menu section, Close properties */
    let cancelBtns = document.querySelectorAll( '[data-am-cancel]' );
    cancelBtns.forEach( function( cancelBtn ) {
        cancelBtn.addEventListener( "click", function( e ) {
            e.preventDefault();
            let item = this.getAttribute( 'data-am-cancel' );
            let panel = document.querySelector( '[data-am-prop='+item+']' );
            panel.classList.add( 'hidden' );
            panel.classList.remove( 'openhot' );
            let plashka = document.querySelector( '[data-am-item='+item+']' );
            plashka.classList.remove( 'hidden' );
        } );
    } );
    
    /* Admin Menu section, Save properties */
    let saveBtns = document.querySelectorAll( '[data-am-save],[data-am-reset]' );
    saveBtns.forEach(function( saveButton ){
        saveButton.addEventListener( "click", function( e ) {
            e.preventDefault();
            let item = this.getAttribute( 'data-am-i' );
            let fn   = this.getAttribute( 'data-am-fn' );
            let selector = '[data-am-prop='+item+']';
            let title = document.querySelector(selector+' [name=title]');
            if ( title ) {
                title = title.value;
            }
            let section = document.querySelector(selector+' [name=section]');
            if ( section ) {
                section = section.value;
            }
            let data = {
                fn:      fn,
                type:    document.querySelector( selector ).getAttribute( 'data-type' ),
                module:  document.querySelector( selector ).getAttribute( 'data-module' ),
                item:    item,
                title:   title,
                sort:    document.querySelector(selector+' [name=sort]').value,
                section: section,
            }
            api2(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);
                }
            });
        });
    });

    /* Admin Menu section, Delete Container */
    let deleteBtns = document.querySelectorAll( '[data-am-delete]' );
    deleteBtns.forEach( function( button ) {
        button.addEventListener( "click", function( e ){
            e.preventDefault();
            let item = this.getAttribute( 'data-am-delete' );
            let childs = document.querySelectorAll('[data-am-childs='+item+'] > div').length;
            if ( childs ) {
                notify( __("Not Empty Container"), 'info-error', 2000 );
                return;
            }
            if ( !confirm( __("Delete?") ) ) return;
            let data = {
                fn:      'admin_menu_del',
                item:    item,
            }
            api2(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);
                }
            });
        });
    } );

    /* Admin Menu section, Hide */
    let hideBtns = document.querySelectorAll( '[data-am-show],[data-am-hide]' );
    hideBtns.forEach( function( button ) {
        button.addEventListener( "click", function( e ){
            e.preventDefault();
            let item, hide;
            if ( this.getAttribute('data-am-hide') ) {
                if ( this.getAttribute('data-am-status') == 'hidden' ) {
                    return false;
                } else {
                    item = this.getAttribute('data-am-hide');
                    hide = 'true';
                }
            }
            if ( this.getAttribute('data-am-show') ) {
                if ( this.getAttribute('data-am-status') == 'showed' ) {
                    return false;
                } else {
                    item = this.getAttribute('data-am-show');
                    hide = 'false';
                }
            }
            // Hide mobile menu
            let mm = document.querySelector( '[data-am-item='+item+'] .admincont-menu-button, [data-am-item='+item+'] .admin-menu-button' );
            if ( mm ) {
                mm.classList.remove( 'open' );
            }
            let el   = document.querySelector('[data-am-prop='+item+']');
            let data = {
                fn:      'admin_menu_hide',
                hide:    hide,
                item:    item,
                type:    el.getAttribute('data-type'),
                module:  el.getAttribute('data-module'),
            }
            if ( data.item == "admin_menu" ) {
                if ( !confirm(__("Hide Admin Menu?")) ) return false;
            }
            api2(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);
                }
            });
        });
    } );

    /* Admin Menu section, Add Section */
    let addSectionBtn = document.querySelector( '[data-am-add-section]' );
    if ( addSectionBtn ) {
        addSectionBtn.addEventListener( "click", function( e ){
            e.preventDefault();
            api2({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);
                }
            });
        });
    }

    /* Call Mobile Menu (Modules) */
    let moduleMobMenus = document.querySelectorAll( '[data-menu-module]' );
    moduleMobMenus.forEach( function( button ) {
        button.addEventListener( "click", function(){
            let id = this.getAttribute('data-menu-module');
            document.querySelector('[data-module="'+id+'"] .module-buttons').classList.add('open');
        });
    } );

    /* Close Mobile Menu (Modules) */
    // не дублирует ли функционал?
    let moduleBtns = document.querySelectorAll( '[data-settings="modules"] .module-buttons' );
    moduleBtns.forEach( function( button ) {
        button.addEventListener( "click", function( e ){
            e.preventDefault();
            this.classList.remove('open');
        });
    } );

    /* Disable Modules */
    let moduleEnDisBtns = document.querySelectorAll( '[data-module-enable],[data-module-disable' );
    moduleEnDisBtns.forEach( function( button ) {        
        button.addEventListener( "click", function( e ){
            e.preventDefault();
            let module, disable;
            if ( this.getAttribute('data-module-enable') ) {
                if ( this.getAttribute('data-module-status') == 'enabled' ) {
                    return false;
                } else {
                    module = this.getAttribute('data-module-enable');
                    disable = 'false';
                    // Hide mobile menu
                    document.querySelector('[data-module="'+module+'"] .module-buttons').classList.remove('open');
                }
            }
            if ( this.getAttribute('data-module-disable') ) {
                if ( this.getAttribute('data-module-status') == 'disabled' ) {
                    return false;
                } else {
                    module = this.getAttribute('data-module-disable');
                    disable = 'true';
                    // Hide mobile menu
                    document.querySelector('[data-module="'+module+'"] .module-buttons').classList.remove('open');
                }
                if ( !confirm(__("Disable Module?")) ) return false;
            }
            let data = {
                fn:      'module_disable',
                disable: disable,
                module:  module,
            }
            api2(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);
                }
            });
        });
    });

    /* Delete Module */
    let moduleDelBtns = document.querySelectorAll( '[data-module-del]' );
    moduleDelBtns.forEach( function( button ) {
        button.addEventListener( "click", function(e){
            e.preventDefault();
            let module = this.getAttribute('data-module-del');
            // Hide mobile menu
            document.querySelector('[data-module="'+module+'"] .module-buttons').classList.remove('open');
            if ( !confirm( __("Delete?") ) ) return;
            let data = {
                fn:      'module_del',
                module:  module,
            }
            api2(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);
                }
            });
        });
    });

    /* Close Sessions */
    let closeSessBtns = document.querySelectorAll( '[data-logged] [data-login]' );
    closeSessBtns.forEach( function( button ) {
        button.addEventListener( "click", function( e ){
            e.preventDefault();
            if ( !confirm( __("Close this session?") ) ) return;
            var data = {
                fn:   'logout',
                sess: this.getAttribute('data-login'),
            }

            api2(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' ) {
                        document.querySelector('[data-login="'+data.sess+'"]').closest('[data-logged]').remove();
                    }
                }
            });
        });
    });

    let eyes = document.querySelectorAll( '.password-eye' );
    eyes.forEach( function( eye ) {
        eye.addEventListener( "click", function( e ){
            this.classList.toggle('showed');
            var inp = this.previousElementSibling;
            var t   = inp.getAttribute('type');
            if ( t == 'password' ) {
                inp.setAttribute( 'type', 'text' );
            } else {
                inp.setAttribute( 'type', 'password' );
            }
        });
    });

    // Open and close Top Right Menu
    let trMenu = document.querySelector( '.coffee-cms_dropdown-right-menu-mobile-button' );
    if ( trMenu ) {
        trMenu.addEventListener( "click", function(){
            coffee_cms_top_right_menu.classList.toggle( "open" );
        });
    }
    let main = document.querySelector( 'main' );
    if ( main ) {
        main.addEventListener( "click", function(){
            coffee_cms_top_right_menu.classList.remove( "open" );
        });
    }

});
