var login_times = 0;
/**
 * Free and simple to use loginDialog for ExtJS 3.x
 *
 * @author  Albert Varaksin (ExtJS 2.x)
 * @author  Sumit Madan (ExtJS 3.x)
 * @license LGPLv3 http://www.opensource.org/licenses/lgpl-3.0.html
 * @version 1.0 beta, 07/12/2008 - ExtJS 2.x
 * @version 1.0, 05/03/2009 - ExtJS 3.x
 * @version 1.1, 07/18/2009 - ExtJS 3.x
 */

Ext.namespace('Ext.ux.form');

/**
 * Login dialog constructor
 *
 * @param {Object} config
 * @extends {Ext.util.Observable}
 */
Ext.ux.form.loginDialog = function (config) {
    Ext.apply(this, config);

    // The CSS needed to style the dialog.
    var css = '.ux-auth-header-icon {background: url("' + this.basePath + '/small/locked.png") 0 4px no-repeat !important;}'
        + '.ux-auth-header {background:transparent url("' + this.basePath + '/large/lock.png") no-repeat center right;padding:10px;padding-right:45px;}'
        + '.ux-auth-login {background-image: url("' + this.basePath + '/medium/key.png") !important;}'
        + '.ux-auth-close {background-image: url("' + this.basePath + '/medium/close.png") !important;}'
		+ '.ux-auth-warning {background:url("'+ this.basePath + '/small/warning.png") no-repeat center left; padding: 2px; padding-left:20px; font-weight:bold;}'
        + '.ux-auth-header .error {color:red;}'
        + '.ux-auth-form {padding:10px;}';
    Ext.util.CSS.createStyleSheet(css, this._cssId);

    if(this.forceVirtualKeyboard) {
        this.enableVirtualKeyboard = true;
    }

    // LoginDialog events
    this.addEvents ({
        'show'      : true, // when dialog is visible and rendered
        'cancel'    : true, // When user cancelled the login
        'success'   : true, // on succesfful login
        'failure'   : true, // on failed login
        'submit'    : true  // about to submit the data
    });
    Ext.ux.form.loginDialog.superclass.constructor.call(this, config);

    // head info panel
    this._headPanel = new Ext.Panel ({
        baseCls : 'x-plain',
        html    : this.message,
        cls     : 'ux-auth-header',
		bodyStyle   : "padding: 1px;",
        region  : 'north',
        height  : 100
    });

    // store username id to focus on window show event
    this._usernameId = Ext.id();
    this._passwordId = Ext.id();
    this._loginButtonId = Ext.id();
    this._cancelButtonId = Ext.id();
    this._imgCheckButtonId = Ext.id();
	
    // form panel
    this._formPanel = new Ext.form.FormPanel ({
        region      : 'center',
        border      : false,
        bodyStyle   : "padding: 10px;",
        waitMsgTarget: true,
        labelWidth  : 75,
        defaults    : { width: 150 },
        items : [{
            xtype           : 'textfield',
            id              : this._usernameId,
            name            : this.usernameField,
            fieldLabel      : this.usernameLabel,
            vtype           : this.usernameVtype,
            validateOnBlur  : false,
			blankText : '帳號只能輸入英文與數字且不能為空',
			minLength : 4,
			minLengthText : '字數太少了!最少要4個字哦',
            allowBlank      : false,
			validationEvent : this.forceVirtualKeyboard == true ? 'blur' : 'keyup',
            enableKeyEvents : true,
            keyboardConfig: {
                    showIcon: true//,
                    //languageSelection: true
            },
            plugins: this.enableVirtualKeyboard == true ? new Ext.ux.plugins.VirtualKeyboard() : null,
            listeners: {
                render: function() {
                    this.capsWarningTooltip = new Ext.ToolTip({
                        target: this.id,
                        anchor: 'top',
                        width: 205,
                        html: '<div class="ux-auth-warning">Caps Lock is On</div><br />' +
                            '<div>Having Caps Lock on may cause you to enter your password incorrectly.</div><br />' +
                            '<div>You should press Caps Lock to turn it off before entering your password.</div>'
                    });

                    // disable to tooltip from showing on mouseover
                    this.capsWarningTooltip.disable();

                    // When the password field fires the blur event,
                    // the tootip gets enabled automatically (possibly an ExtJS bug).
                    // Disable the tooltip everytime it gets enabled
                    // The tooltip is shown explicitly by calling show()
                    // and enabling/disabling does not affect the show() function.
                    this.capsWarningTooltip.on('enable', function() {
                        this.disable();
                    });
                },
				/*鍵盤無作用，只能用螢幕小鍵盤
                keypress: {
                    fn: function(field, e) {
                        if(this.forceVirtualKeyboard) {
                            field.plugins.expand();
                            e.stopEvent();
                        }
                        else {
                            var charCode = e.getCharCode();
                            if((e.shiftKey && charCode >= 97 && charCode <= 122) ||
                                (!e.shiftKey && charCode >= 65 && charCode <= 90)) {

                                field.capsWarningTooltip.show();
                            }
                            else {
                                if(field.capsWarningTooltip.hidden == false) {
                                    field.capsWarningTooltip.hide();
                                }
                            }
                        }
                    },
                    scope: this
                },
				*/
                blur: function(field) {
                    if(this.capsWarningTooltip.hidden == false) {
                        this.capsWarningTooltip.hide();
                    }
                }
            }
        }, {
            xtype           : 'textfield',
            inputType       : 'password',
            id              : this._passwordId,
            name            : this.passwordField,
            fieldLabel      : this.passwordLabel,
            vtype           : this.passwordVtype,
            width           : this.enableVirtualKeyboard == true ? 150 : 170,
            validateOnBlur  : false,
            allowBlank      : false,
			blankText : '密碼只能輸入英文與數字且不能為空',
			minLength : 4,
			minLengthText : '字數太少了!最少要4個字哦',
            validationEvent : this.forceVirtualKeyboard == true ? 'blur' : 'keyup',
            enableKeyEvents : true,
            keyboardConfig: {
                    showIcon: true//,
                    //languageSelection: true
            },
            plugins: this.enableVirtualKeyboard == true ? new Ext.ux.plugins.VirtualKeyboard() : null,
            listeners: {
               
				/*鍵盤無作用，只能用螢幕小鍵盤
                keypress: {
                    fn: function(field, e) {
                        if(this.forceVirtualKeyboard) {
                            field.plugins.expand();
                            e.stopEvent();
                        }
                        else {
                            var charCode = e.getCharCode();
                            if((e.shiftKey && charCode >= 97 && charCode <= 122) ||
                                (!e.shiftKey && charCode >= 65 && charCode <= 90)) {

                                field.capsWarningTooltip.show();
                            }
                            else {
                                if(field.capsWarningTooltip.hidden == false) {
                                    field.capsWarningTooltip.hide();
                                }
                            }
                        }
                    },
                    scope: this
                }
				*/
               
            }
        }, {
			xtype:'numberfield',
			fieldLabel : '驗　證　碼',
			name : 'checknum',
			blankText : '請輸入驗證碼!',
			allowBlank : false
		},{
			xtype: 'container',
			autoWidth: true,
			html :'<center><div id="login_img_check">若無圖片,請按重新產生驗證碼</div></center>'
		}]
    });

    // Default buttons and keys
    var buttons = [{
        id          : this._loginButtonId,
        text        : this.loginButton,
        iconCls     : 'ux-auth-login',
        width       : 40,
        handler     : this.submit,
        scale       : 'medium',
        scope       : this
    }];
    var keys = [{
        key     : [10,13],
        handler : this.submit,
        scope   : this
    }];

	buttons.push({
		id      : this._imgCheckButtonId,
		text    : '產生驗證碼',
		//iconCls : 'ux-accented-icon',
		width : 90,
		handler : function() {  
				load_checkimg('login_img_check');
		},
		scale   : 'medium',
		scope   : this
	});

    // if cancel button exists
   // if (typeof this.cancelButton == 'string') {
        buttons.push({
            id      : this._cancelButtonId,
            text    : '取消',
            iconCls : 'ux-auth-close',
            width   : 60,
            handler : this.cancel,
            scale   : 'medium',
            scope   : this
        });
        keys.push({
            key     : [27],
            handler : this.cancel,
            scope   : this
        });
   // }
	
	
    // create the window
    this._window = new Ext.Window ({
        width       : 300,
        height      : 300,
        closable    : false,
        resizable   : false,
        draggable   : true,
        modal       : this.modal,
        iconCls     : 'ux-auth-header-icon',
        title       : this.title,
        layout      : 'border',
        bodyStyle   : 'padding:5px;',
        buttons     : buttons,
        keys        : keys,
        items       : [this._headPanel, this._formPanel],
		listeners : {
			'show' : function(obj){
				load_checkimg('login_img_check');
			}
		}
    });

    // when window is visible set focus to the username field
    // and fire "show" event
    this._window.on ('show', function () {
        
        Ext.getCmp(this._usernameId).focus(true, 500);
        Ext.getCmp(this._passwordId).setRawValue('');
        this.fireEvent('show', this);
        
    }, this);
};


// Extend the Observable class
Ext.extend (Ext.ux.form.loginDialog, Ext.util.Observable, {

    /**
     * LoginDialog window title
     *
     * @type {String}
     */
    title :'登入視窗',

    /**
     * The message on the LoginDialog
     *
     * @type {String}
     */
    message : '為保護您的密碼不被木馬程式鍵盤側錄，帳號與密碼請改採滑鼠點選螢幕小鍵盤的方式輸入!!<br/><font color="#9900FF">您可用帳號demo密碼demo來測試使用</font>',

    /**
     * When login failed and no server message sent
     *
     * @type {String}
     */
    failMessage : '無法登入',

    /**
     * When submitting the login details
     *
     * @type {String}
     */
    waitMessage : '請稍等待,正在登入中...',

    /**
     * The login button text
     *
     * @type {String}
     */
    loginButton : '登入',

    /**
     * Cancel button
     *
     * @type {String}
     */
    cancelButton : '取消',

    /**
     * Username field label
     *
     * @type {String}
     */
    usernameLabel : '帳　　　號',

    /**
     * Username field name
     *
     * @type {String}
     */
    usernameField : 'user',

    /**
     * Username validation
     *
     * @type {String}
     */
    usernameVtype : 'alphanum',

    /**
     * Password field label
     *
     * @type {String}
     */
    passwordLabel : '密　　　碼',

    /**
     * Password field name
     *
     * @type {String}
     */
    passwordField : 'pwd',

    /**
     * Password field validation
     *
     * @type {String}
     */
    passwordVtype : 'alphanum',

    /**
     * Language field label
     *
     * @type {String}
     */
    languageLabel : '',
    
    /**
     * Language field name
     *
     * @type {String}
     */
    languageField : '',

    /**
     * RememberMe field label
     *
     * @type {String}
     */
    rememberMeLabel : '',

    /**
     * RememberMe field name
     *
     * @type {String}
     */
    rememberMeField : '',

    /**
     * Forgot Password field label
     *
     * @type {String}
     */
    forgotPasswordLabel : '',

    /**
     * Enable Virtual Keyboard for password
     *
     * @type {Bool}
     */
    enableVirtualKeyboard : true,

    /**
     * Force Virtual Keyboard for password entry
     * If true, also sets enableVirtualKeyboard property to true
     *
     * @type {Bool}
     */
    forceVirtualKeyboard : true,

    /**
     * encrypt password using SHA1
     *
     * @type {Bool}
     */
    encrypt : false,

    /**
     * Salt prepended to password, before encryption
     * If encrypt property is false, salt is not used
     *
     * @type {String}
     */
    salt : '',

    /**
     * Forgot Password hyperlink
     *
     * @type {String}
     */
    forgotPasswordLink : 'about:blank',

    /**
     * Request url
     *
     * @type {String}
     */
    url : 'actions/login.php',

    /**
     * Path to images
     *
     * @type {String}
     */
    basePath : '/',

    /**
     * Form submit method
     *
     * @type {String}
     */
    method : 'post',

    /**
     * Open modal window
     *
     * @type {Bool}
     */
    modal : false,

    /**
     * CSS identifier
     *
     * @type {String}
     */
    _cssId : 'ux-LoginDialog-css',

    /**
     * Head info panel
     *
     * @type {Ext.Panel}
     */
    _headPanel : null,

    /**
     * Form panel
     *
     * @type {Ext.form.FormPanel}
     */
    _formPanel : null,

    /**
     * The window object
     *
     * @type {Ext.Window}
     */
    _window : null,

    /**
     * Set the LoginDialog message
     *
     * @param {String} msg
     */
    setMessage : function (msg) {
        this._headPanel.body.update(msg);
    },


    /**
     * Show the LoginDialog
     *
     * @param {Ext.Element} el
     */
    show : function (el) {
        this._window.show(el);
    },


    /**
     * Hide the LoginDialog
     */
    hide : function () {
        this._window.hide()
    },

    /**
     * Hide and cleanup the LoginDialog
     */
    destroy : function () {
        this._window.hide();
        this.purgeListeners();
        Ext.util.CSS.removeStyleSheet(this._cssId);
        var self = this;
        delete self;
    },


    /**
     * Cancel the login (closes the dialog window)
     */
    cancel : function () {
        if (this.fireEvent('cancel', this))
        {
            this._window.close();
        }
    },


    /**
     * Submit login details to the server
     */
    submit : function () {
        var form = this._formPanel.getForm();
        if (form.isValid()){
            Ext.getCmp(this._loginButtonId).disable();
			Ext.getCmp(this._imgCheckButtonId).disable();
            //if(Ext.getCmp(this._cancelButtonId)) {
                Ext.getCmp(this._cancelButtonId).disable();
           // }
		    //Ext.getCmp(this._usernameId).setValue(hex_sha1(Ext.getCmp(this._usernameId).getValue()));
		    //Ext.getCmp(this._passwordId).setValue(hex_sha1(Ext.getCmp(this._passwordId).getValue()));
            /*if(this.encrypt) {
                Ext.getCmp(this._passwordId).setRawValue(
                    Ext.ux.Crypto.SHA1.hash(this.salt + Ext.getCmp(this._passwordId).getValue());
                );
            }*/
			form.findField('user').setValue(hex_sha1(Ext.getCmp(this._usernameId).getValue()));
		    form.findField('pwd').setValue(hex_sha1(Ext.getCmp(this._passwordId).getValue()));
            if (this.fireEvent('submit', this, form.getValues())){
                this.setMessage (this.message);
                form.submit ({
                    url     : this.url,
                    method  : this.method,
					waitTitle : '系統提示',
                    waitMsg : this.waitMessage,
                    success : this.onSuccess,
                    failure : this.onFailure,
                    scope   : this
                });
            }
        }
    },


    /**
     * On success
     *
     * @param {Ext.form.BasicForm} form
     * @param {Ext.form.Action} action
     */
    onSuccess : function (form, action) {
        if (this.fireEvent('success', this, action)) {
            // enable buttons
            Ext.getCmp(this._loginButtonId).enable();
			Ext.getCmp(this._imgCheckButtonId).enable();
           // if(Ext.getCmp(this._cancelButtonId)) {
                Ext.getCmp(this._cancelButtonId).enable();
            //}
			//Ext.Msg.minWidth = 150;
			/*Ext.Msg.alert("系統提示", "您已登入成功!!",function(obj){
				var res = action.result;
				//管理者
				if(9 == res.role || 2 == res.role)
					document.location.href="../back/index.php";
				
			})*/
			document.location.href="back/index.html";
            //this.hide();
			//this._window.hide();
			this._window.close();
        }
    },


    /**
     * On failures
     *
     * @param {Ext.form.BasicForm} form
     * @param {Ext.form.Action} action
     */
    onFailure : function (form, action) {
		var form = this._formPanel.getForm();
        // enable buttons
        Ext.getCmp(this._loginButtonId).enable();
		Ext.getCmp(this._imgCheckButtonId).enable();
       // if(Ext.getCmp(this._cancelButtonId)) {
            Ext.getCmp(this._cancelButtonId).enable();
        //}
       /* if(this.encrypt) {
            Ext.getCmp(this._passwordId).setRawValue('');
        }*/
        Ext.getCmp(this._usernameId).setRawValue('');
		Ext.getCmp(this._passwordId).setRawValue('');
        Ext.getCmp(this._usernameId).focus(true);
		form.findField('checknum').setValue('');
        var msg = '';
        if (action.result && action.result.message) msg = action.result.message || this.failMessage;
        else msg = this.failMessage;
        this.setMessage (this.message + '<br /><center><span class="error">' + msg + ' ('+ login_times +')' +'</span></center>');
        this.fireEvent('failure', this, action, msg);
		if(3 == login_times){
			Ext.Msg.minWidth = 360;
			Ext.Msg.alert("系統提示","<center>您已登入失敗3次</center><br><br>登入失敗的原因可能有:<br>1.您的帳號或密碼不正確<br>2.您的email尚未驗證<br>3.您目前的帳號已被系統管理者封鎖中<br>4.您因為違反版規太多次，帳號已被刪除<br><br>請再試一次或請聯絡系統管理員，將關閉登入視窗!!");
			this._window.close();
			return;
		}else{
			load_checkimg('login_img_check');
			login_times++;
		}
    }

});
