/**
 * This file has functions that allow pages to be fetched and rendered on bootup
*/

var bootup = {}
//
// We implement this function using an observer design pattern
bootup.CMSObserver = function(_context,_domId,_fileURI){
    this._context = _context
    this._domId     = _domId
    this._fileURI   = _fileURI
    this.apply      = function (_caller){
            var http = HttpClient.instance()
            http.setHeader('uri',_fileURI)
            

            uri = '/page'
            if (this._context != '' && this._context != null) {
                uri = this._context + uri
            }
            if (window.location.pathname != '/'){
                uri = ([window.location.pathname,'page']).join('/')
            }
            
            try{
                // var _domElement = jx.dom.get.instance('div')
                
                // _domElement.className = 'busy-loading'
                // jx.dom.append(_domId, _domElement)
                http.post(uri,function(x){
                    if (x.status == 200 && x.readyState == 4){
                        
                        setTimeout(function(){
                            _content = $(x.responseText)
                            var _id = $(_content).attr('id')
                            _pid  = (['#',_domId,' #',_id]).join('')
                            if( $(_pid).length  != 0){
                                $(_pid).remove()
                            }
                            $('#'+_domId).append(x.responseText)
                        },10)

                        
                    }
                    
                    _caller.notify()
                })

            }catch(error){
                _caller.notify()
            }
    }
    
}
//
// Finalize the process of rendering the content on the fly
bootup.finalize = function(_id){
    this.apply = function(_caller){
        // menu.runScript('#'+_id)
        setTimeout(function(){menu.events.finalize(_id);},1000)
        // menu.events.finalize(_id)
    }
}

bootup.init = function(sys_id,_layout){
    if (!_layout) {
        return ;
    }
    if (_layout.on){
        jx.utils.keys(_layout.on.load).forEach(function(_domId){
                
            var observers = 
            jx.utils.patterns.visitor(_layout.on.load[_domId], function(_uri){
                // _uri = _layout.root_prefix != null? (_layout.root_prefix+_uri) : _uri
                return new bootup.CMSObserver(sys_id,_domId,_uri)
            })
            observers.push(new bootup.finalize(_domId))
            //
            // At this point we can execute the observer design pattern
            //
            // console.log(observers)
            jx.utils.patterns.observer(observers,'apply')

        })
    }

}