// Ext.namespace will create these objects if they don't already exist
Ext.namespace('SmsBox.Common');
SmsBox.Common = {
    showError:function(action) {
		var _msg,_title;
		if (action.result) {
			_msg   = action.result.errorMessage;
		} else {
			_title = action.response.statusText;
			_msg   = action.response.responseText;
		}
        _title = _title || trans('Error');
		_msg   = _msg || trans('There where Errors');
        Ext.Msg.show({
             title:_title
            ,msg:_msg
            ,modal:true
            ,icon:Ext.Msg.ERROR
            ,buttons:Ext.Msg.OK
        });
    }
    ,showSuccess:function(_msg, _title) {
        _title = _title || trans('Success');
        Ext.Msg.show({
             title:_title
            ,msg:_msg
            ,modal:true
            ,icon:Ext.Msg.INFO
            ,buttons:Ext.Msg.OK
        });
    }
};

Ext.ns('SmsBox.User');
SmsBox.User = function() {
    // do NOT access DOM from here; elements don't exist yet

    // private variables
    var loadMask = null;

    // private functions

    // public space
    return {
        // public properties, e.g. strings to translate

        // public methods
        init:function(){
            loadMask = new Ext.LoadMask(Ext.getBody(), {
                msg:trans('Loading ...')
            });
        },
        login:function(){
            //init SmsBox User
            this.init();
            var phoneNumber = Ext.get('phone_number');
            var password    = Ext.get('password');

            if (!phoneNumber.getValue() || !password.getValue()) {
                Ext.MessageBox.alert(trans('Message'), trans('Please fill all required fields!'));
                return;
            }

            this.showSpinner(trans('Logging you in...'));
            
            Ext.Ajax.on('requestcomplete', this.hideSpinner, this);

            Ext.Ajax.request({
                url:'/smsbox/user/login',
                scope:this,
                method:'POST',
                params:{
                    msisdn:phoneNumber.getValue(),
                    password:password.getValue()
                },
                success:function(_result,_request){
                    var result = Ext.util.JSON.decode(_result.responseText);
                    if (result.success) {
                        var hasProfile = result.has_profile;
                        if (hasProfile == false) {
                            Ext.Msg.show({
                                title:trans('Warning'),
                                msg:trans('You need to create a profile before you can use free Sms service'),
                                modal:true,
                                icon:Ext.Msg.WARNING,
                                buttons:Ext.Msg.OK,
                                fn:function() {
                                    this.createProfile();
                                },
                                scope:this
                            });
                            return;
                        }
                        window.location.href = '/smsbox/web/home/' + '?_dc=' + (new Date().getTime());
                    } else {
                        Ext.Msg.show({
                            title:trans('Error'),
                            msg:result.errorMessage,
                            modal:true,
                            icon:Ext.Msg.ERROR,
                            buttons:Ext.Msg.OK
                        });
                    }
                },
                failure:function(_result,_request){
                    Ext.Msg.show({
                        title:trans('Error'),
                        msg:_result.responseText,
                        modal:true,
                        icon:Ext.Msg.ERROR,
                        buttons:Ext.Msg.OK
                    });
                }
            });
        },
        showSpinner:function(msg){
            loadMask.msg = msg;
            loadMask.show();
        },
        hideSpinner:function(){
            loadMask.hide();
        },
        createProfile:function(){
            var win = Ext.WindowMgr.get('createProfile');
            if (win) {
                Ext.WindowMgr.bringToFront(win);
            } else {
                win = new SmsBox.User.Profile({
                    title:trans('Create Profile'),
                    loadMask:loadMask,
                    destinationUrl:'/smsbox/web/home/' + '?_dc=' + (new Date().getTime())
                });
                win.show('loginButton');
            }
        },
        lostPassword:function(){
            var win = Ext.WindowMgr.get('lostPassword');
            if (win) {
                Ext.WindowMgr.bringToFront(win);
            } else {
                win = new SmsBox.User.Password({
                    title:trans('Forgot Your Password?')
                });
                win.show('lost_password');
            }
        },
        register:function(){
            var win = Ext.WindowMgr.get('register');
            if (win) {
                Ext.WindowMgr.bringToFront(win);
            } else {
                win = new SmsBox.User.Register({
                    title:trans('Register')
                });
                win.show('register');
            }
        },
        disclaimer:function(){
            var win = Ext.WindowMgr.get('disclaimer');
            if (win) {
                Ext.WindowMgr.bringToFront(win);
            } else {
                win = new SmsBox.User.Disclaimer({
                    title:trans('Disclaimer')
                });
                win.show('disclaimer');
            }
        }
    }
}();

Ext.namespace('SmsBox.User.Activate');
SmsBox.User.Activate = Ext.extend(Ext.Window, {
	//Here you can add static variables for the class. variables that
    // will have the same value for all object instances of this class.
    // If you are not sure put it in the constructor above. Do not  put
    // any object created with 'new' or 'xtype' here. It is safer to
    // put it in the config option of the constructor.
	// overrides

    constructor:function(config) {
        // parent constructor call pre-processing - configure listeners here
        config = config || {};
        config.listeners = config.listeners || {};
        Ext.applyIf(config.listeners, {
            // add listeners config here
        });

        // call parent constructor
        SmsBox.User.Activate.superclass.constructor.call(this, config);

        // parent constructor call post-processing

    } // eo function constructor
	,initComponent:function(){
        
        var handlers = {
             cancel:function() {
                this.minimizeWin(this);
             }
            ,submit:function() {
                if (this.form.getForm().isValid()) {
                    var password = this.form.getForm().findField('password');
                    var repeatPassword = this.form.getForm().findField('repeatPassword');
                    if (password.getValue() != repeatPassword.getValue()) {
                        password.markInvalid(trans("Passwords not match"));
                        repeatPassword.markInvalid(trans("Passwords not match"));
                        password.focus();
                        return;
                    }

                    this.form.getForm().submit({
                         scope:this
                        ,waitMsg:trans('Registering and logging you in...')
                        ,success:handlers.onSuccess
                        ,failure:handlers.onFailure
                    });
                } else {
                    Ext.MessageBox.alert(trans('Message'), trans('Check for errors!'));
                }
            }
            ,onSuccess:function(_form, _action) {
                this.minimizeWin(this);
                window.location.href = this.destinationUrl;
            }
            ,onFailure:function(_form, _action) {
                SmsBox.Common.showError(_action);
            }
        };

        this.form = new Ext.FormPanel({
             border:false
            ,frame:true
            ,labelWidth:100
            ,url:'/smsbox/user/activate'
            ,bodyStyle:'padding:0 10px 0;'
            ,items:[{
                 items: [{
                     xtype:'fieldset'
                    ,title:trans('User Data')
                    ,autoHeight:true
                    ,defaultType:'textfield' // each item will be a radio button
                    ,items: [{
                         name:'msisdn'
                        ,fieldLabel:trans('Phone Number')
                        ,allowBlank:false
                        ,readOnly:true
                        ,width:170
                        ,value:this.msisdn
                    },{
                        name:'pin'
                        ,fieldLabel:trans('PIN Number')
                        ,maxLength:4
                        ,minLength:4
                        ,allowBlank:false
                        ,width:170
                    },{
                         fieldLabel:trans('Password')
                        ,name:'password'
                        ,inputType:'password'
                        ,allowBlank: false
                        ,width:170
                    },{
                         fieldLabel:trans('Repeat Password')
                        ,name:'repeatPassword'
                        ,inputType:'password'
                        ,allowBlank: false
                        ,width:170
                    }]
                },{
                     xtype:'fieldset'
                    ,title:trans('Profile Data')
                    ,autoHeight:true
                    ,defaultType:'radio' // each item will be a radio button
                    ,items: [{
                         fieldLabel:trans('Nick name')
                        ,xtype: 'textfield'
                        ,name:'nickName'
                        ,maxLength:12
                        ,allowBlank:false
                        ,width:170
                    },{
                         checked: true
                        ,fieldLabel:trans('Sex')
                        ,boxLabel:trans('Male')
                        ,name:'sex'
                        ,inputValue:'male'
                    },{
                         fieldLabel:''
                        ,labelSeparator:''
                        ,boxLabel:trans('Female')
                        ,name:'sex'
                        ,inputValue:'female'
                    },{
                         fieldLabel:trans('Disclaimer')
                        ,xtype:'checkbox'
                        ,boxLabel:'<a href="http://www.kitio.com">www.kitio.com</a>'
                        ,name:'disclaimer'
                        ,inputValue:'yes'
                        ,checked:false
                    }]
                }]
            }]
            ,buttons: [{
                 text:trans('Complete Registration')
                ,scope:this
                ,formBind:true
                ,handler:handlers.submit
            },{
                 text:trans('Cancel')
                ,scope:this
                ,handler:handlers.cancel
            }]
        });

        var config = {
            layout:'fit',
            width:360,
            height:400,
            closable:false,
            border:false,
            modal:true,
	        minimizable:false,
            items:this.form
        };// eo config object

        // apply config
        Ext.apply(this, Ext.apply(this.initialConfig, config));

		// And Call the superclass to preserve baseclass functionality
		SmsBox.User.Activate.superclass.initComponent.apply(this, arguments);
		// Here you can add functionality that requires the object to
	    // exist, like event handling.

        
    },
    /**
	 * Minimized Win
	 */
	minimizeWin:function(win) {
	    win.hide();
        this.form.getForm().reset();
    }
}); // eo extend

Ext.namespace('SmsBox.User.Disclaimer');
SmsBox.User.Disclaimer = Ext.extend(Ext.Window, {
	//Here you can add static variables for the class. variables that
    // will have the same value for all object instances of this class.
    // If you are not sure put it in the constructor above. Do not  put
    // any object created with 'new' or 'xtype' here. It is safer to
    // put it in the config option of the constructor.
	// overrides

    constructor:function(config) {
        // parent constructor call pre-processing - configure listeners here
        config = config || {};
        config.listeners = config.listeners || {};
        Ext.applyIf(config.listeners, {
            // add listeners config here
        });

        // call parent constructor
        SmsBox.User.Disclaimer.superclass.constructor.call(this, config);

        // parent constructor call post-processing

    } // eo function constructor
	,initComponent:function(){

        this.handlers = {
            agree:function() {
                var disclaimer = this.form.getForm().findField('disclaimer');
                if (disclaimer.checked) {
                    this.form.getForm().submit({
                         scope:this
                        ,params: {
                            agree: 'yes'
                        }
                        ,waitMsg:trans('Processing ...')
                        ,success:this.handlers.onSuccess
                        ,failure:this.handlers.onFailure
                    });
                } else {
                     Ext.MessageBox.alert(trans('Message'), trans('You need to aggree with disclaimer'));
                }
            }
            ,disagree:function(){
                this.form.getForm().submit({
                     scope:this
                    ,params: {
                        agree: 'no'
                    }
                    ,waitMsg:trans('Processing ...')
                    ,success:this.handlers.onSuccess
                    ,failure:this.handlers.onFailure
                });
            }
            ,onSuccess:function(_form, _action) {
                this.minimizeWin(this);
                var action = _action.result.action;
                if (action == 'clearIdentity') {
                    window.location.href = '/web/cupid/index';
                }
            }
            ,onFailure:function(_form, _action) {
                SmsBox.Common.showError(_action);
            }
        };

        this.form = new Ext.FormPanel({
             border:false
            ,frame:true
            ,labelWidth:150
            ,url:'/smsbox/user/disclaimer'
            ,bodyStyle:'padding:0 10px 0;'
            ,items:[{
                 xtype:'box'
                ,anchor:''
                ,autoEl:{
                    tag:'div',
                    html:trans('Some Accompanying text') + '<br /><br />'
                }
            },{
                 fieldLabel:trans('Disclaimer')
                ,xtype:'checkbox'
                ,boxLabel:'<a href="http://www.kitio.com">www.kitio.com</a>'
                ,name:'disclaimer'
                ,inputValue:'yes'
                ,checked:false
            }]
            ,buttons: [{
                 text:trans('I Agree')
                ,scope:this
                ,handler:this.handlers.agree
            },{
                 text:trans('I Disagree')
                ,scope:this
                ,handler:this.handlers.disagree
            }]
            
        });
        var config = {
            layout:'fit',
            width:350,
            height:150,
            closable:false,
            border:false,
            modal:true,
	        minimizable:false,
            items:this.form
        };// eo config object

        // apply config
        Ext.apply(this, Ext.apply(this.initialConfig, config));

		// And Call the superclass to preserve baseclass functionality
		SmsBox.User.Disclaimer.superclass.initComponent.apply(this, arguments);
		// Here you can add functionality that requires the object to
	    // exist, like event handling.
    },
    // New function added
	/**
	 * Minimized Win
	 */
	minimizeWin:function(win) {
	    win.hide();
        this.form.getForm().reset();
    }
}); // eo extend

Ext.namespace('SmsBox.User.Register');
SmsBox.User.Register = Ext.extend(Ext.Window, {
	//Here you can add static variables for the class. variables that
    // will have the same value for all object instances of this class.
    // If you are not sure put it in the constructor above. Do not  put
    // any object created with 'new' or 'xtype' here. It is safer to
    // put it in the config option of the constructor.
	// overrides

    constructor:function(config) {
        // parent constructor call pre-processing - configure listeners here
        config = config || {};
        config.listeners = config.listeners || {};
        Ext.applyIf(config.listeners, {
            // add listeners config here
        });

        // call parent constructor
        SmsBox.User.Register.superclass.constructor.call(this, config);

        // parent constructor call post-processing

    } // eo function constructor
	,initComponent:function(){
        
        // private functions
        var handlers = {
            close:function(){
               this.minimizeWin(this);
            },
            submit:function() {
                if (this.form.getForm().isValid()) {
                    this.form.getForm().submit({
                         scope:this
                        ,waitMsg:trans('Sending activation code...')
                        ,success:handlers.onSuccess
                        ,failure:handlers.onFailure
                    });
                } else {
                    Ext.MessageBox.alert(trans('Message'), trans('Please fill all required fields!'));
                }
            },
            onSuccess:function(_form, _action) {
                var msg 	= _action.result.msg;
                var msisdn  = _action.result.msisdn;
                Ext.Msg.show({
                    title:trans('Success')
                   ,msg:msg
                   ,modal:true
                   ,icon:Ext.Msg.INFO
                   ,buttons:Ext.Msg.OK
                   ,fn:function() {
                       this.minimizeWin(this);
                       this.showActivationWin(msisdn);
                   }
                   ,scope:this
               });
            }
            ,onFailure:function(_form, _action) {
                if (_action.result.errorCode == 1001) {
                    Ext.Msg.show({
                         title:trans('Error')
                        ,msg:_action.result.errorMessage
                        ,modal:true
                        ,icon:Ext.Msg.ERROR
                        ,buttons:Ext.Msg.OK
                        ,fn:function() {
                           this.minimizeWin(this);
                           this.showForgotPassword();
                       }
                       ,scope:this
                    });
                } else {
                    SmsBox.Common.showError(_action);
                }
            }
        };

        var operators = new Ext.data.JsonStore({
            url:'/smsbox/user/load-operators',
            root:'operators',
            id:0,
            fields: ['value', 'text'],
            autoLoad:true
        });

        this.form = new Ext.FormPanel({
             border:false
            ,frame:true
            ,labelWidth:100
            ,url:'/smsbox/user/register'
            ,defaultType:'textfield'
            ,defaults:{anchor:'-24'}
            ,items:[{
                 name:'msisdn'
                ,fieldLabel:trans('Phone Number')
                ,allowBlank:false
            }, new Ext.form.ComboBox({
                 name:'mobile_operater'
                ,fieldLabel:trans('Mobile Operator')
                ,allowBlank:false
                // Stop users being able to type in the combobox
                ,editable:false
                // Even though the user cant type any more
                // once they select one option it'll remove any
                // others that don't start with the same letters
                // unless we turn off filtering
                ,disableKeyFilter:true
                // Only allow users to pick an option that exists
                // in the list of options (not one of their own)
                ,forceSelection:true
                // This isn't entirely necessary but the combox
                // will start off blank otherwise
                ,emptyText:trans('-- Select Operator --')
                // This one's vital: when the user clicks on the
                // drop-down show ALL options
                ,triggerAction:'all'
                // By default it retrieves remote data,
                // we're using local data
                ,mode: 'local'
                // ComboBox will only accept data from a Store
                // so we have to create a basic one
                ,store:operators
                // Specify which fields in the store hold
                // the value and the display text
                ,valueField:'value'
                ,displayField:'text'
                // Important: by default the POST/GET data
                // for this item will contain the display text
                // not the value. This option creates a hidden field
                // with the same name as the dropdown containing the
                // selected value so it is that which gets returned
                ,hiddenName:'mobile_operater'
            })]
            ,buttons: [{
                 text:trans('Register')
                ,scope:this
                ,formBind:true
                ,handler:handlers.submit
            },{
                 text:trans('Close')
                ,scope:this
                ,handler:handlers.close
            }]
        });

        var config = {
            layout:'fit',
            width:350,
            height:150,
            closable:false,
            border:false,
            modal:true,
	        minimizable:true,
            items:this.form
        };// eo config object

        // apply config
        Ext.apply(this, Ext.apply(this.initialConfig, config));

		// And Call the superclass to preserve baseclass functionality
		SmsBox.User.Register.superclass.initComponent.apply(this, arguments);
		// Here you can add functionality that requires the object to
	    // exist, like event handling.

        this.on({
	    	'minimize':{
	    		fn:this.minimizeWin
	    	    ,scope:this
	    	}
	    });
    },
    // New function added
	/**
	 * Minimized Win
	 */
	minimizeWin:function(win) {
	    win.hide();
        this.form.getForm().reset();
    },
    showActivationWin:function(msisdn) {
        var win = Ext.WindowMgr.get('activation');
        if (!win) {
            win = new SmsBox.User.Activate({
                title:trans('Activation'),
                msisdn:msisdn,
                destinationUrl:'/smsbox/web/home/' + '?_dc=' + (new Date().getTime())
            });
            win.show('register');
        }
        Ext.WindowMgr.bringToFront(win);
    },
    showForgotPassword:function(){
        var win = Ext.WindowMgr.get('lostPassword');
        if (win) {
            Ext.WindowMgr.bringToFront(win);
        } else {
            win = new SmsBox.User.Password({
                title:trans('Forgot Your Password?')
            });
            win.show('lost_password');
        }
        Ext.WindowMgr.bringToFront(win);
    }
}); // eo extend

Ext.namespace('SmsBox.User.Password');
SmsBox.User.Password = Ext.extend(Ext.Window, {
	//Here you can add static variables for the class. variables that
    // will have the same value for all object instances of this class.
    // If you are not sure put it in the constructor above. Do not  put
    // any object created with 'new' or 'xtype' here. It is safer to
    // put it in the config option of the constructor.
	// overrides

    constructor:function(config) {
        // parent constructor call pre-processing - configure listeners here
        config = config || {};
        config.listeners = config.listeners || {};
        Ext.applyIf(config.listeners, {
            // add listeners config here
        });

        // call parent constructor
        SmsBox.User.Password.superclass.constructor.call(this, config);

        // parent constructor call post-processing

    } // eo function constructor
	,initComponent:function(){
        
        var handlers = {
            close:function(){
                this.minimizeWin(this);
            },
            submit:function() {
                if (this.form.getForm().isValid()) {
                    this.form.getForm().submit({
                        waitMsg:trans('Sending your password...'),
                        scope:this,
                        success:handlers.onSuccess,
                        failure:handlers.onFailure
                    });
                } else {
                    Ext.MessageBox.alert(trans('Message'), trans('Please fill all required fields!'));
                }
            },
            onSuccess:function(_form, _action) {
                Ext.Msg.show({
                     title:trans('Success')
                    ,msg:_action.result.successMessage
                    ,modal:true
                    ,icon:Ext.Msg.INFO
                    ,buttons:Ext.Msg.OK
                    ,fn:function() {
                        this.minimizeWin(this);
                    },
                    scope:this
                });
            },
            onFailure:function(_form, _action) {
                SmsBox.Common.showError(_action);
            }
        };

        var operators = new Ext.data.JsonStore({
            url:'/smsbox/user/load-operators',
            root:'operators',
            id:0,
            fields: ['value', 'text'],
            autoLoad:true
        });

        this.form = new Ext.FormPanel({
             border:false
            ,frame:true
            ,labelWidth:100
            ,url:'/smsbox/user/forgot-password'
            ,defaultType:'textfield'
            ,defaults:{anchor:'-24'}
            ,items:[{
                 name:'msisdn'
                ,fieldLabel:trans('Phone Number')
                ,allowBlank:false
            }, new Ext.form.ComboBox({
                 name:'mobile_operater'
                ,fieldLabel:trans('Mobile Operator')
                ,allowBlank:false
                // Stop users being able to type in the combobox
                ,editable:false
                // Even though the user cant type any more
                // once they select one option it'll remove any
                // others that don't start with the same letters
                // unless we turn off filtering
                ,disableKeyFilter:true
                // Only allow users to pick an option that exists
                // in the list of options (not one of their own)
                ,forceSelection:true
                // This isn't entirely necessary but the combox
                // will start off blank otherwise
                ,emptyText:trans('-- Select Operator --')
                // This one's vital: when the user clicks on the
                // drop-down show ALL options
                ,triggerAction:'all'
                // By default it retrieves remote data,
                // we're using local data
                ,mode: 'local'
                // ComboBox will only accept data from a Store
                // so we have to create a basic one
                ,store:operators
                // Specify which fields in the store hold
                // the value and the display text
                ,valueField:'value'
                ,displayField:'text'
                // Important: by default the POST/GET data
                // for this item will contain the display text
                // not the value. This option creates a hidden field
                // with the same name as the dropdown containing the
                // selected value so it is that which gets returned
                ,hiddenName:'mobile_operater'
            })]
            ,buttons: [{
                 text:trans('Send password')
                ,scope:this
                ,formBind:true
                ,handler:handlers.submit
            },{
                 text:trans('Close')
                ,scope:this
                ,handler:handlers.close
            }]
        });

        var config = {
            layout:'fit',
            width:350,
            height:150,
            closable:false,
            border:false,
            modal:true,
	        minimizable:true,
            items:this.form
        };// eo config object

        // apply config
        Ext.apply(this, Ext.apply(this.initialConfig, config));

		// And Call the superclass to preserve baseclass functionality
		SmsBox.User.Password.superclass.initComponent.apply(this, arguments);
		// Here you can add functionality that requires the object to
	    // exist, like event handling.

        this.on({
	    	'minimize':{
	    		fn:this.minimizeWin
	    	    ,scope:this
	    	}
	    });
    }
    // New function added
	/**
	 * Minimized Win
	 */
	,minimizeWin:function(win) {
	    win.hide();
	    this.form.getForm().reset();
    }
}); // eo extend

Ext.namespace('SmsBox.User.Profile');
SmsBox.User.Profile = Ext.extend(Ext.Window, {
	//Here you can add static variables for the class. variables that
    // will have the same value for all object instances of this class.
    // If you are not sure put it in the constructor above. Do not  put
    // any object created with 'new' or 'xtype' here. It is safer to
    // put it in the config option of the constructor.
	// overrides

    constructor:function(config) {
        // parent constructor call pre-processing - configure listeners here
        config = config || {};
        config.listeners = config.listeners || {};
        Ext.applyIf(config.listeners, {
            // add listeners config here
        });

        // call parent constructor
        SmsBox.User.Profile.superclass.constructor.call(this, config);

        // parent constructor call post-processing

    } // eo function constructor
	,initComponent:function(){

        var handlers = {
            submit:function() {
                if (this.form.getForm().isValid()) {
                    this.loadMask.msg = trans('Creating your profile and loggin you in...');
                    this.loadMask.show();
                    this.form.getForm().submit({
                        success:handlers.onSuccess,
                        failure:handlers.onFailure,
                        scope:this
                    });
                } else {
                    Ext.MessageBox.alert(trans('Message'), trans('Please fill all required fields!'));
                }
            },
            onSuccess:function(_form, _action) {
                window.location.href = this.destinationUrl;
            },onFailure:function(_form, _action) {
                SmsBox.Common.showError(_action);
            }
        }

        /**
         * Form
         */
        this.form = new Ext.FormPanel({
            border:false
           ,frame:true
           ,labelWidth:100
           ,url:'/smsbox/user/create-profile'
           ,bodyStyle:'padding:0 10px 0;'
           ,items:[{
               items: {
                   xtype:'fieldset'
                  ,title:trans('Profile Data')
                  ,autoHeight:true
                  ,defaultType:'radio' // each item will be a radio button
                  ,items: [{
                          fieldLabel:trans('Nick name')
                         ,xtype: 'textfield'
                         ,name:'nickName'
                         ,maxLength:12
                         ,allowBlank: false
                         ,width:170
                     },{
                          checked: true
                         ,fieldLabel:trans('Sex')
                         ,boxLabel:trans('Male')
                         ,name:'sex'
                         ,inputValue:'male'
                     },{
                          fieldLabel:''
                         ,labelSeparator:''
                         ,boxLabel:trans('Female')
                         ,name:'sex'
                         ,inputValue:'female'
                  },{
                          fieldLabel:trans('Disclaimer')
                         ,xtype:'checkbox'
                         ,boxLabel:trans('Disclaimer')
                         ,name:'disclaimer'
                         ,inputValue:'yes'
                         ,checked:true
                  }]
              }
           }]
           ,buttons: [{
                text:trans('Create Profile')
               ,scope:this
               ,formBind:true
               ,handler:handlers.submit
           }]
        });

        var config = {
            layout:'fit',
            width:395,
            height:235,
            closable:false,
            border:false,
            modal:true,
	        minimizable:false,
            items:this.form
        };// eo config object

        // apply config
        Ext.apply(this, Ext.apply(this.initialConfig, config));

		// And Call the superclass to preserve baseclass functionality
		SmsBox.User.Profile.superclass.initComponent.apply(this, arguments);
		// Here you can add functionality that requires the object to
	    // exist, like event handling.
    }
}); // eo extend

Ext.namespace('SmsBox.User.RegisterLogin');
SmsBox.User.RegisterLogin = Ext.extend(Ext.Window, {
	//Here you can add static variables for the class. variables that
    // will have the same value for all object instances of this class.
    // If you are not sure put it in the constructor above. Do not  put
    // any object created with 'new' or 'xtype' here. It is safer to
    // put it in the config option of the constructor.
	// overrides
    /**
     * @cfg submitUrl
     */
    submitUrl:'/smsbox/user/register',
    /**
     * @cfg submitTxt
     */
    submitTxt:trans('Sending activation code...'),

    constructor:function(config) {
        // parent constructor call pre-processing - configure listeners here
        config = config || {};
        config.listeners = config.listeners || {};
        Ext.applyIf(config.listeners, {
            // add listeners config here
        });

        // call parent constructor
        SmsBox.User.RegisterLogin.superclass.constructor.call(this, config);

        // parent constructor call post-processing

    } // eo function constructor
	,initComponent:function(){

        var handlers = {
            close:function() {
               this.minimizeWin(this);
            }
            ,submit:function() {
                if (this.form.getForm().isValid()) {
                    this.form.getForm().submit({
                        waitMsg:this.submitTxt,
                        url:this.submitUrl,
                        success:handlers.onSuccess,
                        failure:handlers.onFailure,
                        scope:this
                    });
                } else {
                    Ext.MessageBox.alert(trans('Message'), trans('Please fill all required fields!'));
                }
            }
            ,onSuccess:function(_form, _action) {
                var msg 	= _action.result.msg;
                var action 	= _action.result.action;
                var msisdn  = _action.result.msisdn;
                if (action === 'register') {
                    Ext.Msg.show({
                         title:trans('Success')
                        ,msg:msg
                        ,modal:true
                        ,icon:Ext.Msg.INFO
                        ,buttons:Ext.Msg.OK
                        ,fn:function() {
                            this.minimizeWin(this);
                            this.showActivationWin(msisdn);
                        },
                        scope:this
                    });
                }
                
                if (action == 'login') {
                    var has_profile = _action.result.has_profile
                    if (has_profile) {
                        window.location.href = '/smsbox/web/home/' + '?_dc=' + (new Date().getTime());
                    } else {
                        this.minimizeWin(this);
                        Ext.Msg.show({
                            title:trans('Warning')
                           ,msg:trans('You need to create a profile before you can use free Sms service')
                           ,modal:true
                           ,icon:Ext.Msg.WARNING
                           ,buttons:Ext.Msg.OK,
                           fn:function() {
                                this.createProfile();
                           },
                           scope:this
                       });
                    }
                }
            }
            ,onFailure:function(_form, _action) {
                if (_action.result.errorCode == 1001) {
                    Ext.Msg.show({
                         title:trans('Error')
                        ,msg:_action.result.errorMessage
                        ,modal:true
                        ,icon:Ext.Msg.ERROR
                        ,buttons:Ext.Msg.OK
                        ,fn:function() {
                           this.showForgotPassword();
                       }
                       ,scope:this
                    });
                } else {
                    SmsBox.Common.showError(_action);
                }
            }
        };

        var operators = new Ext.data.JsonStore({
            url:'/smsbox/user/load-operators',
            root:'operators',
            id:0,
            fields: ['value', 'text'],
            autoLoad:true
        });

        // I AM NEW USER
        this.newUser = new Ext.form.FieldSet({
            title:trans('I am a new user'),
            autoHeight:true,
            layout:'form',
            items:[new Ext.form.ComboBox({
                 name:'mobile_operater'
                ,fieldLabel:trans('Mobile Operator')
                // Stop users being able to type in the combobox
                ,editable:false
                // Even though the user cant type any more
                // once they select one option it'll remove any
                // others that don't start with the same letters
                // unless we turn off filtering
                ,disableKeyFilter:true
                // Only allow users to pick an option that exists
                // in the list of options (not one of their own)
                ,forceSelection:true
                // This isn't entirely necessary but the combox
                // will start off blank otherwise
                ,emptyText:trans('-- Select Operator --')
                // This one's vital: when the user clicks on the
                // drop-down show ALL options
                ,triggerAction:'all'
                // By default it retrieves remote data,
                // we're using local data
                ,mode:'local'
                // ComboBox will only accept data from a Store
                // so we have to create a basic one
                ,store:operators
                // Specify which fields in the store hold
                // the value and the display text
                ,valueField:'value'
                ,displayField:'text'
                // Important: by default the POST/GET data
                // for this item will contain the display text
                // not the value. This option creates a hidden field
                // with the same name as the dropdown containing the
                // selected value so it is that which gets returned
                ,hiddenName:'mobile_operater'
                ,allowBlank:false
            })]
        });
        
        // I AM RETURNING USER
        this.returningUser = new Ext.form.FieldSet({
            title:trans('I am a returning user'),
            autoHeight:true,
            layout:'form',
            items:[{
                xtype:'textfield'
               ,inputType:'password'
               ,fieldLabel:trans('Password')
               ,name:'password'
            }]
        });


        this.form = new Ext.FormPanel({
             border:false
            ,frame:true
            ,anchor: "100% 100%"
            ,deferredRender:false
            ,labelWidth:100
            ,items:[{
	        	xtype:'fieldset',
	        	title:trans('Sending SMS from SMSpace is quick and easy'),
	        	autoHeight:true,
                layout:'form',
                defaultType: 'radio',  // each item will be a radio button
                defaults:{
                    bodyStyle:'padding:10px',
                    width:200
                },
                items:[{
                    xtype:'textfield',
                    fieldLabel:trans('Phone Number'),
                    name:'msisdn',
                    allowBlank:false,
                    anchor:'-24'
                },{
                    checked:true,
                    fieldLabel:trans('Choose'),
                    boxLabel:trans('I am a new user'),
                    name:'user-type',
                    inputValue:'new',
                    width:300,
                    listeners:{
                        'check':function(checkbox,checked) {
                            if (checked) {
                                // I am new user
                                this.submitUrl = '/smsbox/user/register';
                                this.submitTxt = trans('Sending activation code...');
                                // I am returning user
                                this.returningUser.hide();
                                this.newUser.show();
                                var f = this.form.getForm();
                                var mobile_operater = f.findField('mobile_operater');
                                var password 	 	= f.findField('password');
                                mobile_operater.allowBlank = false;
                                password.allowBlank = true;
                            }
                        },
                        scope:this
                    }
                },{
                    fieldLabel:'',
                    labelSeparator:'',
                    boxLabel:trans('I am a returning user'),
                    name:'user-type',
                    inputValue:'returning',
                    width:300,
                    listeners:{
                        'check':function(checkbox,checked) {
                            if (checked) {
                                this.submitUrl = '/smsbox/user/login';
                                this.submitTxt = trans('Logging you in...');
                                // I am returning user
                                this.newUser.hide();
                                this.returningUser.show();
                                var f = this.form.getForm();
                                var mobile_operater = f.findField('mobile_operater');
                                var password 	 	= f.findField('password');
                                mobile_operater.allowBlank = true;
                                password.allowBlank = false;
                            }
                        },
                        scope:this
                    }
                }]
            }],
            buttons: [{
                 text:trans('Send')
                ,scope:this
                ,formBind:true
                ,handler:handlers.submit
            },{
                 text:trans('Cancel')
                ,scope:this
                ,handler:handlers.close
            }]
        });

        //add both components
        this.form.add(this.newUser, this.returningUser);
        //hide returning user
        this.returningUser.hide();

        var config = {
            layout:'fit',
            width:360,
            height:275,
            closable:true,
            border:false,
            modal:true,
	        minimizable:true,
            items:this.form
        };// eo config object

        // apply config
        Ext.apply(this, Ext.apply(this.initialConfig, config));

		// And Call the superclass to preserve baseclass functionality
		SmsBox.User.RegisterLogin.superclass.initComponent.apply(this, arguments);
		// Here you can add functionality that requires the object to
	    // exist, like event handling.

        this.on({
	    	'minimize':{
	    		fn:this.minimizeWin
	    	    ,scope:this
	    	}
	    });
    }
    // New function added
	/**
	 * Minimized Win
	 */
	,minimizeWin:function(win) {
	    win.hide();
	    this.form.getForm().reset();
    }
    ,createProfile:function(){
        var win = Ext.WindowMgr.get('createProfile');
        var lMask = new Ext.LoadMask(Ext.getBody(), {
            msg:trans('Loading ...')
        });
        if (!win) {
            win = new SmsBox.User.Profile({
                title:trans('Create Profile'),
                loadMask:lMask,
                destinationUrl:'/smsbox/web/home/' + '?_dc=' + (new Date().getTime())
            });
            win.show('loginButton');
        }
        Ext.WindowMgr.bringToFront(win);
    },
    showActivationWin:function(msisdn) {
        var win = Ext.WindowMgr.get('activation');
        if (!win) {
            win = new SmsBox.User.Activate({
                title:trans('Activation'),
                msisdn:msisdn,
                destinationUrl:'/smsbox/web/home/' + '?_dc=' + (new Date().getTime())
            });
            win.show('register');
        }
        Ext.WindowMgr.bringToFront(win);
    },
    showForgotPassword:function(){
        var win = Ext.WindowMgr.get('lostPassword');
        if (!win) {
            win = new SmsBox.User.Password({
                title:trans('Forgot Your Password?')
            });
            win.show('lost_password');
        }
        Ext.WindowMgr.bringToFront(win);
    }
}); // eo extend
