var initRegiserForm = function() {
    $('#RegistrationForm').ajaxForm({
        beforeSubmit: function(formData, jqForm, options) {
            
            var required_fields = {
                reg_username : 'Username',
                reg_email : 'Email',
                reg_password : '',
                reg_password2 : '',
                reg_firstname : 'Firstname',
                reg_lastname : 'Lastname',
                reg_address1 : 'Address',
                reg_city_town : 'City/Town',
                reg_postcode : 'Postcode/Zipcode'};
                

            var error = false;
            //Get for empty fields.
            for(field in required_fields) {
                if(!$('#' + field).val()) {
                    $('#' + field).css('border', '1px solid #FF0000');
                    if(!error) {
                        error = true;
                    }
                } else {
                    $('#' + field).css('border', '');
                }
            }
            
            if(error) {
                Ext.MessageBox.alert('Error', 'Some of the required fields were empty!');
                return false;
            }
            
            //Check country is selected.
            if($('#reg_country').val() <= 0) {
                Ext.MessageBox.alert('Error', 'Please select a country');
                return false;
            }
            
            //make sure passwords match.
            if($('#reg_password').val() != $('#reg_password2').val()) {
                Ext.MessageBox.alert('Error', 'The passwords you entered do not match!');
                return false;
            }
            
            //Make sure they have agreed to terms and conditions.
            if(!$('#reg_terms_agree').attr('checked')) {
                Ext.MessageBox.alert('Error', 'You must agree to our full terms and conditions');
                return false;
            }

            return true;                 
        },
        success: function(responseObject, statusText) {
            
            if(responseObject['error'] && responseObject['error'].length > 0) {
                if(responseObject['error'] == 'error_username') {
                    //error_username
                    $('#check_availability').val('Try another name').attr('disabled', '');
                    $('#check_availability_image').css('display', 'inline').attr('src', ICON_CROSS);
                    Ext.MessageBox.alert('Error', 'Sorry but someone already has that username!');

                } else if(responseObject['error'] == 'error_fields') {
                   Ext.MessageBox.alert('Error', 'Some of the required fields were empty!');
                   
                    for(i = 0; i < responseObject['missing_fields'].length; i++) {
                        $('#' + responseObject['missing_fields'][i]).css('border', '1px solid #FF0000')
                    }
                } else {
                    Ext.MessageBox.alert('Error', responseObject['error']);
                }
                return;
            }
            
            if(responseObject['success'] && responseObject['success'].length > 0) {
                var sURL = unescape(window.location.pathname);
                window.location.href = sURL + '/thanks/' + $('#reg_username').val() + '/';
            }                    
        },
        dataType:  'json'
    });
}

var initLoginForm = function() {
    $('#loginbox_form').ajaxForm({
        beforeSubmit: function(formData, jqForm, options) {
            
            var form = jqForm[0];
            if(!form.username.value) {
                Ext.MessageBox.alert('Error', 'The username was empty!');
                return false;
            }
            if(!form.password.value) {
                Ext.MessageBox.alert('Error', 'The password was empty!');
                return false;
            }
            return true;                    
        },
        success: function(responseObject, statusText) {
            
            if(responseObject['error']) {
                Ext.MessageBox.alert('Error', responseObject['error']);
            } else if(responseObject['success']) {
                window.location.href = unescape(window.location.pathname);
            }
        },
        dataType:  'json'
    });
}

var showLoginBox = function() {
    $('#loginbox').slideToggle('fast');
    $('#loginbox_username').select();
}

var checkUsername = function() {

    var username = $('#reg_username').val();
    if(username.length > 32) {
        $('#check_availability_image').css('display', 'inline').attr('src', ICON_CROSS);
        return; 
    }
    
    $('#check_availability').val('Checking username...').attr('disabled', 'disabled');
    
    $.ajax({
        type: "POST",
        url: "register",
        data: "ajax=true&cmd=check_availability&username=" + $('#reg_username').val(),
        success: function(check){
            if(check == 'true') { //Username was taken :(
                $('#check_availability').val('Try another name').attr('disabled', '');
                $('#check_availability_image').css('display', 'inline').attr('src', ICON_CROSS);
            } else {
                $('#username_button').css('display', 'none');
                $('#check_availability_image').css('display', 'inline').attr('src', ICON_TICK);
            }
        }
    });
}

var validateUsername = function() {
    
    var username = $('#reg_username').val();
    if(username.length > 32) {
        $('#check_availability_image').css('display', 'inline').attr('src', ICON_CROSS);  
    } else {
        $('#check_availability_image').css('display', 'none');  
    }
    
    $('#username_button').css('display', 'block');
    $('#check_availability').val('Check Availability').attr('disabled', '');
}

var emailChecker = function() {
    var email = $('#reg_email').val();
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

	if (filter.test(email)) {
        $('#reg_email_image').css('display', 'inline').attr('src', ICON_TICK);    
    } else {
        $('#reg_email_image').css('display', 'inline').attr('src', ICON_CROSS);
    }
}

var passwordChecker = function() {
	var passwd = $("#reg_password").val();
	
	var strength = testPassword(passwd);
	
	$('#strength_bar').attr('class', 'pass_' + strength);
	$('#strength_bar_text').html('(' + strength.replace(/_/, ' ') + ' password)');
	
	//Do the passwords match?
	if($('#reg_password').val() == $('#reg_password2').val()) {
        $('#reg_password_image').css('display', 'inline').attr('src', ICON_TICK);
    } else {
        $('#reg_password_image').css('display', 'inline').attr('src', ICON_CROSS);   
    }	
}


testPassword = function(passwd)
{
		var intScore   = 0
		var strVerdict = "weak"
		var strLog     = ""
		
		// PASSWORD LENGTH
		if (passwd.length<5)                         // length 4 or less
		{
			intScore = (intScore+3)
			strLog   = strLog + "3 points for length (" + passwd.length + ")\n"
		}
		else if (passwd.length>4 && passwd.length<8) // length between 5 and 7
		{
			intScore = (intScore+6)
			strLog   = strLog + "6 points for length (" + passwd.length + ")\n"
		}
		else if (passwd.length>7 && passwd.length<16)// length between 8 and 15
		{
			intScore = (intScore+12)
			strLog   = strLog + "12 points for length (" + passwd.length + ")\n"
		}
		else if (passwd.length>15)                    // length 16 or more
		{
			intScore = (intScore+18)
			strLog   = strLog + "18 point for length (" + passwd.length + ")\n"
		}
		
		
		// LETTERS (Not exactly implemented as dictacted above because of my limited understanding of Regex)
		if (passwd.match(/[a-z]/))                              // [verified] at least one lower case letter
		{
			intScore = (intScore+1)
			strLog   = strLog + "1 point for at least one lower case char\n"
		}
		
		if (passwd.match(/[A-Z]/))                              // [verified] at least one upper case letter
		{
			intScore = (intScore+5)
			strLog   = strLog + "5 points for at least one upper case char\n"
		}
		
		// NUMBERS
		if (passwd.match(/\d+/))                                 // [verified] at least one number
		{
			intScore = (intScore+5)
			strLog   = strLog + "5 points for at least one number\n"
		}
		
		if (passwd.match(/(.*[0-9].*[0-9].*[0-9])/))             // [verified] at least three numbers
		{
			intScore = (intScore+5)
			strLog   = strLog + "5 points for at least three numbers\n"
		}
		
		
		// SPECIAL CHAR
		if (passwd.match(/.[!,@,#,$,%,^,&,*,?,_,~]/))            // [verified] at least one special character
		{
			intScore = (intScore+5)
			strLog   = strLog + "5 points for at least one special char\n"
		}
		
									 // [verified] at least two special characters
		if (passwd.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/))
		{
			intScore = (intScore+5)
			strLog   = strLog + "5 points for at least two special chars\n"
		}
	
		
		// COMBOS
		if (passwd.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))        // [verified] both upper and lower case
		{
			intScore = (intScore+2)
			strLog   = strLog + "2 combo points for upper and lower letters\n"
		}

		if (passwd.match(/([a-zA-Z])/) && passwd.match(/([0-9])/)) // [verified] both letters and numbers
		{
			intScore = (intScore+2)
			strLog   = strLog + "2 combo points for letters and numbers\n"
		}
 
									// [verified] letters, numbers, and special characters
		if (passwd.match(/([a-zA-Z0-9].*[!,@,#,$,%,^,&,*,?,_,~])|([!,@,#,$,%,^,&,*,?,_,~].*[a-zA-Z0-9])/))
		{
			intScore = (intScore+2)
			strLog   = strLog + "2 combo points for letters, numbers and special chars\n"
		}
	
	
		if(intScore < 10)
		{
		   strVerdict = "very_weak"
		}
		else if (intScore > 10 && intScore < 25)
		{
		   strVerdict = "weak"
		}
		else if (intScore > 24 && intScore < 35)
		{
		   strVerdict = "medium"
		}
		else if (intScore > 34 && intScore < 45)
		{
		   strVerdict = "strong"
		}
		else
		{
		   strVerdict = "very_strong"
		}
		
		return strVerdict;
}

function postCodeLookup() {
  pc = removeSpaces($('#CustomerPostCode')[0].value);
  $('#lookup_addresses').load('/customers/get_addresses/' + pc);
}

function pickAddress(no, name, road, town, locality) {
  $('#CustomerHomeNameNo')[0].value = no + name;
  $('#CustomerStreet')[0].value = road;
  $('#CustomerTown')[0].value = town;
  $('#CustomerLocality')[0].value = locality;
  $('#lookup_addresses').fadeOut('slow');
}

function removeSpaces(string) {
  var tstring = "";
  string = '' + string;
  splitstring = string.split(" ");
  for(i = 0; i < splitstring.length; i++)
    tstring += splitstring[i];
  
  return tstring;
}
