/**
* default setup form.validate 
*
* form = jQuery object -> form
*
**/

//Function appends the defaultValidation status container (div default status)
$.fn.setDefaultValidationStatus = function(form) {	
	return this.each(function() {
		parentElement = $(this).parent();				
		if(parentElement.find("div.defaultstatus").length == 0){
			$(this).after(
				$(document.createElement("div")).addClass("defaultstatus")
			);
		}
				
		if($(this).val().length > 0 && form != undefined){
			form.validate().element($(this));
		}
	});
};

(function($){
	$.fn.extend({ 
		//plugin name - animatemenu
		setActionbox: function() {
			function PopupBoxactionbox(content) {
				var actionbox = $(document.createElement("div"));			
				
				actionbox.addClass("actionbox")				
				.append (
					$(document.createElement("div"))
						.addClass("actionbox_title")
						.append(
							$(document.createElement("h2"))
								.text("Informatie")
						)
						.append(
							$(document.createElement("a"))
								.text("Sluiten")
								.attr("href", "#")
								.attr("id", "actionbox_close")
								.click(function(event){
									event.preventDefault();
									actionbox.remove();
								})
						)
				)
				.append(
					$(document.createElement("div"))
						.addClass("actionbox_content")
						.append(
							$(document.createElement("div"))
								.addClass("actionbox_content_wrapper")
								.text(content)
						)
				)
				
				return actionbox;
			}
		
    		return this.each(function() {
				var questionmarktitle = this.title;
				$(this).removeAttr("title");
				var actionbox = "";
				
				$(this).click(function (e){
					e.preventDefault();
					trigger = $(this);
					$("body div.actionbox").remove();					
					actionbox = PopupBoxactionbox(questionmarktitle);
					
					if(($("body").width()/2) < e.pageX+5)
					{
						actionbox.addClass("flip");
						actionbox.css({ top: (e.pageY-12), left: ((e.pageX-5)-(actionbox.css("width").replace("px", "")))});
					}
					else
					{
						actionbox.css({ top: (e.pageY-12), left: (e.pageX+5)});
					}
					actionbox.appendTo("body");					
					$("body").bind("click.actionbox", function(event){
						if(($(event.target).attr("id") != trigger.attr("id")) && ($(event.target).attr("class") != actionbox.attr("class")) && ($(event.target).parent().attr("class") != actionbox.attr("class"))  && ($(event.target).parent().parent().attr("class") != actionbox.attr("class"))){
							$("body div.actionbox").remove();						
							$("body").unbind("click.actionbox");
						}
					});
				})
    		});
    	}
	});
})(jQuery);

function validateSetup(form, element, summary) {
	//NOTE: remote validation request has a known bug => to many requests.
	function validatePostalCode (value, element){		
		var postalCode	= value.replace(" ", "");
		var valid 		= false;
		
		if(postalCode.length <= 5)
		{
			valid = false;	
		}else{
			areaCode	= postalCode.substr(0, 4);
			letterCombo	= postalCode.substr(4);
							
			toeter = $.ajax({
	     		url: "/addresslookup.php",
	     		async: false,
	     		cache: false,
	     		type: "POST",	     		
	     		data: ({
					areacode	: areaCode,
					lettercombo	: letterCombo
				}),
				dataType: "json",
				success: function(data, textStatus, XMLHttpRequest){
			    	valid = data.success;			    	
		      	},
		      	error: function(){
		      		valid = false;      		
		      	}		      			      		
			});	
		}
		return valid;	
	}	
	//NOTE: remote validation request has a known bug => to many requests.
	function validateAddress(value, element, POboxCheck){	
		var inputElement	= $(element);
		var valid 			= false;
		var postalCode 		= null;
		var streetNumber 	= null;
		
		if(inputElement.hasClass("postalcode"))
		{			
			postalCode 		= inputElement;
			streetNumber 	= postalCode.parent(".formrow").next().find(".streetnumber");
		}else if(inputElement.hasClass("streetnumber")){			
			streetNumber 	= inputElement;
			postalCode 		= streetNumber.parent(".formrow").prev().find(".postalcode");			
		}				
		
		if(postalCode.val().length > 5 && streetNumber.val().length > 0){
			var areaCode	= postalCode.val().substr(0, 4);
			var letterCombo	= postalCode.val().substr(4);
			
			validateAdressCancel = $.ajax({
	     		url: "/addresslookup.php",
	     		cache: false,
	     		async: false,
	     		type: "POST",	     		
	     		data: ({
					areacode	: areaCode,
					lettercombo	: letterCombo,
					housenumber : streetNumber.val()
				}),
				dataType: "json",
				success: function(data, textStatus, XMLHttpRequest){
			    	valid = data.success;			    	
			    	if(valid === true){
			    		address = streetNumber.parent().find("span.additionalvalidation");
			    	
			    		if(address.length == 0){		    	
					    	streetNumber.next().after(
					    		$(document.createElement("span")).addClass("additionalvalidation").text(data.street + ", " + data.city)
					    	)
			    		}else{
			    			address.text(data.street + ", " + data.city);
			    		}
			    		
			    		//PObox check
			    		if(POboxCheck === true && data.street == "Postbus"){
			    			$("input:radio.shipmentaddress").each(function(){
			    				radiobutton = $(this);
			    			
			    				if(radiobutton.val()=="1"){
			    					radiobutton.attr("checked", "checked");
			    					radiobutton.trigger("change");
			    				}else{
			    					radiobutton.attr("disabled","disabled");
			    				}
			    			});
			    			
			    			$("p.po_info").show();
			    		}else if(POboxCheck === true){
			    			radiobuttons = $("input:radio:disabled.shipmentaddress");
			    			if(radiobuttons.length > 0){
			    				radiobuttons.each(function(){
			    					radiobutton = $(this);
			    					radiobutton.removeAttr("disabled");
			    				});
			    			$("p.po_info").hide();
			    			}
			    		}
			    	}else{
			    		streetNumber.parent().find("span.additionalvalidation").remove();	
			    	}			    	
		      	},
		      	error: function(){
		      		streetNumber.parent().find("span.additionalvalidation").remove();		      	
		      		valid = false;		      		
		      	}		      			      		
			});	
		}
			
		return valid;
	}
	
	function isNonPOBoxAddress(value, element)
	{
		var inputElement	= $(element);
		var valid 			= false;
		var postalCode 		= null;
		var streetNumber 	= null;
		
		if(inputElement.hasClass("postalcode"))
		{			
			postalCode 		= inputElement;
			streetNumber 	= postalCode.parent(".formrow").next().find(".streetnumber");
		}
		else if(inputElement.hasClass("streetnumber"))
		{			
			streetNumber 	= inputElement;
			postalCode 		= streetNumber.parent(".formrow").prev().find(".postalcode");			
		}
		
		if(postalCode.val().length > 5 && streetNumber.val().length > 0)
		{
			var areaCode	= postalCode.val().substr(0, 4);
			var letterCombo	= postalCode.val().substr(4);
		
			validateAdressCancel = $.ajax({
	     		url: "/addresslookup.php",
	     		cache: false,
	     		async: false,
	     		type: "POST",	     		
	     		data: ({
					areacode	: areaCode,
					lettercombo	: letterCombo,
					housenumber : streetNumber.val()
				}),
				dataType: "json",
				success: function(data, textStatus, XMLHttpRequest)
				{	
					streetNumber.parent().find("span.additionalvalidation").remove();		    	 
			    	if(data.street != "Postbus")
			    	{
			    		valid = true;			    			    		
			    	}			    	
		      	},
		      	error: function()
		      	{
		      		streetNumber.parent().find("span.additionalvalidation").remove();		      	
		      		valid = false;		      		
		      	}		      			      		
			});
		}
			
		return valid;
	}
	
	function IsValidBirthDate(element) 
	{ 
	    // just a hack function to take an element, get the drop down fields within it with a particular class name ending with day /month/ year and perform a basic date time test 
	    var dateSelects =  $(element).parent().find("select"); 
	 
	    day 	= $(dateSelects[0]).val();
	    month 	= $(dateSelects[1]).val();
	    year 	= $(dateSelects[2]).val();
	    	    
	    if(day == "" && month == "" && year == ""){
	    	return true;
	    }else if(day == "" || month == "" || year == ""){
	    	return false;
	    }
	    
	    //reduce month by 1 because javascript months begin at zero ( 0 == januari )
	    //Do this after empty check otherwise the value isn't an empty string but minus 1.
	    month = month-1;
	    
	    var birthDate = new Date(); //month minus 1 due to the fact javascript months start from zero == januari
	  	birthDate.setFullYear(year,month,day);	  	
	 
	    if (birthDate.toString() == "NaN" || birthDate.toString() == "Invalid Date" || day != birthDate.getDate() || month != birthDate.getMonth() || year != birthDate.getFullYear())  
	    { 
	        return false; 
	    } else { 
	        return true; 
	    } 
	}
	
	/**
	* validateTelephoneNumber
	* @param {string} telephoneNumber A telephone number.
	* @param {string} defaultCountryCode The country code used when the given telephone number does not have one.
	* @param {Boolean} onlyMobile True or false Defaults to false if undefined.
	*/
	function validateTelephoneNumber(telephoneNumber, defaultCountryCode, onlyMobile)
	{
		// If onlyMobile is undefined, default to false
		if (onlyMobile == undefined)
		{
			onlyMobile = false;
		}
		
		if(telephoneNumber == "")
		{
			return null;
		}
	
		// Clean up the telephone number (remove any characters that don't belong)
		telephoneNumber = telephoneNumber.replace(/\(0\)|\(|\)| |\t|\.|,|-|_|\/|\\/gi, "")
		
		// Check if phonenumber is bigger then only zero's
		if(telephoneNumber <=0 ) {
			return false;
		}
	
		// Check it's an international number for The Netherlands or Belgium
		if (/^(\+|00)(31|32)/.test(telephoneNumber) == true)
		{
			// Remove any's plusses (as they're not covered by the initial replacement)
			telephoneNumber = telephoneNumber.replace(/\+/g, "");
	
			// Remove the prefixed zero's
			telephoneNumber = telephoneNumber.replace(/^00/, "");
		}
		else
		{
			// Remove any's plusses (as they're not covered by the initial replacement)
			telephoneNumber = telephoneNumber.replace(/\+/g, "");
	
			telephoneNumber = telephoneNumber.replace(/^0/, defaultCountryCode);
		}
	
		// Check Dutch numbers (start with 31, 11 characters)
		if (/^31[0-9]{9}$/.test(telephoneNumber) == true && telephoneNumber.length == 11)
		{
			if (onlyMobile == true)
			{
				return /^316[0-9]{8}$/.test(telephoneNumber);
			}
			else
			{
				return true;
			}
		}
	
		// Check Belgian numbers (start with 32, 10 characters)
		if (/^32[0-9]{8}$/.test(telephoneNumber) == true && telephoneNumber.length == 10 && onlyMobile == false)
		{
			return true;
		}
	
		// Check Belgian mobile numbers (start with 32 plus one of the prefices, 11 characters)
		if (/^32(47[0-9])|(48[0-9])|(49[0-9])[0-9]{6}$/.test(telephoneNumber) == true && telephoneNumber.length == 11)
		{
			return true;
		}
	
		return false;
	}
	
	function validateBEVatNumber(vatNumberFieldValue) {
		// Strip "BE", whitespace, dots, comma's, dashes, slashes and backslashes from the value
		var vatNumber = vatNumberFieldValue.replace(/BE| |\t|\.|,|-|\/|\\/gi, "");

		// If the vatNumber is only 9 characters long, add a leading zero
		if (vatNumber.length == 9)
		{
			vatNumber = "0" + vatNumber;
		}

		// VAT number must have 10 characters
		if (vatNumber.length != 10)
		{
			return false;
		}

		// Get the first 7 numbers, with an offset of 1 (skipping leading zero's)
		var modulusValue = Number(vatNumber.substr(1, 7));

		// Get the last 2 numbers
		var verificationValue = Number(vatNumber.substr(8));

		if (97 - (modulusValue % 97) == verificationValue)
		{
			return true;
		}

		return false;
	}

	jQuery.validator.addMethod("emailaddress", function(value, element) { 
		return this.optional(element) || /^[a-z0-9_\.\-\+]+\@([a-z0-9][a-z0-9-]*[a-z0-9]\.)+[a-z]{2,4}$/i.test(value); 
	}, cbVM_Email);
			
	jQuery.validator.addMethod("existingpostalcode", function(value, element) { 		
		return this.optional(element) || validatePostalCode (value, element);
	}, cbVM_Postalcode);
		
	jQuery.validator.addMethod("existingaddress", function(value, element) { 				
		return this.optional(element) || validateAddress (value, element);
	}, cbVM_Address);

	jQuery.validator.addMethod("existingaddressandPOboxcheck", function(value, element) { 				
		return this.optional(element) || validateAddress (value, element, true);
	}, cbVM_AddressAndMailbox);

	jQuery.validator.addMethod("nonpoboxaddress", function(value, element) {		
		return this.optional(element) || isNonPOBoxAddress (value, element);
	}, "Helaas verzenden wij niet naar postbussen.");

	jQuery.validator.addMethod("postalcode_BE", function(value, element) { 
		return this.optional(element) || /^((be?)?(-| )?[0-9]{4})?$/i.test(value); 
	}, cbVM_Postalcode);
	
	jQuery.validator.addMethod("checkbirthdate", function(value, element) { 
	    // function with date logic to return whether this is actually a valid date - you'll need to create this to return a true/false result 
		return this.optional(element) || IsValidBirthDate(element); 	 
	}, cbVM_BirthdayInvalid); 
		
	jQuery.validator.addMethod("phonenumber_NL", function(value, element) { 				
		return this.optional(element) || validateTelephoneNumber(value, "31")
	}, cbVM_PhonenumberInvalid);
	
		
	jQuery.validator.addMethod("phonenumber_BE", function(value, element) { 				
		return this.optional(element) || validateTelephoneNumber(value, "32")
	}, cbVM_PhonenumberInvalid);
	
	jQuery.validator.addMethod("vatnumber_BE", function(value, element) { 				
		return this.optional(element) || validateBEVatNumber(value)
	}, cbVM_VatNumberBEInvalid);
	
	/*jQuery.validator.addMethod("mobilephonenumber_NL", function(value, element) { 				
		return this.optional(element) || validateTelephoneNumber(value, "31", true)
	}, cbVM_MobielTelefoonnummer);*/
	
	if(summary != false){
		errorList = form.find("ul.errors");	
		
		if(errorList.length <= 0){
			$(document.createElement("ul")).addClass("errors").insertBefore(form.find(":button[type=submit]").parent()).hide();			
		}
	}
		
	/**
	* success: Adds an valid class on the label.error, this way the green icon can be displayed
	*
	* errorPlacement: 	The error label is placed within the div.defaultstatus (wich contains de grayed out icon) -
	*					- and will display a red(.error) or green icon(.valid) (and will hide the grayed out icon)
	**/
	
	if(element != false && summary != false)
	{
		jQuery.validator.setDefaults({ 
			success: function(label) {
		 		label.addClass("valid");
			},
			errorPlacement: function(error, element) {
	     		error.appendTo(element.parent().find("div.defaultstatus"));	     		
	   		},
	   		 invalidHandler: function(form, validator) {
	   		 
	   		 	formToValidate 	= $(form.currentTarget);
	   		 	errorList 		= formToValidate.find("ul.errors").empty();	
				
	   		 	if($(validator.errorList).length > 0){
	   		 		var errorMessage = "";	   		 		
	   		 		for (error in validator.errorList){
	   		 			errorName = validator.errorList[error].element.name;
	   		 		   	
	   		 			//Add message if error doesn't belong to a group, if it does, check if message isn't the same as previous errormessage	
	   		 			if(validator.groups[errorName] == undefined || validator.errorList[error].message != errorMessage){	   		 			   		 			
	   		 				errorMessage 	= validator.errorList[error].message;	   		 				
	   		 				errorForId		= validator.errorList[error].element.id;
		   		 			errorList.append( 
		   		 				$(document.createElement("li")).append(
		   		 					$(document.createElement("label")).append(errorMessage).attr("for", errorForId)
	   		 					)
		 					)
	   		 			}
	   		 		}
			    	errorList.show();			   
				}
	   		 }
		});		
		
	}else{
		if(element != false && summary == false){
			jQuery.validator.setDefaults({
				success: function(label) {
			 		label.addClass("valid")
				},
				errorPlacement: function(error, element) {
		     		error.appendTo(element.parent().find("div.defaultstatus"));
		   		}
			});		
		}else if(summary != false && element == false){			
			
			jQuery.validator.setDefaults({			
				onfocusout: 	false,
				onkeyup:		false,
				onclick:		false,				
				errorPlacement: function(error, element) {			
					 errorList = form.find("ul.errors");
		     		 form.find("ul.errors").append(
		    			$(document.createElement("li")).append(error.removeClass("error"))
		    		)
		    		errorList.show();
		   		},
		   		invalidHandler: function(form, validator) {	   		 	
		   		 	formToValidate 	= $(form.currentTarget);
		   		 	errorList 		= formToValidate.find("ul.errors").empty();	
		   		}
			});			
		}
	}
}

function passwordStrength(inputElement){
	var REGEX_PASSWORDSTRENGTH_NUMERIC = /[0-9]/g,
        REGEX_PASSWORDSTRENGTH_UPPERALPHA = /[A-Z]/g,
        REGEX_PASSWORDSTRENGTH_LOWERALPHA = /[a-z]/g,
        REGEX_PASSWORDSTRENGTH_NONALPHANUMERIC = /[^0-9a-zA-Z]/g;
	
	inputElement 		= $(inputElement);
	parentInputElement 	= inputElement.parent();
	
	parentInputElement.append(		
		$(document.createElement("div"))
			.addClass("password_validation")
			.append (
				$(document.createElement("div"))
					.addClass("password_validation_background")
					.append(
						$(document.createElement("div"))
							.addClass("password_validation_block")
							.addClass("password_validation_normal")
					)
			)
			.append(
				$(document.createElement("p"))
					.text("Typ uw wachtwoord")
					.addClass("password_validation_text")
			)
	);
	


	inputElement.keyup(function(event) {
				
	   	var strength 		= 0;		    
	    var indicator 		= parentInputElement.find(".password_validation_block");
	    var indicatortext 	= parentInputElement.find(".password_validation_text");	
	    //var popupboxtext 	= parentInputElement.find(".password_validation_actionbox");
	    var password		= inputElement.val();
	    
	    if (password.match(REGEX_PASSWORDSTRENGTH_NUMERIC) != null) {
	        strength += 10;
	    }
	    if (password.match(REGEX_PASSWORDSTRENGTH_UPPERALPHA) != null) {
	        strength += 26;
	    }
	    if (password.match(REGEX_PASSWORDSTRENGTH_LOWERALPHA) != null) {
	        strength += 26;
	    }
	    if (password.match(REGEX_PASSWORDSTRENGTH_NONALPHANUMERIC) != null) {
	        strength += 32;
	    }
	    
	    indicator.removeClass("password_validation_normal password_validation_short password_validation_weak password_validation_reasonable password_validation_strong password_validation_strongest password_validation_normal");
		
	    strength = strength * password.length;
	    
	    
	    
	    if (password.length < 1) {
	        indicator.addClass("password_validation_normal");
	        indicatortext.empty().text("Typ uw wachtwoord");     
	    }	    
	    else if (password.length < 6) {
	        indicator.addClass("password_validation_short");
	        indicatortext.empty().text("Te kort");
	    }
	    else if (strength < 200) {
	       	indicator.addClass("password_validation_weak");
	        indicatortext.empty().append("Zwak");
	    }
	    else if (strength < 350) {
	        indicator.addClass("password_validation_reasonable");
	        indicatortext.empty().append("Matig");
	    }
	    else if (strength < 500) {
	        indicator.addClass("password_validation_strong");
	        indicatortext.empty().append("Voldoende");
	    }
	    else if (strength > 500) {
	        indicator.addClass("password_validation_strongest");
	        indicatortext.empty().append("Sterk");
	    }
	});
}