var badBrowser = new Ext.Window({
    width: 350,
    autoHeight: true,
    x: 10,
    y: 10,
    layout: 'fit',
    iconCls: 'eventInfoWindow',
    closable: true,
    closeAction: 'hide',
    draggable: false,
    resizable: false,
    title: "Votre navigateur...",
    bodyStyle: "padding: 10px; text-align: center;font-weight: bold;",//color: #FF0000;",div style=' line-height: 80px;height: 80px; padding-left: 80px; background: transparent url(img/warning.png) no-repeat 0px 0px;'>
    html: "<table class='x-window-mc' style='text-align: center; font-weight: bold; padding: 10px;><tr valign='middle'><td><img src='img/warning_opaque.png'/></td><td>"+"L'utilisation d'innoAgenda sur votre navigateur est déconseillée.<br/>Pour obtenir un fonctionnement optimal du produit, nous vous conseillons d'utiliser :"+"</td></tr></table>"+"<div>&nbsp;</div>"
        + "<div class='browser'><div><a href='http://www.mozilla-europe.org/fr/firefox/' target='_blank'><img align='absmiddle' src='img/firefox_mini_opaque.png'/></a> <a href='http://www.mozilla-europe.org/fr/firefox/' target='_blank'>Firefox 3+</a></div><div style='padding-left: 40px;'>ou</div><div><a href='http://www.microsoft.com/france/windows/ie/' target='_blank'><img align='absmiddle' src='img/ie_mini_opaque.png'/></a> <a href='http://www.microsoft.com/france/windows/ie/' target='_blank'>Internet Explorer 8+</div></div>"
});

var badScreenSize = new Ext.Window({
    width: 350,
    autoHeight: true,
    x: 10,
    y: 10,
    layout: 'fit',
    iconCls: 'eventInfoWindow',
    closable: true,
    closeAction: 'hide',
    draggable: false,
    resizable: false,
    title: "Votre navigateur...",
    bodyStyle: "padding: 10px; text-align: center;font-weight: bold;",//color: #FF0000;",div style=' line-height: 80px;height: 80px; padding-left: 80px; background: transparent url(img/warning.png) no-repeat 0px 0px;'>
    html: "<table class='x-window-mc' style='text-align: center; font-weight: bold; padding: 10px;'><tr valign='middle'><td><img src='img/resize.png'/></td><td>"+"Pour un affichage optimal, nous vous recommandons l'utilisation d'une résolution minimale de 1024x768."+"</td></tr></table>"
});


/***
 *  Login Window
 */

innoAgenda.Windows.loginThemeStore = new Ext.data.SimpleStore({
    fields: ['id', 'name'],
    data : [
        ['defaut','par défault'],
        ['slate','Slate']
    ]
});

innoAgenda.Windows.loginThemecombo = new Ext.form.ComboBox({
    store: innoAgenda.Windows.loginThemeStore,
    displayField:'name',
    valueField:'id',
    typeAhead: true,
    mode: 'local',
    triggerAction: 'all',
    value:theme,
    selectOnFocus:true,
    forceSelection: true,
    editable: false,
    x: 100,
    y: 80,
    width: 120,
    id: 'loginThemecombo',
    listeners: {
        select : function(combo, record, index) {
            Ext.Ajax.request({
                url: IACV_SERVER_URL+'changeTheme.php',
                success: function(response) {
                    window.location = IACV_CLIENT_URL;
                },
                failure: function(response) {                    

                },
                params: {
                    theme: record.data.id
                }
            });
        }
    }
});

var newPasswordWindow = false;
function newPassword() {
    if (!newPasswordWindow) {
        newPasswordWindow = new Ext.Window({
            id: 'newPasswordWindow',
            title: 'Mot de passe perdu',
            modal: true,
            width: 300,
            height: (Ext.isIE)?210:180,
            resizable: false,
            draggable: false,
            layout: 'fit',
            iconCls: 'loginWindowIcon',
            closeAction : 'hide',
            shim: true,
            items: [
            {
                xtype: 'form',
                id: 'newPasswordFormPanel',
                url: IACV_SERVER_URL+'lostpassword.php',
                defaultType: 'textfield',
                border: false,
                frame: false,
                //monitorValid:true,
                labelWidth: 70,
                bodyStyle: 'padding: 5px',
                items:[
                {
                    xtype: 'label',
                    width: 230,
                     style: {
                         'margin-bottom': 5
                     },
                    html: '<div style="margin-bottom: 10px;font-size: 12px;text-align: justify;">Saisissez ci-dessous votre <b>nom d\'utilisateur innoAgenda</b> et votre <b>adresse email</b>, un nouveau mot de passe vous y sera envoyé dans les plus brefs délais.</div>'
                },
                {
                    width: 200,
                    fieldLabel: 'Utilisateur',
                    name: 'login',
                    value: '',
                    selectOnFocus: true
                    //,allowBlank: false
                },
                {
                    width: 200,
                    fieldLabel: 'Email',
                    name: 'mail',
                    value: '',
                    selectOnFocus: true
                    //,allowBlank: false
                }]
            }],
            listeners: {
                hide: function(p) {
                    if (Ext.get("banner"))
                        Ext.get("banner").show();
                }
            },
            bbar: ['->',
                {
                    text:'Valider',
                    formBind: true,
                    handler: sendNewPassword,
                    cls: 'x-btn-text-icon',
                    icon: 'img/icons/email_go.png'
                }

            ]
        });


    }
    newPasswordWindow.show();
    if (!newPasswordWindow) {
        new Ext.KeyMap(Ext.getCmp('newPasswordFormPanel').body, [
            {
            key: Ext.EventObject.ENTER,
            fn: sendNewPassword,
            scope: this
        }
        ]);
    }
}

function sendNewPassword() {
    Ext.getCmp('newPasswordFormPanel').getForm().submit({
        method:'POST',
        waitTitle:'Connexion au serveur',
        waitMsg:'Envoi des informations...',
        params: {
            'instance': innoAgenda.Instance.id
        },
        success:function(form, action){
            var responseJSON = Ext.util.JSON.decode(action.response.responseText);
            Ext.Msg.show({
                title: 'Message envoyé',
                buttons: Ext.Msg.OK,
                icon: Ext.MessageBox.INFO,
                fn: function() {
                    if (Ext.get("banner"))
                        Ext.get("banner").show();
                },
                msg: "Un message vient d'être envoyé à l'adresse spécifiée."
            });
            Ext.getCmp('newPasswordFormPanel').getForm().reset();
            Ext.getCmp('newPasswordWindow').hide();
            if (Ext.get("banner"))
                Ext.get("banner").hide();
        },
        failure:function(form, action){

            if(action.failureType == 'server'){
                obj = Ext.util.JSON.decode(action.response.responseText);
                if (obj.errors.reason == 'LOSTPASSWORD_VERIFICATION_ERROR') {
                    reason = "L'utilisateur n'existe pas ou l'adresse mail spécifiée ne correspond pas à cet utilisateur.";
                }

            } else {
                reason = "Impossible de joindre le serveur";
            }
            Ext.Msg.show({
                title: 'Erreur',
                buttons: Ext.Msg.OK,
                icon: Ext.MessageBox.ERROR,
                fn: function() {
                    if (Ext.get("banner"))
                        Ext.get("banner").show();
                },
                msg: reason
            });
            //Ext.getCmp('loginFormPanel').getForm().reset();
            Ext.getCmp('newPasswordFormPanel').getForm().reset();
            Ext.getCmp('newPasswordWindow').hide();
            if (Ext.get("banner"))
                Ext.get("banner").hide();
        }
    });

}

var submit = function(){
    try{
        Ext.getDom("login-submit-btn").click();
    } catch(e){
        Ext.getDom('login-form').submit();
    }
};

var tbsep = new Ext.Toolbar.Separator();

function initLoginWindow() {
    innoAgenda.Windows.login = new Ext.Window({
        layout:'border',
        width: (innoAgenda.Instance.id == "public")?482:360,
        height: (innoAgenda.Instance.id == "public")?240:180,
        closable: false,
        resizable: false,
        draggable: false,
        plain: false,
        border: true,
        iconCls: 'loginWindowIcon',
        title: 'Bienvenue sur innoAgenda',
        bbar: [
            {
                hidden: (innoAgenda.Instance.id == "public")?false:true,
                text:'<b>Inscription</b>',
                handler:   function() {
                    window.location = IACV_CLIENT_URL+"public";
                }
            },tbsep
            ,{
                text:'Mot de passe oublié ?',
                handler:   newPassword
            }
            ,'->'
            ,{
                text:'<b>Connexion</b>',
                formBind: true,
                handler:   submit,
                cls: 'x-btn-text-icon',
                icon: 'img/icons/accept.png',
                type: 'submit'
            }
        ],
        items: [
        {
            xtype: 'panel',
            region: 'west',
            border: false,
            id: 'loginWindowImage',
            cls: 'loginWindowImage',
            html: '<img src="img/instances/default.png" />'
        },{
            region:'center',
            xtype: 'panel',
            id: 'loginFormPanel',
            labelWidth: 95,
            url: IACV_SERVER_URL+'login.php',
            defaultType: 'textfield',
            border: false,
            frame: false,
            monitorValid: true,
            layout: 'absolute',
            items:[{
                    x: 0,
                    y: 85,
                    xtype: 'label',
                    text: 'Apparence',
                    width: 95,
                    style : 'text-align: right;'
                }, innoAgenda.Windows.loginThemecombo]

        }
        ,{
            hidden: (innoAgenda.Instance.id == "public")?false:true,
            id: 'adpanel',
            xtype: 'panel',
            region: 'north',
            height: 61,
            bodyStyle: {
                "border-bottom":  "1px solid #DDDDDD"
            },
            border: false,
            html: ''
        }],
        listeners:{
            show:{
                fn: function(){
                    Ext.fly('login').focus();
                },
                delay:50
            },
            afterlayout: function(){
                innoAgenda.Instance.logo = (innoAgenda.Instance.logo)?innoAgenda.Instance.logo:'default.png';
                Ext.getCmp('loginWindowImage').body.update('<img src="img/instances/'+innoAgenda.Instance.logo+'" />');
                if ((innoAgenda.Instance.id == "public")) {
                    Ext.fly('login').dom.style.width = 150;
                    Ext.fly('pw').dom.style.width = 150;
                    Ext.getCmp('loginThemecombo').setWidth(150);
                    Ext.getCmp('loginWindowImage').setWidth(180);
                    Ext.getCmp('loginWindowImage').body.applyStyles({
                        padding:  "1px solid #DDDDDD",
                        right: "30px"
                    });

                    /*var adcontent = '<object id="banner" style="width: 100%; height: 60px;" type="application/x-shockwave-flash" data="img/annonceurs.swf">'; // width="500" height="100"
                    adcontent += '<param name="movie" value="img/annonceurs.swf" />';
                    adcontent += '<param name="wmode" value="transparent">';
                    adcontent += '</object>';*/

                    var adcontent = '<!-- COMCLICK France : 468 x 60 -->';
                    adcontent += '<iframe src="http://fl01.ct2.comclick.com/aff_frame.ct2?id_regie=1&num_editeur=18823&num_site=2&num_emplacement=1" WIDTH="468" HEIGHT="60" marginwidth="0" marginheight="0" hspace="0" vspace="0" frameborder="0" scrolling="no" bordercolor="#000000">';
                    adcontent += '</iframe>';
                    adcontent += '<!-- FIN TAG -->';


                    Ext.getCmp('adpanel').body.update(adcontent);
                } else {
                    tbsep.hide();
                }
            }
        }
    });

    innoAgenda.Windows.login.render(document.body);

    Ext.fly('login').addKeyListener(Ext.EventObject.ENTER, submit);
    Ext.fly('pw').addKeyListener(Ext.EventObject.ENTER, submit);
    Ext.fly('login-form').dom.action = IACV_SERVER_URL+"auth.php";
    Ext.fly('login-form').appendTo(Ext.getCmp('loginFormPanel').body);
    Ext.fly('login-form').show();
    Ext.get("logincontainer").createChild({
        tag:"input",
        type:"submit",
        value:"login",
        id:"login-submit-btn",
        style:"visibility:hidden"
    });
    
    innoAgenda.Windows.login.show();
    if (AUTO_DEMO_LOGIN && innoAgenda.Instance.id == "demo") {
        Ext.get('login').dom.value = "jean";
        Ext.get('pw').dom.value = "demo";
    }

    if (loginError && loginError > 0) {
        var msg;

        if(loginError == 1 ){
            msg = 'Le nom d\'utilisateur ou le mot de passe sont invalides.';
        } else {
            msg = 'Une erreur est survenue lors de<br/>la tentative de connexion avec serveur.';
        }
        Ext.Msg.show({
            title: 'Erreur',
            buttons: Ext.Msg.OK,
            icon: Ext.Msg.ERROR,
            msg: msg
        });

    }
}

Ext.onReady(function() {
    Ext.QuickTips.init();
    Ext.get('loadingAnim').hide();
    
    
    

   

    if (!Ext.isIE) {
        var f1 = new Ext.form.TextField({
            fieldLabel:"Nom d'utilisateur",
            name:"login",
            allowBlank:false,
            minLength:2,
            maxLength:20,
            validationEvent:"blur",
            labelSeparator: "",
            el:"login"
        });

        var f2 = new Ext.form.TextField({
            fieldLabel:"Mot de passe",
            name:"pw",
            vtype:"password",
            allowBlank:false,
            inputType:"password",
            validationEvent:"blur",
            el:"pw"
        });

    }

    

    initProgress = Ext.MessageBox.progress("Initialisation", "Initialisation en cours ...","");
    Ext.TaskMgr.start(initProgressTask);

    Ext.Ajax.request({
        url: IACV_SERVER_URL+'instance.php',
        success: function(response) {
            var responseJSON = Ext.util.JSON.decode(response.responseText);
            if (!responseJSON.success) {
                initProgress.hide();
                Ext.TaskMgr.stop(initProgressTask);
                if(responseJSON.errors.reason == 1)
                    Ext.Msg.show({
                       title:'Instance inconnue',
                       msg: 'L\'adresse spécifiée n\'est pas valide.<br/>Aucun compte ne correspond à cette adresse.',
                       buttons: Ext.Msg.OK,
                       fn: function() {
                           window.location = DEFAULT_BAD_INSTANCE_URL;
                       },
                       icon: Ext.MessageBox.ERROR
                    });
            } else {
                initProgress.hide();
                Ext.TaskMgr.stop(initProgressTask);

                innoAgenda.Instance = responseJSON.instance;

                if (responseJSON.user && responseJSON.group && responseJSON.prefs && responseJSON.permissions) {
                    window.location = IACV_CLIENT_URL+"agenda.php";
                } else {
                    initLoginWindow();

                    if (Ext.isOpera || (Ext.isIE6 && navigator.userAgent.toLowerCase().indexOf("msie 8") == -1)) {
                        badBrowser.show();
                    } else if (screen.width < 1024 || screen.height < 768) {
                        badScreenSize.show();
                    }
                }

                if (newPwd == 1) {
                    Ext.Msg.show({
                        title: 'Mot de passe',
                        buttons: Ext.Msg.OK,
                        icon: Ext.MessageBox.INFO,
                        msg: "Votre nouveau mot de passe est désormais activé."
                    });
                }
            }
        },
        failure: function(response) {
            Ext.Msg.alert('Erreur', 'Impossible de joindre le serveur innoAgenda.');
        }
    });
    

    
});


