/**
 * @author Bashev
 */

/*
 * Ext JS Library 3.0.RC1.1
 * Copyright(c) 2006-2009, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */

Ext.onReady(function(){
    Ext.QuickTips.init();
    Ext.form.Field.prototype.msgTarget = 'side';
    Ext.form.Field.prototype.labelAlign = 'top';
    
    var loginForm = new Ext.FormPanel({
        url: 'data/login.php',
        border: false,
        labelAlign: 'top',
        ctCls: 'login-form-icon',
        bodyStyle: 'background: #DFE8F6;',
        height: 105,
        defaults: {
            width: 180,
//            blankText: 'Полето е задължително!',
            allowBlank: false
        },
        defaultType: 'textfield',
        items: [{
            name: 'username',
            fieldLabel: 'Username'
        }, {
            name: 'password',
            inputType: 'password',
            fieldLabel: 'Password'
        }]
    });
    
    loginForm.items.each(function(el){
        el.addListener('specialkey', function(f, o){
            if (o.getKey() == 13) {
                checkLogin();
            }
        });
    });
    
    loginWindow = new Ext.Window({
         title: 'Bash CMS System ver. 4.01',
         draggable: false,
         resizable: false,
         closable: false,
         items: loginForm,
         buttons: [{
             text: 'Visit Site',
             iconCls: 'back-icon',
             handler: function() {
                 window.location.href = 'http://www.themarketinganalysts.com';
             }
         }, {
            id: 'login-button',
            text: 'Login',
            handler: checkLogin
        }]
    })
    
    function checkLogin() {
        Ext.util
        loginForm.getForm().submit({
            waitMsg: 'Checking Login Information...', // Wait Message
            success: function(){ // When saving data success
                window.location.href = 'dashboard.php';
            },
            failure: function(form, action){ // when saving data failed
                var response = 'Access Denied.';
                form.items.get(1).reset();
                if (action.failureType == 'client') {
                    response += '<br />All Fields Required.';
                }
                else {
                    response += '<br />' + Ext.util.JSON.decode(action.response.responseText).reason;
                }
                Ext.Msg.show({
                    title: 'Error!',
                    msg: response,
                    buttons: Ext.Msg.OK,
                    icon: Ext.MessageBox.ERROR,
                    minWidth: 300,
                    maxWidth: 350
                });
            }
        });
    }
    loginWindow.show();
});
