(function ($){

	Cufon.replace('#navigation li .top, #footer ul li a.top, #main h1, h2, h3', {
		hoverables:{a:true}
	});

	if($.browser.msie && $.browser.version.substring(0,1) === '6'){ // IE... hate it
		$('#navigation > li').hover(
			function(){$(this).addClass('hover');},
			function(){$(this).removeClass('hover');}
		);
	}

	$.fn.resettable = function ( ) {
		fields = new Array();
		this.each(function() {
		  //check to make sure the element has a name attribute. If not, do nothing!
		  //if (!jQuery(this).attr("name")) return true;
		  jQuery(this).data("original", jQuery(this).val()) ;
		  jQuery(this).focus(function() {
			if ( jQuery(this).val() == jQuery(this).data("original") ) 	jQuery(this).val("");
		  }).blur(function() {
				if (jQuery(this).val() == "") jQuery(this).val( jQuery(this).data("original") );
		  });
		});
		return this;
	}
	$("#search input").resettable();

   function updateMenu() {
     setTimeout(function() {
       Cufon.replace('#navigation a.top', {}, false);
     }, 10);
   }
   $('#navigation li').hover(updateMenu, updateMenu);

   $(".print-link a").click(function() {
		window.print();return false;
	});

   /* Always show werkgever fields..
	$(".werkgever").hide();

	$("input[name^=factuur]").click(function(){
		if ($("input[name^=factuur]:checked").val() == "werkgever")	$(".werkgever").show();
		else $(".werkgever").hide();
	});
	*/

   $.validator.addMethod("defaultInvalid", function(value, element)
    {
     switch (element.value)
     {
      case "Uw naam":
       if (element.name == "Uw naam")
          return false;
	  case "Naam ontvanger":
		if (element.name == "Naam ontvanger")
		  return false;
     }
    });
	$.validator.addMethod("telefoonnummer", function(value, element) {
		return this.optional(element) || /^(\(){0,1}(\+[0-9]{2}|\+[0-9]{2}\s{0,1}\(0\)|\(\+[0-9]{2}\)\s{0,1}\(0\)|(\+)?00[0-9]{2}|0)(\)){0,1}([0-9\-\s]{9,16})$/.test(value);
	}, "Vul a.u.b. een geldig telefoonnummer in.");


    var f = $("form.validate");
	val_options = {
		"errorPlacement": function(er,el){
			el.closest("p").append(er);
		},
		ignore: ".werkgever:not(:visible) input, .step-content:not(:visible) input, #postadres-wrapper:not(:visible) input, #functie-overig-wrapper:not(:visible) input, #send-acc-wrapper:not(:visible) input, #register-wrapper:not(:visible) .required, #referentie-overig-wrapper:not(:visible) input",
		groups: {
			name: "voorletters achternaam",
			postcode: "postcode huisnr",
		/*	vestpostcode: "vestpostcode vestnr", */
			postpostcode: "postpostcode postnr"
		},
		 rules: {
			tel1: {
				required: function(element) {return $("#tel2").val()=="";},
				telefoonnummer: true
			},
			tel2: {
				required: function(element) {return $("#tel1").val()=="";},
				telefoonnummer: true
			},
			tel:{
				telefoonnummer: true
			},
			email2: {
				/*equalTo: ($("#simplemodal-data").size() > 0 ? "#nieuwsbrief_email" : "#email")*/
				equalTo: "#email"
			},
			nieuwsbrief_email2:{
				equalTo: "#nieuwsbrief_email"
			},
			name_sender: "required",
			name_receiver: "required"
		},
		messages: {
			name_sender: "Dit veld is verplicht",
			name_receiver: "Dit veld is verplicht"
		}
	};

	$("a.modal").click(function(){
		var taf = this.href.indexOf("tell-a-friend") !== -1;
		$.get(this.href, function(data){
			var c = $(data);
			if (taf){
				c.find("input[name=url]:hidden").val(window.location.href);
			}
			c.modal({
				"onShow": function(dialog){
					$.extend($.validator.messages, {
						required: "Vul aub dit verplichte veld in",
						remote: "Vul aub een geldige waarde in de veld in",
						email: "Vul aub een geldig e-mailadres in",
						equalTo: "Uw twee e-mail adressen komen niet overeen"
					});
					$("#simplemodal-data form").validate(val_options);
					$(".close-modal").click(function(){$.modal.close();});
					/*$("#simplemodal-data input").resettable();*/
				}
			});
		});
		return false;
	});

	if (f.size() > 0){
		$.extend($.validator.messages, {
			required: "Vul aub dit verplichte veld in",
			remote: "Vul aub een geldige waarde in de veld in",
			email: "Vul aub een geldig e-mailadres in",
			equalTo: "Uw twee e-mail adressen komen niet overeen"
		});

		f.validate(val_options);
	}

	var checkRegistration = function(){
		to_kngf  = $("#to_kngf").is(":checked"), acc_found = $("#acc_found");
		$("#check-registration span[class^=i-]").each(function(){
			var t = $(this), fields = t.attr("class").split("-"), c = "";
			fields.splice(0,1);

			$.each(fields, function(i,v){
				var t2 = $(":visible *[name="+v+"]:enabled, *[name="+v+"]:hidden"), ch = t2.filter(":checked");
				if (v == "functie"){
					if (t2.val()=="overig" && $("#functie_overig").val() != ""){
						c += $("#functie_overig").val()+" ";
					}else{
						c += t2.val()+" ";
					}
				}else if (v=="bron" || v.indexOf("land") !== -1){ // the dropdowns
					c += t2.find("option:selected").text()+" ";
				}else if(v=="to_kngf"){
					if (acc_found.val()=="0"){ // not found
						t.parent().hide().prev().hide(); // hide dt+dd
					}else{
						c += (to_kngf?"Ja":"Nee")+" ";
						t.parent().show().prev().show();
					}
				}else if(v=="lidnr" || v=="register"){
					c += t2.val()+" ";
					if (!to_kngf){
						t.parent().hide().prev().hide();
					}else{
						t.parent().show().prev().show();
					}
				}else if(ch.size()>0){		// checkboxes
					c += ch.parent().text()+" ";
				}else if(t2.is(":not(:radio)")){ // all other normal inputs
					c += t2.val()+" ";
				}

			});
			t.text(c);
		});
		if ($("#factuur2").is(":checked")){
			$("#werkgever-wrapper").show();
		}
		$("#header").get(0).scrollIntoView();
	};

	/* Step on inschrijvingen */
	var steps = $("ul.steps"), steps_form = $("form.steps-form");
	if (steps_form.size() > 0){
		$(".step-content").hide();
		/* get the selected step */
		var stp = steps.find(".selected").attr("id").substring(9), eb = $(".extra-blue-block:first");
		$("#step-"+stp).show();
		if (stp=="1"){
			eb.hide();
		}else{
			eb.show();
		}
		$("form.steps-form a.button, ul.steps li a").live("click", function(){
			var step = this.href.substring(this.href.indexOf("step"));
			if (step=="step-1"){
				eb.hide();
			}else{
				eb.show();
			}
			if (step == "step-3"){
				/* check if the form is valid first */

				if (false === steps_form.valid()){
					steps_form.submit(); // trigger the validator
					return false;
				}
				else{
					var s3 = $("li#step-tab-3");
					s3.html("<a href=\"#step-3\">" + s3.text() + "</a>");
					checkRegistration();
				}
				// else do nothing and show step 3
			}
			steps.find(".selected").removeClass("selected");
			steps.find("li."+step).addClass("selected");

			$(".step-content:visible").hide();
			$("#"+step).show();

			/*fill the name fields */
			var vn = steps_form.find("input[name=voorletters]").val(),
			tn = steps_form.find("input[name=tussenvoegsel]").val(),
			an = steps_form.find("input[name=achternaam]").val(),
			name = vn + (tn==""?"":" "+tn) + " " + an;

			steps_form.find("input[name=name]:hidden").val(name);
			steps_form.find("dd span.name").html(name);

			return false;
		});
	}

	var edu = $("select[name=sEducation].select-training"), crs = $("select[name=sCourse].select-training"), btns = $("#search-training a");
	$("#search-training a").hide();
	edu.change(function(ev){
		var opt = $(this).find(":selected").attr("id"), cid = opt.substring(4); // get the education cid
		crs.each(function(i,el){
			var t = $(this);
			if(i===0) t.blur().click().blur();
			if(t.is(":visible") || $("div#customSelect-"+t.attr("id")).is(":visible")){
				t.attr("disabled", "disabled");
				if ($("body").hasClass("home") && document.all){
					$("div#customSelect-"+t.attr("id")).hide();
				}else{
					t.hide();
				}
			}
		});
		if ($("body").hasClass("home") && document.all){ // if IE, show the customSelect replacer
			$("div#customSelect-course-"+cid).attr("disabled", "").show(); //show the one
		}else{ // otherwise just show the select
			$("select#course-"+cid).attr("disabled", "").show(); //show the one
			//$("div#customSelect-course-"+cid).attr("disabled", "").show(); //show the one
		}

		if (this.value == ""){
			btns.hide();
		}
		btns.each(function(){
			this.href="#";
		});
		return false;
	});



	crs.change(function(ev){
		if ($("body").hasClass("home")){
			var ut = this.value.substring(this.value.indexOf("?"));
			if (this.value == "#"){btns.hide();}else{btns.show();}
			$(this).closest("form").find("a.button.left").attr("href", this.value)
				.end().find("a.button.right").attr("href", "/inschrijven/"+ut);
			return false;
		}
		if (this.value != "#"){
			window.location.href = this.value;
		}
		return false;
	});

//	$("body.home select[name=sCourse].select-training:visible").find("option").eq(1).attr("selected","selected").end().change();

	/* Custom select for selects on homepage */
	if ($("body").hasClass("home") && edu.size() > 0 && document.all){
		//edu.customSelect();
		crs.customSelect();
	}

//	$("body.home select[name=sEducation].select-training").find("option").eq(0).attr("selected","selected").end().change(); // trigger the first valid option to change

	var ac = $(".autocomplete");
	if (ac.size()>0){
		var w = $("body").hasClass("contactformulier")?312:470;
		ac.autocomplete("/remote/uitvoeringen.php", {
			"width": w
		})
		.result(function(event,data,formatted){
			$("form.training-search").submit();
		});

	}

	var il = $("ul#interest-list"), is = $("select#interest-select"), ib = il.closest("form").find("a.button");
	if (il.size() > 0){
		var li = "";
		ib.click(function(){
			var f = il.closest("form"), licontent = "";
			is.find("option:selected").each(function(){
				var v = $(this).text(), cls = this.className;

				if ($("input[class="+cls+"]").size() == 0){
					var courseid = $(this).attr("class").substring(7);
					licontent += "<li>"+v+" <a href=\"#\" class=\"del\">(verwijder)</a></li>";
					f.append("<input type=\"hidden\" name=\"interests["+courseid+"]\" class="+cls+" value=\""+v+"\" />");
				}
			});
			li += licontent;
			il.html(il.html()+li);
			licontent = li = "";
			return false;
		});

		$("a.del").live("click", function(){
			var li = $(this).parent(), t = li.text().substring(0, li.text().indexOf(" ("));
			$("input[value="+t+"]").remove();
			li.remove();
			return false;
		});
	}

	var dp = $(".datepicker");
	if (dp.size() > 0){
		dp.datepicker({"dateFormat": "d-m-yy", "changeMonth": true, "changeYear": true, "yearRange":"-60:+0"});
	}
	$(".date-ico").click(function(){
		$("input.datepicker").focus();
	});


	// give the name attr's of the fields as arguments..
	var fillAddress = function(adres, woonplaats, postcode, huisnr){
		var from_ned = $("#land").val() == "NL",
			$a = $("input[name="+adres+"]:text"), $w = $("input[name="+woonplaats+"]:text"),
			$p = $("input[name="+postcode+"]:text"), $n = $("input[name="+huisnr+"]:text"), timer,
			ku = function(ev){ // keyup event
				 	var reg1 = /[^a-zA-Z0-9]/g, p = $p.val().replace(/\s/g, ""), n = $n.val(),
				 		$ha = $("input[name="+adres+"]:hidden"), $hw = $("input[name="+woonplaats+"]:hidden");
					if (/^[0-9]{4}[a-zA-Z]{2}$/.test(p) && /^[0-9]+$/.test(n)){
						clearTimeout(timer);
						timer = setTimeout(function(){
							$.getJSON("/remote/address.php?postal="+p+"&number="+n+"&callback=?", function(json){
								var addr_msg = $("#addr-msg");
								if (json.msg){
									if (addr_msg.size() === 0){
										$p.parent().append("<label class=\"error\" id=\"addr-msg\">Geen bestaand adres gevonden.</label>");
									}
								}else{
									addr_msg.remove();
								}
								$a.val(json.street);
								$w.val(json.city);
								$ha.val(json.street);
								$hw.val(json.city);
							});
						}, 500);
					}
					else{
						$a.val("");$ha.val("");
						$w.val("");$hw.val("");
					}
				};

		$a.attr("disabled", "disabled");
		$w.attr("disabled", "disabled");
		$a.closest("form").append("<input type=\"hidden\" id=\"hidden-"+adres+"\" name=\""+adres+"\" value=\"\" /><input type=\"hidden\" id=\"hidden-"+woonplaats+"\" name=\""+woonplaats+"\" value=\"\" />");

		$p.keyup(ku).keyup();
		$n.keyup(ku).keyup();
	};

	var deactivateFill = function(adres, woonplaats, postcode, huisnr){
		// enable the disabled forms..
		$("input#"+adres).attr("disabled", "").removeAttr("disabled");
		$("input#"+woonplaats).attr("disabled", "").removeAttr("disabled");
		// remote the hidden forms
		$("input#hidden-"+adres).remove();
		$("input#hidden-"+woonplaats).remove();
		// unbind the keyup event on the postcode and huisnr
		$("input[name="+postcode+"]:text").unbind("keyup");
		$("input[name="+huisnr+"]:text").unbind("keyup");
	};

	var bf = $("#brochure-form"), ifm = $("#inschrijf-form");
	if (bf.size() > 0 || ifm.size() > 0){ // the inschrijfform has 2 adress autofill fields...

		$("#land").change(function(){
			if ($(this).val() == "NL"){
				fillAddress("adres", "woonplaats", "postcode", "huisnr"); // persoonsgegevens
			}else{
				deactivateFill("adres", "woonplaats", "postcode", "huisnr");
			}
		}).change(); // trigger the select change

		bf.find("button[type=submit]").click(function(){
			if (bf.valid() && $("#interest-list li").size() == 0){
				if ($(".extra-error").size() == 0){
					$(".selected-trainings").after("<label generated=\"true\" class=\"extra-error error\">Voeg aub een gewenste opleiding toe.</label>");
				}
				return false;
			}
			else if (bf.valid()){ // succesfull submit
				$(this).after("<p class=\"loading\">Een momentje geduld aub, uw aanvraag wordt verwerkt...</p>");
			}
		});
	}
	if (ifm.size() > 0){

		$("#postland").change(function(){
			if ($(this).val() == "NL"){
				fillAddress("postadres", "postplaats", "postpostcode", "postnr"); // werk gegevens
			}else{
				deactivateFill("postadres", "postplaats", "postpostcode", "postnr");
			}
		}).change(); // trigger the select change


		$("#final-submit").click(function(ev){
			if (ifm.valid()){ // succesfull submit
				$(this).after("<p class=\"loading\">Een momentje geduld aub, uw inschrijving wordt verwerkt...</p>");
			}
		});
	}

	if (document.all){ // IE
		var select = $(".training-select select[name=sCourse]"), w = select.width();
	}

	$(".tooltip").click(function(){
		//close all others
		$(".tooltip-desc:not(#"+this.rel+")").hide();
		$("#"+this.rel).toggle();

		return false;
	});
	$(".close-tooltip").click(function(){
		$(this).parent().hide();
		return false;
	});

	/* Functie */
	var func = $("#functie"), fow = $("p#functie-overig-wrapper"), fowi = fow.find("input"), label = $("label[for=lidnr]");
	if (func.size() > 0){
		func.change(function(){
			if (this.value == "overig"){
				fow.show();
				fowi.attr("disabled", "");
			}else{
				fow.hide();
				fowi.attr("disabled", "disabled");
			}
		});
	}

	$("#select-uitvoering").change(function(){
		window.location.href = $(this).val();
	});

	var map = $("#google-map")
				.height(350)
				.width(550);
	if (map.size() > 0 && GBrowserIsCompatible()){
		var GMap = new GMap2(map[0]),
			latlng = new GLatLng(52.309958,4.945285),
			marker = new GMarker(latlng),
			addr = "<strong>Pro Education - Contact</strong><br/>Atlas Complex, Gebouw Azië<br/>Hoogoorddreef 5<br/>1101 BA Amsterdam<br/>T +31 (0)20-567 79 99<br/>";
		GMap.addMapType(G_PHYSICAL_MAP);
		GMap.addControl(new GMapTypeControl());
		GMap.addControl(new GSmallMapControl());
		GMap.setCenter(latlng, 15);
		GMap.setMapType(G_NORMAL_MAP);

		GMap.addOverlay(marker);
		marker.openInfoWindow(addr);
		GEvent.addListener(map, "click", function(){
			marker.openInfoWindow(addr);
		});
		$(window).unload(GUnload);
	}
	if ($("body").hasClass("bedankt-inschrijving") || $("body").hasClass("bedankt-inschrijving-wachtlijst")){
		document.cookie = "pro-edu-inschrijven=; expires="+(new Date()).toGMTString()+"; path=/inschrijven/";
	}

})(jQuery);
