var PageController = new Class({
    request: [],
    initialize: function() {
        this.request = [];
    },
    load: function(path, container,inner_request, callback) {
        // Verify args
        path = (path.match('^/+(.*)$'))?path.match('^/+(.*)$')[1]:path;
        if (!container) {container = $('content')} else {container = $(container);};
        
        console.log("inner_request: "+inner_request);
        
        if (!inner_request) {inner_request = false};
        callback = (callback)?callback:undefined;
        
        // clean page properties
        //$$('div[id='+historyManager.getCurrentLocation.split('/')[1]+']').destroy();
        
        // Set history state
        //historyManager.addState("/"+path);

        
        // Set local vars
        this.request[path] = {};
        this.request[path].load_path = path;
        this.request[path].load_container = container;  
        this.request[path].load_count = 0;
        this.request[path].load_inner_request = inner_request;
        this.request[path].load_html = "";
        this.request[path].load_js = "";
        this.request[path].load_func;
        this.request[path].load_callback = callback;
        
        console.log("caller:" + this.load.caller);
        // Do session refresh
        this.request[path].load_session_func = function(e) {
        
            console.log('page.load('+this.load_path+'): session refresh success');
        
            // Load page content and do page ations
            this.load_func = function(responseTree, responseElements, responseHTML, responseJavaScript) {
                // Verify load count
                if (this.load_count <= 1) {
                    
                    console.log('page.load('+this.load_path+'): page load success');
                    
                    // Set history state
                    if (($$('div.page-path[id='+this.load_path+']').length == 0) && ($$('div.page-path').length !=0)) {
                        this.load_path = $$('div.page-path[id!='+this.load_path+']')[0].getAttribute('name');
                        historyManager.addState("/"+this.load_path);
                    } else if ($$('div.page-path').length == 2) {
                        this.load_path = $$('div.page-path')[1].getAttribute('name');
                        historyManager.addState("/"+this.load_path);
                    } else if ($$('div.page-path').length > 0) {
                        this.load_path = $$('div.page-path')[0].getAttribute('name');
                        historyManager.addState("/"+this.load_path);
                    } else {
                        historyManager.addState("/"+this.load_path);
                    };
                    
                    // Set new title
                    if (($$('div.page-title[id='+this.load_path+']').length == 0) && ($$('div.page-title').length !=0)) {
                        page.updateTitle($$('div.page-title[id!='+this.load_path+']')[0].getAttribute('name'));
                    } else if ($$('div.page-title').length == 2) {
                        page.updateTitle($$('div.page-title')[1].getAttribute('name'));
                    } else if ($$('div.page-path').length > 0) {
                        page.updateTitle($$('div.page-title')[0].getAttribute('name'));
                    } else {
                        document.title='::::: RMS Avocats :::::';
                    };
                    
                    // Set admin mode if required
                    if(session.adminMode == true && !window.editPanel) {
                        window.editPanel = new EditPanel();
                    };
                    $$('.delete-button').setStyle('display', 'none');
                    if(session.adminMode == true && window.editPanel) {
                        window.editPanel.updateEditMode(this.load_path);
                        window.editPanel.currentElement = null;
                        if (this.load_path.split('/')[0] == 'news') {post.edit_mode();};
                        $$('.delete-button').setStyle('display', 'block');
                    };
                    
                    // Codex
                    if(!session.adminMode && !window.editPanel) {
                        codex.load_ref();
                    };
                    
                    // Accordions
                    if($$('.rmsaccordion') || $$('.codexentry')) {
                        if(session.adminMode) {
                            $$('.rmsnote').setStyle('display', 'block');
                        }
                        else {
                            if($$('.rmsparagraph')) { var vAccordion = false } else { var vAccordion = 0 };
                            var accordion = new Accordion($$('dt'), $$('dd'), {
                                display: vAccordion,
                                alwaysHide: true,
                                onActive: function(toggler) { toggler.setStyles({'color': '#463690', 'font-weight': 'bold'}); },
                                onBackground: function(toggler) { toggler.setStyles({'color': '#2D46A9', 'font-weight': 'normal'}); }
                            });
                        };
                    };
                    
                    // Do callback
                    if (this.load_callback) this.load_callback();
                    
                    // Update load count
                    this.load_count++;
                    
                    // Cleanup
                    this.load_request.removeEvent('success',this.load_func);
                };    
            }.bind(this);
            this.load_error_func = function (response) {
                // catch error code
                if (response.responseText.split('debug_count = ').length > 1) {
                    debug_url = "/_debug/view/" + response.responseText.split('debug_count = ')[1].split(';')[0]
                    style = {width:$('content').getStyle('width'),height:'900px'};
                    $('content').empty();
                    var errorWindow = new IFrame({
                        src:debug_url,
                        name:'request-failure',
                        id:'request-failure',
                        styles:style
                    }).inject($('content'),'top');
                    $('request-failure').contentWindow.document.getElementsByTagName('html')[0].innerHTML = response.responseText;
                }
            }.bind(this);
            this.load_request = new Request.HTML({
                url: this.load_path,
                update: this.load_container,
                data: "request_via=js&render_as=xhtml&inner_request="+this.load_inner_request,
                evalScripts: true
            });
            this.load_request.addEvent('success', this.load_func);
            this.load_request.addEvent('onFailure', this.load_error_func); 
            this.load_request.get();
            
            // Cleanup
            session.removeEvent('refresh-complete', this.load_session_func);
            
        }.bind(this.request[path]);
        session.addEvent('refresh-complete', this.request[path].load_session_func);
        session.refresh();
    },
    refresh: function() {
        var currentPage = historyManager.getCurrentLocation();
        currentPage = (currentPage.match('^/+(.*)$'))?currentPage.match('^/+(.*)$')[1]:currentPage;
        console.log('Function page.refresh ----- currentPage : '+currentPage)
        this.load(currentPage, 'content', false);
    },
    updateTitle: function(title) {
        document.title = "::::: RMS Avocats - " + title + " :::::";
        console.log('----- function updateTitle caller : '+this.updateTitle.caller);
    },
    changeLanguage: function(lang) {
        // lang : 'fr' / 'en'
        session.set('native_lang', lang);
        session.addEvent('refresh-complete', function() {
            location.reload();
        });
    },
    list: function(path, container, include_parent, inner_request, callback) {
        // Verify args
        path = (path.match('^/+(.*)$'))?path.match('^/+(.*)$')[1]:path;
        if (!container) {container = $('content')} else {container = $(container);};
        if (!inner_request) {inner_request = false};
        callback = (callback)?callback:function(){};
        
        // Set local vars
        this.request[path] = {};
        this.request[path].list_path = path;
        this.request[path].list_container = container;  
        this.request[path].list_count = 0;
        this.request[path].list_inner_request = inner_request;
        this.request[path].list_html = "";
        this.request[path].list_js = "";
        this.request[path].list_func;
        this.request[path].list_callback = callback;
        
        // Do session refresh
        this.request[path].list_session_func = function(e) {
            console.log('page.list('+this.list_path+'): session refresh success');
            
            // Load page content and do page ations
            this.list_func = function(responseTree, responseElements, responseHTML, responseJavaScript) {
                // Verify list count
                if (this.list_count <= 1) {
                    
                    console.log('page.list('+this.list_path+'): list load success');
                    
                    // Do callback
                    this.list_callback();
                    
                    // Update load count
                    this.list_count++;
                    
                    // Cleanup
                    this.list_request.removeEvent('success',this.list_func);                        
                };
            }.bind(this)
            this.list_request = new Request.HTML({
                url: this.list_path + '/list',
                update: this.list_container,
                data: "request_via=js&render_as=xhtml&inner_request="+this.list_inner_request,
                evalScripts: true
            });
            this.list_request.addEvent('success', this.list_func)
            this.list_request.get();
            
            // Cleanup
            session.removeEvent('refresh-complete', this.list_session_func);
        }.bind(this.request[path]);
        session.addEvent('refresh-complete', this.request[path].list_session_func);
        session.refresh();
    },
    listAsMenu: function(path, inner_request, callback) {
        if(!inner_request) {inner_request = false};
        this.list(path, 'menu-list', false, inner_request, callback);
    },
    addLightbox: function(path, msg, type) {
        blackscreen = new Element('div', {'id':'lightbox-black'}).inject(document.body);
        lightbox = new Element('div', {'id':'lightbox'}).inject(document.body);
        lightboxTitle = new Element('div', {'id':'lightbox-title'}).inject(lightbox);
        lightboxTitle.set('html', msg);
        lightboxContainer = new Element('div',{'id':'lightbox-container'}).inject(lightbox);
        $('lightbox-black').setStyle('opacity', '0');
        $('lightbox').setStyle('opacity', '0');
        this.lightbox_type = type;
        this.lightbox_add_func = function(responseTree, responseElements, responseHTML, responseJavaScript) {
            $('lightbox-container').set('html', responseHTML);
            $('lightbox-black').fade(0.75);
            if (this.lightbox_type == 'info') {
                lightboxCloseButton = new Element(
                    'div',
                    {
                        'id':'buttons'
                    }
                ).inject($('lightbox-container'));
                lightboxCloseButton.set('html', '<input type="button" value="Fermer" onclick="javascript: page.removeLightbox()" />');
            }
            (function() { $('lightbox').fade('in'); }).delay(500);
            eval(responseJavaScript);
        }.bind(this);
        var urlRequest = new Request.HTML({
            url: path,
            data:"request_via=js&render_as=xhtml",
            evalScripts:true
        });
        urlRequest.addEvent('success', this.lightbox_add_func);
        urlRequest.post();
    },
    addLightboxConfirm: function(msg) {
        blackscreen = new Element('div', {'id':'lightbox-black'}).inject(document.body);
        lightbox = new Element('div', {'id':'lightbox'}).inject(document.body);
        lightboxTitle = new Element('div', {'id':'lightbox-title'}).inject(lightbox);
        lightboxTitle.set('html', msg)
        lightboxContainer = new Element('div', {'id':'lightbox-container'}).inject(lightbox);
        lightboxContainer.set('html', 'Confirmez-vous cette action ?');
        lightboxButtons = new Element('div', {'id':'buttons'}).inject(lightboxContainer);
        lightboxButtons.set('html', '<input type="button" value="Confirmer" onClick="javascript:page.updateLightbox()" /><input type="button" value="Annuler" onClick="javascript:page.removeLightbox()" />');
        $('lightbox-black').setStyle('opacity', '0');
        $('lightbox').setStyle('opacity', '0');
        $('lightbox-black').fade(0.75);
        (function() { $('lightbox').fade('in'); }).delay(500);
    },
    updateLightbox: function() {
        var rawPage = historyManager.getCurrentLocation();
        rawPage = (rawPage.match('^/+(.*)$'))?rawPage.match('^/+(.*)$')[1]:rawPage;
        var currentPage = rawPage.split('/')[0];
        var urlChange = new Request.HTML({
            url: rawPage+'/delete',
            onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript) {
                page.removeLightbox();
                page.load(currentPage, 'content', false);
            }
        });
        urlChange.post();
    },
    removeLightbox: function() {
        var fadeOut = new Fx.Tween($('lightbox'),
            {
                'duration': 'normal',
                onComplete:function() {
                    $('lightbox-black').destroy();
                    $('lightbox').destroy();
                }
            }
        );
        //$('lightbox-black').fade('out');
        fadeOut.start('opacity', 0);
    },
    msgConfirm: function(msg) {
        confirm = new Element('div', {'id':'confirmbox'});
        confirm.inject(document.body);
        confirm.set('html', msg);
        confirm.setStyle('opacity', '0');
        confirm.set('tween', {
            duration: 500,
            link: 'chain',
            onChainComplete: function() { 
                $('confirmbox').destroy();
            }
        });
        confirm.tween('opacity', '1');
        confirm.tween('opacity', '0');
    }
});