/**
 * @author pshah
 */
RegGlobal = ({
    temp: '/MedspacePortal/toRegistration.action',
    recUrl: '/MedspacePortal/togetRecruiters.action',
    validationMsg: "",
    registerPass: "",
    registerEmail: "",
    fname: "",
    registerPanel: "",
    proffSpecUrl: '/MedspacePortal/toProffSpec.action',
    allSpecData: "",
    registerForm: ""
});


/*
 * store to keep Profession data requred for professions
 */
professionStore = new Ext.data.Store({
    id: 'professionstore',
	 listeners: {
        load: sortForOther
    },    
    reader: new Ext.data.JsonReader({
		  id: 'professionCode',
        fields: ['profession', 'professionCode', 'specialties']
    })
});

// sorts the store and puts 'Other' in the last
function sortForOther(store, records, options){
    rec = store.getById('OTH');
    store.remove(rec);
    store.insert(4, rec);
    return store;
}

//store to keep speciality data requred for speciality
specStore = new Ext.data.Store({
    storeId: 'specialtystore',
    reader: new Ext.data.JsonReader({
        fields: ['specCode', 'specailty']
    })
});

//store to keep Profession data requred for these specialty panel
recruiterStore = new Ext.data.Store({
    id: 'recruiterStore',
    reader: new Ext.data.JsonReader({
    id:'recId',
        fields: ['recId','fullName','recruiterCode']
    }),
    sortInfo: {
        field: 'fullName',
        direction: 'ASC'
    },
    pruneModifiedRecords:true, // to replace all
    listeners: {
    'load':sortForUnknownRecruiter
     }
});


// sorts the store and puts 'I dont know my recruiter' in First place
function sortForUnknownRecruiter(store, records, options){
   var unknownRecruiterRecord = Ext.data.Record.create([{
        name: 'fullName'
        }, {
        name: 'recruiterCode'
        }]);
        var unknownRecruiter = new unknownRecruiterRecord({
        fullName: "I don't know my recruiter",
        recruiterCode: "null"
       });
   store.insert(0,unknownRecruiter);
   return store;
}

function loadProfSpecStores(response, options){
    var json = Ext.decode(response.responseText);
    professionStore.loadData(json.psStore);
    allSpecData = "available";
}

function requestProfSpecData(){
    //load the store for profession and specialty
    new Ext.data.Connection().request({
        url: RegGlobal.proffSpecUrl,
        timeout: 50000,
        failure: function(response, options){
            //log exception to the server log
            
            ExceptionReporter.send("RESPONSE: "+Ext.encode(response), 'registeration.js : professionStore');
            
            //Inform user with that there has been error in the operation 
            
            showErrorMsg('Sorry couldn\'t load professions data, please try again  ');
            
        },
        success: loadProfSpecStores
    });
}

function loadRecruiters(response, options){
    var jsonRec = Ext.decode(response.responseText);
    recruiterStore.loadData(jsonRec.recruiters);
}

function requestRecruitersData(){
    //load the store for recruiters
    new Ext.data.Connection().request({
        url: RegGlobal.recUrl,
        timeout: 50000,
        failure: function(response, options){
            //log exception to the server log
            
            ExceptionReporter.send("RESPONSE: "+Ext.encode(response), 'registeration.js : recruitersStore');
            
            //Inform user with that there has been error in the operation 
            
            showErrorMsg('Sorry couldn\'t load recruiters data, please try again  ');
            
        },
        success: loadRecruiters
    });
}

//fucntion called when user selects profession
function getSpecialties(combo, rec, indx){
    specStore = Ext.StoreMgr.get('specialtystore');
    specStore.removeAll();
    Ext.getCmp('specialty').clearValue();
    specStore.loadData(rec.get('specialties'));
}


function checkSSNLength(ssn){
    if (ssn.getValue().length >= 4) {
        ssn.setValue(ssn.getValue().substring(0, 3));
        return false;
    }
}

function getRegisterPanel(){
    return new Ext.FormPanel({
        labelWidth: 125, // label settings here cascade unless overridden
        frame: true,
        id: 'registerForm',
        bodyStyle: 'padding:5px 5px 0',
        hideBorders: true,
        width: 380,
        renderTo: 'content',
        autoHeight: true,
        items: [{
            xtype: 'textfield',
            fieldLabel: 'First Name',
            name: 'fname',
            id: 'fname',// reqd
            enableKeyEvents: true,
            listeners: {
                'specialkey': function(f, event){
                    if (event.getKey() == event.ENTER) {
                        Ext.getCmp("regBtn").handler.call(Ext.getCmp("regBtn").scope);
                    }
                },
                render: function(comp){
                    comp.focus(false, true);
                },
                'blur': function(){
                    this.setValue(this.getValue().trim());
                }
            }
        }, {
            xtype: 'textfield',
            fieldLabel: 'Last Name',
            name: 'lname',
            id: 'lname',// reqd
            enableKeyEvents: true,
            listeners: {
                'specialkey': function(f, event){
                    if (event.getKey() == event.ENTER) {
                        Ext.getCmp("regBtn").handler.call(Ext.getCmp("regBtn").scope);
                    }
                },
                'blur': function(){
                    this.setValue(this.getValue().trim());
                }
            }
        
        }, {
            xtype: 'textfield',
            fieldLabel: 'Last 4 Digits of SSN',
            name: 'ssn',
            id: 'ssn',// reqd
            enableKeyEvents: true,
            autoCreate: {tag: "input", type: "text", maxlength: 4},// this creates core api properties, which was needed for maxlength
			maskRe: /[+0-9]/,
            allowBlank: true,
            listeners: {
                'specialkey': function(f, event){
                    if (event.getKey() == event.ENTER) {
                        Ext.getCmp("regBtn").handler.call(Ext.getCmp("regBtn").scope);
                    }
                },
                'blur': function(){
                    this.setValue(this.getValue().trim());
                }
           }
        }, {
            id: 'ssninfo',
            html: '<div class="text margin10px">We request the last 4 digits of your SSN to match your information on file only. If you do not have an SSN, there will be up to a 48-hour delay between registration and logging into MedSpace.</div>'
        }, {
            xtype: 'textfield',
            fieldLabel: ' Email Address',
            name: 'regEmail',
            id: 'regEmail',// reqd
            enableKeyEvents: true,
            vtype: 'email',
            vtypeText: 'Please enter email address in proper format',
            listeners: {
                'specialkey': function(f, event){
                    if (event.getKey() == event.ENTER) {
                        Ext.getCmp("regBtn").handler.call(Ext.getCmp("regBtn").scope);
                    }
                },
                'blur': function(){
                    this.setValue(this.getValue().trim());
                }
            }
        }, {
            id: 'emailinfo',
            html: '<div class="text margin10px">Registration confirmation will be sent to this email address and enable you to log back into the application process.</div>'
        }, {
            xtype: 'textfield',
            fieldLabel: ' Password',
            name: 'password',
            inputType: 'password',
            enableKeyEvents: true,
            vtype: 'password',
            id: 'Pass',
            maxLength:40,
            listeners: {
                'specialkey': function(f, event){
                    if (event.getKey() == event.ENTER) {
                        Ext.getCmp("regBtn").handler.call(Ext.getCmp("regBtn").scope);
                    }
                },
                'blur': function(){
                    this.setValue(this.getValue().trim());
                }
            }
        }, {
            id: 'passwordinfo',
            html: '<div class="text margin10px">Password must be at least 6 characters and must contain at least 1 number and 1 uppercase letter.</div>'
        }, {
            xtype: 'textfield',
            fieldLabel: 'Confirm Password',
            name: 'confirmPassword',
            inputType: 'password',
            vtype: 'password',
            id: 'confirmPass',
            initialPassField: 'Pass', // id of the initial password field
            listeners: {
                'specialkey': function(f, event){
                    if (event.getKey() == event.ENTER) {
                        Ext.getCmp("regBtn").handler.call(Ext.getCmp("regBtn").scope);
                    }
                },
                'blur': function(){
                    this.setValue(this.getValue().trim());
                }
            }
        }, {
            xtype: 'combo',
            emptyText: 'Profession',
            fieldLabel: 'Profession',
            mode: 'local',
            editable: false,
            triggerAction: 'all',
            forceSelection: true,
            displayField: 'profession',
            valueField: 'professionCode',
            hiddenName: 'professionCode',
            listAlign: 'left',
            listClass: "checkbox-profession-specialty-reg",
            listeners: {
                beforerender: requestProfSpecData,
                select: getSpecialties
            },
            store: professionStore,
            id: 'profession',
            name: 'profession'
        }, {
            xtype: 'combo',
            fieldLabel: 'Specialty',
            name: 'specialty',
            emptyText: 'Speciality',
            id: 'specialty',
            msgTarget: 'title',
            mode: 'local',
            shadow: true,
            hiddenId: 'specialtyId',
            hiddenName: 'specialtyCode',
            editable: false,
            triggerAction: 'all',
            forceSelection: true,
            displayField: 'specailty',
            valueField: 'specCode',
            lastQuery: "", // Important
            listClass: 'checkbox-profession-specialty-reg',
            store: specStore
        }, {
            xtype: 'combo',
            fieldLabel: 'Recruiter',
            name: 'recruiter',
            emptyText: 'Recruiter',
            msgTarget: 'title',
            shadow: true,
            id: 'recruiter',
            shadow: true,
            mode: 'local',
            //  mode: 'remote',//remote
            // valueField: 'recId',
            listeners: {
                beforerender: requestRecruitersData//,   
                //select : function(){ alert(this.getValue().trim());this.setValue(this.getValue().trim());}      
            },
            remoteSort: true,
            lastQuery: '', // Important
            editable: false,
            triggerAction: 'all',
            displayField: 'fullName',
            valueField: 'recruiterCode',
            hiddenName: 'recruiterCode',
            forceSelection: true,
            store: recruiterStore,
            listClass: 'checkbox-profession-specialty-reg'
        }, {
            style: 'display:none',
            id: 'RegGlobal.validationMsg',
            width: 360,
            value: RegGlobal.validationMsg,
            html: '<p><b>' + RegGlobal.validationMsg
        }],
        buttonAlign: 'left',
        buttons: [{
            // style: 'margin-left:11.5em; ',
            text: 'Register',
            id: 'regBtn',
            handler: function(){
                validateRegisterationForm();
                if (RegGlobal.validationMsg != "" && RegGlobal.validationMsg != undefined) {
                    Ext.fly('RegGlobal.validationMsg').update('<font color=red><p><B>' + RegGlobal.validationMsg + '</p></B></font>');
                    document.getElementById('RegGlobal.validationMsg').style.display = "block";
                }
                else {
                    document.getElementById('RegGlobal.validationMsg').style.display = "none";
                    registerSubmit();
                    Ext.getCmp('regBtn').disable();
                    Ext.getCmp('regBtn').setText('Registering...');
                }
                
            }
        }]
    });
    
}

function validateRegisterationForm(){
    var NUMERIC_REGEX = /[0-9]/;
    var LOWER_CASE_REGEX = /[a-z]/;
    var UPPER_CASE_REGEX = /[A-Z]/;
    fname = document.getElementById('fname').value;
    var lname = document.getElementById('lname').value;
    var ssn = document.getElementById('ssn').value;
    var confirmPass = document.getElementById('confirmPass').value;
    registerEmail = document.getElementById('regEmail'); //getValue gives the default value and not the one which user entered so used this
    registerPass = document.getElementById('Pass').value;
    var prof = document.getElementById('profession').value;
    var spec = document.getElementById('specialty').value;
    var rec = document.getElementById('recruiter').value;
    if (fname != undefined && fname.trim() === '') {
        Ext.getCmp('fname').markInvalid('First Name can not be blank');
        Ext.getCmp('fname').focus();
        RegGlobal.validationMsg = 'First Name can not be blank';
    }
    else 
        if (lname != undefined && lname.trim() === '') {
            Ext.getCmp('lname').markInvalid('Last Name can not be blank');
             Ext.getCmp('lname').focus();
            RegGlobal.validationMsg = 'Last Name can not be blank';
        }
        else 
            if (registerEmail != undefined && registerEmail.value.trim() === '') {
                Ext.getCmp('regEmail').markInvalid('Email Address can not be blank');
                 Ext.getCmp('regEmail').focus();
                RegGlobal.validationMsg = 'Email Address can not be blank';
            }
            else 
                if (registerPass != undefined && registerPass.trim() === '') {
                    Ext.getCmp('Pass').markInvalid('Password can not be blank');
                    Ext.getCmp('Pass').focus();
                    RegGlobal.validationMsg = 'Password can not be blank';
                }
                else 
                    if (confirmPass != undefined && confirmPass.trim() === '') {
                        Ext.getCmp('confirmPass').markInvalid('Confirm Password can not be blank');
                        Ext.getCmp('confirmPass').focus();
                        RegGlobal.validationMsg = 'Confirm Password can not be blank';
                    }
                    else 
                        if (prof != undefined && prof.trim() === 'Profession') {
                            Ext.getCmp('profession').markInvalid('Profession can not be blank');
                            Ext.getCmp('profession').focus();
                            RegGlobal.validationMsg = 'Profession can not be blank';
                        }
                        
                        else 
                            if (spec != undefined && spec.trim() === 'Speciality') {
                                Ext.getCmp('specialty').markInvalid('Specialty can not be blank');
                                 Ext.getCmp('specialty').focus();
                                RegGlobal.validationMsg = 'Specialty can not be blank';
                            }
                            else 
                                if (rec != undefined && rec.trim() === 'Recruiter') {
                                    Ext.getCmp('recruiter').markInvalid('Recruiter can not be blank');
                                     Ext.getCmp('recruiter').focus();
                                    RegGlobal.validationMsg = 'Recruiter can not be blank';
                                }
                                else 
                                    if (!checkAlphabetic(fname)) {
                                        Ext.getCmp('fname').markInvalid('Please enter alphabets only.');
                                        Ext.getCmp('fname').focus();
                                        RegGlobal.validationMsg = 'Please enter valid Name.';
                                    }
                                    else 
                                        if (!checkAlphabetic(lname)) {
                                            Ext.getCmp('lname').markInvalid('Please enter alphabets only.');
                                            Ext.getCmp('lname').focus();
                                            RegGlobal.validationMsg = 'Please enter valid Name.';
                                        }
                                        
                                        else 
                                            if (!isEmail(registerEmail.value.trim())) {
                                                Ext.getCmp('regEmail').markInvalid('Please enter valid email address.');
                                                Ext.getCmp('regEmail').focus();
                                                RegGlobal.validationMsg = 'Please enter valid email address.';
                                            }
                                            else 
                                                if (registerPass.length < 6) {
                                                     Ext.getCmp('Pass').focus();
                                                    RegGlobal.validationMsg = " Password must contain at least six characters!";
                                                    
                                                }
                                                else 
                                                    if (!NUMERIC_REGEX.test(registerPass)) {
                                                     Ext.getCmp('Pass').focus();
                                                        RegGlobal.validationMsg = " Password must contain at least one number (0-9)!";
                                                    }
                                                    else 
                                                        if (!LOWER_CASE_REGEX.test(registerPass)) {
                                                         Ext.getCmp('Pass').focus();
                                                            RegGlobal.validationMsg = " Password must contain at least one lowercase letter (a-z)!";
                                                        }
                                                        else 
                                                            if (!UPPER_CASE_REGEX.test(registerPass)) {
                                                             Ext.getCmp('Pass').focus();
                                                                RegGlobal.validationMsg = " Password must contain at least one uppercase letter (A-Z)!";
                                                            }
                                                            else 
                                                                if (registerPass.indexOf(" ") > -1) {
                                                                 Ext.getCmp('Pass').focus();
                                                                    RegGlobal.validationMsg = " Password can not contain spaces!";
                                                                }
                                                                else 
                                                                    if (registerPass != confirmPass) {
                                                                    Ext.getCmp('confirmPass').focus();
                                                                        RegGlobal.validationMsg = " Password and Confirm Password do not match!";
                                                                    }
                                                                    else {
                                                                        RegGlobal.validationMsg = "";
                                                                    }
    
    if (RegGlobal.validationMsg != undefined && RegGlobal.validationMsg != "") {
        return RegGlobal.validationMsg;
    }
}

function checkText(field, event){
    var isNN = (navigator.appName.indexOf("Netscape") != -1);
    var asciCode = event.which;
    var KeyTyped = (isNN) ? String.fromCharCode(event.which) : String.fromCharCode(event.keyCode);
    var lCode = KeyTyped.charCodeAt(0);
    if ((lCode >= 97 && lCode <= 122) ||
    (lCode >= 65 && lCode <= 90) ||
    (lCode >= 0 && lCode <= 32)) {
        return true;
    }
    else {
        return false;
    }
}

// Add the additional 'advanced' VTypes
Ext.apply(Ext.form.VTypes, {
    password: function(val, field){
        if (field.initialPassField) {
            var pwd = Ext.getCmp(field.initialPassField);
            return (val == pwd.getValue());
        }
        return true;
    },
    passwordText: 'Passwords do not match'
});

function registerSubmit(){
    regForm = Ext.getCmp('registerForm');
    regForm.getForm().submit({
        url: RegGlobal.temp,
        waitMsg: 'Saving Data...',
        success: registerSuccess,
        failure: registerFailure
    });
}

function registerSuccess(form, action){
	s.events="event4";
	pageTracker._trackPageview('/MedspacePortal/forms/registration.jsp');
    pageTracker._trackEvent('Before Login', 'Registration Success', 'Successful registration');
    window.location.href = '/MedspacePortal/viewport.jsp';
 }

//comman function for server request failure
function registerFailure(form, action){
    //Any custom message can be displyed to client if some error occurs at server side hear.
    var failureMessage = "";
    if (action.failureType == Ext.form.Action.CONNECT_FAILURE) {
        failureMessage = 'Error while connecting to server...';
    }
    if (action.failureType == Ext.form.Action.LOAD_FAILURE) {
        failureMessage = 'Error loading data from server...';
    }
    if (action.failureType == Ext.form.Action.CLIENT_INVALID) {
        failureMessage = "Plese enter all the required fields in the required format.";
    }
    if (action.failureType == Ext.form.Action.SERVER_INVALID) {
        failureMessage = action.result.errors.message;
    }
    
    Ext.fly('RegGlobal.validationMsg').update('<font color=red><p><B>' + failureMessage + '</p></B></font>');
    document.getElementById('RegGlobal.validationMsg').style.display = "block";
    Ext.getCmp('regBtn').enable();
    Ext.getCmp('regBtn').setText('Register');
}
