function getDynRenderer(config){
    return function(o){
        Ext.Ajax.request(Ext.apply(config, {
            success: function(res){
                var JSON = Ext.decode(res.responseText);
                var component = Ext.ComponentMgr.create(JSON, 'panel');
                this.add(component);
                this.doLayout();
                component.show();
            },
            scope: o
        }));
    }
}

function getDynReloader(config){
    return function(){
        if (typeof(config.component) == 'string') {
            var o = Ext.getCmp(config.component);
        }
        else {
            var o = config.component;
        }
        if (config.type == 'url') {
            o.load({
                url: config.url,
                scripts: true,
                params: config.params
            });
        }
        else {
            getDynRenderer({
                url: config.url,
                params: config.params
            })(o);
        }
    }
}

function getFormSubmiter(config){
    return function(){
        var myForm = Ext.getCmp(config.form);
        myForm.form.submit({
            failure: function(form, action){
                var mess = (Ext.isEmpty(action.result)) ? 'Formulaire invalide' : action.result.errorInfo;
                Ext.MessageBox.show({
                    title: config.msg,
                    msg: mess,
                    buttons: Ext.MessageBox.OK,
                    width: 400
                });
            },
            success: config.callback
        });
    }
}

function getDynFormSubmiter(config){
    config.callback = getDynReloader({
        component: config.component,
        url: config.url
    });
    return getFormSubmiter(config);
}

function getHttpJsonStore(config){
    var store_config = {
        proxy: new Ext.data.HttpProxy(config["proxy"]),
        reader: new Ext.data.JsonReader(config["reader"], config["reader_mapping"])
    };
    if (config["baseParams"]) {
        store_config["baseParams"] = config["baseParams"];
    }
    if (config["sortInfo"]) {
        store_config["sortInfo"] = config["sortInfo"];
    }
    if (config["listeners"]) {
        store_config["listeners"] = config["listeners"];
    }
    return new Ext.data.Store(store_config);
}

var actions = {
    'save-calque': function(){
        getFormSubmiter({
            form: 'calque_form',
            msg: 'Formulaire de calque',
            callback: function(req, data){
                actions['refresh-main-menu']("gestio");
                center.load({
                    url: "user_interface/views/editCalque.php",
                    scripts: true,
                    text: "Chargement...",
                    params: {
                        id: data.result.insert_id,
                        type: data.result.insert_type
                    }
                });
            }
        })();
    },
    'save-salle': function(){
        getFormSubmiter({
            form: 'salle_form',
            msg: 'Formulaire de salle',
            callback: function(req, data){
                actions['refresh-main-menu']("admin");
                center.load({
                    url: "user_interface/views/editSalle.php",
                    scripts: true,
                    text: "Chargement...",
                    params: {
                        salles: data.result.insert_id
                    }
                });
            }
        })();
    },
    'save-plan': function(){
        getFormSubmiter({
            form: 'plan_form',
            msg: 'Formulaire de plannificateur',
            callback: function(req, data){
                actions['refresh-main-menu']("admin");
                center.load({
                    url: "user_interface/views/editPlannificateur.php",
                    scripts: true,
                    text: "Chargement...",
                    params: {
                        numpl: data.result.insert_id
                    }
                });
            }
        })();
    },
    'save-add-droit': function(){
        getFormSubmiter({
            form: 'droit_form',
            msg: 'Formulaire de droits',
            callback: function(req, data){
                actions['refresh-main-menu']("admin");
                center.load({
                    url: "user_interface/views/editDroit.php",
                    scripts: true,
                    text: "Chargement...",
                    params: {
                        idg: data.result.insert_id
                    }
                });
            }
        })();
    },
    'save-droit': function(){
        getFormSubmiter({
            form: 'droits_form',
            msg: 'Formulaire de droits',
            callback: function(req, data){
                actions['refresh-main-menu']("admin");
                center.load({
                    url: "user_interface/views/editDroit.php",
                    scripts: true,
                    text: "Chargement...",
                    params: {
                        idg: data.result.insert_id
                    }
                });
            }
        })();
    },
    'delete-droit': function(){
        var field = Ext.getCmp('droits_form').getForm().findField("action");
        ;
        field.setValue('delete');
        getFormSubmiter({
            form: 'droits_form',
            msg: 'Formulaire de droits',
            callback: function(req, data){
                actions['refresh-main-menu']("admin");
                center.load({
                    url: "user_interface/views/editDroit.php",
                    scripts: true,
                    text: "Chargement...",
                    params: {
                        idg: data.result.insert_id
                    }
                });
            }
        })();
    },
    'refresh-main-menu': function(sel){
        if (!sel) {
            sel = "rapid_search";
        }
        getDynReloader({
            component: "dyn_menus_main",
            url: "user_interface/menus/main_menu.php",
            params: {
                selected: sel
            }
        })();
    },
    'close-add-refresh': function(){
        closeAllWindowWidget();
        refreshWidget();
    },
    'save-cours': function(){
        getFormSubmiter({
            form: 'cours_form',
            msg: 'Formulaire de cours',
            callback: actions["close-add-refresh"]
        })();
    },
    'update-cours-params': function(store){
        var oldBaseParams = store.baseParams;
        store.baseParams = {};
        Ext.getCmp("cours_form").getForm().isValid();
        var vals = Ext.getCmp("cours_form").getForm().getValues();
        store.baseParams = Ext.apply(vals, {
            todo: oldBaseParams.todo,
            query: oldBaseParams.query
        });
    },
    'bureau': function(){
        center.load({
            url: 'user_interface/views/bureau.php',
            scripts: true,
            text: "Chargement...",
            params: {
                redirect: false
            }
        });
    },
    'unlock-cours-champ': function(checked, champ){
        var ch = Ext.getCmp("cours_form").getForm().findField(champ);
        ch.reset();
        ch.store.reload();
    },
    'update-cours-pauses': function(){
        var frm = Ext.getCmp("cours_form").getForm();
        var debut = time_txt2nbr(frm.findField("debut").getValue());
        var fin = time_txt2nbr(frm.findField("fin").getValue());
        if (debut > fin) {
            Ext.Msg.alert("Attention", "L'heure de d&eacute;but doit &egrave;tre superieure &agrave; l'heure de fin");
        }
        else {
            var champ_pause = frm.findField("pause");
            var champ_pauserepas = frm.findField("pauserepas");
            var nbr_pauses = 0;
            if (debut < 615 && fin > 600) {
                nbr_pauses++;
            }
            if (debut < 945 && fin > 930) {
                nbr_pauses++;
            }
            champ_pause.setValue(nbr_pauses);
            if (debut < 810 && fin > 735) {
                champ_pauserepas.setValue(true)
            }
            else {
                champ_pauserepas.setValue(false)
            }
        }
    },
    'print-cursus': function(){
        var frm = Ext.getCmp("print_cursus_form").getForm();
        window.open('actions/gets/get_calendar.php?' + frm.getValues(true));
    },
    'print-plannificateur': function(){
        var frm = Ext.getCmp("print_plannificateur_form").getForm();
        if (!Ext.isEmpty(frm.findField("numpl").getValue())) {
            window.open('actions/gets/get_calendar.php?' + frm.getValues(true));
        }
        else {
            Ext.Msg.alert("Formulaire", "Remplissez le plannificateur");
        }
    },
    'load-multival': function(new_val){
        var params_in = {};
        var chaque = new_val.split(",");
        for (var i = 0; i < chaque.length; i++) {
            var splited = chaque[i].split("/");
            if (!params_in[splited[0]]) {
                params_in[splited[0]] = splited[1];
            }
            else {
                params_in[splited[0]] += "," + splited[1];
            }
        }
        center.load({
            url: 'user_interface/views/viewCalendar.php',
            params: params_in,
            scripts: true,
            text: 'Chargement...'
        });
    }
};
function doAction(e, t){
    e.stopEvent();
    actions[t.id]();
}

function addDefaultCalendar(type, value, reload){
    var o = Ext.state.Manager.get('calendar-args', {});
    Ext.state.Manager.clear('calendar-args');
    var new_val = new Array();
    new_val.push(value);
    try {
        var old_val = o[type];
        old_val = old_val.split(',');
        for (var i = 0; i < old_val.length; i++) {
            if (new_val.indexOf(old_val[i]) == -1 && old_val[i] != "") {
                new_val.push(old_val[i]);
            }
        }
    } 
    catch (e) {
    }
    o[type] = new_val.join(',');
    Ext.state.Manager.set('calendar-args', o);
    if (reload) {
        actions['refresh-main-menu']();
    }
}

function removeDefaultCalendar(type, value){
    var o = Ext.state.Manager.get('calendar-args', {});
    Ext.state.Manager.clear('calendar-args');
    var new_val = new Array();
    var old_val = o[type];
    old_val = old_val.split(',');
    for (var i = 0; i < old_val.length; i++) {
        if (old_val[i] != value && old_val[i] != "") {
            if (new_val.indexOf(old_val[i]) == -1) {
                new_val.push(old_val[i]);
            }
        }
    }
    if (new_val.length > 0) {
        o[type] = new_val.join(',');
    }
    else {
        delete o[type];
    }
    Ext.state.Manager.set('calendar-args', o);
    actions['refresh-main-menu']();
}

var windows_opened = [];
function createWindowWidget(config_window, config_dyn_request){
    win = new Ext.Window(Ext.apply(config_window, {
        layout: 'fit',
        constrainHeader: true
    }));
    win.on('render', getDynReloader(Ext.apply(config_dyn_request, {
        component: win
    })));
    win.show();
    windows_opened.push(win);
}

function closeAllWindowWidget(){
    for (var i = 0; i < windows_opened.length; i++) {
        windows_opened[i].close();
    }
    windows_opened = [];
}

function action_services(action, node, object){
    var config_window = {
        'width': 600,
        'height': 600,
        'modal': true
    };
    var config_dyn_request = {
        'url': 'user_interface/views/editCommentaire.php',
        'params': {}
    };
    var noeudtmp = object['id'];
    var noeud = noeudtmp.split("/");
    if (noeud[0] == 'centrales') {
        config_window.title = 'Ajout de commentaire';
        config_dyn_request.params.numc = object.numc;
        config_dyn_request.params.type = 'centrale';
        config_dyn_request.params.enseignant_id = object.enseignant_id;
        if (action.trim() == '') {
            return '';
        }
        else 
            if (action == 'add') {
                config_dyn_request.params.action = 'add';
                return "<img onclick ='event.stopPropagation();createWindowWidget(" + Ext.util.JSON.encode(config_window) + "," + Ext.util.JSON.encode(config_dyn_request) + ")' src=\"./framework/style/icons/add.png\" />";
            }
            else 
                if (action == 'edit') {
                    config_dyn_request.params.action = 'edit';
                    return "<img onclick ='createWindowWidget(" + Ext.util.JSON.encode(config_window) + "," + Ext.util.JSON.encode(config_dyn_request) + ")' src=\"./framework/style/icons/editee_16.png\" />";
                }
                else 
                    if (action == 'view') {
                        config_dyn_request.params.id = noeud[1];
                        return "<img onclick ='createWindowWidget(" + Ext.util.JSON.encode(config_window) + "," + Ext.util.JSON.encode(config_dyn_request) + ")' src=\"./framework/style/icons/editee_16.png\" />";
                    }
    }
    else 
        if (noeud[0] == 'persos') {
            config_window.title = 'Ajout de cours personnels';
            config_dyn_request.params.type = 'perso';
            if (action.trim() == '') {
                return '';
            }
            else 
                if (action == 'add') {
                    return "<img onclick ='event.stopPropagation();createWindowWidget(" + Ext.util.JSON.encode(config_window) + "," + Ext.util.JSON.encode(config_dyn_request) + ")' src=\"./framework/style/icons/add.png\" />";
                }
                else 
                    if (action == 'edit') {
                        config_dyn_request.params.id = noeud[1];
                        return "<img onclick ='createWindowWidget(" + Ext.util.JSON.encode(config_window) + "," + Ext.util.JSON.encode(config_dyn_request) + ")' src=\"./framework/style/icons/editee_16.png\" />";
                    }
        }
        else 
            if (noeud[0] == 'forfaitaires') {
                config_window.title = 'Ajout de cours forfaitaires';
                config_dyn_request.params.type = 'forfaitaire';
                if (action.trim() == '') {
                    return '';
                }
                else 
                    if (action == 'add') {
                        return "<img onclick ='event.stopPropagation();createWindowWidget(" + Ext.util.JSON.encode(config_window) + "," + Ext.util.JSON.encode(config_dyn_request) + ")' src=\"./framework/style/icons/add.png\" />";
                    }
                    else 
                        if (action == 'edit') {
                            config_dyn_request.params.id = noeud[1];
                            return "<img onclick ='createWindowWidget(" + Ext.util.JSON.encode(config_window) + "," + Ext.util.JSON.encode(config_dyn_request) + ")' src=\"./framework/style/icons/editee_16.png\" />";
                        }
            }
            else 
                if (noeud[0] == 'profs') {
                    var pdf = "<img onclick ='event.stopPropagation();window.open(\"actions/gets/get_services.php?view=pdf&Eid=" + noeud[1] + "\");' src=\"./framework/style/icons/printer.png\" alt=\"Pdf\" />";
                    if (action.trim() == '') {
                        return ' ' + pdf;
                    }
                    else 
                        if (action == 'unvalid') {
                            return pdf + "<img onclick ='event.stopPropagation();validation(" + Ext.util.JSON.encode(action) + ",\"user_interface/views/editServices.php\"," + noeud[1] + ");' src=\"./framework/style/icons/validee_16.png\" alt=\"Validée\" />";
                        }
                        else 
                            return ' ' + pdf;
                }
                else {
                    return "";
                }
}

function validation(action, url, id){
    var txt = "Valider";
    if (action == 'unvalid') {
        txt = "Unvalider";
    }
    var mafonction = function(){
        center.load({
            'url': url,
            'script': true
        });
    };
    Ext.Msg.confirm('Confirm', 'Etes vous sur de vouloir ' + txt + ' ces états de services? Cette opération est irreversible! ', function(btn, text){
        if (btn == 'yes') {
            Ext.Ajax.request({
                'url': 'actions/saves/save_validation.php',
                'params': {
                    'action': action,
                    'id': id
                },
                'success': mafonction
            });
        }
    });
}

function refreshWidget(){
    try {
        widget.changeStartDateFromInput(widget.__dateSwitcherTool);
    } 
    catch (e) {
    }
}

function time_txt2nbr(txt){
    splited = txt.split(":");
    retour = parseInt(splited[0].replace(/^0/, '')) * 60 + parseInt(splited[1].replace(/^0/, ''));
    return retour;
}

var center = false;
var head = false;
var foot = false;
var menus = false;
var viewport = false;
Ext.onReady(function(){
    Ext.QuickTips.init();
    Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
    head = new Ext.BoxComponent({
        region: 'north',
        el: 'head',
        height: 45
    });
    foot = new Ext.BoxComponent({
        region: 'south',
        el: 'foot',
        height: 15
    });
    menus = new Ext.Panel({
        region: 'west',
        layout: 'border',
        id: 'west-menu',
        margins: '5 5 5 0',
        title: 'Menu',
        split: true,
        width: 230,
        minSize: 175,
        maxSize: 400,
        collapsible: true,
        cmargins: '5 5 5 0',
        items: [{
            region: 'center',
            layout: 'fit',
            border: false,
            id: 'dyn_menus_main',
            listeners: {
                render: getDynRenderer({
                    url: 'user_interface/menus/main_menu.php'
                })
            }
        }, {
            region: 'south',
            height: 50,
            border: false,
            layout: 'fit',
            id: 'dyn_menus_auth',
            listeners: {
                render: getDynRenderer({
                    url: 'user_interface/menus/auth_menu.php'
                })
            }
        }]
    });
    center = new Ext.Panel({
        region: 'center',
        id: 'center',
        margins: '5 5 0 0',
        autoScroll: true,
        autoLoad: {
            url: 'user_interface/views/bureau.php',
            scripts: true
        }
    });
    viewport = new Ext.Viewport({
        layout: 'border',
        items: [head, menus, center, foot]
    });
    var themes_array = [['', 'Bleu'], ['gray', 'Gris'], ['slate', 'Metal'], ['darkgray', 'Gris-Noir'], ['black', 'Noir'], ['purple', 'Violet']];
    var current_theme = Ext.state.Manager.get('theme-args', '');
    //if (!Ext.isIE) {
    if (true){
	    theme_selector = new Ext.form.ComboBox({
            typeAhead: false,
            editable: false,
            displayField: 'name',
            valueField: 'id',
            width: 100,
            store: new Ext.data.SimpleStore({
                fields: ['id', 'name'],
                data: themes_array
            }),
            mode: 'local',
            triggerAction: 'all',
            renderTo: 'theme_selector',
            value: current_theme,
            listeners: {
                select: function(combo){
                    var nval = combo.getValue();
                    Ext.util.CSS.swapStyleSheet('theme', './ext-2.0/resources/css/xtheme-' + nval + '.css');
                    Ext.state.Manager.set('theme-args', nval);
                }
            }
        });
    }
    Ext.util.CSS.swapStyleSheet('theme', './ext-2.0/resources/css/xtheme-' + current_theme + '.css');
    Ext.MessageBox.minWidth = 100;
});
