var systemMessage  = new SystemMessage();

Ext.apply(Ext.form.VTypes, {
     'phoneNumber': function(){
         var re = /^(\+?[-\s0-9]+)$/;
         return function(v){
             return re.test(v);
         }
     }(),
     'phoneNumberText' : 'The field Phone only allows numbers, +, -, and spaces'
});

Ext.onReady(function(){

    Ext.QuickTips.init();
    
    // turn on validation errors beside the field globally
    //Ext.form.Field.prototype.msgTarget = 'side';
    
    /* Personal details */
    var salutation = getSalutationComboBox();
    var promotionKey = null;
    
	var minLength2Validator = function(value){
		if(value.length >= 2){
			return true;
		}else{
			return false;
		}
	};
	
	var minLength6Validator = function(value){
		if(value.length >= 6){
			return true;
		}else{
			return false;
		}
	};
	
	var url = window.location.href;
	if(url.indexOf('key=') != -1){
		promotionKey = url.substring(url.indexOf('key=') + 4);
	}
	
    var promotionCode = new Ext.ux.TextFieldMessage({
		applyTo: 'promotionCode',
        id: 'promotionCode',
        name: 'promotionCode',
        messageText: 'Information Box',
        fieldLabel: 'Promotion Code',
        maxLength: 100,
		x_axis:420,
		y_axis:-10,
		keyUpEvent:getPromotion,
        allowBlank: true
    });
    
    if(promotionKey != null){
    	promotionCode.setValue(promotionKey);
    	promotionCode.disable();
    }
    
    //var informationBox = new Ext.Template('<div id="promotionText"></div>');
    
    var firstName = new Ext.form.TextField({
		applyTo: 'firstName',
        id: 'firstName',
        name: 'firstName',
        fieldLabel: 'First Name',
		msgTarget: 'firstName-error',
		msgDisplay: 'block',
        maxLength: 100,
		//blankText: 'The field First Name is required',
        invalidText: 'The first name must be at least 2 characters long',
		validator: minLength2Validator,
        allowBlank: true,
        anchor: '95%'
    });
	
    var lastName = new Ext.form.TextField({
		applyTo: 'lastName',
        id: 'lastName',
        name: 'lastName',
        fieldLabel: 'Last Name',
		msgTarget: 'lastName-error',
		msgDisplay: 'block',
		blankText: 'The field Last Name is required',
        invalidText: 'The last name must be at least 2 characters long',
		validator: minLength2Validator,
        maxLength: 100,
        allowBlank: false,
        anchor: '95%'
    });
	
    var companyName = new Ext.form.TextField({
		applyTo: 'companyName',
        id: 'companyName',
        name: 'companyName',
        fieldLabel: 'Company',
		msgTarget: 'companyName-error',
		msgDisplay: 'block',
		blankText: 'The field Company Name is required',
        invalidText: 'The company must be at least 2 characters long',
		validator: minLength2Validator,
        maxLength: 100,
        allowBlank: false,
        anchor: '95%'
    });
	
    var position = new Ext.form.TextField({
		applyTo: 'position',
        id: 'position',
        name: 'position',
        fieldLabel: 'Position',
		msgTarget: 'position-error',
		msgDisplay: 'block',
		//blankText: 'The field Position is required',
        invalidText: 'The position must be at least 2 characters long',
		validator: minLength2Validator,
        maxLength: 100,
        allowBlank: true,
        anchor: '95%'
    });
	
    var country = getCountryComboBox();
    // country.width = 310;
    var email = new Ext.form.TextField({
		applyTo: 'email',
        id: 'email',
        name: 'email',
        fieldLabel: 'Email',
		msgTarget: 'email-error',
		msgDisplay: 'block',
        vtype: 'email',
        emptyText: 'name@domain.com',
		blankText: 'The field Email is required',
        allowBlank: false,
        anchor: '95%'
    });
	
    var confirmEmail = new Ext.form.TextField({
		applyTo: 'confirmEmail',
        id: 'confirmEmail',
        name: 'confirmEmail',
        validator: emailValidator,
        fieldLabel: 'Confirm Email',
		msgTarget: 'confirmEmail-error',
		msgDisplay: 'block',
        vtype: 'email',
        emptyText: 'name@domain.com',
		blankText: 'The field Confirm Email is required',
        allowBlank: false,
        anchor: '95%'
    });
	
    var phone = new Ext.form.TextField({
		applyTo: 'phone',
        id: 'phone',
        name: 'phone',
        fieldLabel: 'Phone',
		vtype: 'phoneNumber',
		msgTarget: 'phone-error',
		msgDisplay: 'block',
        invalidText: 'The phone must be at least 6 characters long',
		validator: minLength6Validator,
		blankText: 'The field Phone is required',
        allowBlank: false,
        anchor: '95%'
    });
    
    /* User details */
    var userName = new Ext.form.TextField({
		applyTo: 'userName',
        id: 'userName',
        validator: userNameValidator,
        name: 'userName',
        fieldLabel: 'User Name',
		msgTarget: 'userName-error',
		msgDisplay: 'block',
		blankText: 'The field User name is required',
        allowBlank: false,
        anchor: '95%'
    });
	
    var password = new Ext.ux.PasswordField({
		applyTo: 'password',
        id: 'password',
        name: 'password',
        fieldLabel: 'Password',
		msgTarget: 'password-error',
		msgDisplay: 'block',
        inputType: 'password',
        allowBlank: false,
        anchor: '95%',
        showCapsWarning: true,
        showStrengthMeter: true,
		pwStrengthMeterCls : document.getElementById('password-div'),
		blankText: 'The field Password is required',
        invalidText: 'The password must be at least 6 characters long',
        validator: function(pw){
            if (this.calcStrength(pw) > 25 && pw.length > 5 && pw.length < 15) {
                return true;
            }
            else {
				if(pw.length < 5){
					this.invalidText = 'The password must be at least 6 characters long';
				}else if(pw.length >= 15){
					this.invalidText = 'The password must be shorter than 15 characters long';
				}
                return false;
            }
        },
        pwStrengthTest: function(pw){
            return this.calcStrength(pw);
        }
    });
	
    var checkPassword = new Ext.form.TextField({
		applyTo: 'checkPassword',
        id: 'checkPassword',
        validator: passwordValidator,
        name: 'checkPassword',
        fieldLabel: 'Password Check',
		msgTarget: 'checkPassword-error',
		msgDisplay: 'block',
		blankText: 'The field Password check is required',
        inputType: 'password',
		validator: function(value){
            if (value == password.getValue()) {
                return true;
            }
            else {
                return "Passwords do not match";
            }
        },
        maxLength: 15,
        allowBlank: false,
        anchor: '95%'
    });
    
    var typesDef = Ext.data.Record.create([{
        name: 'name'
    }]);
    
    var hearAbout = getFoundComboBox();
    var companySize = getSizeComboBox();
    var industry = getIndustryComboBox();
    
    var termsConditions = new Ext.form.Checkbox({
        applyTo: 'termsConditionsBox',
        fieldLabel: 'Accept Terms and Conditions',
        name: 'termsConditions'
    });
    
    /*termsConditions.on('check', function(el, checked){
        if (checked) {
            Ext.getCmp('saveButton').enable();
        }
        else {
            Ext.getCmp('saveButton').disable();
        }
    });*/
    
	var mandatoryField = new Array(/*salutation, firstName,*/ lastName, companyName, /*position,*/ country, phone, email, confirmEmail, userName, password, checkPassword, hearAbout/*, companySize, industry*/);

	setupMandatoryFields(mandatoryField);

	systemMessage.setMessageContainer("signupValidation");
	
	var signup = Ext.get('signup');
	
	signup.on('click', function(){
		if (Ext.getCmp('salutation').isValid() &&
        Ext.getCmp('firstName').isValid() &&
        Ext.getCmp('lastName').isValid() &&
        Ext.getCmp('companyName').isValid() &&
        Ext.getCmp('position').isValid() &&
        Ext.getCmp('country').isValid() &&
        Ext.getCmp('phone').isValid() &&
        Ext.getCmp('email').isValid() &&
        Ext.getCmp('confirmEmail').isValid() &&
        Ext.getCmp('userName').isValid() &&
        Ext.getCmp('password').isValid() &&
        Ext.getCmp('checkPassword').isValid() &&
        Ext.getCmp('hearAbout').isValid() &&
        Ext.getCmp('companySize').isValid() &&
        Ext.getCmp('industry').isValid()) {
            if (termsConditions.getValue()) {
                saveDetails();
            } else {
                systemMessage.displayErrorMessage('You must accept the Terms and Conditions before signing up');
            }
        } else {
			systemMessage.displayErrorMessage('The form needs some corrections before it can be submitted.<br/>Please make the corrections marked in red bellow.');	
        }
	});
     
	//add others industries     
	industry.on("select", function(){
		if(industry.getValue() == "industry.other"){
			var popup  = getOthersPopup(function(btn, text){
				industry.setRawValue(text);
			},industry);
		}
	});
    
    
});

var getPromotion = function(value,func){
    var code = {
        arg0: value
    };
    var requestAjax = Ext.Ajax.request({
        url: JSON + '/account/getPromotionCode',
        params: {
            json: Ext.encode(code)
        },
        method: 'POST',
        disableCaching: true,
        success: function(result, request){
            var resultQuery = Ext.util.JSON.decode(result.responseText);
		   	func(resultQuery);
        },
        failure: function(result, request){
            systemMessage.displayErrorMessage('Server communication problem');
        }
    });
    return true;
}


var userNameValid = false;
var userNameValidText = "Username already in use";
var isUserNameValidText = "The only reserved characters allowed are ., -, _ and @";
var userNameValidator = function(value){
    var field = Ext.getCmp('userName');
    var user = {
        arg0: field.getValue()
    }
    
    if (!isUserNameValid(field.getValue())) {
        return isUserNameValidText;
    }
    
    Ext.Ajax.request({
        url: JSON + '/account/isUserExist',
        params: {
            json: Ext.encode(user)
        },
        method: 'POST',
        disableCaching: true,
        success: function(result, request){
            try {
                var resultQuery = Ext.util.JSON.decode(result.responseText);
                if (resultQuery.result == "true") {
                    userNameValid = true;
                }
                else {
                    userNameValid = false;
                }
            } 
            catch (err) {
                userNameValid = false;
            }
        },
        failure: function(result, request){
            userNameValid = false;
        }
    });
    
    if (!userNameValid) {
        return userNameValidText;
    }
    else {
        return userNameValid;
    }
}

var passwordValidator = function(value){
    var password = Ext.getCmp('password').getValue();
    if (value == password) {
        return true;
    }
    else {
        return false;
    }
}

var emailValidator = function(value){
    var email = Ext.getCmp('email').getValue();
    if (value == email) {
        return true;
    }
    else {
        return "Email does not match";
    }
}


//********************************************SAVE REGISTARATION DETAILS**********************************					
function saveDetails(){
    var person = {
        'salutation': Ext.getCmp('salutation').getValue(),
        'firstname': Ext.getCmp('firstName').getValue(),
        'lastname': Ext.getCmp('lastName').getValue(),
        'company': Ext.getCmp('companyName').getValue(),
        'position': Ext.getCmp('position').getValue(),
        'country': Ext.getCmp('country').getValue(),
        'phone': Ext.getCmp('phone').getValue(),
        'email': Ext.getCmp('email').getValue(),
        'username': Ext.getCmp('userName').getValue(),
        'password': Ext.getCmp('password').getValue(),
        'key': Ext.getCmp('promotionCode').getValue()
		
    }
    
    var profile = [{
        'key': Ext.getCmp('hearAbout').getValue(),
		'input': Ext.getCmp('hearAbout').getRawValue()
    }, {
        'key': Ext.getCmp('companySize').getValue(),
		'input': Ext.getCmp('companySize').getRawValue()
    }, {
        'key': Ext.getCmp('industry').getValue(),
		'input': Ext.getCmp('industry').getRawValue()
    }];
    var registerPerson = {
        arg0: person,
        arg1: profile
    }
    
    Ext.Ajax.request({
        url: JSON + '/account/createNewMasterAccount',
        params: {
            json: Ext.encode(registerPerson)
        },
        method: 'POST',
        disableCaching: true,
        success: function(result, request){
            //Ext.getCmp('saveButton').enable();//enable button when respond recieved
            try {
                var res = Ext.util.JSON.decode(result.responseText);
                if (res.result == "true") {
                    Ext.MessageBox.confirm('Success', 'A new account has been created. You will receive an email shortly to activate your account. Would you like to activate it now?', doActivateAccount);
                }
                else {
                    systemMessage.displayErrorMessage('Fail to create an account please try again later.');
                }
            } 
            catch (err) {
                systemMessage.displayErrorMessage('Could not decode');
            }
        },
        failure: function(result, request){
            //Ext.get('signup').enable();//enable button if account was not activated 
            systemMessage.displayErrorMessage('There was an error communicating with the server.<br/>Please try again in a few minutes.');
        }
    });
}

function doActivateAccount(btn){
    if (btn == 'yes') {
        window.location = ADDRESS_SSL + '/activateAccount.html';
    }
    else {
        window.location = ADDRESS;
    }
};
