/**
* Form initialisation & validation
*/
// Require jQuery

/**
*
*** Extend validator plugin with custom data types, w00t! ***
*
*/

/**
* Checks Dutch bank accounts (and giro)
*/
$.validator.addMethod("eleventest", function(value, element) {		
		var n = value.replace(/[^\d\.]/g,'');
		var c = n.replace(/\D/g,'').split(''), a = c.length, e = 0;
		if (a == 9) 
			for (var i = 0; i < 9; i++) 
				e += (9 - i) * c[i];
	    var res = (a < 6 || a == 8 || e % 11 != 0 ||  a > 9);
	    
		return this.optional(element) || !res;
	},  "Account number verification failed");

/**
* Validate BIC/SWIFT codes
*/
$.validator.addMethod("bic", function(value, element) {
		if (value.length < 1)
			return true;
		var regSWIFT = /^([a-zA-Z]){4}([a-zA-Z]){2}([0-9a-zA-Z]){2}([0-9a-zA-Z]{3})?$/;
		return regSWIFT.test(value);
	}, "Not a valid Bank Identification Code");


$.validator.addMethod("alphanumeric", function(value, element) {
	return this.optional(element) || /^\w+$/i.test(value);
}, "Letters, numbers, spaces or underscores only please");  

$.validator.addMethod("zip", function(value, element) {
	return this.optional(element) || /^[0-9A-Z\s]+$/i.test(value);
}, "Letters, numbers and spaces only please");  

$.validator.addMethod("nonumber", function(value, element) {
	return this.optional(element) || ! /^\d+$/i.test(value);
}, "A mix of letters and numbers is required");  


$.validator.addMethod("lettersonly", function(value, element) {
	return this.optional(element) || /^[a-z]+$/i.test(value);
}, "Letters only please"); 

$.validator.addMethod("phone", function(value, element) {
	return this.optional(element) || /^[0-9\-\(\)\s]+$/i.test(value);
}, "Letters only please"); 

$.validator.addMethod("nowhitespace", function(value, element) {
	return this.optional(element) || /^\S+$/i.test(value);
}, "No white space please"); 

/**
* Validate IBAN
*/
$.validator.addMethod( "iban", function(value, element) {
		if (value.length < 1)
			return true;
		
		if (value.length < 5) 
			return false; // too short
		s = value.substring(4) + value.substring(0, 4); 
		for (i = 0, r = 0; i < s.length; i++ ) { 
			c = s.charCodeAt(i); 
			if (48 <= c && c <= 57) { 
					if (i == s.length-4 || i == s.length-3) // Positions 1 and 2 cannot contain digits
						 return false;
					k = c - 48;
			} else if (65 <= c && c <= 90) { 
					if (i == s.length-2 || i == s.length-1) // Positions 3 and 4 cannot contain letters
					return false;
					k = c - 55; 
			}  else { 
				// Only digits and uppercase letters are allowed
				return false;
			}
			if (k > 9) 
				r = (100 * r + k) % 97; 
			else 
				r = (10 * r + k) % 97; 
		} 
		return (r == 1); // The check digits are invalid
	}, "Not a valid International Bank Account Number (IBAN)");


$(document).ready(function() {
	if(document.location.href.match(/confirm/))
		$(".lng img").hide();
	
	// Init fields
	$('.foreign').toggle($("#foreign:checked").length);
	$("#foreign").change(function(event) {
		$(".foreign").toggle($(this).attr('checked'));
	});
	
	$("input[name=country_select]").autocomplete('validate/country/', {
			max: 10,
			mustMatch: true,
			minChars: 3,
			extraParams: {
				l: $("input[name=l]").val()
			}
			
		}).result(function(event, item) {
			if (item && item.length)
				$("input[name=country]").val(item[1]);
		});

	$("input[name=model]").autocomplete('validate/nickname/', {
			max: 10,
			minChars: 3,
			mustMatch: true,
			extraParams: {
				id_code: $("input[name=id_code]").val()
			}
		});

	$('#step1').validate({
		debug: false,		
		errorElement: "b",
		errorContainer: $("#warning"),		
		rules: {
			email: {
				email: true,
				required: true
			},
			name: {
				required: true
			},
			geboortedag: {
				required: true,
				range: function(element) {
					var end = 32 - new Date(
										$("select[name=geboortejaar]").val(), 
										$("select[name=geboortemaand]").val()-1,
										32
									).getDate();
					return [1,end];
				}
			},
			geboortemaand: {
				required: true
			},
			geboortejaar: {
				required: true
			}
		}
	});
	
	$("#step_terms").validate({
		debug: false,
		errorElement: "b",
		errorContainer: "#warning",
		wrapper: "span",		
		rules: {
	 		'terms_confirmed': "required"
	 	}
	});
	
	// Populate country field
	// Set up formchecks
	$('#step2').validate({
		debug: false,
		errorElement: "b",
		errorContainer: "#warning",
		wrapper: "span",
		rules: {
			'terms_confirmed': "required",		
	 		'bank': {
	 			required: function(element) {
					return ($("#foreign:checked").length < 1);

	 			},
	 			minlength: 4,
	 			eleventest: {
	 				// Only check for domestic accounts when foreign bank is clear
	 				depends: function(element) {
	 					return $("#foreign:checked").length < 1;
	 				}
	 			}
	 		},
	 		'bic': {
	 			minlength: 8,
	 			// Only required if marked as foreign bank
 				required: function(element) {
 					return $("#foreign:checked").length > 0;
 				},
 				// Validate as BIC
	 			bic: true
	 		},
	 		'iban': {
				required: function(element) {
					// Only required if bank # is empty
					if ($("#foreign:checked").length)
						return $("input[name=bank]").val() ? false : true;
					return false;
				},
				// validate as IBAN code
	 			iban: true
	 		},
			'model': {
				required: true,
				minlength: 4,
				maxlength: 10,
				nonumber: true,
				nowhitespace: true
	 		},
	 		'phone': {
	 			required: true,
	 			minlength: 10,
	 			phone: true
	 		},
	 		'name': 'required',
	 		'address': 'required',
	 		'zip': {
	 			required: true,
	 			zip: true
	 		},
	 		'country_select': 'required',
	 		'city': 'required',
	 		'password': 'required',
	 		'description': 'required',
	 		'gender': 'required',
	 		'couple': 'required'	
		} // End rules
	});
});

