/**
 * 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');
/* 擴展欄位驗證型態 */
Ext.applyIf(Ext.form.VTypes,{
	repeat:function(val,field){//密碼是否重覆
		var pwd_id = Ext.getCmp(field.repeat.targetId);
		if(val == pwd_id.getValue()){
			return true;
		}
		return false;
	},
	repeatText: '與密碼不相同!!'
});
/* 語言檔採用了Ext4 已有更改，所以在這要套用原來的 */
Ext.apply(Ext.form.DateField.prototype, {
   disabledDaysText  : "無法使用",
   disabledDatesText : "無法使用",
   minText           : "此欄位之日期必須在 {0} 之後",
   maxText           : "此欄位之日期必須在 {0} 之前",
   invalidText       : "{0} 不是正確的日期格式 - 必須像是 「 {1} 」 這樣的格式",
   format            : "Y/m/d"
});
/**
 * Login dialog constructor
 *
 * @param {Object} config
 * @extends {Ext.util.Observable}
 */
Ext.ux.form.registerDialog = function (config) {
    Ext.apply(this, config);

    // The CSS needed to style the dialog.
    var css = '.ux-auth-header-icon {background: url("' + this.basePath + '/medium/cake.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/accept.png") !important;}'
        + '.ux-auth-close {background-image: url("' + this.basePath + '/medium/close.png") !important;}'
        + '.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.registerDialog.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  : 195
    });

    // store username id to focus on window show event
    this._userId = Ext.id();
	this._pwdId =  'newpwd';
	this._pwd2Id = Ext.id();
	this._nickId = Ext.id();
    this._mailId = Ext.id();
	this._birthdayId = Ext.id();
    this._okButtonId = 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 },
		defaultType : 'textfield',
        items : [{
            id : this._userId,
            name : this.userField,
            fieldLabel : this.userLabel,
            vtype : this.userVtype,
            validateOnBlur : false,
            allowBlank : false,
			maxLength : 10,
			maxLengthText : '超過字數了!最多只能10個字哦',
			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
                }*/
				
            }
        }, {
			inputType : 'password',
            id : this._pwdId,
            name : this.pwdField,
            fieldLabel : this.pwdLabel,
            vtype : this.pwdVtype,
            validateOnBlur : false,
            allowBlank : false,
			maxLength : 10,
			maxLengthText : '超過字數了!最多只能10個字哦',
			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
                }*/
				
            }
        }, {
			inputType : 'password',
            id : this._pwd2Id,
            name : this.pwd2Field,
            fieldLabel : this.pwd2Label,
            vtype : 'repeat',
			repeat:{targetId:'newpwd'},
            allowBlank : false,
			maxLength : 10,
			maxLengthText : '超過字數了!最多只能10個字哦',
			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
                }*/
				
            }
        },{
            id  : this._nickId,
            name  : this.nickField,
            fieldLabel  : this.nickLabel,
			maxLength : 10,
			maxLengthText : '超過字數了!最多只能10個字哦!',
            validateOnBlur : false,
            allowBlank  : false
        },{
            id  : this._mailId,
            name  : this.mailField,
            fieldLabel  : this.mailLabel,
            vtype  : this.mailVtype,
            validateOnBlur : false,
            allowBlank  : false
        },{
			id  : this._birthdayId,
			xtype : 'datefield',
			fieldLabel : '生　　日',
			name : 'birthday',
			//maxLength : 10,
			//maxLengthText : '超過字數了!最多只能10個字哦!',
			format : 'Y-m-d',
			allowBlank : false
		},{
			xtype: 'radiogroup',
            fieldLabel: '訂電子報',
            items: [
                {boxLabel: '是', name: 'edm', inputValue: 'true', checked: true},
                {boxLabel: '否', name: 'edm', inputValue: 'false'}
            ]
		}, {
			xtype:'numberfield',
			fieldLabel : '驗  證  碼',
			name : 'checknum',
			blankText : '請輸入驗證碼!',
			allowBlank : false
		},{
			xtype: 'container',
			autoWidth: true,
			html :'<center><div id="register_img_check">若無圖片,請按重新產生驗證碼</div></center>'
		},{   
			name : 'date',
			inputType : 'hidden'//, 
			//value: (new Date()).format('Y-m-d')
		}]
    });

    // Default buttons and keys
    var buttons = [{
        id          : this._okButtonId,
        text        : this.okButton,
        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('register_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      : 540,
        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('register_img_check');
			}
		}
    });

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


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

    /**
     * LoginDialog window title
     *
     * @type {String}
     */
    title :'註冊使用視窗',

    /**
     * The message on the LoginDialog
     *
     * @type {String}
     */
    message : '免責聲明：<div style="color:#CC3300; font-size:12px; line-height:18px;">本網站保有隨時更新網站內容的權利，若造成資料遺失不負任何賠償責任！本站仍會儘力維護資料的完整性與正確性！<br/><font color="#000000">注意：</font><br/>由於本網站採用寬鬆的註冊程序，請確定您所輸入的資料是正確的！您可以使用帳號demo與密碼demo來登入測試，再決定是否要註冊！</div>',

    /**
     * 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}
     */
    okButton : '送出',

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

    userLabel : '帳　　號',
    userField : 'user',
    userVtype : 'alphanum',
    pwdLabel : '密　　碼',
    pwdField : 'pwd',
    pwdVtype : 'alphanum',
    pwd2Label : '確認密碼',
    pwd2Field : 'pwd2',
    nickLabel : '暱　　稱',
    nickField : 'nick',
	birthdayLabel : '生　　日',
    birthdayField : 'birthday',
    mailLabel : '郵　　件',
    mailField : 'mail',
    mailVtype : 'email',

    /**
     * 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/register.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();
		form.findField('date').setValue(new Date().format('Y-m-d H:m:s'));
        if (form.isValid())
        {
            Ext.getCmp(this._okButtonId).disable();
			Ext.getCmp(this._imgCheckButtonId).disable();
           // if(Ext.getCmp(this._cancelButtonId)) {
                Ext.getCmp(this._cancelButtonId).disable();
           // }
           /* if(this.encrypt) {
                Ext.getCmp(this._passwordId).setRawValue(
                    Ext.ux.Crypto.SHA1.hash(this.salt + 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._okButtonId).enable();
			Ext.getCmp(this._imgCheckButtonId).enable();
            //if(Ext.getCmp(this._cancelButtonId)) {
                Ext.getCmp(this._cancelButtonId).enable();
            //}
			this.setMessage (this.message + '<font color="#6600FF">您已註冊成功，驗證email後，就可登入哦</font>');
			Ext.get('counts').load({url: 'actions/counts.php'});
            //this.hide();
        }
    },


    /**
     * On failures
     *
     * @param {Ext.form.BasicForm} form
     * @param {Ext.form.Action} action
     */
    onFailure : function (form, action) {
		
        // enable buttons
        Ext.getCmp(this._okButtonId).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._userId).focus(true);

        var msg = '';
       /* if (action.result && action.result.message) 
			msg = action.result.message || this.failMessage;
        else */
		msg = this.failMessage + action.result.msg;
        this.setMessage (this.message + '<span class="error">' + msg + '</span>');
        this.fireEvent('failure', this, action, msg);
		load_checkimg('register_img_check');
    }

});
