/* === rmc.js === */


(function($) {
	$.extend( {
		
		config: (function() {
			// Put config settings in confObj (private):
			var confObj = {
				printLabel:			"Print",
				siteSearchEmpty:	"U heeft geen zoekterm opgegeven.\nVul een of meerdere zoektermen in en klik op \"zoeken\", of druk op Enter.",
				jsLinks:			{	// actual [link text] between square brackets
										back:		"Ga [terug].",
										close:		"[Sluit venster]"
									},
				searchForm:			{
										checkAll:	true,
										label:		"Alles selecteren",
										infoIcon:	"images/ico_info.png"
									},
				reqPassword:		{
										forgotLink:	"Wachtwoord vergeten?",
										backLink:	"Terug naar inloggen"
									},
				nlMonths:			[ "januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december" ]
			};
			
			// Private methods:
			var extend = function(conf, callbacks) {
				if (!conf || typeof conf !== "object") { return; }
				var proceed;
				for (var key in conf) {
					proceed = true;
					if (callbacks) {
						// Call appropriate callback function, if specified:
						if (confObj[key] && callbacks.onAlter) { proceed = callbacks.onAlter(key, conf[key], confObj[key]); }
						else if (!confObj[key] && callbacks.onAdd) { proceed = callbacks.onAdd(key, conf[key]); }
					}
					// Set value, unless callback function returned false:
					if (proceed || proceed == null) { confObj[key] = conf[key]; }
				}
			};
			var get = function(key) {
				return key ? confObj[key] : confObj;
			};
			
			// Interface:
			return {extend: extend, get: get};
		})(),
		
		initMainNav: function() {
			var navID = "#mainNav";
			var expClass = "jsExpand";
			var mainNav = $(navID);
			if (mainNav.length == 0) { return; }
			
			function expandToggle(exp) {
				mainNav.toggleClass(expClass, exp);
			}
				
			// opening #mainNav on page load:
			if (window.location.hash == navID) {
				expandToggle(true);
			}
			
			// navigating #mainNav (order in which classNames of #mainNav are added/removed makes a difference in IE6!):
			mainNav
				.hover(
					function() { expandToggle(true); },
					function() { expandToggle(false); }
				)
				.find("h3")
					.removeClass("offScreen")
					.click(function() {
						expandToggle(!mainNav.hasClass(expClass));
					});
					
			mainNav
				.addClass("jsNav")
				.removeClass("offScreen")	// className only added on homepage, see script in template (right after #mainNav)
				.find("li a")
					.focus(function() {
						expandToggle(true);
					})
					.blur(function() {
						expandToggle(false);
					});
				
			// navigating to #mainNav using skipLink:
			$("#skipLinks a[href='" + navID + "']")
				.click(function() {
					expandToggle(true);
				});
		},
		
		popImages: function() {
			var links = $.config.get("popImages");	// gets defined in template
			for (lnk in links) {
				$("#" + lnk).popLink({width:links[lnk][0], height:links[lnk][1]})
			}
		}
		
		/*initSiteSearch: function() {
			// simple validation:
			$("#siteSearch")
				.submit(function(e){
					var jSearchBox = $("#zkr_words");
					if (!jSearchBox.val()) {
						e.preventDefault();
						var msg = $.config.get().siteSearchEmpty;
						alert(msg);
						jSearchBox.focus();
					}
				});
		},
		
		addJSLinks: function() {
			$.initPrintPage();
			if ($.config.get("isPopup")) {
				$.returnLinks("#sendPageDone", "close");
			}
		},
		
		initPrintPage: function() {
			if (window.print) {
				$("#pageTools ul.nav").prepend('<li id="printPage"><a href="#">' + $.config.get().printLabel + '</a></li>');
				$("#printPage").click( function(e) {
					e.preventDefault();
					window.print();
				});
			}
		},
		
		returnLinks: function(parentSelector, type) {
			if (!parentSelector) { return; }
			if (!type) { type = "goBack" }
			
			var returnLink = $.config.get("jsLinks")[type].replace(/(.*)\[(.*)\](.*)/, '<p class="' + type + '">$1<a href="#">$2</a>$3</p>');
			$(parentSelector).append(returnLink);
			
			// go back:
			$("p.back a").click(function(e) {
				e.preventDefault();
				window.history.back();
			});
			
			// close window:
			$("p.close a").click(function(e) {
				e.preventDefault();
				window.close();
			});
		},
		
		popImages: function() {
			var links = $.config.get("popImages");	// gets defined in template
			for (lnk in links) {
				$("#" + lnk).popLink({width:links[lnk][0], height:links[lnk][1]})
			}
		}*/,
		
		searchForms: function(expr) {
			var sfConfig = $.config.get("searchForm");
			if (!sfConfig || sfConfig.checkAll === false) { return; }
			
			var formDiv = $(expr);
			
			function checkAll(collection, check) {
				var checkBoxes = collection.find("input:checkbox");
				check ? checkBoxes.attr("checked", "checked") : checkBoxes.removeAttr("checked");
			}
			
			formDiv
				.each(function() {
					var jThis = $(this);
					var total = jThis.find("input:checkbox");
					var checked = total.filter("input:checked");
					var id = jThis.attr("id").substring(3).toLowerCase();
					var allID = "option_all." + id;
					var allName = "option_all[" + id + "]";
					var checkAllBox = '<li><label for="' + allID + '"><input type="checkbox" id="' + allID + '" name="' + allName + '" />' + sfConfig.label + '</label></li>';
					jThis
						.data("total", total.length)
						.data("checked", checked.length)
						.prepend(checkAllBox);
				})
				.click(function(e) {
					var target = $(e.target);
					if (target.is("label")) { target = target.find("input:checkbox"); }
					var jThis = $(this);
					var checkAllID = "option_all." + jThis.attr("id").substring(3).toLowerCase();
					var checked = !!target.attr("checked");	// convert to boolean
					if (target.attr("id") == checkAllID) {
						checkAll(jThis, checked);
					} else {
						checkAllID = checkAllID.replace(/\./, "\\\.");
						var others = jThis.find("input:checkbox:not(#" + checkAllID + ")");
						others = checked ? others.not(":checked") : others.filter(":checked");
						if (others.length == 0) {
							checkAll(jThis, checked);
						} else {
							$("#" + checkAllID).removeAttr("checked");
						}
					}
				});
				
			var infoIcon = sfConfig.infoIcon;
			if (infoIcon) {
				formDiv
					.addClass("jsInfo")
					.find("div.infoLayer")
					.prepend('<a href="#"><img src="' + infoIcon + '" alt="info" /></a>')
					.hover(
						function(e) {
							var jThis = $(this);
							jThis.addClass("jsHover");
							jThis.closest("li").addClass("jsHover");
						},
						function(e) {
							var jThis = $(this);
							jThis.removeClass("jsHover");
							jThis.closest("li").removeClass("jsHover");
						});
			}
		},
		
		initSlideshow: function() {
			var slideshow = $("body.home div.slideShow");
			var slides = slideshow.find("ul.slides li.slide");
			var startIndex = slides.index(slides.not("li.hide")) || 0;
			slides.removeClass("hide");
			var show = slideshow.slideShow({
			   interval: 5,
			   start: startIndex,
			   transition: { mode: "fade", speed: 2000 }
			});
			if (slideshow.find("li.hide").length == 0) {
				slideshow.addJsLink("<img src=\"/images/slides/slidenav_prev.png\" alt=\"vorige\" />", {
						wrapper: "<ul class=\"slidesNav\"><li class=\"prev\">[@]</li></ul>"
					}, function() {
						show.gotoSlide(show.current - 1, true);
					})
					.find("ul.slidesNav")
						.addJsLink("<img src=\"/images/slides/slidenav_next.png\" alt=\"volgende\" />", {
								wrapper: "<li class=\"next\">[@]</li>"
							}, function() {
								show.gotoSlide(show.current + 1, true);
							});
			}
		},
		
		initSiteSearch: function() {
			// overLabel:
			$("#zkr_words").overLabel().blur();
			
			// simple validation:
			$("#siteSearch")
				.submit(function(e){
					var jSearchBox = $("#zkr_words");
					if (!jSearchBox.val()) {
						e.preventDefault();
						var msg = $.config.get().siteSearchEmpty;
						alert(msg);
						jSearchBox.focus();
					}
				});
		},
		
		emailDays: function() {
			var days = $("#searchForm.emailServiceProfile #dagen, #searchForm.cvProfile #dagen");
			days
				.keyup(function() {
					// validate value:
					var jThis = $(this);
					var val = jThis.val();
					var absIntVal = Math.abs(parseInt(val), 10);
					if (val != absIntVal && val != "") {
						val = absIntVal;
					}
					if (isNaN(val)) {
						val = 0;
					}
					if (val > 99) {
						val = 99;
					}
					jThis.val(val);
					
					calcDate(val);
				})
				.blur(function() {
					// validate value:
					var jThis = $(this);
					var val = jThis.val();
					if (val == "") {
						jThis.val("0");
					}
					calcDate(jThis.val());
				});
				
			function calcDate(period) {
				if (period >= 0) {
					var today = new Date();
					var futureDate = new Date(today.getTime() + 86400000 * period);	// 24 * 60 *60 * 1000 = 86400000 milliseconds in a day
					var dateTxt = futureDate.getDate() + " " + $.config.get("nlMonths")[futureDate.getMonth()] + " " + futureDate.getFullYear();
					var endDate = $("#verloopdatum");
					var finalDate = $("#finalDate");
					if (finalDate.length == 0) {
						endDate.before(', tot <span id="finalDate">' + dateTxt + '</span>');
						finalDate = $("#finalDate");
					}
					finalDate.text(futureDate.toLocaleDateString());
					endDate.val(dateTxt);
				}
			}
			
			function leadingZero(num) {
				return num < 10 ? "0" + num : num;
			}
			
			calcDate(days.val());
		},
		
		requestPassword: function() {
			var emailServiceForm = $("#emailService #searchForm");
			var reqPassword = emailServiceForm.find("#requestPassword");
			var login = emailServiceForm.find("#login");
			if (!login || login.length == 0 || !reqPassword || reqPassword.length == 0) { return; }
			
			emailServiceForm.addClass("jsSwap");
			var links = $.config.get("reqPassword");
			login.append('<p class="swapLink"><a href="#">' + links.forgotLink + '</a></p>');
			reqPassword.append('<p class="swapLink"><a href="#">' + links.backLink + '</a></p>');
			emailServiceForm
				.find("p.swapLink a")
				.click(function(e) {
					e.preventDefault();
					emailServiceForm.toggleClass("jsRequest");
				})
		}/*,
		
		requestPassword: function() {
			var emailServiceForm = $("#emailService #searchForm");
			var reqPassword = emailServiceForm.find("#requestPassword");
			var login = emailServiceForm.find("#login");
			if (!login || login.length == 0 || !reqPassword || reqPassword.length == 0) { return; }
			
			emailServiceForm.addClass("jsSwap");
			var links = $.config.get("reqPassword");
			login.append('<p class="swapLink"><a href="#">' + links.forgotLink + '</a></p>');
			reqPassword.append('<p class="swapLink"><a href="#">' + links.backLink + '</a></p>');
			emailServiceForm
				.find("p.swapLink a")
				.click(function(e) {
					e.preventDefault();
					emailServiceForm.toggleClass("jsRequest");
				})
		},
		
		initOpleidingen: function() {
			var institutes = $("#oplInstitutes");
			var oplLists = institutes.find("div.opl");
			if (oplLists.length === 0) { return; }
			
			oplLists.prev().find("a")
				.addClass("toggleOplList")
				.append("<span></span>");
			
			institutes
				.addClass("jsExpandable")
				.click(function(e) {
					var jTarget = $(e.target);
					if (jTarget.is("a.toggleOplList")) {
						e.preventDefault();
						jTarget.closest("li").toggleClass("jsExpand");
					}
				});
			
		},
		
		emailDays: function() {
			var days = $("#searchForm.emailServiceProfile #dagen");
			days
				.keyup(function() {
					// validate value:
					var jThis = $(this);
					var val = jThis.val();
					var absIntVal = Math.abs(parseInt(val), 10);
					if (val != absIntVal && val != "") {
						val = absIntVal;
					}
					if (isNaN(val)) {
						val = 0;
					}
					if (val > 99) {
						val = 99;
					}
					jThis.val(val);
					
					calcDate(val);
				})
				.blur(function() {
					// validate value:
					var jThis = $(this);
					if (jThis.val() == "") {
						jThis.val("0");
					}
					calcDate(val);
				});
				
			function calcDate(period) {
				if (period > 0) {
					var today = new Date();
					var futureDate = new Date(today.getTime() + 86400000 * period);	// 24 * 60 *60 * 1000 = 86400000 milliseconds in a day
					var dateTxt = futureDate.getDate() + " " + $.config.get("nlMonths")[futureDate.getMonth] + " " + futureDate.getFullYear();
					var endDate = $("#verloopdatum");
					var finalDate = $("#finalDate");
					if (finalDate.length == 0) {
						endDate.before(', tot <span id="finalDate">' + dateTxt + '</span>');
						finalDate = $("#finalDate");
					}
					finalDate.text(futureDate.toLocaleDateString());
					endDate.val(
						leadingZero(finalDate.getDate()) + " " + 
						leadingZero(finalDate.getMonth()) + " " + 
						finalDate.getFullYear()
					);
				}
			}
			
			function leadingZero(str) {
				return str.length == 2 ? str : "0" + str;
			}
		}*/
	} );
	
	$.fn.extend( {
		validateForm: function(checkObj) {
			/* optional checkObj keys:
				{
					required: Boolean (default: true),
					pattern: RegExp, or one of the keys in config.patterns (e.g. "email"),
					label: String (name used in error message),
					error: String (additional error message)
				} 	*/
			var config = {
				defProps:	{
								required: true
							},
				errorMsg:	"De volgende velden zijn niet (juist) ingevuld:",
				patterns:	{
								email: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i
							}
			}
			for (field in checkObj) {
				var fieldObj = checkObj[field];
				for (prop in config.defProps) {
					if (fieldObj[prop] == null) {
						fieldObj[prop] = config.defProps[prop];
					}
				}
				if (fieldObj.pattern && config.patterns[fieldObj.pattern]) {
					fieldObj.pattern = config.patterns[fieldObj.pattern];
				}
				if (!fieldObj.label) {
					fieldObj.label = field;
				}
			}
			
			var jThis = $(this);
			var fields = jThis.is("form :input") ? jThis : jThis.find(":input");
			fields.each(function() {
				var jThis = $(this);
				jThis.data("valObj", checkObj[jThis.attr("name")]);
			});
			var jForm = $($.unique(fields.closest("form")));
			jForm.submit(function(e) {
				var jThis = $(this);
				var errorStr = "";
				var firstItem;
				jThis.find(":input")
					.each(function() {
						var jThis = $(this);
						var value = jThis.val();
						var valObj = jThis.data("valObj");
						if (valObj) {
							if ((valObj.required && !value) || (value && valObj.pattern && !value.match(new RegExp(valObj.pattern)))) {
								errorStr += "\n- " + valObj.label;
								if (valObj.error) {
									errorStr += " (" + valObj.error + ")";
								}
								if (!firstItem) {
									firstItem = jThis;
								}
							}
						}
					});
				if (errorStr != "") {
					e.preventDefault();
					alert(config.errorMsg + errorStr);
					firstItem.focus();
				}
			});
		},
		
		initSlideshows: function(options, nav) {
			if (nav && typeof nav == "object") {
				
			}
			this.slideShow(options);
		}
	} );
} )(jQuery);

jQuery( function( $ ) {
	
	// extend $.config with window.config (if any):
	$.config.extend(window.config);
	
	// init mainNav:
	$.initMainNav();
	
	// init searchForms:
	$.searchForms("#searchForm fieldset.checkboxField ul.overview");
	
	// select box navigation:
	$("#mainContent div.resultsNav select").selectNav();
	
	// init slideshows:
	$.initSlideshow();

	// init #siteSearch:
	$.initSiteSearch();
	
	// overLabel:
	$("#emailService label, #cvBank label").overLabel();
	
	// requestPassword swap:
	$.requestPassword();
	
	// popLinks:
	$.popImages();
	$("#sendPage a, #mainContent p.reportToUs a").popLink({ width: 540, height: 600, props: ["resizable", "scrollbars"] });
	
	// make entire block elements clickable:
	$("#results li").clickable();
	
	// validate forms:
	$("#searchForm.emailServiceProfile").validateForm({
		"voornaam": { label: "Voornaam" },
		"achternaam": { label: "Achternaam" },
		"straat": { label: "Straat" },
		"huisnummer": { label: "Huisnummer + toevoegsel" },
		"postcode": { label: "Postcode" },
		"plaats": { label: "Woonplaats" },
		"email": { label: "E-mailadres", pattern: "email", error: "vul een geldig e-mailadres in" }
	});
	$("#wrapper div.sendPage #email_form").validateForm({
		"fields[uwnaam]": { label: "Uw naam" },
		"fields[email]": { label: "E-mailadres van de ontvanger", pattern: "email", error: "vul een geldig e-mailadres in" },
		"fields[onderwerp]": { label: "Onderwerp" }
	});
	$("#wrapper div.wrongVac #email_form").validateForm({
		"fields[uwnaam]": { label: "Uw naam" },
		"fields[uwemail]": { label: "Uw e-mailadres", pattern: "email", error: "vul een geldig e-mailadres in" }
	});
	
	// set final date email service/CV bank:
	$.emailDays();
	
} );


// Google Analitics:
/*var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));

try {
	var pageTracker = _gat._getTracker("UA-6990976-21");
	pageTracker._trackPageview();
} catch(err) {}*/