/*
* Let us load the menu items here ...
*/
var menu = {}
/*
* This function will load menu items from the configuration file
* :uri
* :id
* :pid  parent identifier                                            
*/

menu.apply  = function (uri,id,pid,_context){
    id = id.replace(/ /g,'-')
    if(uri == null){
        return ;
    }
    $('.content').children().hide()
    
    var httpclient = HttpClient.instance()
   
        httpclient.setHeader('uri',uri)
        httpclient.setHeader('dom',id)
        httpclient.post(_context+'/page',function(x){
            var _html = x.responseText
            var template = document.createElement('template');
            template.innerHTML = _html.trim();
            var _dom =  template.content.firstChild;
            if(jx.dom.exists(pid) && jx.dom.exists(id)){
                jx.dom.remove(id)
            }
            $('#'+pid).append(_dom)
            // jx.dom.append(pid,_dom)
            // $('#'+id).show('fast',function(){
                // $('#'+pid).slideUp()
            // })
            
            $('#'+pid).children().slideUp('fast', function(){
                $('#'+id).slideDown('fast',function(){
                    $('#'+pid).slideDown('fast',function(){
                        var input = $('#'+pid).find('input')
                        if (input.length > 0 ){
                            $(input[0]).focus()
                        }
                    })
                   
                })
    
            })
            
                // $('.content').append(_dom)
        })
    
}

menu.apply_link =function(_args,_context){
    //
    // type:
    //  redirect open new window
    //  dialog      open in a dialog
    //
    
    var url = _args['url']
    _args.type = (_args.type == null)? 'redirect' :_args.type
    
    if (_args.type.match(/dialog|embed/i) ) {
        //
        // calling jx.modal.show
        if (_args.url){
            jx.modal.show(_args.url)
        }else{
            // _html = jx.dom.get.value(_args.text)
            // console.log(_html)
            // jx.modal.show(_html)
            var http = HttpClient.instance()
            http.setHeader('uri',_args.uri)
            http.setHeader('dom',(_args.title)?_args.title:'dialog')
            // http.setHeader('dom',_args.text)
            http.get(_context+'/dialog',function(x){
                
                jx.modal.show({html:x.responseText,id:'dialog'})
                console.log([$('.jxmodal')])
                menu.runScript ('.jxmodal')
            })
        }
    }else{
        window.open(_args.url,_args.text)
    }

}

var _delegate = {scripts:{}}
menu.runScript  = function(_id){
    var scripts = $(_id+' script')
    
    jx.utils.patterns.visitor(scripts,function(_item){
       if(_item.text.trim().length > 0){
            
          var _code = eval(_item.text)
          var id = _id
          if (_item.parentNode != null){
            var id = _item.parentNode.id == null?_item.parentNode.className : _item.parentNode.id
          }
          id = (id != null)?id : _id 
          
        //   _delegate.scripts[id] = _code
       }
    })    
}
menu.events = {}
menu.events._dialog = function (_item,_context){
    // var url = _args['url']
    _item.type = (_item.type == null)? 'redirect' :_item.type
    var http = HttpClient.instance()
    _regex = /uri=(.+)/;
    if (_item.uri.match(_regex)) {
        _seg = _item.uri.match(_regex)
        _item.uri = _seg[_seg.length - 1]
    }
    http.setHeader('uri',_item.uri)
    http.setHeader('dom',(_item.title)?_item.title:'dialog')
    // http.setHeader('dom',_args.text)
    http.get(_context+'/dialog',function(x){
        
        jx.modal.show({html:x.responseText,id:'dialog'})
        menu.events.finalize ('.jxmodal')
    })

}
menu.events._openTabs = function (_TabContentPane, _id) {
    _id = _id[0] != '.' ? ('.'+_id) : _id
    $(_TabContentPane).children().slideUp('fast')
    $(_id).slideDown()
}
menu.events._open = function (id,uri,_context){    
    id = id.replace(/ /g,'-')
    
    var pid = '#content'
    $('.content').children().slideUp()
    // if ( $('#'+id).parent() == null){
    //     $('.content').children().slideUp()
    // }else{
    //     var parent = $('#'+id).parent()
    //     parent.slideUp()
    //     if (parent[0].id == null){
    //         pid = ('.' + parent[0].className)
    //     }else{
    //         pid = ('#'+parent[0].id)
    //     }
        
    // }
    $('#'+id).remove()
    
    var httpclient = HttpClient.instance()
        _context  = (_context == null)?'':_context;
        httpclient.setHeader('uri',uri)
        httpclient.setHeader('dom',id)
        httpclient.post(_context+'/page',function(x){
            if(x.readyState == 4 && x.status == 200){
            var _html = x.responseText
            var _dom = $(_html)
            
            if(jx.dom.exists(pid) && jx.dom.exists(id)){
                jx.dom.remove(id)
                
            }
            $(pid).append(_dom)
            var ref = pid + ' #'+id
            // menu.events.finalize (ref)
            $(pid).children().slideUp('fast', function(){
                
                $(ref ).slideDown('fast',function(){

                    $(pid).slideDown('fast',function(){
                        var input = $(pid).find('input')
                        if (input.length > 0 ){
                            $(input[0]).focus()
                        }
                    })
                   
                })
    
            })

            
        }
            
            
                // $('.content').append(_dom)
        })

}

menu.utils = {}
menu.utils.format = function(text){
    return text.replace(/(-|_)/g,' ').trim()
}
menu.utils._delegate = function (_id,_itemIndex,_index) {
    if ($(_id).children().length >= _itemIndex ){
        var _node = $(_id).children()[_itemIndex ]
        if ($(_node).children().length >= _index ){
            var _node = $(_node).children()[_index]
            _node = $(_node).find('.active')
            if ($(_node).length > 0 ){
                $(_node)[0].click()
            }
        }
        
    
    }
}
menu.events.finalize = function (ref) {
    var scripts = $(ref+' script')
  
    jx.utils.patterns.visitor(scripts,function(_item){
        if(_item.text.trim().length > 0){
            
           var _code = eval(_item.text)
           var id = ref
           if (_item.parentNode != null){
             var id = _item.parentNode.id == null?_item.parentNode.className : _item.parentNode.id
           }
           id = (id != null)?id : ref 
           
         //   _delegate.scripts[id] = _code
        }
     })      
}

/**
 * Let's build the tab handling here ...
 * 
 */
var QCMSBasic= function(_layout,_context,_clickEvent) {
    this._layout = _layout
    this._context= _context
    this._make = function (_items){
        var _panes = []
        var _context = this._context ;
        
        _items.forEach(_item=>{
            var _div = jx.dom.get .instance('DIV')
        
            _div.innerHTML = menu.utils.format(_item.text)
            
            //
            // We need to check for the override text and see if it goes here
            _div.className = 'active'
            _div.data = _item
            _panes.push(_div)
            $(_div).on('click', function (){
                //
                // how do we process this ...
                if(this.data.uri && this.data.type != 'open') {

                    if (this.data.type == 'dialog') {
                        // console.log(this.data)
                        menu.events._dialog(this.data,_context)
                    }else{
                        menu.events._open(menu.utils.format(this.data.text),this.data.uri,_context)
                    }
                }else{
                    if (this.data.uri != null){
                        window.open(this.data.uri,'_self')
                    }else{
                        window.open(this.data.url,menu.utils.format(this.data.text))
                    }
                }
            })

    
        })
        return _panes ;
        
    }
    this.init = function (){
        var _me = this ;
        var _make = this._make
        var _layout = this._layout
        
        var _names = _layout.order.menu.length > 0 ? _layout.order.menu : Object.keys(_layout.menu)
        
        // Object.keys(this._layout.menu)
        _names.forEach(function(_name){
            
            var _div = _me._make(_layout.menu[_name]) ;
            
            
            var _sub = jx.dom.get.instance('DIV')
            var _menuItem = jx.dom.get.instance('DIV')
            _menuItem.innerHTML = menu.utils.format (_name)
            _sub.className  = 'sub-menu  border-round border '
            _menuItem.className = 'item'
            _div.forEach(_item=>{$(_sub).append(_item) })
            $(_sub).append(_div)
            _menuItem.appendChild(_sub)
            
            $('.main .menu').append(_menuItem)
        })
    }
}

var QCMSTabs = function(_layout,_context,_clickEvent){
    //
    // This object will make tabs in the area of the menu 
    // @TODO: we can parameterize where the menu is made to improve flexibility
    //
    this.tabs = jx.dom.get.instance('DIV')
    this.tabs.className = 'tabs'
    this._context = _context
    this._layout = _layout
    this._make = function (text,_item,_event){
        var text = text.trim().replace(/(_|-)/ig,' ').trim()
        var _context = this._context;
        if (text.match(/\//)){
            text = text.split(/\//g).slice(-1)[0]
        }
        var _button = jx.dom.get.instance('INPUT')
        var _label = jx.dom.get.instance('LABEL')
        _button.type= 'radio'
        _button.id = text+'tab'
        _button.name = 'menu-tabs'
        
        _label.data = {id:text.toLowerCase(),uri:_item[0].uri}
        // _button._uri = _label._uri
        
        // if(this._layout.icons[text] != null) {
            
            if (this._layout.icon){
                var _icon = jx.dom.get.instance('I')
                    _icon.className = this._layout.icons[text]
                $(_label).append(_icon)
            }
            
            text = ' ' + text
            
        // }
        $(_label).append(text)
        // _button.value= text.toLowerCase()
        $(_button).val(text.toLowerCase())
        _label.htmlFor = _button.id
        $(_label).on('click',function (){
            
            menu.events._open(this.data.id,this.data.uri,_context)
        })
        // $(_button).on('click',function (){
        //     menu.events._open(this.value,this._uri,_context) ;})
        
        return [_button,_label]
    
    }
    
    
    this.init = function (){
        var _me = this;
        var _make  = this._make
        var tabs = this.tabs
        var _names = _layout.order.menu.length > 0 ? _layout.order.menu : Object.keys(_layout.menu)
        // Object.keys(_layout.menu).
        _names.forEach(function(_key){
            _item = _layout.menu[_key]
        //    console.log([_item])
            _tabItem = _me._make(_key,_item)
            $(tabs).append(_tabItem)
        })
        
        this.tabs.className  = 'tabs'
        $('.main .menu').append(this.tabs) 
        $('.main .menu').css({'border':'1px solid transparent'})
        $('.main .menu').css({'grid-template-columns':'64px auto'})
    }
    //
    // We need to load the pages here ...
    //

       
    
}

menu.delegate = {    }

// menu.tabs.make = function(text,_clickEvent){
//     var _id = text.trim()
//     if (text.match(/\//)){
//         _id = text.split(/\//g).slice(-1)[0]
//     }
//     var _button = jx.dom.get.instance('div')
//     var _label = jx.dom.get.instance('LABEL')
//     _button.type= 'radio'
//     _button.id = _id

//     _label.innerHTML = _id.toLowerCase()
//     $(_label).on('click',_clickEvent)
//     return [_button,_label]
// }
menu.init =function (_layout,_context){
    //
    // Let us determine what kind of menu is suited for this
    // @TODO: Make menus configurable i.e on other areas of the site
    //
    
    if (_layout.order != null){
        if (_layout.order.length == null && _layout.order.menu == null){
            _layout.order = {menu:[]}
            
        }else if (_layout.order.menu == null){
            _layout.order.menu = []
        }
    }else{
        _layout.order = {menu:[]}
    }
    

    var _count = 0
    var _items = 0
    Object.keys(_layout.menu).forEach(_name=>{
        _items += _layout.menu[_name].length
        _count += 1
    })
    
    if (_count == _items){
         var _menuObject = new QCMSTabs (_layout,_context)
    }else{
        var _menuObject = new QCMSBasic (_layout,_context)
    }
    
    _menuObject.init()
    
}




/***
 * 
 * Source Code
 */
if (! code){
    var code = {}
}
code.copy = function(_node) {
    var _code = $(_node.parentNode).text().trim().replace(/ {8}/g,'').replace(/ {4}/g,'\t').replace(/\r/g,'\n')
    navigator.clipboard.writeText(_code);
    $(_node).empty()
    $(_node).html('<i class="fa-solid fa-check"></i>')
    setTimeout(function(){
        $(_node).empty()
        $(_node).html('<i class="fa-regular fa-copy"></i>')
    },750)
}