var addthis_disable_flash = true;

$(function() {
	$("#gradient, #shadow, #crumb-lang li a").ifixpng();
	$.localScroll();
	
	var focus;
	
	$('#zoek').hover(function() {
		$('#zoek-bericht').fadeIn(250);
	}, function() {
		if (!focus) $('#zoek-bericht').fadeOut(250);
	});
	
	$('#zoeken').focus(function() {
		if (this.value == $(this).attr('defaultValue')) {
			this.value = '';
		}
		
		$('#zoek-bericht').fadeIn(250);
		focus = true;
	});
	
	$('#zoeken').blur(function() {
		if ($.trim(this.value) == '') {
			this.value = $(this).attr('defaultValue');
		}
		
		$('#zoek-bericht').fadeOut(200);
		focus = false;
	});
	
	$('#zoek-bericht a').click(function() {
		if ($('#zoeken').val() && $('#zoeken').val() != "Zoeken...") $('#zoek').submit();
	});
	
	$('#zoekoptions').find('select').change(function() {
		$('#zoek2').attr('method','post').submit();
	}).end().find('input:not("[type=submit]")').click(function() {
		$('#zoek2').attr('method','post').submit();
	});
	
	$('#zoek2').find('[type=submit]').remove().end().submit(function() {
		if (this.method.match(/post/i)) {
			$(this).find('[type=text],[type=hidden]').removeAttr('name');
			// alert('post');
		} else {
			$('#zoekoptions').find('select,input').removeAttr('name');
		}	
	});

	
	$('#content .subp:not(".select")').hide();
	$('#page-programmas .subp').show();

	
	$('#home-actueel').actueelSlide();
	
	
	$('#home-pki .pki').colHeight();
	
	$('#home-themas .thema').colHeight();
	
	$('#news-cat').hide().after('<br />').prev().find('a').click(function() {
		$('#news-cat').slideToggle();
		return false;
	});
	
	
	$('a[href=#]').click(function() { return false; });
	
	$('a[href$=.pdf]').addClass('pdf').attr("rel","external");
	
	// $('a[href='+document.location.pathname+']').click(function() { return false; });
	
	$("a[href^='http://']:not([href*="+location.host+"])").attr("rel","external");
	$("a[rel=external]").attr("target","_blank").addClass('external').each(function(i) {
		var title = $(this).attr("title") ? $(this).attr("title") : $('img', this).attr("title");
		title = $.trim(title) ? $.trim(title) : $.trim($(this).text());
		if (title) $(this).attr("title", title + " (Externe link)");
		else $(this).attr("title", "Externe link");
	}).filter(":has(img)").removeClass('external').removeClass('pdf');
	
	$('.date').find('.external').removeClass('external');
	
	
	$('a[rel*=lightbox]').lightBox();

	
	$('#acties').show();

	reactiesysteem = '<ul id="actiemenu">';
	reactiesysteem += '<li id="actie_reactie"><a href="#">Stuur een reactie naar ITpreneurs</a></li>';
	reactiesysteem += '<li id="actie_door"><a href="#">Doorsturen naar een collega</a></li>';
	if (!ie6()) {
		reactiesysteem += '<li id="actie_print"><a href="#">Print dit artikel</a></li>';
		reactiesysteem += '<li id="actie_abo"><a href="#">RSS feed van de laatste artikelen</a></li> </ul>';
	}
	reactiesysteem += '</ul>';
	
	$('#actiemenu').replaceWith(reactiesysteem);

	$('#actiemenu')
	.find('#actie_reactie a').click(function() {
		$('#actiemenu').hide();
		$('#reactie').slideDown(function() {
			$(this).find('input:blank:first').focus();
		});
		return false;
	}).end()
	.find('#actie_door a').click(function() {
		$('#actiemenu').hide();
		$('#doorsturen').slideDown(function() {
			$(this).find('input:blank:first').focus();
		});
		return false;
	}).end()
	.find('#actie_print a').click(function() {
		window.print();
		return false;
	}).end()
	.find('#actie_abo a').click(function() {
		window.open('http://www.itpreneurs.nl/feed/feed.xml');
		return false;
	});

	$("#acties input:reset").click(function() {
		$('#acties').find('form').slideUp();
		reactieValidate.resetForm();
		doorsturenValidate.resetForm();
		// acties.resetForm();
		$('#actiemenu').show();
	});


	$('.contactform').prepend('<div class="actie-load"><div><img src="/styles/images/ico-loading.gif" alt="" /></div></div><input type="hidden" name="ajax" value="1" />');

	// $('.actie-load')
	// .parent().css({position:'relative'}).end()
	// .css({background:'url(/styles/images/form_overlay.png)',width:'100%',height:'100%',position:'absolute'})
	// .find('div').css({'margin-top':'40%','text-align':'center'}).end()
	// .hide();

	$('.actie-load').ajaxStart(function() {
		$(this).show();
	
		var winTop = $(window).scrollTop();
		var formTop = $('.contactform').offset().top-20;
		if (winTop > formTop) $('html, body').animate({scrollTop: formTop});
		
		// alert('start');
	}).ajaxSuccess(function() {
		// $(this).find('img').fadeOut();
		// $(this).hide();
	});
	
	
	$.validator.setDefaults({
		groups: {
			pc_plaats: "pc_cijfers pc_letters plaats",
			fact_pc_plaats: "fact_pc_cijfers fact_pc_letters fact_plaats"
		},
		rules: {
			fact_naam: {
				required: "#factuuradres:checked"
			},
			fact_org: {
				required: "#factuuradres:checked"
			},
			fact_adres: {
				required: "#factuuradres:checked"
			},
			fact_pc_cijfers: {
				required: "#factuuradres:checked"
			},
			fact_pc_letters: {
				required: "#factuuradres:checked"
			},
			fact_plaats: {
				required: "#factuuradres:checked"
			}
		},
		errorPlacement: function(error, element) {
			if (element.attr("type") == "radio" || element.attr("type") == "checkbox")
				error.insertAfter(element.nextAll(':last'));
			else if (element.attr("name") == "pc_cijfers" || element.attr("name") == "pc_letters")
				error.insertAfter("#plaats");
			else if (element.attr("name") == "fact_pc_cijfers" || element.attr("name") == "fact_pc_letters")
				error.insertAfter("#fact_plaats");
			else
				error.insertAfter(element);
		}
	});


	var reactieValidate = $("#reactie").validate({
		submitHandler: function(form) {
			submitActie(form);
		}
	});

	var doorsturenValidate = $("#doorsturen").validate({
		submitHandler: function(form) {
			submitActie(form);
		}
	});

	function submitActie(form) {
		$(form).ajaxSubmit(function() {
			$(form).slideUp(2000,function() {
				$('.actie-load').hide();
				$(this).resetForm();
			});
			$('#actiemenu').show();
		});
	}

	$("#contact, #masterclass, #klantendag, #innovatielab, #masterclassvragen, #portfolioquiz, #kennissessie, #nieuwsbrief, #contact2, #klankbordbijeenkomst, #rapport_downloaden").validate({
		submitHandler: function(form) {
			$('h4.error').remove();
			$(form).ajaxSubmit({
				success: function(responseText) {
					// $('html, body').animate({scrollTop: $(form).offset().top-20});
					
					if (responseText.match("e-mailadres is al in gebruik.")) {
						$('#email', form).parent().prepend('<h4 class="error">' + responseText + '</h4>');
					} else {
						$(form).replaceWith("<div>" + responseText + "</div>");
						// $(form).parent().html(responseText);
					}
				}/*,
				resetForm: true */
			});
		}
	});
	
	$('#factuur, .nb2hide').hide();
	
	$('#factuuradres').click(function() {
		$('#factuur').slideToggle('fast');
	});
	
	$("#nieuwsbrief2").validate({
		submitHandler: function(form) {
			$('h4.error').remove();
			$(form).ajaxSubmit({
				beforeSubmit: function(formdata) {
					var submit = formdata[formdata.length-1].value;
				/*
					if (submit) {
							return confirm(submit);
						}
				*/
					if (submit.match(/uitschrijven/i)) {
						return confirm("Weet u zeker dat u zich wilt uitschrijven?");
					}
				},	
				success: function(responseText) {
					// $('html, body').animate({scrollTop: $(form).offset().top-20});
					
					if (responseText.match(/e-mailadres is (.)+ in gebruik.?$/)) {
						$('#email', form).parent().prepend('<h4 class="error">' + responseText + '</h4>');
					} else if (responseText.match(/json$/)) {
						$('.nb2hide').slideDown(1000);
						$('#uitschrijven').remove();
						$.getJSON('/forms/nieuwsbrief_user.php', function(json) {
							$.each(json, function(att, val) {
								$('input[type=text][name='+att+']',form).val(val);
								$('input[type=radio][name='+att+'][value='+val+']',form).attr('checked','checked');
								if (val) $('input[type=checkbox][value='+att+']',form).attr('checked','checked');
							});
							$('#selecteren').attr('id','bijwerken').attr('value', 'Bijwerken');
							$('.notrequired', form).removeClass('notrequired').addClass('required').each(function() {
								if (this.type != 'radio' && this.type != 'checkbox') 
									$('label[for='+this.id+']', form).append('&nbsp;<b>*</b>');
							});
						});
					} else {
						$(form).replaceWith("<div><h4 class=\"ok\">" + responseText + "</h4></div>");
					}
				}
			});
		}
	});
	
	// $.cookie('enebled', 1, {path: '/'});
	
	if (!$.cookie('__utmb')) {
		$('#nieuwsbrief2').before('<p class="warning">Uw cookies staat uitgeschakeld, dit heeft als gevold dat deze pagina niet naar behoren zal werken.</p>');
	}
	
	
	$('a[href$=media/ganzenbord/]').popUp({width:1024,height:640});
	$('a[href$=media/kvds_ecoach/]').popUp({width:1000,height:700});
	$('a[href$=Dutch_Demo/L_Engine/start.html]').popUp({width:1000,height:720});
	$('a[href$=media/presentatie/]').popUp({width:800,height:600});
	$('a[href$=media/digitaaltrainer/]').popUp({width:800,height:600});



	$("#contact3").css('min-height', 400).validate({
	    submitHandler: function(form) {
	        $(form).ajaxSubmit({
	            success: function(responseText) {
	                $(form).replaceWith("<div>" + responseText + "</div>");
	            }
	        });
	    }
	});

	
});

/*
 * Translated default messages for the jQuery validation plugin.
 * Language: NL
 */
jQuery.extend(jQuery.validator.messages, {
        required: "Dit is een verplicht veld.",
        remote: "Controleer dit veld.",
        email: "Vul hier een geldig email adres in.",
        url: "Vul hier een geldige URL in.",
        date: "Vul hier een geldige datum in.",
        dateISO: "Vul hier een geldige datum in (ISO).",
        number: "Vul hier een geldig nummer in.",
        digits: "Vul hier alleen nummers in.",
        creditcard: "Vul hier een geldig credit card nummer in.",
        equalTo: "Vul hier dezelfde waarde in.",
        accept: "Vul hier een waarde in met een geldige extensie.",
        maxlength: jQuery.format("Vul hier maximaal {0} tekens in."),
        minlength: jQuery.format("Vul hier minimaal {0} tekens in."),
        rangelength: jQuery.format("Vul hier een waarde in van minimaal {0} en maximaal {1} tekens."),
        range: jQuery.format("Vul hier een waarde in van minimaal {0} en maximaal {1}."),
        max: jQuery.format("Vul hier een waarde in kleiner dan of gelijk aan {0}."),
        min: jQuery.format("Vul hier een waarde in groter dan of gelijk aan {0}.")
});

jQuery.validator.addMethod("telefoon", function(value, element) {
	return this.optional(element) || /^[\d-\+()\s]+$/i.test(value);
}, "Vul hier een geldige telefoonnummer in.");

jQuery.validator.addMethod("pc_cijfers", function(value, element) {
	return this.optional(element) || /^[\d]{4}$/i.test(value);
}, "Vul hier een geldige postcode in.");

jQuery.validator.addMethod("pc_letters", function(value, element) {
	return this.optional(element) || /^[a-z]{2}$/i.test(value);
}, "Vul hier een geldige postcode in.");


function ie6() {
	if($.browser.msie && $.browser.version == '6.0') {
		return true;
	}
}


jQuery.fn.actueelSlide = function(settings) {
	settings = jQuery.extend({
		delay: 5000,
		transition: 800
	}, settings);
	
	return this.each(function() {		
		var $this = $(this);
		var over = false;
		var current = 0;
		var tabs = $('.tab',$this);
		var length = tabs.length;
		var count = 0;
		
		tabs.each(function(i) { $(this).css('z-index', length-i); });
		
		$('#counter').show().find('li:first').addClass('selcount');
		
		function slide() {
			current = current < length ? current : 0;
			
			if (!over) {
				count = count < length-1 ? count+1 : 0;
				$('#counter li').removeClass().eq(count).addClass('selcount');
				tabs.show();
				$('.tab:eq('+current+')',$this).fadeOut(settings.transition,function() {
					tabs.each(function(i) {
						var y = parseInt($(this).css('z-index'));
						var z = y == length ? 1 : ++y;
						$(this).css('z-index', z);
					});
					current++;
					$(this).find('h2').show().end().show();
				});
			}
			
			$('body').animate({delay:1},settings.delay,slide);
		}
		
		$this.hover(function() { over = true; },function() { over = false; });
		
		if (length > 1) 
			$('body').animate({delay:1},settings.delay,slide);
	});
};

jQuery.fn.colHeight = function() {
		var heights = [];
		$(this).each(function() {
			heights.push($(this).height());
		});

		heights.sort().reverse();
		$(this).css('min-height',heights[0]);
		
		return this;
};

jQuery.fn.popUp = function(settings) {
	var screenWidth = screen.availWidth;
	var screenHeight = screen.availHeight;
	
	settings = jQuery.extend({
		name: 'popup',
		width: screenWidth * .95,
		height: screenHeight * .9,
		scrollbars: 0,
		resizable: 0,
		toolbar: 0,
		location: 0,
		statusbar: 0,
		menubar: 0	
	}, settings);
	
	return this.each(function() {
		$(this).click(function() {
			var url = this.href;
			var left = (screenWidth - settings.width)/2;
			var top = (screenHeight - settings.height)/2;
	
			var props = 'width='+settings.width+',height='+settings.height+',left='+left+',top='+top+',toolbar='+settings.toolbar+',scrollbars='+settings.scrollbars+',location='+settings.location+',statusbar='+settings.statusbar+',menubar='+settings.menubar+',resizable='+settings.resizable+',directories=0';
	

			if (url) {
				window.open(url, settings.name, props).focus();
			} else {
				alert(url);
			}

			return false;
		});
	});
};

