/* 
-----------------------------------------

INITIALISATIE JQUERY JAVASCRIPT
jQuery 1.4.4
Nederlandse versie

------------------------------------------
*/

$(document).ready(function() {	
				
				
		/* DEFAULT VORM VALUES
		----------------------------------------
		Gebruikt de jQuery Form Example Plugin
		*/
		if(jQuery().example) {
			$("form#inschrijvennieuwsbrief input#emailadres").example("E-mailadres");
			$("form#tellfriend input#emailadres").example("E-mailadres");
			$("form#voorraademail input#reminderemail").example("Uw e-mailadres");
			$("form#tellfriend input#uwnaam").example("Uw naam");
			$("form#tellfriend input#uwemail").example("Uw e-mailadres");
			$("form#tellfriend input#emailadresfriend").example("E-mailadres vriend");
			$("form#wachtwoordvergeten input#email").example("voorbeeld@domein.nl");
			$("form#inloggen input#email").example("voorbeeld@domein.nl");
			$("form#accountgegevens input#Fax").example("Optioneel");
			$("form#accountgegevens input#Toevoeging").example("Optioneel");
			$("form#registreer input#Fax").example("Optioneel");
			$("form#registreer input#Toevoeging").example("Optioneel");
		};
		
		
		
		/* NAVIGATIE ACTIEF
		----------------------------------------
		Maakt navigatie button actief bij laden
		*/
		$("#navbar_highlight ul li a").bind("click", function(){
			$("#navbar_highlight ul li").removeClass("current");
			$(this).parents("li").addClass("current");
		});
		

		
		/* LEGENDA
		----------------------------------------*/
		//Verberg de gele legenda div op de productoverzichten
		$("div#legenda").hide();
		
		//Toggle legenda
		$("p#tabelinfo a").click(function(e){
			e.preventDefault();
			$("div#legenda").slideToggle(300);
		});
		
		//Tooltip, gebruikt de jQuery Qtip plugin
		if(jQuery().qtip) {
			$("p.status_icon:not(div#legenda p.status_icon)").qtip({
				content: '<div id=\"legenda\"><p class=\"big\">Legenda</p><p class=\"status_icon small voorraad\">Direct leverbaar uit eigen voorraad. Op werkdagen voor 17.00 uur besteld, morgen in huis.</p><p class=\"status_icon small eenatweedag\">Op voorraad in extern magazijn. De levertijd van dit product is 1 tot 3 werkdagen.</p><p class=\"status_icon small tweeavijfdag\">De levertijd van dit product is 2 tot 9 werkdagen.</p><p class=\"status_icon small tijdelijknietleverbaar\">Dit product is <em>tijdelijk</em> niet leverbaar.</p><p class=\"status_icon small nietmeerleverbaar\">Dit product is niet meer leverbaar.</p><p class=\"status_icon small belvoorlevertijd\">De levertijd van dit product is onbekend. Neem contact met ons op voor informatie.</p></div>',
				style: {name: 'cream',  tip: 'topMiddle'},
				position: {corner: {target: 'bottomMiddle', tooltip: 'topMiddle'}}
			});
		};
		
		
		
		/* LIGHTBOX IMAGE VIEWER
		----------------------------------------
		Gebruikt de jQuery Fancybox Plugin
		*/
		if(jQuery().fancybox) {
			$("a.lightbox").fancybox({
				'titleShow'		: false,
				'speedIn' 		: 100,
				'speedOut'		: 100
			});
		};
		
		
		
		/* AUTOSUGGEST ZOEKRESULTATEN
		----------------------------------------
		Gebruikt de jQuery UI Autocomplete Plugin
		*/
		
		//Monkeypatchen van jQuery autocomplete plugin
		$.extend( $.ui.autocomplete, {	
			filter: function(array, term) {
				
				//Split term in individuele woorden
				var zoekwoorden = $.trim(term).split(" ");
				var aantalZoekwoorden = zoekwoorden.length;
	
				//Vind alle producten uit de array die voldoen aan het filter
				return $.grep( array, function(item) {
					
					var matches = $.grep(zoekwoorden, function(zoekwoord) {
						var matcher = new RegExp($.ui.autocomplete.escapeRegex(zoekwoord), "i" );
						var overeenkomst = matcher.test(item.label);
						if (overeenkomst) {return overeenkomst;}
					});
					
					//Retourneer indien er kwalitatiefe matches zijn
					return matches.length > 0 && matches.length >= aantalZoekwoorden;

				});      
			}
		});
		$.widget( "custom.autocomplete", $.ui.autocomplete, {
			_renderMenu: function(ul, items) {
				var self = this, currentCategory = "";
				var aantalProducten = items.length;
				
				if (aantalProducten == 1) {
					ul.append("<li class=\"ui-autocomplete-title\">Zoekt u misschien:</li>");
				} else {//Meer dan 1 product gevonden
					ul.append("<li class=\"ui-autocomplete-title\">Zoekt u een van deze " + aantalProducten + " producten?</li>");
				};
				
				$.each(items, function(index, item) {
					if (item.categorie != currentCategory) {
						ul.append( "<li class=\"ui-autocomplete-category attention\">" + item.categorie + "<span class=\"opencat\">" + item.categorie + "<input type=\"hidden\" name=\"url\" value=\"" + item.categorie_url + "\"/></span></li>" );
						currentCategory = item.categorie;
					}
					self._renderItem(ul, item);
				});
			}
		});
				
		//Autosuggest alleen als zoekveld daadwerkelijk bestaat
		if ($("form#zoeken input#zoekstring").length > 0 && ($(window).width() >= 767)) {
			
			//JSON ophalen met assortiment (lokale url: scripts/zoeksuggestie.php, online url: /site/d_nieuw/scripts/zoeksuggestie.php)
			$.getJSON('/site/d_nieuw/scripts/zoeksuggestie.php', function(producten) {
				
				//AutoComplete plugin init
				$("form#zoeken input#zoekstring").autocomplete({
					source: producten,
					select: function(event, ui) {
						$(this).val(ui.item.value).parents("form").submit();
					},
					minLength: 3
				})
				.data("autocomplete")._renderItem = function(ul, item) {
					return $( "<li></li>" )
						.data( "item.autocomplete", item )
						.append( "<span class=\"img-container\"><img src=\" "+ item.thumb + "\" width=\"40\" /></span><a>" + item.label + "</a>" )
						.appendTo(ul);
				};
				
			});
			
			
			//Klikken op open cat in zoeksuggesties
			$(".ui-autocomplete-category .opencat").live('click', function() {
				if (! $(this).find("input").length == 0) {
					var url = $(this).find("input").val();
				}
				if (! url.length == 0) {
					$("form#zoeken input#zoekstring").autocomplete("close").val("");
					window.location = $.trim(url);
				};
			});
			
			
			//Bij laden pagina focus, indien er geen # in url staat en gebruiker nog niet op website is geweest
			$(window).bind('load',function(){
				if (!(/#/.test(window.location)) && !zatAlOpWebsite() && ($(window).width() >= 767)) {
					$("form#zoeken input#zoekstring").focus();
				};
			});
			
			
			function zatAlOpWebsite () {
				if (document.referrer != '') {
					var hostname = toString(window.location.hostname);
					var referrer = toString(document.referrer);
					if (referrer.toLowerCase().indexOf('google'.toLowerCase()) >= 0) {
						return true;
					}
					if (referrer.toLowerCase().indexOf(hostname.toLowerCase()) >= 0) {
						return true;
					}
					return false;
				} 
				return false;	
			};
			
		};
		
		
		//Bij focus class focus toevoegen
		$("form#zoeken input#zoekstring").focus(function() {
			$(this).addClass("focus");
		});
		
					  
		//Bij blur class focus verwijderen
		$("form#zoeken input#zoekstring").blur(function() {  
			$(this).removeClass("focus");    
		});
		
		/* GEO POPUP
		----------------------------------------
		Toon de Geo Popup
		*/
		/*var toonGeoPopup = $("input[name$='showGeoPopup']").val();

		if (toonGeoPopup == "true") {
			
			//Toon popup
			showGeoPopup();
			
			//Sluit bij druk op sluit icoon of klikken naast box
			$("div#transparancy, div#geo-popup a#close, div#geo-popup a#sluit").click(function(e) {
				e.preventDefault();
				hideGeoPopup();
			});
		};
		
		
		function showGeoPopup () {
			$("#skeleton_geopopup").stop(true,true).show().find("#geo-popup").fadeIn();
		};
		
		function hideGeoPopup () {
			$("#skeleton_geopopup").hide();
		};*/
		
		
		
		/* SHOP TABS
		----------------------------------------*/
			
		//Geef links met huidige domein de class current-domain mee
		$("div#skeleton_shoptabs li:not(#wegwijs) a").filter(function() {
    		return this.hostname == location.hostname;
		}).attr('class', 'current-domain');
		
		
		$("#default-shops #wegwijs a").mouseover(function() {
			$(this).parent('#wegwijs').addClass('active');
			$('#mask').fadeIn(200);
			
			$('#more-shops').fadeIn(100, function() {
				positioneerMoreShops();
			});
		});
		
		
		function positioneerMoreShops() {
			var offset = $('#default-shops #wegwijs').offset();
			var position = offset.top + $('#default-shops #wegwijs a').outerHeight(false) + 2;
			$('#more-shops').css("top", position);
		};
		
		
		$("#mask").mouseover(function() {
			$('#more-shops').hide();
			$('#mask').hide();
			$('#default-shops #wegwijs').removeClass('active');
		});
		
		
		
		/* SPECIAAL BESTELD
		----------------------------------------
		Melding dat een product speciaal wordt besteld
		*/
		
		$("#speciaal-besteld, div#prodsidebar form#inmandje a.button").mouseover(function() {
			$("#speciaal-besteld").find("#extra").show();
		}).mouseout(function(){
			$("#speciaal-besteld").find("#extra").hide();
		});
		
		
		/* POSTCODECHECK
		----------------------------------------
		Initialiseer postcodechecks met postcodecheck plugin
		*/
		
		//Alleen uitvoeren als plugin postcodeCheck is geladen
		if(jQuery().postcodeCheck) {
			
			//Registreer
			$("form#registreer").postcodeCheck();	
			
			//Account gegevens
			$("form#accountgegevens").postcodeCheck();
		};
		

		
		/* BESTELGESCHIEDENIS: TOON EN VERBERG
		----------------------------------------
		Toon of verberg details bij bestelgeschiedenis
		*/
		
		//Verberg details
		$("div.bestelbox div.bestelling-details").hide();
		
		
		//Toggle details
		$("div.bestelbox a.details-bestelling-link").toggle(function(){
			$(this).text("Verberg details").removeClass("downlink").addClass("uplink");
			$(this).parents("div.bestelbox").find("div.bestelling-details").show();
			}, function () {
			$(this).text("Toon details").removeClass("uplink").addClass("downlink");
			$(this).parents("div.bestelbox").find("div.bestelling-details").hide();
		});
		
		
		
		/* ACCOUNT GEGEVENS TYPE KLANT EN BTW NUMMER
		----------------------------------------
		Type klant en btw nummer in account, inc. validatie
		*/

		//Bij laden pagina
		toonOfVerbergBedrijfsgegevensAccount();
			
			
		//Bij keuze type klant
		$("form#accountgegevens input.horizontal-radio[name$='type-klant']").bind(($.browser.msie ? "click" : "change"), function () {
			$("form#accountgegevens input#Bedrijfsnaam").val("").removeClass('LV_invalid_field').removeClass('LV_valid_field');
			$("form#accountgegevens input#BTWnummer").val("").removeClass('LV_invalid_field').removeClass('LV_valid_field');
			toonOfVerbergBedrijfsgegevensAccount();
		});
		
		
		function toonOfVerbergBedrijfsgegevensAccount () {
			if ($("form#accountgegevens input.horizontal-radio[name$='type-klant']:checked").val() == "bedrijf"){//Klant is bedrijf
				if ( $("form#accountgegevens #veld-bedrijfsnaam").is(':hidden') ){
					$("form#accountgegevens #veld-bedrijfsnaam").show();
					startValidatieBtwnummerAccount();
					toonOfVerbergLabelBtwNummerAccount();
					plaatsBTWUitlegAccount($("form#accountgegevens select[name$='Land']").val());
					startValidatieBedrijfsnaamAccount();
				};
			} 
			else {  //Klant is particulier 
				if ( $("form#accountgegevens #veld-bedrijfsnaam").is(':visible') ){
					verwijderValidatieBtwnummerAccount();
					verwijderValidatieBedrijfsnaamAccount();
					$("form#accountgegevens #veld-bedrijfsnaam").hide();
				};
			};
		};
		
		
		function startValidatieBtwnummerAccount () {
			//Start validatie als veld zichtbaar is
			if ( $("form#accountgegevens #veld-bedrijfsnaam").is(':visible') ){
				var btwnummer = new LiveValidation('BTWnummer', { validMessage: ' ', wait: 8000});
				btwnummer.enable();
				btwnummer.add(Validate.Custom, { against: function(value, args){ return (checkVATNumber(value)) }, failureMessage: ' ' } );
				
				//Btwnummer is verplicht voor niet-Nederlanders
				if ($("form#accountgegevens select[name$='Land']").val() != "Nederland") {
					btwnummer.add(Validate.Presence, {failureMessage: ' '});
				};
			};
		};
		
		
		function verwijderValidatieBtwnummerAccount () {
			//Verwijder validatie als veld zichtbaar is
			if ( $("form#accountgegevens #veld-bedrijfsnaam").is(':visible') ){
				var btwnummer = new LiveValidation('BTWnummer', { validMessage: ' ', wait: 8000});
				btwnummer.disable();
			};
		};
		
		
		function toonOfVerbergLabelBtwNummerAccount () {
			if ($("form#accountgegevens select[name$='Land']").val() == "Nederland") {
				$("form#accountgegevens #veld-btwnummer label[for$='BTWnummer']").html("BTW nummer");
			} else {
				$("form#accountgegevens #veld-btwnummer label[for$='BTWnummer']").html("<img src=\"/site/d_nieuw/img/bestelproces/verplicht-veld.gif\" alt=\"indicator voor verplicht veld\" /> BTW nummer");
			};
		};
		
		
		function startValidatieBedrijfsnaamAccount () {
			//Start validatie als veld zichtbaar is
			if ( $("form#accountgegevens #veld-bedrijfsnaam").is(':visible') ){
				var bedrijfsnaam = new LiveValidation('Bedrijfsnaam', { validMessage: ' ', wait: 8000});
				bedrijfsnaam.enable();
				bedrijfsnaam.add(Validate.Presence, {failureMessage: ' '});
				bedrijfsnaam.add(Validate.Length, {minimum: 2, maximum:50, tooShortMessage: ' ', tooLongMessage: ' '});
			};
		};
		
		
		function verwijderValidatieBedrijfsnaamAccount () {
			//Verwijder validatie als veld zichtbaar is
			if ( $("form#accountgegevens #veld-bedrijfsnaam").is(':visible') ){
				var bedrijfsnaam = new LiveValidation('Bedrijfsnaam', { validMessage: ' ', wait: 8000});
				bedrijfsnaam.disable();
			};
		};
		
		
		//Verberg bedrijfsgegevens indien land wordt veranderd
		$("form#accountgegevens select[name$='Land']").bind(($.browser.msie ? "click" : "change"), function () {
			verwijderValidatieBtwnummerAccount();
			verwijderValidatieBedrijfsnaamAccount();
			$("form#accountgegevens input#Bedrijfsnaam").val("").removeClass('LV_invalid_field').removeClass('LV_valid_field');
			$("form#accountgegevens input#BTWnummer").val("").removeClass('LV_invalid_field').removeClass('LV_valid_field');
			$("form#accountgegevens #veld-bedrijfsnaam").hide("fast");	
			$("form#accountgegevens input.horizontal-radio[name$='type-klant']").removeAttr("checked");
			$("form#accountgegevens #type-klant-particulier").attr("checked", "checked");
		});
		
		
		//Hoofdletters
		$(["form#accountgegevens #veld-btwnummer input#BTWnummer"]).each(function(i, veld){
			$(veld).keyup(function(event){
				$(veld).val(String($(this).val()).toUpperCase());
			});
			$(veld).change(function(event){
				$(veld).val(String($(this).val()).toUpperCase());
			});
		});
		
		
		//Verwijder whitespace, dashes (-) en punten
		$(["form#accountgegevens #veld-btwnummer input#BTWnummer"]).each(function(i, veld){
			var txt = $(veld);
			var func = function() {
				txt.val(txt.val().replace(/\s/g, '').replace('-', '').replace('.', ''));
			}
			txt.keyup(func).blur(func);
		});
		
		
		function plaatsBTWUitlegAccount (landVoorBtw) {
			btwUitleg = $("form#accountgegevens #veld-btwnummer span#uitleg-btwnummer");
			
			if (landVoorBtw == "Nederland") {
				btwUitleg.html("Bijvoorbeeld NL819538814B01");
			}
			else if (landVoorBtw == "Belgie") {
				btwUitleg.html("Bijvoorbeeld BE753011097");
			}
			else if (landVoorBtw == "Luxemburg") {
				btwUitleg.html("Bijvoorbeeld LU10089356");
			}
			else if (landVoorBtw == "Duitsland") {
				btwUitleg.html("Bijvoorbeeld DE193252304");
			}
			else if (landVoorBtw == "Frankrijk") {
				btwUitleg.html("Bijvoorbeeld FR78432297109");
			}
			else if (landVoorBtw == "Italie") {
				btwUitleg.html("");
			}
			else if (landVoorBtw == "Spanje") {
				btwUitleg.html("");
			}
			else if (landVoorBtw == "Portugal") {
				btwUitleg.html("");
			};
		};
		
		
		//Toon foutmelding onderin formulier
		$("form#accountgegevens input[name$='submit']").click(function() {
			
			//Dirty code: krijg geen callback van Livevalidation, dus toon foutmelding
			//2 sec. na klikken op button. Zodra form gesubmit wordt (dus geldig is) wordt de
			//foutmelding gewist.
			setTimeout(function() { $("form#accountgegevens #form-foutmelding").show();}, 2000);

			$("form#accountgegevens input[name$='submit']").submit(function() {
				$("form#accountgegevens #form-foutmelding").hide();
			});  			
			
		});
		
		
		/* REGISTREER PAGINA BEDRIJFSGEGEVENS
		----------------------------------------
		Bedrijfsgegevens op registreer pagina
		*/

		//Bij laden pagina
		toonOfVerbergBedrijfsgegevensRegistreer();
			
			
		//Bij keuze type klant
		$("form#registreer input.horizontal-radio[name$='type-klant']").bind(($.browser.msie ? "click" : "change"), function () {
			$("form#registreer input#Bedrijfsnaam").val("").removeClass('LV_invalid_field').removeClass('LV_valid_field');
			$("form#registreer input#BTWnummer").val("").removeClass('LV_invalid_field').removeClass('LV_valid_field');
			toonOfVerbergBedrijfsgegevensRegistreer();
		});
		
		
		function toonOfVerbergBedrijfsgegevensRegistreer () {
			if ($("form#registreer input.horizontal-radio[name$='type-klant']:checked").val() == "bedrijf"){//Klant is bedrijf
				if ( $("form#registreer #veld-bedrijfsnaam").is(':hidden') ){
					$("form#registreer #veld-bedrijfsnaam").show();
					startValidatieBtwnummerRegistreer();
					toonOfVerbergLabelBtwNummerRegistreer();
					plaatsBTWUitlegRegistreer($("form#registreer select[name$='Land']").val());
					startValidatieBedrijfsnaamRegistreer();
				};
			} 
			else {  //Klant is particulier 
				if ( $("form#registreer #veld-bedrijfsnaam").is(':visible') ){
					verwijderValidatieBtwnummerRegistreer();
					verwijderValidatieBedrijfsnaamRegistreer();
					$("form#registreer #veld-bedrijfsnaam").hide();
				};
			};
		};
		
		
		function startValidatieBtwnummerRegistreer () {
			//Start validatie als veld zichtbaar is
			if ( $("form#registreer #veld-bedrijfsnaam").is(':visible') ){
				var btwnummer = new LiveValidation('BTWnummer', { validMessage: ' ', wait: 8000});
				btwnummer.enable();
				btwnummer.add(Validate.Custom, { against: function(value, args){ return (checkVATNumber(value)) }, failureMessage: ' ' } );
				
				//Btwnummer is verplicht voor niet-Nederlanders
				if ($("form#registreer select[name$='Land']").val() != "Nederland") {
					btwnummer.add(Validate.Presence, {failureMessage: ' '});
				};
			};
		};
		
		
		function verwijderValidatieBtwnummerRegistreer () {
			//Verwijder validatie als veld zichtbaar is
			if ( $("form#registreer #veld-bedrijfsnaam").is(':visible') ){
				var btwnummer = new LiveValidation('BTWnummer', { validMessage: ' ', wait: 8000});
				btwnummer.disable();
			};
		};
		
		
		function toonOfVerbergLabelBtwNummerRegistreer () {
			if ($("form#registreer select[name$='Land']").val() == "Nederland") {
				$("form#registreer #veld-btwnummer label[for$='BTWnummer']").html("BTW nummer");
			} else {
				$("form#registreer #veld-btwnummer label[for$='BTWnummer']").html("<img src=\"/site/d_nieuw/img/bestelproces/verplicht-veld.gif\" alt=\"indicator voor verplicht veld\" /> BTW nummer");
			};
		};
		
		
		function startValidatieBedrijfsnaamRegistreer () {
			//Start validatie als veld zichtbaar is
			if ( $("form#registreer #veld-bedrijfsnaam").is(':visible') ){
				var bedrijfsnaam = new LiveValidation('Bedrijfsnaam', { validMessage: ' ', wait: 8000});
				bedrijfsnaam.enable();
				bedrijfsnaam.add(Validate.Presence, {failureMessage: ' '});
				bedrijfsnaam.add(Validate.Length, {minimum: 2, maximum:50, tooShortMessage: ' ', tooLongMessage: ' '});
			};
		};
		
		
		function verwijderValidatieBedrijfsnaamRegistreer () {
			//Verwijder validatie als veld zichtbaar is
			if ( $("form#registreer #veld-bedrijfsnaam").is(':visible') ){
				var bedrijfsnaam = new LiveValidation('Bedrijfsnaam', { validMessage: ' ', wait: 8000});
				bedrijfsnaam.disable();
			};
		};
		
		
		//Verberg bedrijfsgegevens indien land wordt veranderd
		$("form#registreer select[name$='Land']").bind(($.browser.msie ? "click" : "change"), function () {
			verwijderValidatieBtwnummerRegistreer();
			verwijderValidatieBedrijfsnaamRegistreer();
			$("form#registreer input#Bedrijfsnaam").val("").removeClass('LV_invalid_field').removeClass('LV_valid_field');
			$("form#registreer input#BTWnummer").val("").removeClass('LV_invalid_field').removeClass('LV_valid_field');
			$("form#registreer #veld-bedrijfsnaam").hide("fast");	
			$("form#registreer input.horizontal-radio[name$='type-klant']").removeAttr("checked");
			$("form#registreer #type-klant-particulier").attr("checked", "checked");
		});
		
		
		//Hoofdletters
		$(["form#registreer #veld-btwnummer input#BTWnummer"]).each(function(i, veld){
			$(veld).keyup(function(event){
				$(veld).val(String($(this).val()).toUpperCase());
			});
			$(veld).change(function(event){
				$(veld).val(String($(this).val()).toUpperCase());
			});
		});
		
		
		//Verwijder whitespace, dashes (-) en punten
		$(["form#registreer #veld-btwnummer input#BTWnummer"]).each(function(i, veld){
			var txt = $(veld);
			var func = function() {
				txt.val(txt.val().replace(/\s/g, '').replace('-', '').replace('.', ''));
			}
			txt.keyup(func).blur(func);
		});
		
		
		function plaatsBTWUitlegRegistreer (landVoorBtw) {
			btwUitleg = $("form#registreer #veld-btwnummer span#uitleg-btwnummer");
			
			if (landVoorBtw == "Nederland") {
				btwUitleg.html("Bijvoorbeeld NL819538814B01");
			}
			else if (landVoorBtw == "Belgie") {
				btwUitleg.html("Bijvoorbeeld BE753011097");
			}
			else if (landVoorBtw == "Luxemburg") {
				btwUitleg.html("Bijvoorbeeld LU10089356");
			}
			else if (landVoorBtw == "Duitsland") {
				btwUitleg.html("Bijvoorbeeld DE193252304");
			}
			else if (landVoorBtw == "Frankrijk") {
				btwUitleg.html("Bijvoorbeeld FR78432297109");
			}
			else if (landVoorBtw == "Italie") {
				btwUitleg.html("");
			}
			else if (landVoorBtw == "Spanje") {
				btwUitleg.html("");
			}
			else if (landVoorBtw == "Portugal") {
				btwUitleg.html("");
			};
		};
		
		
		//Toon foutmelding onderin formulier
		$("form#registreer input[name$='submit']").click(function() {
			
			//Dirty code: krijg geen callback van Livevalidation, dus toon foutmelding
			//2 sec. na klikken op button. Zodra form gesubmit wordt (dus geldig is) wordt de
			//foutmelding gewist.
			setTimeout(function() { $("form#registreer #form-foutmelding").show();}, 2000);

			$("form#registreer input[name$='submit']").submit(function() {
				$("form#registreer #form-foutmelding").hide();
			});  			
			
		});
		
		
		/* VALIDATIE GEMEENSCHAPPELIJKE VELDEN
		----------------------------------------
		Terugkerende velden bestellen, factuuradres, registreer
		*/	
		if (($("form#accountgegevens").length > 0) || ($("form#registreer").length > 0) ){

			var naam = new LiveValidation('Naam', { validMessage: ' ', wait: 8000});
			naam.add(Validate.Presence, {failureMessage: ' '});
			naam.add(Validate.Length, {minimum: 2, maximum:50, tooShortMessage: ' ', tooLongMessage: ' '});
			naam.add(Validate.Exclusion, { within: [ '@' , '@', '!', '$', '%', '*', '{', '}', '?', '~' ], partialMatch: true, failureMessage: ' ' } );
			
			var postcode = new LiveValidation('Postcode', { validMessage: ' ', wait: 8000});
			postcode.add(Validate.Presence, {failureMessage: ' '});
			postcode.add(Validate.Length, {minimum: 4, maximum:10, tooShortMessage: ' ', tooLongMessage: ' '});
			
			var nummer = new LiveValidation('Huisnummer', { validMessage: ' ', wait: 8000});
			nummer.add(Validate.Presence, {failureMessage: ' '});
			nummer.add(Validate.Length, {minimum: 1, maximum:15, tooShortMessage: ' ', tooLongMessage: ' '});
			
			var straatnaam = new LiveValidation('Straatnaam', { validMessage: ' ', wait: 8000});
			straatnaam.add(Validate.Presence, {failureMessage: ' '});
			straatnaam.add(Validate.Length, {minimum: 1, maximum:100, tooShortMessage: ' ', tooLongMessage: ' '});
			
			var plaats = new LiveValidation('Plaats', { validMessage: ' ', wait: 8000});
			plaats.add(Validate.Presence, {failureMessage: ' '});
			plaats.add(Validate.Length, {minimum: 1, maximum:100, tooShortMessage: ' ', tooLongMessage: ' '});
			
			var tel = new LiveValidation('Telefoon', { validMessage: ' ', wait: 8000});
			tel.add(Validate.Presence, {failureMessage: ' '});
			tel.add(Validate.Length, {minimum: 8, maximum:30, tooShortMessage: ' ', tooLongMessage: ' '});
			
			var email = new LiveValidation('Email', { validMessage: ' ', wait: 8000});
			email.add(Validate.Email, {failureMessage: ' '} );
			email.add(Validate.Presence, {failureMessage: ' '});
			email.add(Validate.Length, {minimum: 2, maximum:50, tooShortMessage: ' ', tooLongMessage: ' '});
			
			var email2 = new LiveValidation('Email2', { validMessage: ' ', wait: 8000});
			email2.add(Validate.Presence, {failureMessage: ' '});
			email2.add(Validate.Confirmation, {match: 'Email', failureMessage: ' ' } );
		
		};

		
		
		/* VAT PLUGIN
		----------------------------------------
		Functie dat boolean retourneert of btwnummer geldig is
		*/
		
		function checkVATNumber (toCheck) {
		  var vatexp = new Array ();
		  var defCCode = "NL";
		
		  vatexp.push (/^(AT)U(\d{8})$/);                           //** Austria
		  vatexp.push (/^(BE)(\d{9,10})$/);                         //** Belgium 
		  vatexp.push (/^(BG)(\d{9,10})$/);                         // Bulgaria 
		  vatexp.push (/^(CY)(\d{8}[A-Z])$/);                       //** Cyprus 
		  vatexp.push (/^(CZ)(\d{8,10})(\d{3})?$/);                 //** Czech Republic
		  vatexp.push (/^(DE)(\d{9})$/);                            //** Germany 
		  vatexp.push (/^(DK)((\d{8}))$/);                          //** Denmark 
		  vatexp.push (/^(EE)(\d{9})$/);                            //** Estonia 
		  vatexp.push (/^(EL)(\d{8,9})$/);                          //** Greece 
		  vatexp.push (/^(ES)([A-Z]\d{8})$/);                       //** Spain (1)
		  vatexp.push (/^(ES)(\d{8}[A-Z])$/);                       // Spain (2)
		  vatexp.push (/^(ES)([A-Z]\d{7}[A-Z])$/);                  //** Spain (3)
		  vatexp.push (/^(EU)(\d{9})$/);                            //** EU-type 
		  vatexp.push (/^(FI)(\d{8})$/);                            //** Finland 
		  vatexp.push (/^(FR)(\d{11})$/);                           //** France (1)
		  vatexp.push (/^(FR)[(A-H)|(J-N)|(P-Z)]\d{10}$/);          // France (2)
		  vatexp.push (/^(FR)\d[(A-H)|(J-N)|(P-Z)]\d{9}$/);         // France (3)
		  vatexp.push (/^(FR)[(A-H)|(J-N)|(P-Z)]{2}\d{9}$/);        // France (4)
		  vatexp.push (/^(GB)?(\d{9})$/);                           //** UK (standard)
		  vatexp.push (/^(GB)?(\d{10})$/);                          //** UK (Commercial)
		  vatexp.push (/^(GB)?(\d{12})$/);                          //UK (IOM standard)
		  vatexp.push (/^(GB)?(\d{13})$/);                          //UK (IOM commercial)
		  vatexp.push (/^(GB)?(GD\d{3})$/);                         //** UK (Government)
		  vatexp.push (/^(GB)?(HA\d{3})$/);                         //** UK (Health authority)
		  vatexp.push (/^(GR)(\d{8,9})$/);                          //** Greece 
		  vatexp.push (/^(HU)(\d{8})$/);                            //** Hungary 
		  vatexp.push (/^(IE)(\d{7}[A-W])$/);                       //** Ireland (1)
		  vatexp.push (/^(IE)([7-9][A-Z\*\+)]\d{5}[A-W])$/);        //** Ireland (2)
		  vatexp.push (/^(IT)(\d{11})$/);                           //** Italy 
		  vatexp.push (/^(LV)(\d{11})$/);                           //** Latvia 
		  vatexp.push (/^(LT)(\d{9}|\d{12})$/);                     //** Lithunia
		  vatexp.push (/^(LU)(\d{8})$/);                            //** Luxembourg 
		  vatexp.push (/^(MT)(\d{8})$/);                            //** Malta
		  vatexp.push (/^(NL)(\d{9})B\d{2}$/);                      //** Netherlands
		  vatexp.push (/^(PL)(\d{10})$/);                           //** Poland
		  vatexp.push (/^(PT)(\d{9})$/);                            //** Portugal
		  vatexp.push (/^(RO)(\d{2,10})$/);                         //** Romania
		  vatexp.push (/^(SI)(\d{8})$/);                            //** Slovenia
		  vatexp.push (/^(SK)(\d{9}|\d{10})$/);                     // Slovakia Republic
		  vatexp.push (/^(SE)(\d{10}\d[1-4])$/);                    //** Sweden
		
		  // Load up the string to check
		  var VATNumber = toCheck.toUpperCase();
		  
		  // Remove spaces from the VAT number to help validation
		  var chars = [" ","-",",","."];
		  for ( var i=0; i<chars.length; i++) {
			while (VATNumber.indexOf(chars[i])!= -1) {
			  VATNumber = VATNumber.slice (0,VATNumber.indexOf(chars[i])) + VATNumber.slice (VATNumber.indexOf(chars[i])+1);
			}
		  }
		
		  // Assume we're not going to find a valid VAT number
		  var valid = false;                         
		  
		  // Check the string against the types of VAT numbers
		  for (i=0; i<vatexp.length; i++) {
			if (vatexp[i].test(VATNumber)) {
			  
			  var cCode = RegExp.$1;                             // Isolate country code
			  var cNumber = RegExp.$2;                           // Isolate the number
			  if (cCode.length == 0) cCode = defCCode;           // Set up default country code
			  
			  // Now look at the check digits for those countries we know about.
			  switch (cCode) {     
				case "AT":
				  valid = ATVATCheckDigit (cNumber);
				  break;        
				case "BE":
				  valid = BEVATCheckDigit (cNumber);
				  break;          
				case "BG":
				  // The SIMA validation rules are incorrect for Bulgarian numbers.
				  valid = true;
				  break;             
				case "CY":
				  valid = CYVATCheckDigit (cNumber);
				  break;          
				case "CZ":
				  valid = CZVATCheckDigit (cNumber);
				  break;      
				case "DE":
				  valid = DEVATCheckDigit (cNumber);
				  break;       
				case "DK":
				  valid = DKVATCheckDigit (cNumber);
				  break;                 
				case "EE":
				  valid = EEVATCheckDigit (cNumber);
				  break;             
				case "EL":
				  valid = ELVATCheckDigit (cNumber);
				  break;       
				case "ES":
				  valid = ESVATCheckDigit (cNumber);
				  break;       
				case "EU":
				  valid = EUVATCheckDigit (cNumber);
				  break;       
				case "FI":
				  valid = FIVATCheckDigit (cNumber);
				  break;        
				case "FR":
				  valid = FRVATCheckDigit (cNumber);
				  break;         
				case "GB":
				  valid = UKVATCheckDigit (cNumber);
				  break;                     
				case "GR":
				  valid = ELVATCheckDigit (cNumber);
				  break;             
				case "HU":
				  valid = HUVATCheckDigit (cNumber);
				  break;         
				case "IE":
				  valid = IEVATCheckDigit (cNumber);
				  break;              
				case "IT":
				  valid = ITVATCheckDigit (cNumber);
				  break;            
				case "LT":
				  valid = LTVATCheckDigit (cNumber);
				  break;            
				case "LU":
				  valid = LUVATCheckDigit (cNumber);
				  break;            
				case "LV":
				  valid = LVVATCheckDigit (cNumber);
				  break;             
				case "MT":
				  valid = MTVATCheckDigit (cNumber);
				  break;           
				case "NL":
				  valid = NLVATCheckDigit (cNumber);
				  break;            
				case "PL":      
				  valid = PLVATCheckDigit (cNumber);
				  break;         
				case "PT":
				  valid = PTVATCheckDigit (cNumber);
				  break;           
				case "RO":
				  valid = ROVATCheckDigit (cNumber);
				  break;       
				case "SE":
				  valid = SEVATCheckDigit (cNumber);
				  break;        
				case "SI":
				  valid = SIVATCheckDigit (cNumber);
				  break;     
				default:
				  valid = true;
			  }
					
			  // Load new VAT number back into the form element
			  if (valid) valid = valid;
			  
			  // We have found that the number is valid - break from loop
			  break;
			}
		  }
		  
		  // Return with either an error or the reformatted VAT number
		  return valid;
		}
		
		function ATVATCheckDigit (vatnumber) {
		
		  // Checks the check digits of an Austrian VAT number.
		  
		  var total = 0;
		  var multipliers = [1,2,1,2,1,2,1];
		  var temp = 0;
		  
		  // Extract the next digit and multiply by the appropriate multiplier.  
		  for (var i = 0; i < 7; i++) {
			temp = Number(vatnumber.charAt(i)) * multipliers[i];
			if (temp > 9)
			  total = total + Math.floor(temp/10) + temp%10
			else
			  total = total + temp;
		  }  
		  
		  // Establish check digit.
		  total = 10 - (total+4) % 10; 
		  if (total == 10) total = 0;
		  
		  // Compare it with the last character of the VAT number. If it is the same, 
		  // then it's a valid check digit.
		  if (total == vatnumber.slice (7,8)) 
			return true
		  else 
			return false;
		}
		
		function BEVATCheckDigit (vatnumber) {
		
		  // Checks the check digits of a Belgium VAT number.
		  
		  // First character of 10 digit numbers should be 0
		  if (vatnumber.length == 10 && vatnumber.slice(0,1) != "0") return false;
		  
		  // Nine digit numbers have a 0 inserted at the front.
		  if (vatnumber.length == 9) vatnumber = "0" + vatnumber;
		  
		  // Modulus 97 check on last nine digits
		  if (97 - vatnumber.slice (0,8) % 97 == vatnumber.slice (8,10)) 
			return true
		  else 
			return false;
		}
		
		function CYVATCheckDigit (vatnumber) {
		
		  // Checks the check digits of a Cypriot VAT number.
		  
		  // Extract the next digit and multiply by the counter.
		  var total = 0;
		  for (var i = 0; i < 8; i++) {
			var temp = Number(vatnumber.charAt(i));
			if (i % 2 == 0) {
			  switch (temp) {
				case 0: temp = 1; break;
				case 1: temp = 0; break;
				case 2: temp = 5; break;
				case 3: temp = 7; break;
				case 4: temp = 9; break;
				default: temp = temp*2 + 3;
			  }
			}
			total = total + temp;
		  }
		  
		  // Establish check digit using modulus 26, and translate to char. equivalent.
		  total = total % 26;
		  total = String.fromCharCode(total+65);
		  
		  // Check to see if the check digit given is correct
		  if (total == vatnumber.substr (8,1)) 
			return true 
		  else 
			return false;
		}
		
		function CZVATCheckDigit (vatnumber) {
		
		  // Checks the check digits of a Czech Republic VAT number.
		  
		  var total = 0;
		  var multipliers = [8,7,6,5,4,3,2];
		  
		  // Only do check digit validation for standard VAT numbers
		  if (vatnumber.length != 8) return true;
		  
		  // Extract the next digit and multiply by the counter.
		  for (var i = 0; i < 7; i++) total = total + Number(vatnumber.charAt(i)) * multipliers[i];
		  
		  // Establish check digit.
		  total = 11 - total % 11;
		  if (total == 10) total = 0; 
		  if (total == 11) total = 1; 
		  
		  // Compare it with the last character of the VAT number. If it is the same, 
		  // then it's a valid check digit.
		  if (total == vatnumber.slice (7,8)) 
			return true
		  else 
			return false;
		}
		
		function DEVATCheckDigit (vatnumber) {
		
		  // Checks the check digits of a German VAT number.
		  
		  var product = 10;
		  var sum = 0;     
		  var checkdigit = 0;                      
		  for (var i = 0; i < 8; i++) {
			
			// Extract the next digit and implement perculiar algorithm!.
			sum = (Number(vatnumber.charAt(i)) + product) % 10;
			if (sum == 0) {sum = 10};
			product = (2 * sum) % 11;
		  }
		  
		  // Establish check digit.  
		  if (11 - product == 10) {checkdigit = 0} else {checkdigit = 11 - product};
		  
		  // Compare it with the last two characters of the VAT number. If the same, 
		  // then it is a valid check digit.
		  if (checkdigit == vatnumber.slice (8,9))
			return true
		  else 
			return false;
		}
		
		function DKVATCheckDigit (vatnumber) {
		
		  // Checks the check digits of a Danish VAT number.
		  
		  var total = 0;
		  var multipliers = [2,7,6,5,4,3,2,1];
		  
		  // Extract the next digit and multiply by the counter.
		  for (var i = 0; i < 8; i++) total = total + Number(vatnumber.charAt(i)) * multipliers[i];
		  
		  // Establish check digit.
		  total = total % 11;
		  
		  // The remainder should be 0 for it to be valid..
		  if (total == 0) 
			return true
		  else 
			return false;
		}
		
		function EEVATCheckDigit (vatnumber) {
		
		  // Checks the check digits of an Estonian VAT number.
		  
		  var total = 0;
		  var multipliers = [3,7,1,3,7,1,3,7];
		  
		  // Extract the next digit and multiply by the counter.
		  for (var i = 0; i < 8; i++) total = total + Number(vatnumber.charAt(i)) * multipliers[i];
		  
		  // Establish check digits using modulus 10.
		  total = 10 - total % 10;
		  if (total == 10) total = 0;
		  
		  // Compare it with the last character of the VAT number. If it is the same, 
		  // then it's a valid check digit.
		  if (total == vatnumber.slice (8,9))
			return true
		  else 
			return false;
		}
		
		function ELVATCheckDigit (vatnumber) {
		
		  // Checks the check digits of a Greek VAT number.
		  
		  var total = 0;
		  var multipliers = [256,128,64,32,16,8,4,2];
		  
		  //eight character numbers should be prefixed with an 0.
		  if (vatnumber.length == 8) {vatnumber = "0" + vatnumber};
		  
		  // Extract the next digit and multiply by the counter.
		  for (var i = 0; i < 8; i++) total = total + Number(vatnumber.charAt(i)) * multipliers[i];
		  
		  // Establish check digit.
		  total = total % 11;
		  if (total > 9) {total = 0;};  
		  
		  // Compare it with the last character of the VAT number. If it is the same, 
		  // then it's a valid check digit.
		  if (total == vatnumber.slice (8,9)) 
			return true
		  else 
			return false;
		}
		
		function ESVATCheckDigit (vatnumber) {
		
		  // Checks the check digits of a Spanish VAT number.
		  
		  var total = 0; 
		  var temp = 0;
		  var multipliers = [2,1,2,1,2,1,2];
		  var esexp = new Array ();
		  esexp.push (/^[A-H]\d{8}$/);
		  esexp.push (/^[N|P|Q|S]\d{7}[A-Z]$/);
		  esexp.push (/^[0-9]{8}[A-Z]$/);
		  var i = 0;
		  
		  // With profit companies
		  if (esexp[0].test(vatnumber)) {
		  
			// Extract the next digit and multiply by the counter.
			for (i = 0; i < 7; i++) {
			  temp = Number(vatnumber.charAt(i+1)) * multipliers[i];
			  if (temp > 9) 
				total = total + Math.floor(temp/10) + temp%10 
			  else 
				total = total + temp;
			}   
			
			// Now calculate the check digit itself. 
			total = 10 - total % 10;
			if (total == 10) {total = 0;}
			
			// Compare it with the last character of the VAT number. If it is the same, 
			// then it's a valid check digit.
			if (total == vatnumber.slice (8,9)) 
			  return true
			else 
			  return false;
		  }
		  
		  // Non-profit companies
		  else if (esexp[1].test(vatnumber)) {
		  
			// Extract the next digit and multiply by the counter.
			for (i = 0; i < 7; i++) {
			  temp = Number(vatnumber.charAt(i+1)) * multipliers[i];
			  if (temp > 9) 
				total = total + Math.floor(temp/10) + temp%10 
			  else 
				total = total + temp;
			}    
			
			// Now calculate the check digit itself.
			total = 10 - total % 10;
			total = String.fromCharCode(total+64);
			
			// Compare it with the last character of the VAT number. If it is the same, 
			// then it's a valid check digit.
			if (total == vatnumber.slice (8,9)) 
			  return true
			else 
			  return false;
		  }
			
		  // Personal number (NIF)
		  else if (esexp[2].test(vatnumber)) {
			return vatnumber.charAt(8) == 'TRWAGMYFPDXBNJZSQVHLCKE'.charAt(Number(vatnumber.substring(0, 8)) % 23);
		  }
			
		  else return true;
		}
		
		function EUVATCheckDigit (vatnumber) {
		
		  // We know litle about EU numbers apart from the fact that the first 3 digits 
		  // represent the country, and that there are nine digits in total.
		  return true;
		}
		
		function FIVATCheckDigit (vatnumber) {
		
		  // Checks the check digits of a Finnish VAT number.
		  
		  var total = 0; 
		  var multipliers = [7,9,10,5,8,4,2];
		  
		  // Extract the next digit and multiply by the counter.
		  for (var i = 0; i < 7; i++) total = total + Number(vatnumber.charAt(i)) * multipliers[i];
		  
		  // Establish check digit.
		  total = 11 - total % 11;
		  if (total > 9) {total = 0;};  
		  
		  // Compare it with the last character of the VAT number. If it is the same, 
		  // then it's a valid check digit.
		  if (total == vatnumber.slice (7,8)) 
			return true
		  else 
			return false;
		}
		
		function FRVATCheckDigit (vatnumber) {
		
		  // Checks the check digits of a French VAT number.
		  
		  if (!(/^\d{11}$/).test(vatnumber)) return true;
		  
		  // Extract the last nine digits as an integer.
		  var total = vatnumber.substring(2); 
		  
		  // Establish check digit.
		  total = (total*100+12) % 97;
		  
		  // Compare it with the last character of the VAT number. If it is the same, 
		  // then it's a valid check digit.
		  if (total == vatnumber.slice (0,2)) 
			return true
		  else 
			return false;
		}
		
		function HUVATCheckDigit (vatnumber) {
		
		  // Checks the check digits of a Hungarian VAT number.
		  
		  var total = 0;
		  var multipliers = [9,7,3,1,9,7,3];
		  
		  // Extract the next digit and multiply by the counter.
		  for (var i = 0; i < 7; i++) total = total + Number(vatnumber.charAt(i)) * multipliers[i];
		  
		  // Establish check digit.
		  total = 10 - total % 10; 
		  if (total == 10) total = 0;
		  
		  // Compare it with the last character of the VAT number. If it is the same, 
		  // then it's a valid check digit.
		  if (total == vatnumber.slice (7,8)) 
			return true
		  else 
			return false;
		}
		
		function IEVATCheckDigit (vatnumber) {
		
		  // Checks the check digits of an Irish VAT number.
		  
		  var total = 0; 
		  var multipliers = [8,7,6,5,4,3,2];
		  
		  // If the code is in the old format, we need to convert it to the new.
		  if (/^\d[A-Z\*\+]/.test(vatnumber)) {
			vatnumber = "0" + vatnumber.substring(2,7) + vatnumber.substring(0,1) + vatnumber.substring(7,8);
		  }
			
		  // Extract the next digit and multiply by the counter.
		  for (var i = 0; i < 7; i++) total = total + Number(vatnumber.charAt(i)) * multipliers[i];
		  
		  // Establish check digit using modulus 23, and translate to char. equivalent.
		  total = total % 23;
		  if (total == 0)
			total = "W"
		  else
			total = String.fromCharCode(total+64);
		  
		  // Compare it with the last character of the VAT number. If it is the same, 
		  // then it's a valid check digit.
		  if (total == vatnumber.slice (7,8)) 
			return true
		  else 
			return false;
		}
		
		function ITVATCheckDigit (vatnumber) {
		
		  // Checks the check digits of an Italian VAT number.
		  
		  var total = 0;
		  var multipliers = [1,2,1,2,1,2,1,2,1,2];
		  var temp;
			
		  // The last three digits are the issuing office, and cannot exceed more 201
		  temp=Number(vatnumber.slice(0,7));
		  if (temp==0) return false;
		  temp=Number(vatnumber.slice(7,10));
		  if ((temp<1) || (temp>201)) return false;
		  
		  // Extract the next digit and multiply by the appropriate  
		  for (var i = 0; i < 10; i++) {
			temp = Number(vatnumber.charAt(i)) * multipliers[i];
			if (temp > 9) 
			  total = total + Math.floor(temp/10) + temp%10 
			else 
			  total = total + temp;
		  }
		  
		  // Establish check digit.
		  total = 10 - total % 10;
		  if (total > 9) {total = 0;};  
		  
		  // Compare it with the last character of the VAT number. If it is the same, 
		  // then it's a valid check digit.
		  if (total == vatnumber.slice (10,11)) 
			return true
		  else 
			return false;
		}
		
		function LTVATCheckDigit (vatnumber) {
		
		  // Checks the check digits of a Lithuanian VAT number.
		  
		  // Only do check digit validation for standard VAT numbers
		  if (vatnumber.length != 9) return true;
		  
		  // Extract the next digit and multiply by the counter+1.
		  var total = 0;
		  for (var i = 0; i < 8; i++) total = total + Number(vatnumber.charAt(i)) * (i+1);
		  
		  // Can have a double check digit calculation!
		  if (total % 11 == 10) {
			var multipliers = [3,4,5,6,7,8,9,1];
			total = 0;
			for (i = 0; i < 8; i++) total = total + Number(vatnumber.charAt(i)) * multipliers[i];
		  }
		  
		  // Establish check digit.
		  total = total % 11;
		  if (total == 10) {total = 0;}; 
		  
		  // Compare it with the last character of the VAT number. If it is the same, 
		  // then it's a valid check digit.
		  if (total == vatnumber.slice (8,9)) 
			return true
		  else 
			return false;
		}
		
		function LUVATCheckDigit (vatnumber) {
		
		  // Checks the check digits of a Luxembourg VAT number.
		  
		  if (vatnumber.slice (0,6) % 89 == vatnumber.slice (6,8)) 
			return true
		  else 
			return false;
		}
		
		function LVVATCheckDigit (vatnumber) {
		
		  // Checks the check digits of a Latvian VAT number.
		  
		  // Only check the legal bodies
		  if ((/^[0-3]/).test(vatnumber)) return true; 
		  
		  var total = 0;
		  var multipliers = [9,1,4,8,3,10,2,5,7,6];
		  
		  // Extract the next digit and multiply by the counter.
		  for (var i = 0; i < 10; i++) total = total + Number(vatnumber.charAt(i)) * multipliers[i];
		  
		  // Establish check digits by getting modulus 11.
		  if (total%11 == 4 && vatnumber[0] ==9) total = total - 45;
		  if (total%11 == 4) 
			total = 4 - total%11
		  else if (total%11 > 4) 
			total = 14 - total%11
		  else if (total%11 < 4) 
			total = 3 - total%11;
		  
		  // Compare it with the last character of the VAT number. If it is the same, 
		  // then it's a valid check digit.
		  if (total == vatnumber.slice (10,11)) 
			return true
		  else 
			return false;
		}
		
		function MTVATCheckDigit (vatnumber) {
		
		  // Checks the check digits of a Maltese VAT number.
		  
		  var total = 0;
		  var multipliers = [3,4,6,7,8,9];
		  
		  // Extract the next digit and multiply by the counter.
		  for (var i = 0; i < 6; i++) total = total + Number(vatnumber.charAt(i)) * multipliers[i];
		  
		  // Establish check digits by getting modulus 37.
		  total = 37 - total % 37;
		  
		  // Compare it with the last character of the VAT number. If it is the same, 
		  // then it's a valid check digit.
		  if (total == vatnumber.slice (6,8) * 1) 
			return true
		  else 
			return false;
		}
		
		function NLVATCheckDigit (vatnumber) {
		
		  // Checks the check digits of a Dutch VAT number.
		  
		  var total = 0;                                 // 
		  var multipliers = [9,8,7,6,5,4,3,2];
		  
		  // Extract the next digit and multiply by the counter.
		  for (var i = 0; i < 8; i++) total = total + Number(vatnumber.charAt(i)) * multipliers[i];
		  
		  // Establish check digits by getting modulus 11.
		  total = total % 11;
		  if (total > 9) {total = 0;};  
		  
		  // Compare it with the last character of the VAT number. If it is the same, 
		  // then it's a valid check digit.
		  if (total == vatnumber.slice (8,9)) 
			return true
		  else 
			return false;
		}
		
		function PLVATCheckDigit (vatnumber) {
		
		  // Checks the check digits of a Polish VAT number.
		  
		  var total = 0;
		  var multipliers = [6,5,7,2,3,4,5,6,7];
		  
		  // Extract the next digit and multiply by the counter.
		  for (var i = 0; i < 9; i++) total = total + Number(vatnumber.charAt(i)) * multipliers[i];
		  
		  // Establish check digits subtracting modulus 11 from 11.
		  total = total % 11;
		  if (total > 9) {total = 0;};
		  
		  // Compare it with the last character of the VAT number. If it is the same, 
		  // then it's a valid check digit.
		  if (total == vatnumber.slice (9,10)) 
			return true
		  else 
			return false;
		}
		
		function PTVATCheckDigit (vatnumber) {
		
		  // Checks the check digits of a Portugese VAT number.
		  
		  var total = 0;
		  var multipliers = [9,8,7,6,5,4,3,2];
		  
		  // Extract the next digit and multiply by the counter.
		  for (var i = 0; i < 8; i++) total = total + Number(vatnumber.charAt(i)) * multipliers[i];
		  
		  // Establish check digits subtracting modulus 11 from 11.
		  total = 11 - total % 11;
		  if (total > 9) {total = 0;};
		  
		  // Compare it with the last character of the VAT number. If it is the same, 
		  // then it's a valid check digit.
		  if (total == vatnumber.slice (8,9)) 
			return true
		  else 
			return false;
		}
		
		function ROVATCheckDigit (vatnumber) {
		
		  // Checks the check digits of a Romanian VAT number.
		  
		  var multipliers = [7,5,3,2,1,7,5,3,2,1];
		  
		  // Extract the next digit and multiply by the counter.
		  var VATlen = vatnumber.length;
		  multipliers = multipliers.slice (10-VATlen);
		  var total = 0;
		  for (var i = 0; i < vatnumber.length-1; i++) {
			total = total + Number(vatnumber.charAt(i)) * multipliers[i];
		  }  
		  
		  // Establish check digits by getting modulus 11.
		  total = (10 * total) % 11;
		  if (total == 10) total = 0; 
		  
		  // Compare it with the last character of the VAT number. If it is the same, 
		  // then it's a valid check digit.
		  if (total == vatnumber.slice (vatnumber.length-1, vatnumber.length))
			return true
		  else 
			return false;
		}
		
		function SEVATCheckDigit (vatnumber) {
		
		  // Checks the check digits of a Swedish VAT number.
		  
		  var total = 0;
		  var multipliers = [2,1,2,1,2,1,2,1,2];
		  var temp = 0;
		  
		  // Extract the next digit and multiply by the appropriate multiplier.
		  for (var i = 0; i < 9; i++) {
			temp = Number(vatnumber.charAt(i)) * multipliers[i];
			if (temp > 9)
			  total = total + Math.floor(temp/10) + temp%10
			else 
			  total = total + temp;
		  }
		  
		  // Establish check digits by subtracting mod 10 of total from 10.
		  total = 10 - (total % 10); 
		  if (total == 10) total = 0;
		  
		  // Compare it with the 10th character of the VAT number. If it is the same, 
		  // then it's a valid check digit.
		  if (total == vatnumber.slice (9,10)) 
			return true
		  else 
			return false;
		}
		
		function SKVATCheckDigit (vatnumber) {
		
		  // Checks the check digits of a Slovak VAT number.
		  
		  var total = 0; 
		  var multipliers = [8,7,6,5,4,3,2];
		  
		  // Extract the next digit and multiply by the counter.
		  for (var i = 3; i < 9; i++) {
			total = total + Number(vatnumber.charAt(i)) * multipliers[i-3];
		  }  
		  
		  // Establish check digits by getting modulus 11.
		  total = 11 - total % 11;
		  if (total > 9) total = total - 10;  
		  
		  // Compare it with the last character of the VAT number. If it is the same, 
		  // then it's a valid check digit.
		  if (total == vatnumber.slice (9,10)) 
			return true
		  else 
			return false;
		}
		
		function SIVATCheckDigit (vatnumber) {
		
		  // Checks the check digits of a Slovenian VAT number.
		  
		  var total = 0; 
		  var multipliers = [8,7,6,5,4,3,2];
		  
		  // Extract the next digit and multiply by the counter.
		  for (var i = 0; i < 7; i++) total = total + Number(vatnumber.charAt(i)) * multipliers[i];
		  
		  // Establish check digits by subtracting 97 from total until negative.
		  total = 11 - total % 11;
		  if (total > 9) {total = 0;};  
		  
		  // Compare the number with the last character of the VAT number. If it is the 
		  // same, then it's a valid check digit.
		  if (total == vatnumber.slice (7,8)) 
			return true
		  else 
			return false;
		}
		
		function UKVATCheckDigit (vatnumber) {
		
		  // Checks the check digits of a UK VAT number.
		  
		  var multipliers = [8,7,6,5,4,3,2];
		  
		  // Government departments
		  if (vatnumber.substr(0,2) == 'GD') {
			if (vatnumber.substr(2,3) < 500) 
			  return true 
			else 
			  return false;
		  }
		  
		  // Health authorities
		  if (vatnumber.substr(0,2) == 'HA') {
			if (vatnumber.substr(2,3) > 499) 
			  return true 
			else 
			  return false;
		  }
		  
		  // Standard and commercial numbers
		  if (vatnumber.length == 9 || vatnumber.length == 10) {
			var total = 0;
			if (vatnumber.length == 10 && vatnumber.slice (9,10) != '3') return false;
			
			// Extract the next digit and multiply by the counter.
			for (var i = 0; i < 7; i++) total = total + Number(vatnumber.charAt(i)) * multipliers[i];
		  
			// Establish check digits by subtracting 97 from total until negative.
			while (total > 0) {total = total - 97;}    
		  
			// Get the absolute value and compare it with the last two characters of the
			// VAT number. If the same, then it is a valid check digit.
			total = Math.abs(total);
			if (total == vatnumber.slice (7,9)) 
			  return true 
			else  
			  return false;
		  }
		  
		  // We don't check 12 and 13 digit UK numbers - not only can we not find any, 
		  // but the information found on the format is contradictory.
		  
		  return true;
		}

		
});

