	$(document).ready(function(){    
    $("input[name='drvrslicenseorpassport']").bind("click", IdType)
    $("#client_time_at_address").change(function() { TimeAtAddress($(this).val()) });
  	$('#client_dob').datepicker({dateFormat: 'dd/mm/yy', defaultDate: -10220});
    $('#client_date_next_pay').datepicker({dateFormat: 'dd/mm/yy', minDate: '-0y', maxDate: '5y'});
    $("#form-application").validate({ 
     		onfocusout: false,
     		onkeyup: false,
     		onclick: false,
     		focusInvalid: true,
     		focusCleanup: false,
     		
     		errorPlacement: function(error, element) {
	     		error.appendTo(element.next("div"));
	     		//element.parents("tr").filter(".formerror").addClass("showerror");
   			},
   			
   		    highlight: function(element, errorClass) {
   		    	var elem = jQuery(element);
   		    	elem.parents("tr").filter(".formerror").addClass("showerror");
     		},
     		
     	    unhighlight: function(element, errorClass) {
     	    	var elem = jQuery(element);
     	    	elem.parents("tr").filter(".formerror").removeClass("showerror");     			
  			},
   			
   			rules: {
  				client_purpose_of_loan: "required",
     			client_title: "required",
     			client_firstname: "required",
				client_lastname: "required",
				client_dob : {
     				required: true,
       				dateFormat: true,
       				dob: true
     			},
				client_mobile : {
     				required: true,
     				phone: true
     			},
     			client_phone_home : {
     				required: true,
     				phone: true
     			},
     			client_work_phone : {
     				required: true,
     				phone: true
     			},
				client_email : {
       				required: true,
       				email: true
     			},
     			drvrslicenseorpassport: "required",
     			client_drivers_license_number: {
     			    required: function(element) {
              if($("input[name='drvrslicenseorpassport']:checked").val() == 1)
								return true;
							else
								return false;
     			    }
     			},
     			client_drivers_license_states: {
	     			required: function(element) {
     					if($("input[name='drvrslicenseorpassport']:checked").val() == 1)
     						return true;
							else
								return false;
	 			    	}
	 			},
     			client_passport_number: {
     			    required: function(element) {
		 					if($("input[name='drvrslicenseorpassport']:checked").val() == 2)
		 						return true;
							else
								return false;
	 			    	}
	 			},
     			client_passport_country: {
     			    required: function(element) {
		 					if($("input[name='drvrslicenseorpassport']:checked").val() == 2)
		 						return true;
							else
								return false;
	 			    	}
	 			},
				client_password: {
					required: true,
					minlength: 6
				},
				client_number: "required",
				client_street: "required",
				client_street_type: "required",
				client_suburb: "required",
				client_state: "required",
				client_postcode : {
       				required: true,
       				number: true,
       				minlength: 4,
       				maxlength: 4
     			},
     			client_time_at_address: "required",
     			client_prev_address_number: {
     			    required: function(element) {
     				if($('#client_time_at_address').val() == '7_months_to_1_year' || $('#client_time_at_address').val() == '1_year_to_2_years' || $('#client_time_at_address').val() == 'more_than_2_years'){
	     					return false;
	     				}else{
	     					return true;
	     				}
 			    	}
	 			},
     			client_prev_address_street_name: {
     			    required: function(element) {
	 					if($('#client_time_at_address').val() == '7_months_to_1_year' || $('#client_time_at_address').val() == '1_year_to_2_years' || $('#client_time_at_address').val() == 'more_than_2_years'){
	     					return false;
	     				}else{
	     					return true;
	     				}
			    	}
 				},
     			client_prev_address_city: {
     			    required: function(element) {
 						if($('#client_time_at_address').val() == '7_months_to_1_year' || $('#client_time_at_address').val() == '1_year_to_2_years' || $('#client_time_at_address').val() == 'more_than_2_years'){
	     					return false;
	     				}else{
	     					return true;
	     				}
			    	}
 				},
     			client_prev_address_state: {
     			    required: function(element) {
 						if($('#client_time_at_address').val() == '7_months_to_1_year' || $('#client_time_at_address').val() == '1_year_to_2_years' || $('#client_time_at_address').val() == 'more_than_2_years'){
	     					return false;
	     				}else{
	     					return true;
	     				}
			    	}
 				},
     			client_prev_address_postcode: {
     			    required: function(element) {
 						if($('#client_time_at_address').val() == '7_months_to_1_year' || $('#client_time_at_address').val() == '1_year_to_2_years' || $('#client_time_at_address').val() == 'more_than_2_years'){
	     					return false;
	     				}else{
	     					return true;
	     				}
			    	},
     			   	number: true,
      				minlength: 4,
      				maxlength: 4
	 			},
	 			client_employer_address: "required",
	 			client_employer_city: "required",
	 			client_employer_state: "required",
				client_employment_type: "required",
				client_employment_position: "required",
				client_net_pay : {
       				required: true,
       				number: true
     			},
				client_pay_frequency: "required",
				client_time_with_employer_years: "employmentlength",
				client_time_with_employer: "employmentlength",
				client_date_next_pay : {
     				required: true,
       				dateFormat: true
     			},
     			client_payment_type: "required",
				client_amount_requested: "required",
				client_rent_mortage : {
     				required: true,
     				number: true
     			},
				client_rent_repayments_per : "required",
				client_other_monthly_expenses : {
     				required: true,
     				number: true
     			},
				client_employer_name: "required",
				client_bank_bsb: {
       				required: true,
       				number: true,
       				minlength: 6,
       				maxlength: 6
     			},
				client_bank_account_number: "required",
				client_bank_account_type: "required",
				client_bank_account_holder_name: "required",
				terms_conditions: "required"
   			},
   			messages: {
				client_email: {
			       required: "Your email address is required",
			       email: "Your email address must be in the format of name@domain.com"
			    },
				client_postcode: {
					required : "Postcode is required",
					number : "This must be a number",
					minlength : "Postcode must be 4 digits",
					maxlength : "Postcode must be 4 digits"
				},
			    client_net_pay: {
					required : "Net pay is required",
					number : "This must be a number"
				},
				client_date_next_pay: {
					required : "Next pay date is required",
					number : "This must be a valid date (dd/mm/yyyy)"
				},
				client_rent_mortage: {
					required : "Rent/Mortgage is required",
					number : "This must be a number"
				},
				client_password: {
					required : "Password is required",
					minlength : "Password must be a minimum of 6 characters"
				}
			}
   			//,debug : true
   			
   			//,submitHandler: function() { submitValidApp() }
   	 });     
  });
  
jQuery.validator.addMethod(
	"employmentlength",
	function(){
		if($('#client_time_with_employer_years').val() == '' || $('#client_time_with_employer').val() == ''){
      return false;
		}else{
			return true;
		} 
	},
	"Enter the length of employment with your current employer"
);

jQuery.validator.addMethod(
	"dob",
	function(){
		var today = new Date();
		var DOB = new Date($('#client_dob').val());	
		
		if (DOB > today)
		{
		  	return false;
		}else{
			return true;
		}
	},
	"Your date of birth cannot be in the future"
);

jQuery.validator.addMethod(
	"dateFormat",
	function(dtStr){
		dtCh = '/';
		var daysInMonth = DaysArray(12)
		var pos1=dtStr.indexOf(dtCh)
		var pos2=dtStr.indexOf(dtCh,pos1+1)
		var strDay=dtStr.substring(0,pos1)
		var strMonth=dtStr.substring(pos1+1,pos2)
		var strYear=dtStr.substring(pos2+1)
		strYr=strYear
		if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
		if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
		for (var i = 1; i <= 3; i++) {
			if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
		}
		month=parseInt(strMonth)
		day=parseInt(strDay)
		year=parseInt(strYr)
		if (pos1==-1 || pos2==-1){
			return false
		}
		if (strMonth.length<1 || month<1 || month>12){
			return false
		}
		if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
			return false
		}
		if (strYear.length != 4 || year==0){
			return false
		}
		if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
			return false
		}
		return true;
	},
	"Incorrect date format. Date must be in dd/mm/yyyy format"
);

jQuery.validator.addMethod("phone", function(phone_number, element) {
    phone_number = phone_number.replace(/\s+/g, "");

	return this.optional(element) || phone_number.length == 10 &&
		phone_number.match(/^\+?[0-9 ()-.]+[0-9]$/);
}, "Please specify a valid phone number");

function submitValidApp(){
	if (!$("#submitappbutton").is(":disabled"))
       {
           $("#submitappbutton").attr("disabled", "disabled");
           $("#submitappbutton").html("<h4>Processing... Please Wait!</h4>"); 
       }
	   var f = $("#form-application");
	   var serializedForm = f.serialize();	      
	   $.post("pingLoanProviders.php", 
	   	   	serializedForm,	   	   	   	
    		function(data) {			    			 		    	

    			var result = eval(data);
    			var sTag = '?' + Math.random();    			
    			if (result[0] == "ACCEPT")
    			{    				   
 				   	$('#pagebody').attr("style", "background-color:#fff");
 				   	$('#everything').hide(); 			
   					$.blockUI({ message: '<img src="/images/animated-logo.gif' + sTag + '"/>' });
   					setTimeout('document.location.href="' + urldecode(result[1]) + '"', 3000);  					   					    			
    			}    
    			else
    			{    				
    			  	$('#pagebody').attr("style", "background-color:#fff");
    			  	$('#everything').hide(); 
   					$.blockUI({ message: '<img src="/images/animated-logo.gif' + sTag + '"/>' });
   					setTimeout('document.location.href="' + urldecode(result[1]) + '"', 3000); 					
    			}
    		}    
    	);
}

function IdType() {
	
  	$(".driverslicense").hide();
    $(".passport").hide();
    //document.getElementById('driverslicensedetails').style.display = 'none';
    //document.getElementById('passportdetails').style.display = 'none';

    if ($(this).val() == 1) {
        $(".driverslicense").show();
    }
    else {
        $(".passport").show();
    }
}

function TimeAtAddress(val) {
    if (val != "7_months_to_1_year" && val != "1_year_to_2_years" && val != "more_than_2_years") {
        document.getElementById('previousaddressdetails').style.display = 'block';
    }
    else {
        document.getElementById('previousaddressdetails').style.display = 'none';
    }
}

function Submit_onClick()
{	
	//Should probably only do his when validating ha worked.
    getResponseEmail();
}

function DOBValidate(dob)
{	
	var today = new Date();
	var DOB = new Date(dob);	
	if (isNaN(DOB))
	{
		alert("Sorry, but we don't recognize that date string. Please enter a " +
			  "date in the format of DD/MM/YYYY");
		return false;
	}
	if (DOB > today)
	{
	  alert('Your date of birth cannot be in the future.');
	  return false;
	}	 
}


function checkBank(bankVal){
    if(bankVal == "Other"){
      document.getElementById("otherbankname").style.display = "block";
    }else{
      document.getElementById("otherbankname").style.display = "none";
    }
}

function toggleRentMortgage(selOption){
	if(selOption == 0){
		document.getElementById('client_rent_mortage').value = '';
		document.getElementById('client_rent_mortage').disabled = true;
		document.getElementById('client_rent_repayments_per').value = '';
		document.getElementById('client_rent_repayments_per').disabled = true;
	}else{
		document.getElementById('client_rent_mortage').disabled = false;
		document.getElementById('client_rent_repayments_per').disabled = false;
	}
}

function IsNumeric(sText)
{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
}

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function validateRentAmt()
{
	if(document.getElementById('client_rent_mortage').value == '0')
	{
		document.getElementById('client_pay_rent_0').checked = true;
		toggleRentMortgage(0);
	}
}
function registerImpression()
{
	$.post("/apply-now.php", {registerImpression:true}, function(data){});
}

function urldecode (str) {
    var hash_map = {}, ret = str.toString(), unicodeStr='', hexEscStr='';
    
    var replacer = function (search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The hash_map is identical to the one in urlencode.
    hash_map["'"]   = '%27';
    hash_map['(']   = '%28';
    hash_map[')']   = '%29';
    hash_map['*']   = '%2A';
    hash_map['~']   = '%7E';
    hash_map['!']   = '%21';
    hash_map['%20'] = '+';
    hash_map['\u00DC'] = '%DC';
    hash_map['\u00FC'] = '%FC';
    hash_map['\u00C4'] = '%D4';
    hash_map['\u00E4'] = '%E4';
    hash_map['\u00D6'] = '%D6';
    hash_map['\u00F6'] = '%F6';
    hash_map['\u00DF'] = '%DF';
    hash_map['\u20AC'] = '%80';
    hash_map['\u0081'] = '%81';
    hash_map['\u201A'] = '%82';
    hash_map['\u0192'] = '%83';
    hash_map['\u201E'] = '%84';
    hash_map['\u2026'] = '%85';
    hash_map['\u2020'] = '%86';
    hash_map['\u2021'] = '%87';
    hash_map['\u02C6'] = '%88';
    hash_map['\u2030'] = '%89';
    hash_map['\u0160'] = '%8A';
    hash_map['\u2039'] = '%8B';
    hash_map['\u0152'] = '%8C';
    hash_map['\u008D'] = '%8D';
    hash_map['\u017D'] = '%8E';
    hash_map['\u008F'] = '%8F';
    hash_map['\u0090'] = '%90';
    hash_map['\u2018'] = '%91';
    hash_map['\u2019'] = '%92';
    hash_map['\u201C'] = '%93';
    hash_map['\u201D'] = '%94';
    hash_map['\u2022'] = '%95';
    hash_map['\u2013'] = '%96';
    hash_map['\u2014'] = '%97';
    hash_map['\u02DC'] = '%98';
    hash_map['\u2122'] = '%99';
    hash_map['\u0161'] = '%9A';
    hash_map['\u203A'] = '%9B';
    hash_map['\u0153'] = '%9C';
    hash_map['\u009D'] = '%9D';
    hash_map['\u017E'] = '%9E';
    hash_map['\u0178'] = '%9F';
    hash_map['\u00C6'] = '%C3%86';
    hash_map['\u00D8'] = '%C3%98';
    hash_map['\u00C5'] = '%C3%85';
 
    for (unicodeStr in hash_map) {
        hexEscStr = hash_map[unicodeStr]; // Switch order when decoding
        ret = replacer(hexEscStr, unicodeStr, ret); // Custom replace. No regexing
    }
    
    // End with decodeURIComponent, which most resembles PHP's encoding functions
    ret = decodeURIComponent(ret);
 
    return ret;
}
