/// <reference path="JQuery.Intellisense.js"/> 
var dropdownHeight = 0;
var amountvg = 50; // set aantal vakgebieden homepage
var tresholdvg = 1 // treshold (1 vakgebieden: alles tonen)
var jsonOpleidingen = {};
var jsonPlaatsDatum = {};

var functions = {};
var idreams = idreams || {};

/* Cookie function */
idreams.cookie = function (key, value, options) {
 
    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = options || {};
 
        if (value === null || value === undefined) {
            options.expires = -1;
        }
 
        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }
 
        value = String(value);
 
        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }
 
    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

functions.IsEmpty = function(obj) {
    for(var k in obj) {
        if(obj.hasOwnProperty(k))
            return false;
    }
    return true;
}

functions.AddOption = function(selectbox, text, value)
{
	var option = document.createElement("option");
	option.text = text;
	option.value = value;
	selectbox.options.add(option);
}

functions.AddOptions = function(selectbox, options)
{
	for (var key in options) {
		var option = $('<option />');
		option.attr('value', key).html(options[key]).appendTo(selectbox);
	}
}

functions.SetProps = function(id){
	
	$(".jqOpleidingName").val("");
	$(".jqOpleidingID").val("");
	$(".jqOpleidingInvestering").val("");
	$(".jqOpleidingHotel").val("");
	$(".jqOpleidingBTW").val("");
	$(".jqOpleidingZelfstudie").val("");
	$(".jqOpleidingBrochure").val("");
	
	if (jsonOpleidingen != undefined && !functions.IsEmpty(jsonOpleidingen)) { 
		var obj = jsonOpleidingen[id];

		if (obj != undefined && !functions.IsEmpty(obj)) { 
			$(".jqOpleidingName").val(obj["name"]);
			$(".jqOpleidingID").val(obj["id"]);
			$(".jqOpleidingInvestering").val(obj["investering"]);
			$(".jqOpleidingHotel").val((obj["hotel"])?"Ja":"Nee");
			$(".jqOpleidingBTW").val((obj["btw"])?"Ja":"Nee");
			$(".jqOpleidingZelfstudie").val((obj["zelfstudie"])?"Ja":"Nee");
			$(".jqOpleidingBrochure").val(obj["brochurecode"]);
			$(".jqOpleidingBrochureID").val(obj["brochureID"]);
			
			//######################### ZELFSTUDIE
			
			if ($(".jqPlaatsDatum").length > 0) {
				if (obj["zelfstudie"]) {
					$(".jqPlaatsDatum").hide();
					removeFromValidation("formInschrijven_plaats", $(".jqValidate"));
					removeFromValidation("formInschrijven_startdatum", $(".jqValidate"));
				}
				else {
					$(".jqPlaatsDatum").show();
					var validateFields = $(".jqValidate").val();
					addToValidation("formInschrijven_plaats", $(".jqValidate"));
					addToValidation("formInschrijven_startdatum", $(".jqValidate"));
				}
			}
			
			//######################### ACTIVERINGSCODE
			
			if ($(".jqShowActivation").length > 0) {
				if (obj["activeringscode"]) {
					$(".jqShowActivation").removeClass("hidden");
					addToValidation("formInschrijven_activeringscode", $(".jqValidate"));
					$(".jqExclude").val($(".jqExclude").val().replace(",Activeringscode", ""));
				}
				else {
					$(".jqShowActivation").addClass("hidden");
					removeFromValidation("formInschrijven_activeringscode", $(".jqValidate"));
					exclude = $(".jqExclude").val() + ",Activeringscode";
					$(".jqExclude").val(exclude);
				}
			}
			
			//######################### HOTEL
			
			if ($(".jqShowHotel").length > 0) {
				if (obj["hotel"]) {
					$(".jqShowHotel").show();
					
					$(".jqShowHotel input[type='radio']").each(function(){
						$(this).click(function(){
							if ($(this).val() == 'Ja') {
								$(".jqArrivalDate").show();
								$(".jqDepartureDate").show();
								$(".jqExclude").val($(".jqExclude").val().replace(",Aankomstdatum", ""));
								$(".jqExclude").val($(".jqExclude").val().replace(",Vertrekdatum", ""));
								addToValidation('formInschrijven_aankomstdatum,formInschrijven_vertrekdatum', $(".jqValidate"));
							}
							else {
								$(".jqArrivalDate").hide();
								$(".jqDepartureDate").hide();
								var exclude = $(".jqExclude").val() + ",Aankomstdatum" + ",Vertrekdatum";
								$(".jqExclude").val(exclude);
								removeFromValidation('formInschrijven_aankomstdatum,formInschrijven_vertrekdatum', $(".jqValidate"));
							}
						})
					});
					
				}
				else {
					$(".jqShowHotel").hide();
					removeFromValidation('formInschrijven_aankomstdatum,formInschrijven_vertrekdatum', $(".jqValidate"));
				}
			}
			
			//######################### BTW
			
			if (obj["btw"]){
				$(".jqVoorwaardenExBTW").hide();
				$(".jqVoorwaardenInclBTW").show();
			} else {
				$(".jqVoorwaardenExBTW").show();
				$(".jqVoorwaardenInclBTW").hide();
			}
		}
	}
}


functions.LoadTrainingen = function(id, sel){
	var id = id;
	var trainingSelect = $(".jqTraining");
	if (id) {
		var url = "/ajax_gettrainingbyfield.html";
	} else {
		var url = "/ajax_gettrainingen.html";
	}
	if (trainingSelect.hasClass("jqTrainingBrochure")) {
		url = "/ajax_gettrainingbrochure.html";
	}
	if (trainingSelect.hasClass("jqTrainingTrail")) {
		url = "/ajax_gettrainingtrail.html";
	}
	if (trainingSelect.hasClass("jqTrainingGeneral")) {
		url = "/ajax_gettrainingbycourse.html";
	}
	var plaatsSelect = $(".jqPlaats");
	var datumSelect = $(".jqDatum");
	var txtDefault = ($(trainingSelect).attr("data-default")) ? $(trainingSelect).attr("data-default") : "-- selecteer";
	var txtWait = ($(trainingSelect).attr("data-wait")) ? $(trainingSelect).attr("data-wait") : "-- data ophalen.. ogenblik";
	var txtNoresult = ($(trainingSelect).attr("data-noresult")) ? $(trainingSelect).attr("data-noresult") : "-- geen opleidingen gevonden.";
	
	
	$.ajax({
		type: "GET",
		url: url,
		dataType: 'json',
		data: {
			id: id
		},
		beforeSend: function(){
			trainingSelect.attr("disabled", "disabled");
			trainingSelect.empty();
			trainingSelect.addOption({"" : txtWait }, false);
			plaatsSelect.empty();
			plaatsSelect.addOption({"" : txtDefault }, false);
			datumSelect.empty();
			datumSelect.addOption({"" : txtDefault }, false);
			functions.SetProps(0);
		},
		success: function(data){
			
			jsonOpleidingen = data;
			var options = {};
			$.each(data, function(k, object){
				options[object.id] = object.name;
			});
			functions.AddOptions(trainingSelect, options);
			trainingSelect.selectOptions("" + sel);
			trainingSelect.removeAttr("disabled").find("option:first").text(txtDefault);
			functions.SetProps(sel);
			if (!trainingSelect.hasClass("jqTrainingBrochure") && !trainingSelect.hasClass("jqTrainingTrail") && !trainingSelect.hasClass("jqTrainingGeneral")) {
				functions.LoadStartData(sel);
			}
		},
		complete: function(data) {
			if (trainingSelect.find("option:first").text() != txtDefault){
				trainingSelect.removeAttr("disabled").find("option:first").text(txtNoresult);
			}
		}
	});
}

functions.LoadStartData = function(id) {
	var plaatsSelect = $(".jqPlaats");
	var datumSelect = $(".jqDatum");
	
	var txtDefault = ($(plaatsSelect).attr("data-default")) ? $(plaatsSelect).attr("data-default") : "-- selecteer";
	var txtWait = ($(plaatsSelect).attr("data-wait")) ? $(plaatsSelect).attr("data-wait") : "-- data ophalen.. ogenblik";
	
	if (id) {
		
		if (id > 0) {
			
			$.ajax({
				 type: "GET",
				 url: "/ajax_getdates.html",
				 dataType: 'json',
				 data: {
				 id: id
			 },
			 beforeSend: function(){
				 plaatsSelect.empty();
				 plaatsSelect.addOption({"" : txtWait}, false);
				 plaatsSelect.attr("disabled", "disabled");
				 datumSelect.empty();
				 datumSelect.addOption({"" : txtDefault}, false);
			 },
			 success: function(data){
				 jsonPlaatsDatum = data;
				 var options = {}; 
				 plaatsSelect.find("option").remove();
				 plaatsSelect.addOption({"" : txtWait}, false);
				 $.each(data, function(k, object){
				 	options[k] = object.plaats;
				 	functions.AddOption(document.getElementById(plaatsSelect.attr("id")), object.plaats, k);
			 	});
			 	plaatsSelect.removeAttr("disabled").find("option:first").text(txtDefault);
			 },
			 complete: function(){
				 if (plaatsSelect.find("option:first").text() != txtDefault) {
				 	plaatsSelect.removeAttr("disabled").find("option:first").text(txtDefault);
				 }
			 }
			 });
		}
		else {
			plaatsSelect.empty();
			datumSelect.empty();
			plaatsSelect.addOption({"" : txtDefault}, false);
			datumSelect.addOption({"" : txtDefault}, false);
		}
	}
}

$(document).ready(function() {
	
	/*** update migratie ***/
    /*************************/
	
	$(".jqCourse").bind("change", function(){
		var id = $(this).val();
		var fieldSelect = $(".jqField");
		var trainingSelect = $(".jqTraining");
		var plaatsSelect = $(".jqPlaats");
		var datumSelect = $(".jqDatum");
		
		var txtDefault = ($(this).attr("data-default")) ? $(datumSelect).attr("data-default") : "-- selecteer";
		var txtWait = ($(this).attr("data-wait")) ? $(datumSelect).attr("data-wait") : "-- data ophalen.. ogenblik";
		
		$(".jqCourseField").val($(this).find("option:selected").text().replace( /\&amp;/g, '&' ));
		$.ajax({
			type: "GET",
			url: "/ajax_getfieldbycourse.html",
			dataType: 'json',
			data: {
				id: id
			},
			beforeSend: function(){
				trainingSelect.empty();
				trainingSelect.addOption({"" : txtDefault}, false);
				plaatsSelect.empty();
				plaatsSelect.addOption({"" : txtDefault}, false);
				datumSelect.empty();
				datumSelect.addOption({"" : txtDefault}, false);
				fieldSelect.empty();
				fieldSelect.addOption({"" : txtDefault}, false);
				fieldSelect.attr("disabled", "disabled")
				fieldSelect.addOption({"" : txtWait}, false);
				functions.SetProps(0);
			},
			success: function(data){
				var options = {};
				$.each(data, function(k, object){
					options[object.id] = object.name;
				});
				functions.AddOptions(fieldSelect, options);
				fieldSelect.removeAttr("disabled").find("option:first").text(txtDefault);
			}
		});
	});
	
	$(".jqField").bind("change", function(){
		$(".jqFieldField").val($(this).find("option:selected").text().replace( /\&amp;/g, '&' ));
		functions.LoadTrainingen($(this).val());
	});
	
	$(".jqTraining").bind("change", function() {
		functions.SetProps($(this).val());
		if (!$(this).hasClass("jqTrainingBrochure") && !$(this).hasClass("jqTrainingTrail") && !$(this).hasClass("jqTrainingGeneral")) {
			functions.LoadStartData($(this).val());
		} else {
			
		}
		
	});
	
	$(".jqPlaats").bind("change", function() {
		var datumSelect = $(".jqDatum");
		var plaatsField = $(".jqPlaatsField");
		var txtDefault = ($(datumSelect).attr("data-default")) ? $(datumSelect).attr("data-default") : "-- selecteer";
		var txtWait = ($(datumSelect).attr("data-wait")) ? $(datumSelect).attr("data-wait") : "-- data ophalen.. ogenblik";
		
		datumSelect.empty();
		datumSelect.addOption({"" : txtDefault}, false);
		var json = jsonPlaatsDatum[$(this).val()];
		plaatsField.val($(this).find("option:selected").text());
		var options = {};
		if (!functions.IsEmpty(json)) {
			$.each(json.data, function(k, object){
				options[object] = object;
			});
			
			functions.AddOptions(datumSelect, options);
		}
	});
	
	$(".jqCourseBrochure").bind("change", function(){
		var id = $(this).val();
		var trainingSelect = $(".jqTraining");
		$(".jqCourseField").val($(this).find("option:selected").text().replace( /\&amp;/g, '&' ));
		
		var txtDefault = ($(this).attr("data-default")) ? $(datumSelect).attr("data-default") : "-- selecteer";
		var txtWait = ($(this).attr("data-wait")) ? $(datumSelect).attr("data-wait") : "-- data ophalen.. ogenblik";
		var txtNoResult = ($(this).attr("data-noresult")) ? $(datumSelect).attr("data-noresult") : "-- geen opleidingen met brochure gevonden.";
		
		$.ajax({
			type: "GET",
			url: "/ajax_gettrainingbrochure.html",
			dataType: 'json',
			data: {
				id: id
			},
			beforeSend: function(){
				trainingSelect.empty();
				trainingSelect.attr("disabled", "disabled");
				trainingSelect.addOption({"" : txtWait}, false);
				functions.SetProps(0);
			},
			success: function(data){
				jsonOpleidingen = data;
				var options = {};
				$.each(data, function(k, object){
					var val = object.id; var txt = object.name;
					options[val] = txt;
				});
				functions.AddOptions(trainingSelect, options);
				trainingSelect.removeAttr("disabled").find("option:first").text(txtDefault);
			},
			complete: function(data) {
				if (trainingSelect.find("option:first").text() != txtDefault){
					trainingSelect.removeAttr("disabled").find("option:first").text(txtNoResult);
				}
			}
		});
	});
	
	$(".jqCourseTrail").bind("change", function(){
		var id = $(this).val();
		var trainingSelect = $(".jqTraining");
		$(".jqCourseField").val($(this).find("option:selected").text().replace( /\&amp;/g, '&' ));
		
		var txtDefault = ($(this).attr("data-default")) ? $(datumSelect).attr("data-default") : "-- selecteer";
		var txtWait = ($(this).attr("data-wait")) ? $(datumSelect).attr("data-wait") : "-- data ophalen.. ogenblik";
		var txtNoResult = ($(this).attr("data-noresult")) ? $(datumSelect).attr("data-noresult") : "-- geen proeflessen gevonden.";
		
		$.ajax({
			type: "GET",
			url: "/ajax_gettrainingtrail.html",
			dataType: 'json',
			data: {
				id: id
			},
			beforeSend: function(){
				trainingSelect.empty();
				trainingSelect.attr("disabled", "disabled");
				trainingSelect.addOption({"" : txtWait}, false);
				functions.SetProps(0);
			},
			success: function(data){
				jsonOpleidingen = data;
				var options = {};
				$.each(data, function(k, object){
					var val = object.id; var txt = object.name;
					options[val] = txt;
				});
				functions.AddOptions(trainingSelect, options);
				trainingSelect.removeAttr("disabled").find("option:first").text(txtDefault);
			},
			complete: function(data) {
				if (trainingSelect.find("option:first").text() != txtDefault){
					trainingSelect.removeAttr("disabled").find("option:first").text(txtNoResult);
				}
			}
		});
	});
	
	$(".jqCourseGeneral").bind("change", function(){
		var id = $(this).val();
		var trainingSelect = $(".jqTraining");
		$(".jqCourseField").val($(this).find("option:selected").text().replace( /\&amp;/g, '&' ));
		
		var txtDefault = ($(this).attr("data-default")) ? $(datumSelect).attr("data-default") : "-- selecteer";
		var txtWait = ($(this).attr("data-wait")) ? $(datumSelect).attr("data-wait") : "-- data ophalen.. ogenblik";
		var txtNoResult = ($(this).attr("data-noresult")) ? $(datumSelect).attr("data-noresult") : "-- geen opleidingen gevonden.";
		
		$.ajax({
			type: "GET",
			url: "/ajax_gettrainingbycourse.html",
			dataType: 'json',
			data: {
				id: id
			},
			beforeSend: function(){
				trainingSelect.empty();
				trainingSelect.attr("disabled", "disabled");
				trainingSelect.addOption({"" : txtWait}, false);
				functions.SetProps(0);
			},
			success: function(data){
				jsonOpleidingen = data;
				var options = {};
				$.each(data, function(k, object){
					var val = object.id; var txt = object.name;
					options[val] = txt;
				});
				functions.AddOptions(trainingSelect, options);
				trainingSelect.removeAttr("disabled").find("option:first").text(txtDefault);
			},
			complete: function(data) {
				if (trainingSelect.find("option:first").text() != "-- selecteer"){
					trainingSelect.removeAttr("disabled").find("option:first").text(txtNoResult);
				}
			}
		});
	});
	
	
	
	
	
	
	
	
	
	
	

    /*** General behaviours ***/
    /*************************/

    /* Browser detection */
    var ie6 = $.browser.msie && $.browser.version < 7;
	
	/* Mobile detection */
	(function(a) { jQuery.browser.mobile = /android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4)) })(navigator.userAgent || navigator.vendor || window.opera);
	
	if(jQuery.browser.mobile && idreams.cookie('mobileSite')=="true" && !document.referrer)
		window.location = "http://m.avansplus.nl";
	if(jQuery.browser.mobile && !idreams.cookie('mobileSite') && document.location.pathname.length <= 1) {
		if(confirm("U bezoekt www.avansplus.nl vanaf een mobiel toestel. Speciaal voor mobiele gebruikers heeft Avans+ de site m.avansplus.nl gemaakt. Wilt u deze site nu bezoeken?")) {
			idreams.cookie('mobileSite',"true", { expires: 7, path: '/', domain: '.avansplus.nl'});
			window.location = "http://m.avansplus.nl";
		} else {
			idreams.cookie('mobileSite',"false", { expires: 7, path: '/', domain: '.avansplus.nl'});
		}
	}
	
    /* PUSHBOX - 18.01.2011 - Marty */

	// vertical alignment of text since IE does not support display:table-cell
	$(".pushboxNav a").vAlign();

	// pushbox
	jQuery('#jqPushbox').each( function(){

		var count = 0,
		hover = false,
		zindexCount = 10,
		bannersWrap = $(this).find(".pushboxPanes"),
		banners = bannersWrap.find("a"),
		oldItem,
		menu = $(this).find(".pushboxNav").eq(0),
		menuItems = menu.find("a"),
		arrow = menu.find(".arrow"),
		arrowPositions = [0, 41, 82, 123, 164, 205],
		pushTimer;
		
		function init(){
			animate();
			startPushTimer();
			
		};
		
		function animate(){
			if(oldItem >= 0){
				// reset previous item
				menuItems.eq(oldItem).removeClass("active");
				if(oldItem !== count){
					banners.eq(oldItem).fadeOut({},500);
				}
			};
			var index = (hover !== false)? hover : count;
			// animate banner image
			banners.eq(index).css("z-index",zindexCount).fadeIn({}, 350);
			// animate arrow
			var newPos = arrowPositions[index] + "px";
			arrow.stop().animate({ top: newPos }, 350);
			// set class on active item
			menuItems.eq(index).addClass("active");
			oldItem = count;
		};
		
		function startPushTimer(){
			pushtimer = setInterval( doNext, 3000); 
		};
		
		function stopPushTimer(){
			clearInterval(pushtimer);
		};
		
		function doNext(){
			if(updateCount()){
				animate();
			};
		}
		
		function updateCount(){
			if(count < banners.length-1){
				count++;
				return true;
			} else {
				count = 0;
				zindexCount++;
				return true;
			};
		};
		
		menuItems.hover( 
			function(){
				stopPushTimer();
				var index = menuItems.index($(this));
				hover = index;
				oldItem = count;
				count = hover;
				animate();
			},
			function(){
				oldItem = hover;
				hover = false;
				startPushTimer();
		});
		
		banners.hover(
			function(){
				stopPushTimer();
			},
			function(){
				startPushTimer();
		});



		init();

	}); 

/* END OF PUSHBOX */
    
    /* Add target attribute on external links */

    $("a[href^='http://']").click(function() {
        if (this.host.indexOf(window.location.hostname) == -1) {
            $(this).attr("target", "_blank");
            _gaq.push(["_trackPageview", $(this).attr("href")]);
        }
    });

    $("a[href^='https://']").click(function() {
        if (this.host.indexOf(window.location.hostname) == -1) {
            $(this).attr("target", "_blank");
            _gaq.push(["_trackPageview", $(this).attr("href")]);
        }
    });

    /*** Visual corrections ***/
    /**************************/

    /* rounded corners */
    $("div.jqRounded").append("<div class='corner tl'></div><div class='corner tl'></div><div class='corner tr'></div><div class='corner br'></div><div class='corner bl'></div>");

    /* no border on last menu item */
    $("ul.globalMenu a:last").css("border", "0");
    /* no border on first and last row item */
    $("div.row:first-child").css("border-top", "0");

    /* ul following p */
    $(".article p + ul").css("margin-top", "-10px");

    /* png transparacy fix for ie6 */
    if (ie6) {
        DD_belatedPNG.fix('div.nav, img.mask');
    }

    /*** Visual enhancements ***/
    /**************************/

    /* table row hover */
    $("table.specialisatie tr").hover(function() {
        $(this).addClass("hover");
    }, function() {
        $(this).removeClass("hover");
    });

    /*** Global behaviours ***/
    /*************************/


    /* Print area */
    $("div.faq a.print")
		.each(
			function() {
			    $(this)
				.click(
					function() {
					    $(this).closest(".jqTopic").printArea();
					}
				);
			}
		);
    // print area



    /*** Specific behaviours ***/
    /*************************/

    /* Mega drop down trigger */
    $("a.navButton")
		.click(
			function(e) {
			    e.stopPropagation();
			    var target = $("div.nav").eq(0);
			    var target_ul = target.find("ul").eq(0);
			    if (target.is(':visible')) {
			        target.animate({ top: "100px" }, 400, "linear", function() { target.hide() })
					.find(".inner").fadeOut("fast");
			    } else {
					//Track menu trigger
			    	_gaq.push(["_trackEvent", "Dropdown opleiding menu", "Menu Klik"]);
					
			        target.show().animate({ top: "125px" }, 400)
					.find(".inner").fadeIn("fast");

			        var navObj = $("div.nav");

			        if (dropdownHeight < navObj.find(".inner > ul ul").height()) {
			            var height = 0;
			            for (i = 0; i < navObj.find(".inner > ul > li > ul").size(); i++) {
			                var obj = navObj.find(".inner > ul > li > ul").get(i);
			                if ($(obj).height() > height) {
			                    height = $(obj).height();
			                }

			            }
			        }
			        else {
			            height = dropdownHeight;
			        }

			        if (height > 0) {
			            navObj.find(".inner").height(height + 10);
			            navObj.find(".inner > ul").height(height);
			            navObj.find(".inner > ul ul").height(height);
			        }

			    }
			}
		);
    // mega drop down trigger

    /* Click outside Mega drop down */
    $("body")
		.click(
			function() {
			    var target = $("div.nav");
			    if (target.is(':visible')) {
			        target.animate({ top: "93px" }, 400, "linear", function() { target.hide() })
					.find(".inner").fadeOut("fast");
			    }
			}
		);
    // click outside mega drop down
	
	var gaTexts;
    /* Mega drop down navigation */
   
    (function() {
        var navObj = $("div.nav");
        navObj.click(function(e) { e.stopPropagation(); });

        var level2;
		
        // first level li's
        // init tab widget (jquery.tools)
        navObj.find(".inner > ul").tabs
			(
				$("div.paneWrap", navObj),
					{
					    tabs: '> li',
					    initialIndex: -1,
					    effect: 'default',
					    current: 'active',
					    onBeforeClick: function() {
					        if (level2) {
					            navObj.find(".inner ul ul li.active").removeClass("active");
					            var api = level2.tabs();
					            // reset the selected index
					            api.click(null);
					        }
					    },
					    onClick: function(o, index) {
					        navObj.find('div.info').hide();
							
							var api = navObj.find(".inner > ul").data("tabs");
							var cur = api.getCurrentTab();
							gaTexts = new Array(cur.find("> a").text());
							
							//Track choice opleidingsrichting
							_gaq.push(["_trackEvent", "Dropdown opleiding menu", "Opleidingsrichting Klik", gaTexts[0]]);
					    }
					}
			);

        // second level li's
        // init tab widget (jquery.tools)
        navObj.find(".inner ul ul").each
			(
				function() {
				    var obj = $(this);
				    var firstLevel = navObj.find(".inner > ul > li");
				    var paneWrapIndex = firstLevel.index(obj.parent());
				    var paneWrap = navObj.find(".paneWrap").eq(paneWrapIndex);
				    obj.tabs
					(
					 	$("div.pane", paneWrap),
							{
							    tabs: '> li',
							    initialIndex: -1,
							    effect: 'default',
							    current: 'active',
							    onBeforeClick: function(i) {
							        navObj.find("div.info").hide();
							        // get the pane to be opened
							        var pane = this.getPanes().eq(i);
							        // if it is empty ..         
							        if (pane.is(":empty")) {
							            // load it with a page specified in the tab's href attribute
							            pane.load(this.getTabs().eq(i).find("a").attr("href") + " .article *");
							        }
							    },
							    onClick: function(i, e) {
							        level2 = obj;
							        if (i !== -1) {
							            navObj.find("div.info").fadeIn();
										if(i != null)
										{
											var api = level2.data("tabs");
											var cur = api.getCurrentTab();
											gaTexts[1] = cur.find("> a").text();
											
											//Track choice opleidingsrichting
											_gaq.push(["_trackEvent", "Dropdown opleiding menu", "Opleidings Klik", gaTexts[0] + " - " + gaTexts[1]]);
										}
							        }
							        //return false;
							    }
							}
					);
				}
			);

    })()
    // mega drop down navigation 


    /* Mega drop down - Redirect filter button */
    $("div.nav a.jqRedirect")
		.click(
			function() {
				//Track button bekijk opleidingen
				_gaq.push("_trackEvent", "Dropdown opleiding menu", "Bekijk opleidingen Klik", gaTexts[0] + " - " + gaTexts[1]);
				//pageTracker._trackEvent("Dropdown opleiding menu", "Bekijk opleidingen Klik", gaTexts[0] + " - " + gaTexts[1] );
				
			    var url = $("div.nav li.active li.active a").attr("rel");
			    window.location.href = url;
			}
		);
    // mega drop down - redirect filter button

    /* init equal height of connected submenu and box */
    equalHeight.checkHeight("col1_1", "col1_2");

    /* Filter toggle */
    $("a.jqFilterToggle").click(function() {
        equalHeight.resetHeight("col1_2"); // TO DO: overgang vloeiender maken
        $(this).parent().toggleClass("active")
		.parent().next(".filter").slideToggle("fast", function() {
		    equalHeight.checkHeight("col1_1", "col1_2"); //TO DO: overgang vloeiender maken
		});
    });
	
	/* Whitepaper formulieruitbreiding */
	$("#formWhitepaper_pensioentraining").click(function(){
		if($(this).attr('checked')){$("#jqExtraQuestions").css('display','block')}
		else{$("#jqExtraQuestions").css('display','none')}
	});
	
	/* Banner buttons fully clickable */
	$('.banner').each(function(){
		if(!($(this).hasClass('vraag')) && !($(this).hasClass('sendafriend-small')) && !($(this).hasClass('uberteaser'))){
			$(this).css('cursor','pointer').click(function(){
				location.href = $(this).find('a').attr('href');
			});
		}
	});
	
	/* Scrollable ankeiler */
	$(".scrollable").each(function(){
		var countScrollableItems = $(this).find(".items div").length;
		if(countScrollableItems > 1){
			$(this).scrollable({ circular: true }).autoscroll({ steps: 1, interval: 6000, autopause: true, autoplay: true }).click(function() {
				$(this).data("scrollable").next();		
			}).navigator();
		}
	});
	
	/* Homepage rows determine last item */
	$('.box.attention.homep .rowP:last').addClass('noBorderBottom');
	
    /*** Overzicht behaviours ***/
    /***********************/
		
	/* Google Button tracking */
	$(".jqGABtn").each(function(){
		$(this).click(function()
		{
			if(checkIDMenuBoven($(this).attr("rel")))
			{
				_gaq.push(["_trackEvent", "Menu boven - Navigatie", "Geklikt "+$(this).text()]);
			}
			if(checkOpleidingBtn($(this)))
			{
				_gaq.push(["_trackEvent", "Knoppen opleiding", "Geklikt "+$(this).text()]);
			}
		});
	});
	
	function checkIDMenuBoven( id )
	{
		//Checking two specific buttons in the global navigation
		if(id == "1033" || id == "8242")
			return true;
		else 
			return false;
	}
	
	function checkOpleidingBtn( btn )
	{
		//Tracking buttons in the mainContent div.
		if($(btn).parents(".mainContent"))
		{
			return true;
		}
		return false;
	}
	
    /* filter box toggle */
    $("#boxfilter").click(function() {
        $("div.filter").slideToggle(100, equalHeight.resetHeight("col1_2"));
        $(this).parent().toggleClass("active");
        equalHeight.resetHeight("col1_2");
    });

    equalHeight.resetHeight("col1_2");
	
	/* EduHub correction */
	$(".eduhub [id^='eduhub-widget-button']").css('cssText','position: absolute ! important; bottom: 0 !important; _bottom: 30px; font-size: 13px ! important; letter-spacing: 0pt ! important; font-family: Arial,sans-serif ! important; clear: left ! important; z-index: 100000 ! important; margin: 0pt 0pt 10px 10px ! important; color: rgb(0, 55, 104) ! important; text-decoration: none ! important; display: block ! important; height: 31px ! important; line-height: 30px ! important; text-align: center ! important; width: 166px ! important; background-image: url("http://www.eduhub.nl/images/widget/eduhub-widget-components.png") ! important; background-repeat: no-repeat ! important; background-position: 0pt 0pt;');
	
	/* Zegel Amsterdam IE6 */
	if(ie6){ $('.box.jqTabs').css('position','relative'); }
	
    /*** Form behaviours ***/
    /***********************/
	$("input:radio.jqAnders").click(function() {
		$("input:text.jqAnders").val("");
	});
	$("input:text.jqAnders").focus(function(){
		$("input:radio.jqAnders").eq(3).attr("checked", true);
	})

	/* RadioButtons disabled */
	$(".jqChoise input:radio").click( function() {
		$(this).parent().parent().find("input:radio").attr("disabled",true);
		$(this).parent().parent().parent().find("." + $(this).parent().attr("class") + " input:radio").attr("disabled",true);
	});	
		
	$(".jqChoise #reset").click( function() {
		$(".jqChoise input").attr("disabled",false);
		$(".jqChoise input").attr("checked",false);
	});
	

	$(".jqChoise .jqRadio").each( function(){
		$(this).click( function(){
			var radioValue = $(this).attr('value');			
			$(this).parent().parent().find("input.jqRadioField").attr("value", radioValue);
		});
	});

    /* onChange && onAjaxComplete set inputfields */
    $(".jqUpdate").ajaxComplete(function() {
        updateHidden($(this).attr("id"), false);
    })
    $("select.jqUpdate").change(function() {
        updateHidden($(this).attr("id"), false);
    });
    $(".jqUpdateBrochure").change(function() {
        updateBrochureCode($(this).attr("id"));
    });
    $(".jqUpdateBrochure").ajaxComplete(function() {
        updateBrochureCode($(this).attr("id"));
    })
    $("select.jqUpdateValues").change(function() {
        updateHidden($(this).attr("id"), true);
    });
	$(".jqUpdateSelectOpleiding").change(function() {
        updateOpleidingField($(this).attr("id"));
    })
  
    $("select.jqVakgebied").change(function() {
        pageid = $(this).parents("div.fieldWrap").find(".jqPage").val();
        $(this).find("option:selected").each(function() {
            values = $(this).val().split(";");
        });
        id = values[1];
        code = values[0];

        updateHidden($(this).attr("id"), true, ";", 0);

        getFunctions(id, pageid);
    });
		
	/******************************************
	******Toggle obliged with radiubutton****** 
	******NOT REUSABLE form specific***********
	*******************************************/
	$("$.jqToggleRadio input").change(function(){
		if($(this).val() == "zakelijk")
		{
			if( $(this).parents("form").find(".jqValidate").val().indexOf("formBrochure_organisatie") < 0 )
			{
				var values = $(this).parents("form").find(".jqValidate").val().split(";");
				values[0] += ",formBrochure_organisatie";
				$(this).parents("form").find(".jqValidate").val(values[0]+";"+values[1]);
			}
		}
		else
		{
			if( $(this).parents("form").find(".jqValidate").val().indexOf("formBrochure_organisatie") > -1 )
			{
				var newval = $(this).parents("form").find(".jqValidate").val().replace(",formBrochure_organisatie", "");
				$(this).parents("form").find(".jqValidate").val(newval);
				$(this).parents("form").find("#formBrochure_organisatie").unbind("keyup click");
				$(this).parents("form").find("#formBrochure_organisatie").removeClass("notValid");
			}
		}
		
	})

    /* Toggle initial values on input fields */
    $("input.jqValue")
		.focus(
			function() {
			    if ($(this).val() == $(this).attr("title")) {
			        $(this).val("");
			    }
			}
		).blur(
			function() {
			    if ($(this).val().length < 1) {
			        $(this).val($(this).attr("title"));
			    }
			}
		);
    // toggle initial values

    /* FORM DATUM SELECTBOXES */

    $(".jqDatumDD").change(function() { syncDate(); });
    $(".jqDatumMM").change(function() { syncDate(); });
    $(".jqDatumJJJJ").change(function() { syncDate(); });
    function syncDate() {
        $(".jqGeboorteDatum").val($(".jqDatumDD").val() + "-" + $(".jqDatumMM").val() + "-" + $(".jqDatumJJJJ").val());
    }
	
	$(".jqAankomstDatumDD").change(function() { syncAankomstDate(); });
    $(".jqAankomstDatumMM").change(function() { syncAankomstDate(); });
    $(".jqAankomstDatumJJJJ").change(function() { syncAankomstDate(); });
    function syncAankomstDate() {
        $(".jqAankomstDatum").val($(".jqAankomstDatumDD").val() + "-" + $(".jqAankomstDatumMM").val() + "-" + $(".jqAankomstDatumJJJJ").val());
    }
	
	$(".jqVertrekDatumDD").change(function() { syncVertrekDate(); });
    $(".jqVertrekDatumMM").change(function() { syncVertrekDate(); });
    $(".jqVertrekDatumJJJJ").change(function() { syncVertrekDate(); });
    function syncVertrekDate() {
        $(".jqVertrekDatum").val($(".jqVertrekDatumDD").val() + "-" + $(".jqVertrekDatumMM").val() + "-" + $(".jqVertrekDatumJJJJ").val());
    }

    /* /FORM DATUM SELECTBOXES */

    /* FORM file upload restrictions */
    $(".jqFile").each(function() {
        var types = $(this).attr("rel").split(",");
        $(this).change(function() {
            var extension = $(this).val().split(".");
            var valid = false;
            for (var i = 0; i < types.length; i++) {
                if (types[i] == extension[1].toString()) {
                    valid = true;
                }
            }

            if (!valid) {
                $(this).val("");
                showErrorMsg($(this), types);
            }
            else {
                removeErrorMsg($(this));
            }
        });

    });

    /* FORM VALIDATION Trigger */
    $(".jqValidate").each(
			function() {
			    var paramsObj = $(this);

			    $(this).parents("form").submit(function() {

			        var params = paramsObj.attr("value").split(/\s*;\s*/);


			        if (validateForm($(this), params[0], params[1], params[2]) === false) {

			            return false;
			        }
			        else 
			        {
			            checkECommerce($(this));
			            
			            return true;
			        }

			    });
			});
    
    function checkECommerce(obj)
    {
    	if($(obj).hasClass("jqECommerce"))
    	{
			var sku = $(".jqOpleidingID").val();
    		var id = sku + "-" + guidGenerator();
    		var price = $(".jqOpleidingInvestering").val();
    		var tax = (Math.floor(price * 0.198 * 100)/100).toString();
    		var training = $(".jqOpleidingName").val();
    		var category = $(".jqOpleidingCourse").val();
    		
    		_gaq.push(["_addTrans", id, "", price, tax, "0", "", "", ""]);
    		_gaq.push(["_addItem", id, sku, training, category, price, "1"]);
    		_gaq.push(["_trackTrans"]);
    	}
    }
	
	function guidGenerator() 
	{
		var S4 = function() 
		{
		   return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
		};
		return (S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
	}


    // form validation trigger
    /* Google form tracking */
    $("form.jqGAForm").each(function() {
        var formName = $(this).attr("id").replace("form", "") + " Formulier";
        /* send event to GA for counting total views of this page
        * we don't do this at unload event because now we save one request for other fields (on the unload event we have a limit number of request we could send to GA)*/
        _gaq.push(["_trackEvent", formName, "Totaal aantal bezoekers"]);
        $(window).unload(function() {
            //get the required inputfields
            var required;
            //if the form id is formInschrijven we'll need to replace these required fields as well
            if ($(".jqGAForm").attr("id") == "formInschrijven") {
                //we don't use it in the validation? .replace(/formInschrijven_startdatum/, "formfield_startdatum")
                required = $(".jqValidate").val().replace(/form_/gi, "formfield_").replace(/formInschrijven_plaats/, "formfield_plaats").split(/\s*,\s*/);
            }
            else {
                required = $(".jqValidate").val().replace(/form_/gi, "formfield_").split(/\s*,\s*/);
            }
            //we'll validate the form and the inputs which are empty or invalid will be send to GA.
            //This way the client could see which fields are an issue for the user.
            /* var action = "n/a";
            var label = "n/a";*/
            var formFieldName = "";
            var parents = "Parents: ";
            //check for empty fields
            $("form.jqGAForm input").each(function() {
                //if opleiding & opleidingsrichting are available get the values for GA
                var req = false;
                for (var i = 0; i < required.length; i++) {
                    if ($(this).attr("id") == required[i]) {
                        req = true;
                        break;
                    }
                }
                if (req) {
                    if ($(this).val() == "" || $(this).val() == null || $(this).val() == "-- selecteer") {
                        //extra check for invisble parts of the form if invisible we dont need to send them to GA
                        if ($(this).parents("div.hidden").attr("class") == undefined || $(this).parents("div.hidden").css("display") == "block") {
                            formFieldName = $(this).attr("name");
                            //send empty fields to GA
                            _gaq.push("_trackEvent", formName, formFieldName);
                        }
                    }
                }
            });
        });
    });
// Action Form validation trigger
	$("form.jqActionForm").each(function()
	{
	    $(this).submit(function(evt)
	    {
	        var params = $(this).find("input.jqValidateActionForm").val().split(";");
	        var optionalParams = $(this).find("input.jqValidateActionFormOptional").val().split(";");
	        var optionalFields = optionalParams[0].split(",");
	        var i = 0;

	        while (i < optionalFields.length)
	        {
	            var field = document.getElementById(optionalFields[i]);
	            if (field != null && field.value != "")
	            {
	                if (params[0] != "") { params[0] += ","; }
	                params[0] += optionalParams[1];
	                i = optionalFields.length;
	            }
	            else
	            {
	                i++;
	            }
	        }

	        return validateForm($(this), params[0], params[1], null);
	    });
	});

    /* Show/Hide related form fields */
    $("input.jqShowBetaling:checked").each(
			function() {
			    if ($(this).hasClass("jqOn")) $("div.jqShowBetaling").show();
			}
		);
    $("input.jqShowFactuur:checked").each(
			function() {
			    if ($(this).hasClass("jqOn")) $("div.jqShowFactuur").show();
			}
		);
    $("input.jqShowEmail:checked").each(
			function() {
			    $("div.jqShowEmail").show();
			}
		);


    $("input.jqShowBetaling")
		.click(
			function() {
			    var target = $("div.jqShowBetaling");
			    var mainValidationObj = $(this).parents("form").find(".jqValidate");
			    var validationString = target.find("input.jqAddValidate").val();

			    if ($(this).is(":checked") && $(this).hasClass("jqOn")) {
			        target.show();
			        addToValidation(validationString, mainValidationObj);
			    } else {
			        target.hide();
			        removeFromValidation(validationString, mainValidationObj);
			        // hide nested level + reset + remove from validation by triggering click event
			        $("input.jqShowFactuur").click();
			    }
			});

    $("input.jqShowFactuur")
		.click(
			function() {
			    var target = $("div.jqShowFactuur");
			    var mainValidationObj = $(this).parents("form").find(".jqValidate");
			    var validationString = target.find("input.jqAddValidate").val();

			    if ($(this).is(":checked") && $(this).hasClass("jqOn")) {
			        $("div.jqShowFactuur").show();
			        addToValidation(validationString, mainValidationObj);
			    } else {
			        $("div.jqShowFactuur").hide();
			        removeFromValidation(validationString, mainValidationObj);
			    }
			});

    $("input.jqShowEmail")
		.click(
			function() {
			    var target = $("div.jqShowEmail");
			    var mainValidationObj = $(this).parents("form").find(".jqValidate");
			    var validationString = target.find("input");

			    if ($(this).is(":checked")) {
			        target.show();
			        addToValidation(validationString, mainValidationObj);
			    } else {
			        target.hide();
			        removeFromValidation(validationString, mainValidationObj);
			    }

			});
    // Show/Hide related form fields 		
    /* haal adres op */

    $(".jqWS").each(function() {
        var params = $(this).attr("value").split(/\s*;\s*/);
        params[0] = params[0].split(",");
        params[1] = params[1].split(",");
        $("input[id=" + params[1][0] + "],input[id=" + params[1][1] + "]").attr("readonly", "readonly").addClass("readonly");
        $("input[id=" + params[0][0] + "],input[id=" + params[0][1] + "]").blur(function() {
            var pcnum = "";
            if ($("#" + params[0][0]).val().replace(" ", "") != "" && $("#" + params[0][1]).val().replace(" ", "") != "") {
                pcnum = $("#" + params[0][0]).val().replace(" ", "") + $("#" + params[0][1]).val().replace(" ", "");
            }
            if (pcnum) {
                $("#" + params[1][0]).val("Adres wordt opgehaald, ogenblik...");
                $.ajax({
                    type: "GET",
                    url: "/ajax.aspx",
                    cache: false,
                    data: { action: "getAddress", pcnum: pcnum },
                    async: true,
                    success: function(result) {
                        if (result != "fout") {
                            result = result.split("|");
                            $("#" + params[1][0]).val(result[0]);
                            $("#" + params[1][1]).val(result[1]);
                            $("input[id=" + params[1][0] + "],input[id=" + params[1][1] + "]").attr("readonly", "readonly").addClass("readonly");
                        }
                        else {
                            $("input[id=" + params[1][0] + "],input[id=" + params[1][1] + "]").removeAttr("readonly").val("").removeClass("readonly");
                        }
                    }
                });
            }
        });
    });



    // niveau filter
    $("input[class=nvcheck]").click(function() {
        var nv = this.id.split("nvcheck"); nv = nv[1];
        $(".niveau" + nv).toggle();
        setFilter(true);
    });
    $("input[class=filtercheck]").click(function() {
		//Checkbox in the filter lets track this with GA
		var id = $(this).attr("id");
		var name;
		var state = $(this).attr("checked");
		$(this).parent().find("label").each(function()
		{
			if($(this).attr("for") == id)
			{
				name = $(this).text();	
			}
		});
		if(state)state = "aan"; else state = "uit";
		_gaq.push(["_trackEvent", "Filter opleiding", "Geklikt: "+name, state+" gezet"]);
		
        $("input[class=nvcheck]").each(function() {
            $(this).removeAttr("checked");
            var nv = this.id.split("nvcheck"); nv = nv[1];
            $(".niveau" + nv).hide();
        });
        $("input[class=filtercheck]:checked").each(function() {
            var nv = this.id.split("filtercheck"); nv = nv[1];
            $("input#nvcheck" + nv).attr("checked", "checked");
            $(".niveau" + nv).show();
        });
        setFilter(true);
        equalHeight.resetHeight("col1_2");
    });
    setFilter(false);



    /*** Table Sorter ***/
    /***********************/

    $(".specialisatie:not('.nonsort')").tablesorter({
        headers: {
            2: { sorter: false },
            7: { sorter: false }
        }
    });

    $(".specialisatie:not('.nonsort')").tablesorter({ sortList: [[0, 0]] });

    $(".sort a.button").click(function() {
        $(".specialisatie").tablesorter({ sortList: [[$(this).attr("name"), 0]] });
        $(".sort a.button").each(function() {
            $(this).removeClass("active");
        });
        $(this).addClass("active");
    });



    /* TABS */
   
   $("div.jqTabs .tabs").tabs("div.jqTabs div.pane", { current: 'active' });
   

    //Track the tabs in opleidingen details
    $("div.jqGA").each(function() {
        //Initializing tabs let's trace the first tab as nobody will click it....
        var opleiding;
        var opleidingsrichting;
        var action;
        var tabname;
        //find the opleiding & opleidingsrichting
        $(this).parents().find(".breadcrumbs").each(function() {
            opleiding = $(this).find("a:last").text();
            opleidingsrichting = $(this).find("a").slice(3, 4).text();
            action = opleidingsrichting + " - " + opleiding;
        });
        tabname = $(this).find(".tabs a:first").text();
        _gaq.push(["_trackEvent", "Bezochte tabjes - opleidingen", action, tabname]);

        $(this).find(".tabs a").click(function() {
            tabname = $(this).text();
            _gaq.push(["_trackEvent", "Bezochte tabjes - opleidingen", action, tabname]);
        })
    });

    /* FAQ accordion */
    // initialy hide panes
    $("div.faq div.pane").hide();
    // init tab plugin
    $("div.faq").tabs("div.faq div.pane", { tabs: 'h3', effect: 'slide', current: 'active' });

    /* POPUP */
    $("a.jqPopup").click(function() {
		    var cover = $("div.popupCover");
			var target = $("div.jqPopup");
			var title = $(this).attr("title");
			var args = $.evalJSON( $(this).attr("rel") );
			target.find(".bar h3").text(title);
			
			var flashvars = false;
			var params = {
				allowfullscreen: "true",
				allowscriptacces: "always",
				bgcolor: args.params.bgcolor,
				wmode: args.params.wmode,
				flashvars: "file="+args.flashvars.file+"&image="+args.flashvars.image+"&plugins=gapro-1&gapro.accountid="+gaAccount
			};
			var attributes = {};
						
			swfobject.embedSWF(args.swf, 'popup_flash_content', args.width, args.height, args.version, args.express, flashvars, params, attributes, checkSize );

		    function checkSize(e) {

		        if (ie6) {
		            cover.css("height", $("div.stage").height());
		            target.css("top", target.offset().top + parseInt($("#" + e.id).attr("height")));
		        }

		    }

		    cover.show();
		    target.show();
		    return false;
		});

    $(".popupCover").add("div.jqPopup a.close").click(
		function() {
		    $("div.popupCover").hide();
		    $("div.jqPopup").hide().find(".body").html("<div id='popup_flash_content'></div>");
		});

	/* Function for creating the random tagcloud */
	$("li.jqTagCloud").each(function(){
		var textSize = Math.floor(Math.random()*4);
		if(textSize==0){textSize=1};
		$(this).addClass("size-"+textSize);
	});
	
	/* Check checkboxes in forms */
	$(".jqCheckboxField").val("");
    $(".jqCheckbox").click(function() {
        $(".jqCheckboxField").val("");
        $(".jqCheckbox:checked").each(function() {
            $(".jqCheckboxField").val("1");
        });
    });
	
	//on pageload
    $(".jqCheckbox:checked").each(function() {
        $(".jqCheckboxField").val("1");
    });
	
	
	/* Slide open intro */
	$(".jqSlideOpen").each(function(){
		var container = $(this).find(".slideOpen");		
		var maskHeight = container.height();
		var height = $(this).find(".innerContent").height();
		var realHeight = height + "px";
		$(".jqOpen").hide();
		if( height > maskHeight ){			
			$(".jqOpen").show();
			$(".jqOpen").click(function(){
				if($(this).hasClass("close")){
					container.animate({				
						height: maskHeight
					}, 1000, function() {
						// Animation complete.
					});		
					$(this).html("Lees verder").removeClass("close");					
				}			
				else {
					$(this).html("Sluiten").addClass("close");
					container.animate({				
						height: realHeight
					  }, 1000, function() {
						// Animation complete.
					  });
				}
			
			});
		}
	
	});
	
	
	/* show/hide fieldWrap in form */
	$(".jqHiddenFieldWrap").each(function(){
		var hiddenField = $(this).find(".jqHiddenField");
		var btnShow = $(this).find(".jqShow");
		var btnHide = $(this).find(".jqHide");
		
		hiddenField.hide();
		
		btnShow.click(function(){
			hiddenField.show();
		});
		
		btnHide.click(function(){
			hiddenField.hide();
		});
	});
	
	
}); 

/* Equal height of connected submenu and box */ 
equalHeight = {

	resetHeight: function(id2){
		$("#"+id2).css("height","auto");
	},

	updateCover: function(h,c){
		if (h)h = h - 3;
		if (c === "sameHeight") {
			$("div.jqCover").css("height", h + "px").css("width", "15px").addClass("sameHeight");
		}
		else {
			$("div.jqCover").css("height", h + "px").css("width", "14px").removeClass("sameHeight");
		}
	},

	checkHeight: function(id1,id2){
		var obj1 = $("#"+id1);
		var obj2 = $("#"+id2);
		var obj1h = Math.ceil(obj1.height()/50)*50; //obj1.height();
		var obj2h = Math.ceil(obj2.height()/50)*50; //obj2.height();
		
		if (obj2h > obj1h)
		{
			obj1.css("height", obj1h + "px");
			obj2.css("min-height", obj1h + "px");
			this.updateCover(obj1.height(),"");
		}
		else
		{
			obj1.css("height", obj1h + "px");
			obj2.css("min-height", obj1h-2 + "px");
			this.updateCover(obj1h,"sameHeight");
		}
		

	}
	

};

Array.prototype.contains = function(element) 
{
	for (var i = 0; i < this.length; i++) 
	{
		if (this[i] == element) 
		{
			return true;
		}
}
	return false;
}

jQuery.fn.fadeToggle = function(speed, easing, callback) 
{ 
   return this.animate({opacity: 'toggle'}, speed, easing, callback); 
}

function setFilter(save)
{
	var arrChk = [];
	
	
	if (!save)
	{
		var filter = getFilter().split(",");
		if (!(filter[0] > 0)) { $("div.filter").hide(); $("#boxfilter").parent().removeClass("active"); equalHeight.checkHeight("col1_1","col1_2"); } // toggle filter box
		$("input[class=nvcheck]").each(function(){
			var nv = this.id.split("nvcheck"); nv = nv[1];
			if (filter[0] != 0)
			{
				if (filter.contains(nv))
				{
					this.checked = true;
					$("#filtercheck" + nv).attr("checked", "checked");
					$(".niveau" + nv).show();
				}
				else
				{
					this.checked = false;
					$("#filtercheck" + nv).removeAttr("checked");
					$(".niveau" + nv).hide();
				}
			}
			else
			{
				this.checked = true;
				$(".niveau" + nv).show();
			}
		});
	}
	$("input[class=filtercheck]").each(function(){
		$(this).removeAttr("checked");
	});
	
	$("input[class=nvcheck]:checked").each(function(){
		var nv = this.id.split("nvcheck"); nv = nv[1];
		$("input#filtercheck" + nv).attr("checked", "checked");
		arrChk.push(nv);
	});
	
	$(".row .set").each(function(){
		var count = 0;
		var vgcount = 0;
		var butmore = $(this).find("a.iconDocs").size();
		$(this).find("span[id^=vg]").each(function(){
			var id = this.id.split("vg"); id = id[1];
			var total = 0;
			
			for (i=0;i < arrChk.length;i++)
			{
				var val = eval("n" + id + "_" + arrChk[i]);
				total += val;
			}
			
			if (total != 0)
			{
				count++;
				if (count > amountvg && butmore > 0)
				{
					$("#vg"+id).text(total).parent().parent().hide();
					vgcount++;
				}
				else
				{
					$("#vg"+id).text(total).parent().parent().fadeIn(100);
				}
				if (vgcount == tresholdvg)
				{
					$("#vg"+id).text(total).parent().parent().fadeIn(100);
				}
			}
			else
			{
				if (!save) { $("#vg"+id).text(total).parent().parent().hide(); }
				else { $("#vg"+id).parent().parent().fadeOut(200, function(){$("#vg"+id).text(total);}); }
			}

		});
		
		if (count > amountvg && butmore > 0 && vgcount > tresholdvg)
		{
			$(this).find("a.iconDocs").fadeIn(200).html("<em>"+vgcount+" meer vakgebieden</em>").click(function(){
				$(this).hide();																												
				$(this).parent().find("span[id^=vg]").each(function(){
					var id = this.id.split("vg"); id = id[1];
					if ($("#vg"+id).text() != 0)
					{
						$("#vg"+id).parent().parent().fadeIn(100);
					}
				})
			});
		}
		else
		{
			$(this).find("a.iconDocs").hide();
		}
	});	
	if (save) { saveFilter(arrChk); }
}

function deleteOpleiding(id)
{
	$("tr#bekekenopleiding" + id).hide();
	$.ajax({
		type: "GET",
		url: "/ajax_deleteviews.html",
		cache: false,
		data: { id: id },
		async: false,
		success: function(){ $("#numBekekenOpleidingen").text($("#numBekekenOpleidingen").text()-1); }
	});
}

function saveFilter(arrid)
{
	$.ajax({
		type: "GET",
		url: "/ajax_savefilter.html",
		cache: false,
		data: { nv: arrid },
		async: false
	});
}

function getFilter()
{
	var output = $.ajax({
		type: "GET",
		url: "/ajax_getfilter.html",
		cache: false,
		async: false
	}).responseText;
	return output;
}



function getOpleidingenMeeloopdag(id,active,field)
{
	id = id.split("_");
	id = id[0];
	$.ajax({
		type: "GET",
		url: "/ajax.aspx",
		cache: false,
		data: { action: "getOpleidingenMeeloopdag", id: id, active: active, template: "opleidingen: detail" },
		async: false,
		success: function(result){
			$("#" + field).html(result);
		}
	});
}




/* ADD TO VALIDATION ON DEMAND */
function addToValidation(obj,validationObj) 
{
	// add single obj or string
	var stringToAdd = (typeof obj === 'string')? obj : obj.attr("id");
	// check if obj is already added
	if(validationObj.val().indexOf(stringToAdd) != -1) return;
	// add to validation
	var validationString = validationObj.val();
	validationString = validationString.replace(";",","+stringToAdd+";");
	validationObj.val(validationString);
};

function removeFromValidation(obj,validationObj) 
{
	// add single obj or string
	var stringToRemove = (typeof obj === 'string')? obj : obj.attr("id");
	// check if obj is present
	if(validationObj.val().indexOf(stringToRemove) == -1) return;
	var validationString = validationObj.val();
	validationString = validationString.replace(","+stringToRemove,"");
	validationObj.val(validationString);
};

// add to validation on demand

/* FORM VALIDATION */
function validateDreamBoxForm() {
	var form = $(".jsDreamBoxForm");
	var params = $(".jqValidate").val().split(";");
	return validateForm(form,params[0],params[1],params[2]);
}

function validateForm(frmObj,required,msg,echo){
	var emailfilter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	var telefoonfilter = /^([0-9-+]{5})/;
	//var postcodefilter = /^[1-9][0-9]{3}\s?[a-zA-Z]{2}$/;
	var postcodefilter = /^([0-9-a-zA-Z]{4})/;
	var datefilter = /^([0-9]{2})-([0-9]{2})-([0-9]{4})$/;
	var errorFields = '';

	var requiredFields = required.split (/\s*,\s*/);
	
	for(var i=0;i<requiredFields.length;i++){
		
		var fldObj = frmObj.find("#"+requiredFields[i])[0];
		
		function hasErrors(obj){
			if(obj.type != 'checkbox' && obj.value == '') return true;
			else if(obj.type != 'checkbox' && obj.value == obj.title) return true;
			else if(obj.type == 'checkbox' && obj.checked == false) return true;
			else if(obj.name.toLowerCase().indexOf("e-mailadres") != -1 && !emailfilter.test(obj.value)) return true;
			else if(obj.name.toLowerCase().indexOf("e-mail") != -1 && !emailfilter.test(obj.value)) return true;
			else if(obj.name.toLowerCase().indexOf("email") != -1 && !emailfilter.test(obj.value)) return true;
			else if(obj.name == "Geboortedatum" && !datefilter.test(obj.value)) return true;
			else if((obj.name.toLowerCase().indexOf("telefoonnummer") != -1 || obj.name == "Mobiel") && !telefoonfilter.test(obj.value)) return true;
			else if(obj.name.toLowerCase().indexOf("postcode") != -1 && !postcodefilter.test(obj.value)) return true;
			//else if(obj.name.toLowerCase().indexOf("postcode") != -1) return true;
			else if(obj.name.indexOf("Herhaal") != -1 && notSame(obj)) return true;
			else if(obj.value.indexOf("<") != -1) return true;
			else if(obj.value.indexOf("--") != -1) return true;
			else return false;
		}

		function notSame(obj){
			if(obj.value != $(obj).parent().prev().find("input").val())	return true;
		}
		
		if(hasErrors(fldObj)){
			var name = fldObj.getAttribute("title");
		    if (name == null || name == "") { name = fldObj.getAttribute("name"); }
			errorFields += name.replace("Select", "") + ", ";

			$(fldObj).addClass("notValid").parent().addClass("notValid");
			
			// Bind key up functionality on input and textarea
			$(fldObj).not("select").not(":checkbox").bind("keyup click", function(){
				// re-validate
				if(!hasErrors(this)) $(this).removeClass("notValid");
				else $(this).addClass("notValid");
			});
			
			// Bind change and keyup functionality on selectboxes
			$(fldObj).not("input:not(:checked)").not("textarea").bind("change keyup", function(){
				// re-validate
				if(!hasErrors(this)) $(this).removeClass("notValid");
				else $(this).addClass("notValid");
			});
			
			// Bind click functionality on checkbox
			$(fldObj).filter("input:checkbox").bind("click", function(){
				// re-validate
				if($(this).is(":checked")) $(this).removeClass("notValid");
				else $(this).addClass("notValid");
			});
			

		}
	};

	// Handle error message
	if(errorFields != ''){
		errorFields = errorFields.substring(-1,errorFields.length-2) + ".";
		frmObj.find("div.notValidMsg").remove();
		var errors = (echo && echo === "noEcho")? "" : " "+errorFields;
		errors = (errors.length > 129)? errors.substring(0,129)+"..." : errors;
		frmObj.find("input.submit").prev().before("<div class='notValidMsg'><p>"+ msg +"<strong>"+ errors +"</strong></p></div>").prev("div.notValidMsg").hide().slideDown();
		return false;
	};

}


function searchform(obj)
{
	if(document.getElementById(obj).value!=document.getElementById(obj).title && document.getElementById(obj).value != '') { return true; } else { return false; }
}

function updateHidden( _id, valToVal, splitter, index ) 
{
	var id = "#"+_id;
	var re = /formInschrijven|form/ig;
	var inputID = id.replace(re, "formfield");
	
	if(!valToVal)
	{
	    $(id).parents().find(inputID).val($(id).selectedTexts());
	}
	else {
	    $(id).find("option:selected").each(function() {
	        if (splitter != undefined && splitter != "") {
	            var values = $(id).val().split(splitter);
	            $(id).parents().find(inputID).val(values[index]);
	        }
	        else {
	            $(id).parents().find(inputID).val($(id).val());
	        }
	    });
	}
}

function removeErrorMsg( obj )
{
	$(obj).removeClass("notValid");
	
	/* we can't remove this because when the user has already pressed submit the box will be removed as well */
	/*var frmObj = $(obj).parents("form");
	frmObj.find("div.notValidMsg").slideUp( '400', function(){ $(this).remove() } );*/
}
 
function showErrorMsg( obj, types ) 
{
	$(obj).addClass("notValid");
	
	var frmObj = $(obj).parents("form");
		
	frmObj.find("div.notValidMsg").remove();
	
	var msg = "U dient een van de volgende bestanden te selecteren: <br/>";
	for(var i = 0; i < types.length; i++)
	{
		msg += "." + types[i] + ", ";	
	}
	frmObj.find("input.submit").prev().before("<div class='notValidMsg'><p>"+ msg +"</p></div>")
	.prev("div.notValidMsg").hide().slideDown();
}


// form validation

function getFunctions(id, pageid)
{
	$.ajax({
		type: "GET",
		url: "/"+pageid+"/vakgebied-selector.html?id="+id,
		cache: false,
		async: true,
		success: function(result){
			$(".jqFunctie").html(result);
		}
	});
}

function updateBrochureCode( _id )
{
	var id = "#formfield_brochurecode";
	var id2 = "#formfield_opleidingid";
	var brochureCode;
	var opleidingID;
	
	$("#"+_id).find("option:selected").each(function(){
		var values = $(this).val().split("_");
		brochureCode = values[2];
		opleidingID = values[0];
	})
	
	$(id).val( brochureCode );
	$(id2).val( opleidingID );
}

function updateOpleidingField(_id)
{
	var id = "#formfield_opleiding";
	var id2 = "#formfield_opleidingid";
	var opleiding;
	var opleidingID;
	
	$("#"+_id).find("option:selected").each(function(){
		var values = $(this).val().split("_");
		opleiding = (values[1])?values[1]:"";
		opleidingID = (values[0])?values[0]:"";
	})
	
	$(id).val( opleiding );
	$(id2).val( opleidingID );
}



