document.createElement('header');
document.createElement('footer');
document.createElement('nav');
document.createElement('article');
document.createElement('section');
document.createElement('aside');

$(document).ready(function(){

	// png fix op document
	// edaarna colorboxinladen (ivm conflict)
    $(document).pngFix().getScript('/public/js/jquery.colorbox-min.js', function() {

		//## colorbox ##
		if (typeof $().colorbox == 'function')
		{

			/**
			 *	-- Gebruik --
			 *	Geef een anchor de class .js_colorbox en de href de locatie van de afbeelding
			 *	Voor een slideshow:
			 *	Geef meerdere anchor's met .js_colorbox dezelfde rel="" waarde
			 *	Voorbeeld slideshow:
			 *	<a class="js_colorbox" rel="testblaat" href="/public/img/video2.jpg">klik</a>
			 *	<a class="js_colorbox" rel="testblaat" href="/public/img/banner.jpg">klik</a>
			 */
			//set
			$('.js_colorbox').colorbox({
				transition:'elastic'
			});

			/**
			* Html tonen in colorbox:
			* <a class="js_htmlcolorbox" rel="idvanjehtmldiv">Klik</a>
			*/
			$('.js_htmlcolorbox').click(function(){
				var targetid = $(this).attr('rel');
				if (typeof targetid == 'undefined' || targetid == '') return ;

				$(this).colorbox({
					open: true,
					inline:true,
					transition:'none',
					href:"#" + targetid
				});
			});

			/**
			* Contact form tonen in colorbox:
			* Verschil met htmlcolorbox is
			* dat deze de pagina herlaadt als hij sluit
			* (om form te resetten)
			* <a class="js_contactcolorbox" rel="idvanjehtmldiv">Klik</a>
			*/
			$('.js_contactcolorbox').click(function(){
				var targetid = $(this).attr('rel');
				if (typeof targetid == 'undefined' || targetid == '') return ;

				$(this).colorbox({
					open: true,
					inline:true,
					transition:'none',
					href:"#" + targetid,
					onClosed:function(){
						// pagina herladen
						if(ajaxFormChanged) {
							window.location.href = window.location.href;
						}
					}
				});
			});

			/**
			* Youtube movie tonen in colorbox:
			 *	Voor een slideshow:
			 *	Geef meerdere anchor's met .colorbox dezelfde rel="" waarde
			 *	Voorbeeld slideshow:
			* <a class="js_youtubecolorbox" rel="testblaat" href="http://www.youtube.com/v/[movie-id]">Klik</a>
			*/
			$('.js_youtubecolorbox').colorbox({
				iframe:true,
				innerWidth: 640,
				innerHeight:505,
				transition:'elastic'
			});
		}

    });

	$(document).documentReady();
});

jQuery.fn.documentReady = function (target)
{
	if ('undefined' == typeof target)
		target = this;

	//taalkeuze
	$(target).find('form[name*=js_taalkeuze] select').change(function(){
		document.location = $(this).val();
	})
	
	// flash inladen
	// als een div aangemaakt wordt met als class "js_flash",
	// en als inhoud het absolute pad naar de flash en de variable
	// wordt deze automatisch ingeladen
	$(target).find('.js_flash').each(function(){
		slideshowvars = $(this).find('.js_flashlink').html();
		//strip HTML comment from flash vars
		slideshowvars = slideshowvars.replace(/^<!--/, "");
		slideshowvars = slideshowvars.replace(/-->$/, "");
		slideshowheight = $(this).css('height');
		slideshowwidth = $(this).css('width');
		
		$(this).html("");
		$(this).flash({
	    	src: slideshowvars,
	    	width: slideshowwidth,
	    	height: slideshowheight,
			wmode: 'transparent',
			allowFullScreen: 'true'
		});
	});
	
	
	
	// homeslideblokken
	var thumbBreedte = 0;
	$('.js_slideblok').each(function(){
			thumbBreedte += $(this).width();
	});
	
	var thumholder = $('.js_slides');
	var maxBreedte = 957;
	var maxMargin = 0-thumbBreedte+maxBreedte-2;
	var minimalePositie = 0-thumbBreedte+(maxBreedte*2);
	
	thumholder.width(thumbBreedte);
	
	$('.js_sliderblock_prev').addClass('disabled');
	
	if(maxBreedte >= thumbBreedte){
		$('.js_sliderblock_next').addClass('disabled');
	} else {              
		$(".js_sliderblock_next").click(function(){
			$('.js_sliderblock_prev').fadeIn('fast');
			if(minimalePositie < thumholder.css('marginLeft').replace('px','')){
				thumholder.animate({marginLeft:'-='+maxBreedte},750);
			} else {
				thumholder.animate({marginLeft:maxMargin},750);
				$('.js_sliderblock_next').fadeOut('fast');
			}
		});
		$(".js_sliderblock_prev").click(function(){
			$('.js_sliderblock_next').fadeIn('fast');
			if(0-maxBreedte > thumholder.css('marginLeft').replace('px','')){
				thumholder.animate({marginLeft:'+='+maxBreedte},750);
			} else {
				thumholder.animate({marginLeft:'0'},750);
				$('.js_sliderblock_prev').fadeOut('fast');
			}
		});
	}
	
	

	// solutions for you blok
	$(target).find('.js_solutions > .js_header > a').click(function() {
		// openen of sluiten + class aan link
		if (!$(this).parents('.js_solutions').hasClass("js_solutions_open")){
			$('.js_solutions > nav').slideToggle();
			$('.js_solutions > .js_header > a').toggleClass('active');
		}
	});
	// direct open zetten indien class js_solutions_open
	$(target).find('.js_solutions_open > .js_header > a').addClass('active');
	$(target).find('.js_solutions_open > nav').css('display','block');

	//## Klapblokken ##

	if (0 < $('.js_uitklapblokken').length)
	{
		$('.js_uitklaplink').click(function ()
		{
			var obj = $(this).parents('.js_uitklapblok:first').find('.js_uitklapdetail:first');

			if (!$(this).hasClass('js_keepothers')) //andere blokken sluiten
			{
				$(this).parents('.js_uitklapblokken').find('.js_uitklapdetail').each(function(){
					if (!$(this).hasClass('js_dontclose')) //dit blok niet altijd open houden
					{
						$(this).slideUp();
						$(this).find('.js_uitklaplink').removeClass('open');
					}
				})
			}

			//overal active verwijderen
			$(this).parents('.js_uitklapblokken').find('.js_uitklaplink').removeClass('active');

			if (obj.css('display')=='none') //geklikt item openen
			{
				obj.slideDown('fast', function(){$(this).css('display', 'block');}); //callback zodat het in IE8 nog steeds werkt
				$(this).addClass('active');
				$(this).addClass('open');
			}
			else //geklikt item sluiten
			{
				obj.slideUp('fast', function(){obj.hide();});
				$(this).removeClass('open');
			}
		});
	}

	// home slider (sudo slider)
	$(target).find(".js_homeslider").sudoSlider({
        auto: true,
		pause: '5000',
		prevNext: false,
		speed:'400',
		customLink:'a.js_homesliderlink',
		clickableAni: true,
		updateBefore: true
    });

	$(target).find('a.js_homesliderlink').hover(function(){
		var item = $(this).attr('rel');
		$(target).find(".js_homeslider").sudoSlider(item);
//		var elements = $('.js_homeslider li a');
//		$(elements[item]).css('background-position', 'left bottom');
	},
	function(){
//		$('.js_homeslider li a').css('background-position', '')
	});

	$(target).find('a.js_homesliderlink').click(function(){
		document.location = $(this).attr('href');
	});

	// thumnails slider en knoppen
	$(target).find(".js_thumbslider").sudoSlider({
        prevNext: false,
		afterAniFunc: function(){
			$(".js_detailthumbslider ul").css('width', 1000);
		}
    });

	$(target).find(".js_next").click(function(){
		// breedte van de ul bepalen aan de hand van li's (sudoslider doet dat niet goed)
		var ul = $(this).siblings(".js_thumbslider").find("ul"); // juiste ul bepalen aan de hand van positie knop
		var next = $(this);
		var prev = $(this).siblings(".js_prev");

		var ulbreedte = 0;

		ul.find("li").each(function(){
			ulbreedte += 53;
		});
		// ul iets grotere breedte geven, zodat li's passen
		ul.css('width', ulbreedte+10);

		// sliden
		if(!ul.hasClass('animating') && ulbreedte > 159){ // alleen scrollen als dat niet nog bezig is en niet alles in beeld is

			// status op animating zetten middels class aan ul
			ul.addClass('animating');

			// nog niet bijna aan het einde? Dan hele 159pixels scollen (breedte)
			if(ul.css('margin-left').replace('px','') > 318 - ulbreedte)
			{
				prev.removeClass('disabled');
				ul.animate(
					{marginLeft: '-=159px'},
					750,
					function() {
   						ul.removeClass('animating');
  					});

			}
			else // anders scrollen naar het einde
			{
				prev.removeClass('disabled');
				next.addClass('disabled');
				ul.animate(
					{marginLeft: 159 - ulbreedte + 'px'},
					500,
					function() {
   						ul.removeClass('animating');
  					});
			}
		}
	});

	$(target).find(".js_prev").click(function(){

		// juiste ul bepalen aan de hand van positie knop
		var ul = $(this).siblings(".js_thumbslider").find("ul");
		var next = $(this).siblings(".js_next");
		var prev = $(this);

		// sliden
		if(!ul.hasClass('animating')){ // alleen scrollen als dat niet nog bezig is

			// status op animating zetten middels class aan ul
			ul.addClass('animating');

			// nog niet bijna aan het einde? Dan hele 159pixels scollen (iets minder als breedte)
			 if(ul.css('margin-left').replace('px','') <= -200)
			{
				next.removeClass('disabled');
				ul.animate(
						{marginLeft: '+=159px'},
						750,
						function() {
							ul.removeClass('animating');
						});
			}
			else // anders scrollen naar 0
			{
				prev.addClass('disabled');
				if (3 < ul.find('li').length)
					next.removeClass('disabled');
				
				ul.animate(
					{marginLeft: '0px'},
					500,
					function() {
   						ul.removeClass('animating');
  					});
			}
		}
	});


	//field hints
	$(target).find(".js_hintfield").each(function() {
		$(this).addClass("js_hint");
		$(this).val($(this).attr("title"));

        $(this).bind("focus", function() {
            if ($(this).val() == $(this).attr("title")) {
                $(this).val("");
				$(this).removeClass("js_hint");
            }
        });
        $(this).bind("blur", function() {
            if ($(this).val() == "") {
				$(this).addClass("js_hint");
				$(this).val($(this).attr("title"));
            } else {
				$(this).removeClass("js_hint");
			}
        });
	});

	//submit form link
	$(target).find('.js_submitform').click(function(){
		$(this).parents('form:first').submit();
		return false;
	})


	//AJAX FORMS automatisch
	if (typeof $().ajaxForm == 'function')
	{
		$(target).find('form.js_ajaxform').each(function(){
			$(this).append('<input type="hidden" name="ajax_post" value="oke" />');
			var form = $(this);
			$(this).ajaxForm({
				dataType: 'json',
				beforeSerialize: function(){
					form.find('.js_hint').val('');
				},
				beforeSubmit: function(){
					form.parent().find('.js_errormelding').remove();

					//vereiste velden
					form.find('.js_required').each(function(){
						if ($(this).val().replace(' ', '') == '' || $(this).hasClass('js_hint')) //leeg of bevat nog de hint
						{
							return false;
							$(this).addClass('formerror');
						}
						else
							$(this).removeClass('formerror');
					});
					form.find('.js_required.email').each(function(){
						var regex = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
						if (!regex.test($(this).val()))
						{
							return false;
							$(this).addClass('formerror');
						}
					});
				},
				success: function(response){
					if (response.success)
					{
						if (form.attr('data-alerts'))
							alert(response.message);
						else
							form.html('<p>'+response.message+'</p>');
						
						var trackurl = form.attr('data-trackurl');
						if (!trackurl)
							trackurl = location.pathname + '-bedankt';

						if ( typeof _gaq == 'object' )
							_gaq.push(['_trackPageview', trackurl]);
						else if ( typeof pageTracker == 'object' )
							pageTracker._trackPageview( trackurl );
					}
					else if (response.message)
					{
						if (0 < form.find('.error').length)
							form.find('.error').html(response.message).removeClass('hidden');
						else if (form.attr('data-alerts'))
							alert(response.message.replace(/(<([^>]+)>)/ig,""));
					}
					form.find('.errorfield').removeClass('errorfield');
					if ('undefined' !=  typeof response.errorfields && 0 < response.errorfields.length)
					{
						for (var i in response.errorfields)
						{
							form.find('[name='+response.errorfields[i]+']').addClass('errorfield');
						}
					}
					form.find('.js_hint').trigger('blur');
				}
//				,complete: function (response)
//				{
//					alert (response.responseText);
//				}
			})
		})
	}

	$(target).find('form.zoekform').submit(function(){
		document.location = $(this).attr('action') + '/' + encodeURI($(this).find('input[name=q]').val());
		return false;
	})

	//sales office page
	$(target).find('a.js_link').each(function(){
return;
		if (!$.browser.msie)
		{
			this.onclick = function(){ return false }; //use js handler to prevent link from opening

			var href = $(this).attr('href');
			$(this).click(function(){
				$(this).parents('nav:first').find('a.active').each(function(){
					$(this).removeClass('active');
				});

				$(this).addClass('active');
				$('article.js_cms_content').html('');
				$.ajax({
					url: href,
					type: 'POST',
					data: '&ajax=1',
					dataType: 'html',
					success: function(response){
						if ('undefined' != typeof response)
						{
							$('article.js_cms_content').html(response).documentReady();
						}
					}
				});
			})
		}
	});

	$(target).find('.js_partner').hide();
	$('article.js_cms_content').find('div.nohide').show();

	$(target).find('form.js_postcode').submit(function(event){
		$(this).find('.js_postcodesubmit').trigger('click');
	});
	$(target).find('.js_postcodesubmit').click(function(){
		var data =$(target).find('form.js_postcode').serialize();

		$.ajax({
		url: PATH + '/public/ajax/postcode.php',
		type: "POST",
		data: data,
		dataType: "json",
		success: function(response){
			if ('undefined' != typeof response.success && response.success && 'undefined' != typeof response.offices)
			{
				$('article.js_cms_content').find('p').hide();
				$('article.js_cms_content').find('div.js_partner').hide();
				if (0 == response.offices.length)
				{
					$('article.js_cms_content p[class~=js_notfound]').show();
				}
				else
				{
					for (var i in response.offices)
					{
						$('.js_partner[data-partner='+response.offices[i]+']').show();
					}
				}
			}
		},
		error: function(){

		}
		});
	});

	$(target).find('select[name=js_areaselect]').change(function(){
		$('article.js_cms_content').find('p').hide();
		$('article.js_cms_content').find('div.js_partner').hide();
		if ('' == $(this).val())
		{
			$('article.js_cms_content').find('.js_notfound').show();
		}
		else
		{
			$('.js_partner[data-area='+$(this).val()+']').show();
		}
	});
	
	$('.js_truncateslidetekst').each(function(){
		var w = $(this).width();
		$(this).truncate({
		    width: w * 4,
		    after: '..',
		    center: false,
		    addclass: false,
		    addtitle: false
		});
	});
	
	$('.js_truncateslidetitle').truncate({
	    width: 'auto',
	    after: '..',
	    center: false,
	    addclass: false,
	    addtitle: false
	});
}

function showAgent(landcode)
{
	if ('undefined' != typeof sales_offices) //sales_offices should be defined in the html output
	{
		for (var i in sales_offices)
		{
			if (landcode == sales_offices[i].landcode)
			{
//				if ($.browser.msie)
//				{
					document.location = sales_offices[i].url+'#detail';
					return;
//				}
				$('article.js_cms_content').html('');
				$('nav.js_submenu').html('');

				$.ajax({
					url: sales_offices[i].url,
//					type: 'GET',
					type: 'POST',
					data: '&ajax=1&loadAgent=1',
					dataType: 'text',
					success: function(response){
						if ('undefined' != typeof response)
						{
							var page = $('<div>' + response + '</div>');
//							var page = $(innerShiv('<div>' + response + '</div>', false));
							$('article.js_cms_content').html(page.find('article.js_cms_content').html()).documentReady();
							$('nav.js_submenu').html(page.find('nav.js_submenu').html()).documentReady();
							$('section.js_directcontact').html(page.find('section.js_directcontact').html()).documentReady();
							$('article.js_salesofficeinfo').html(page.find('article.js_salesofficeinfo').html()).documentReady();
						}
					}
				});
			}
		}
	}
	if ('undefined' != typeof contact_offices) //sales_offices should be defined in the html output
	{
		for (var i in contact_offices)
		{
			if (landcode == contact_offices[i].landcode)
			{
//				if ($.browser.msie)
//				{
					document.location = sales_offices[i].url;
					return;
//				}
				$('article.js_cms_content').html('');
				$('nav.js_submenu').html('');

				$.ajax({
					url: contact_offices[i].url,
					type: 'POST',
					data: '&ajax=1&loadAgent=1',
					dataType: 'html',
					success: function(response){
						if ('undefined' != typeof response)
						{
							var page = $('<div>' + response + '</div>');
//							var page = $(innerShiv('<div>' + response + '</div>', false));
							$('article.js_cms_content').html(page.find('article.js_cms_content').html()).documentReady();
							$('nav.js_submenu').html(page.find('nav.js_submenu').html()).documentReady();
							$('section.js_directcontact').html(page.find('section.js_directcontact').html()).documentReady();
							$('article.js_contactfficeinfo').html(page.find('article.js_contactfficeinfo').html()).documentReady();
						}
					}
				});
			}
		}
	}
}

/*
//slide an element up without causing blinking flash content
 
function slideUp(object, speed, slideTime)
{
    if (parseInt(speed) == NaN) return false;
    if (object.jquery == undefined) object = $(object);
	if (object.height() <= 0) return true;
    object.css('overflow', 'hidden');
    var ppf = (object.height() / speed * 20);
    var orgh = object.height();
    var timeout = setInterval(function(){
        object.height(object.height() - ppf);
        if (object.height() <= 0){
            object.hide();
            object.height(orgh);
            clearInterval(timeout);
        }
    }, 10);
    return true;
}

//slide an element down without causing blinking flash content
function slideDown(object, speed)
{
    if (parseInt(speed) == NaN) return false;
    if (object.jquery == undefined) object = $(object);
    object.css('overflow', 'hidden');
    var ppf = (object.height() / speed * 20);
    var orgh = object.height();
    object.height(0);
    object.show();
    var timeout = setInterval(function(){
        object.height(object.height() + ppf);
        if (object.height() >= orgh){
            object.height(orgh);
            clearInterval(timeout);
        }
    }, 10);
    return true;
}
 */
