$.browser.safari ? $(window).load(init) : $(init);

// prevent IE to be unhappy with forgotten console.log()
if (typeof console == "undefined" || typeof console.log == "undefined") var console = { log: function() {} }; 

function init(){
	$('body').removeClass('nonjs').addClass('js');
/*
	//header zoom only on homepage, all the other pages get a slideshow
	if ($('body').attr('id') == 'home') {
		$("#header-image").css({backgroundImage : 'url(assets/images/home_head_L.jpg)', width : '1500px', top : '-70px', right : '-50px'});
		$("#header-image").animate({width: "965px", top: "0", right: "0"}, 3500, "easeInCubic");
	}
	else {
		if (window.sfeerCollectionId) $.getCollectionImages(sfeerCollectionId, function(json){
			$('#header .row2').cycleImg(json, {durationInterval: 5500, fadeInDuration: "slow", fadeOutDuration: "slow"});
		});
	}
	*/
	$.ifixpng('assets/images/pixel.gif');
	//$('#topMenu .helper1, #topMenu .helper2').ifixpng();
	$('#lightboxClose').ifixpng();
	
	$('.vloot').smidtjeGallery();
	
	$.ewyseGallery.set({
		imgPath: 'assets/images/gallery/',
		maxHeight: 540,
		minHeight: 540,
		minWidth: 720,
		maxWidth: 720,
		autoMaxDimension: true
	});

	$('.mediaBar').ewyseGallery('a', {rewriteFunction: resizeImage});	
	
	$('div.mediaBar > div.collection_innerWrapper').prettyOverflow({innerWrap: true});
	
	$('#searchField').example($('#searchField').metadata().empty);


	PopupMessage.prototype.set({lightboxButton: "assets/images/gallery/close.png"});
	$('#emailPage').lightbox();	
	$('#homePage').lightbox();	
 	processContent('body');
	
	/****************
	page specific
	****************/
	



 
	//contact form
	$('#reserveringForm input, #reserveringForm textarea').each(function(){
		$(this).example($(this).metadata().empty);		
	});
	$('#reserveringForm select').selectbox();
	
	
	//fotoboek
	$('div.gallery ul a').each(function() {
		var doc_id = $.parseGetParameters(this.href)['doc_id'];
		if (!isNaN(doc_id)) $(this).ewyseGallery({rewriteFunction: resizeImage, mode: 'json', url: $.makeURL(rootURL, {output: 'json', retrieve: 'collectionImages', doc_id: doc_id})});	
	});
	
	//For the Dutch version
	$("input#date").click(function() {
		new jQuery.calendar(this);
	});
	/*
	//For the English and German version, which contains other form names
	$("#date").click(function() {
		new jQuery.calendar(this);
	});
	*/
}


(function($){
	
	$.fn.imageReady = function(callback, callbackParams) {
		callbackParams = callbackParams || [];
		var images = this.filter('img'), count = images.length, loaded = 0, self = this;
		images.each(function() {
			if (this.complete) loaded++;
			else $(this).one('load', function() {
				loaded++;
				if (loaded == count) callback.apply(self, callbackParams);
			});
		})
		if (loaded == count) callback.apply(self, callbackParams);
		return this;
	};

	
	//return the number of vars contained in a js object
	$.objectLength = function(o){
		var j = 0;
		for (i in o){
			j++;
		}
		return j;	
	}	
	//allows to append things within a div and prevent them to overlap outside of that div
	$.fn.innerFrame = function(css){
		if (!css) var css = {};
		$(this).each(function(){
			var $wrap = $(this);
			if ($('span.innerFrame', $wrap).length == 0) $wrap.css({position: 'relative'}).wrapInner('<span class="innerFrame"/>');
			var $innerFrame = $('span.innerFrame', $wrap);
			$innerFrame.css({position: 'absolute', overflow: 'hidden', top: 0, left: 0, right: 0, bottom: 0, height: '100%', width: '100%'}).css(css);
		});
		return $(this);
	}
	
	//we'll loop in json[i].src
	$.fn.cycleImg = function(json, options){
		var defaults = {durationInterval: 5000, durationFadeIn: "slow", durationFadeOut: "slow"};
		var opts = $.extend(defaults, options);
		$(this).each(function(){
			var $container = $(this);
			var i = 0;
			var animateHeader = setInterval(function(){
					$container.showImg(json, i, opts);
					i++;
					if (i >= $.objectLength(json)) i = 0;
				}, opts.durationInterval);
		});
		return $(this);			
	}

	//use for the header slideshow
	$.fn.showImg = function(json, i, options){
		var defaults = {durationFadeIn: "slow", durationFadeOut: "slow"};
		var opts = $.extend(defaults, options);
		var $wrap = $(this), $loadedImgs = $('img', $wrap), $imgToShow = false, $imgOnTop = false, highestZIndex = 0;// $lastImg = $('img:visible', $container);

		$wrap.innerFrame();
		
		$loadedImgs.each(function(j){
			if ($(this).attr('src') == json[i].src)	$imgToShow = $(this);
			if ($(this).attr('z-index') > highestZIndex) {
				$imgOnTop = $(this);
				highestZIndex = $(this).attr('z-index');
			}
		});
		if (!$imgToShow) $imgToShow = $('<img src="'+json[i].src+'" class="showImg"/>');
		if ($imgOnTop.length === 1){
			$imgOnTop.fadeOut(opts.durationFadeOut, function(){
				$imgToShow.hide().css({position: 'absolute', top: 0, left: 0, zIndex: 2}).appendTo($wrap.find('.innerFrame')).fadeIn(opts.durationFadeIn);		
			}).hide().css({zIndex: 1}).show();
		} else	$imgToShow.hide().css({position: 'absolute', top: 0, left: 0, zIndex: 2}).appendTo($wrap.find('.innerFrame')).fadeIn(opts.durationFadeIn);
		
	}	
	
	// return object img => {src: src, alt: alt, title: title}
	$.getFirstCollectionImage = function(collectionId, callback){
		$.getJSON('?output=json&retrieve=collectionImages&doc_id='+collectionId, function(json){
			if (callback) callback(json.images[0]);		
		});
	}
	
	$.getCollectionImages = function(collectionId, callback){
		console.log('getCollectionImages');
		$.getJSON('?output=json&retrieve=collectionImages&doc_id='+collectionId, function(json){
			if (callback) callback(json.images);		
		});
	}	
	
	//play a reverse zoom effect on a image (within a container)
	$.fn.innerZoom = function(options){
		var defaults = { img: {src: 'assets/images/sfeer-smidtje.jpg'}, beforeDuration: 2000};
		var opts = $.extend(defaults, options);		
		$(this).each(function(){
			var $wrap = $(this);
			$wrap.innerFrame();
			preload(opts.img, function(img){
				$(img).appendTo($('.innerFrame', $wrap)).css({marginLeft: -540, marginTop: -200});
				var wait = setTimeout(function(){
					$('.innerFrame img', $wrap).animate({width: 968, height: 255, marginLeft: 0, marginTop: 0}, 3500, 'easeInOutCubic' );
				}, opts.wait);			
			});			
		});
		
		return $(this);
	}
	
	// img => {src: src, alt: alt, title: title}
	function preload(img, callback) {
		// Store the context, because THIS won't be available in callback functions
		var self = this;
		// If we already have an image object, check what to do with it.
		if (img.obj) {
			if (callback) {
				if (img.obj.complete) {
					callback.apply(self, [img.obj]);
					return;
				} else {
					$(img.obj).one('load', function(e) {
						callback.apply(self, [this]);
					});
					return;
				}
			}
		} else img.obj = new Image();
	
		if (callback) {
			$(img.obj).one('load', function(e) {
				callback.apply(self, [this]);
			});
		}
		
		// Store the currently used width and height, so we know when to reload the images
		img.obj.alt = $.trim(img.alt) || '';
		img.obj.title = '';
		img.obj.src = img.src;
	};	
	
	
	//set the height of each element of a set to match the tallest
	$.fn.equalheight = function(){
		var maxheight = 0;
		$(this).each(function(){
			if ($(this).height() > maxheight) maxheight = $(this).height();			
		});
		$(this).each(function(){
			$(this).height(maxheight);		
		});			
		return $(this);
	}
	

		
	$.fn.smidtjeGallery = function(options){
		var defaults = {};
		var opts = $.extend(defaults, options);

		function grow() {
			var $li = $(this).data('state', 'grow'), $siblings = $li.siblings(), $anim = $('span.animatedContent', $li), $short = $('span.collection_item_short', $anim);
			
			$('>a>img', $li).stop().animate({width: 180}, 'slow');
			
			$li.stop().animate({width: 375, marginRight: 7, marginTop: 10}, 'slow');
			$anim.stop().animate({opacity: 0}, 'fast', function(){
				$short.css({display: 'block'});
				$anim.children('span.collection_item_title').css('padding', '4px 0');
				$anim.css({left: 188, width: 180, opacity: 0, backgroundColor: 'transparent'}).animate({opacity: 1}, 'fast');
			})
			
			return $(this);
		}

		
		function shrink(){
			var self = $(this).data('state', 'shrink'), $short = $('span.collection_item_short', self), $anim = $('span.animatedContent', self);
			var width = 100, marginTop = 40, marginRight = 7;
			$anim.stop().animate({opacity: 0}, 'fast');
			$short.css({display: 'none'});
			$(this).each(function(){
				var $li = $(this), $img = $('>a>img', $li);
				$li.stop().animate({marginTop: marginTop, marginRight: marginRight, width: width}, 'slow');
				$img.stop().animate({width: width}, 'slow');
			});
		}
		
					
		function initialState(){
			var $ul = $(this), $siblings = $ul.children('li').data('state', 'initial'),  $short = $('span.collection_item_short', $siblings), $anim = $('span.animatedContent', $siblings);
			var width = 129, marginRight = 28, marginTop = 30;
			
			$short.css({display: 'none'});
			
			$siblings.stop().animate({width: width, marginRight: marginRight, marginTop: marginTop}, 'slow', function(){
				$(this).css({width: 'auto'});
				
			});
			$('>a>img', $siblings).stop().animate({width: width}, 'slow');
			$anim.children('span.collection_item_title').css('padding', '');
			$anim.stop().css({left: '', opacity: 0, width: '', backgroundColor: 'white'}).animate({opacity: 1}, 'slow');
		}	

		this.each(function(){
			var $ul = ($(this).is('ul')) ? $(this) : $('ul:first', this);
			var hideDelayTimer = null;		
			$('>li', $ul).each(function(){
				var $li = $(this), $siblings = $li.siblings();
				$li.find('a span').wrapAll('<span class="animatedContent"/>');
				$li.hoverIntent(function(e){
					shrink.apply($siblings);
					grow.apply($li);	
				}, function() {});
			});
			$ul.hoverIntent(function() {}, function(e){
				initialState.apply($ul);
			});
		});	

		return this;
	}
	
		
	// Show a link in a lightbox
	$.fn.lightbox = function() {
		this.filter('a:not(.processedLink)').addClass('processedLink').each(function() {
			var a = $(this), base = this.href.split('?')[0], args = $.parseGetParameters(this.href);
			$.extend(args, {output: 'json', retrieve: 'content'});
			var url = $.makeURL(base, args);
			a.bind('click', function(e) {
				e.preventDefault();
				$.getJSON(url, function(json) {
					PopupMessage().lightbox(json.content, {onShow: processContent});
				});
			});
		});
		return this;
	}
	
	
	//returns an array of the params of the url contained in the current node if it is a form or a link, otherwise the params of the page url.
	$.fn.args = function(args) {
		return this.each(function() {
			if (/FORM|A/.test(this.nodeName)) {
				var url = this.href || this.action, index;
				var oldArgs = parseGetParameters(url);
				if ((index = url.indexOf('?')) > -1) url = url.substring(0, index || url.length);
				args = $.extend({}, oldArgs, args);
				$(this).attr(this.nodeName == 'FORM' ? 'action' : 'href', $.makeURL(url, args));
			}
		});
	}
	

	// Returns an array with either the current get-arguments or the get-arguments of the given url.
	$.parseGetParameters = function (url, noEnv){
		var array = {}, index, args, arg, i;
		if ((url || (!noEnv && (url = window.location.search))) && (index = url.indexOf('?')) !== -1) {
			console.log(url);
			args = url.substring(index + 1).split(/&amp;|&/);
			for (i = 0; i < args.length; i++) {
				arg = args[i].split('=');
				array[arg[0]] = (typeof(arg[1]) != 'undefined') ? decodeURIComponent(arg[1]) : '';
			}
		}
		return array;	
	}
	//add arguments to an url string
	$.makeURL = function(url, args){
		if (args) url += (url.match(/\?/) ? "&" : "?") + (typeof args == 'string' ? args : $.param(args, true));
		return url;
	}
	
	
	$.removeArgs = function(url, args){
		delete args.blaat;
		
	}

	// Needs the mousewheel plugin and the imageReady plugin
	$.fn.prettyOverflow = function(options) {
		var options = $.extend({}, options);
		this.filter(':not(.jq_prettyOverflow)').addClass('jq_prettyOverflow').each(function() {
			var helper = $(this), content, helperWidth, contentWidth, currentLeft;
			
			// Wait for images to be loaded; otherwise we don't know the width of the element
			$('img', helper).imageReady(goOnThen);
			
			function goOnThen() {
				if (options.innerWrap) helper.css({position: 'relative'}).wrapInner('<div/>');
				helperWidth = helper.parent().width();
				content = helper.children(':first').css({position: 'absolute'});
				contentWidth = content.width();
				var checkButtons = function() {
					bUp.css('display', (currentLeft < 0 ? 'block' : 'none'));
					bDown.css('display', (-(currentLeft - helperWidth) < contentWidth ? 'block' : 'none'));
				};
				
				currentLeft = content.position().left;
				
				if (contentWidth > helperWidth) {
					helper.css({overflow: 'hidden', zoom: 1});
					var helperParent = helper.parent();
					var bDown = $('<img class="nextButton"/>')
						.appendTo(helperParent)
						.attr('src', rootURL + 'assets/images/buttons/next.png')
						.click(function(e) {
							currentLeft -= helperWidth;
							if (-(currentLeft - helperWidth) > contentWidth) currentLeft = -contentWidth + helperWidth;
							content.stop().animate({left: currentLeft}, 'normal', 'easeOutCubic', checkButtons);
						});
					var bUp = $('<img class="prevButton"/>')
						.prependTo(helperParent)
						.attr('src', rootURL + 'assets/images/buttons/prev.png')
						.click(function() {
							currentLeft += helperWidth;
							if (currentLeft > 0) currentLeft = 0;
							content.stop().animate({left: currentLeft}, 'normal', 'easeOutCubic', checkButtons);
						});
					
					checkButtons();
					
					var scrollTimeout = false;
					helper.mousewheel(function(e, delta) {
						e.preventDefault();
						currentLeft += delta * 150;
						if (currentLeft > 0) currentLeft = 0;
						if (-(currentLeft - helperWidth) > contentWidth) currentLeft = -contentWidth + helperWidth;
						content.get(0).style.left = currentLeft + 'px';
						checkButtons();
					});
				}
			}
			
		});
		return this;
	}
})(jQuery);	


/*
//create mail-to-a-friend box
function showMailpage() {
	$('#mailpageForm, #popupmessageSubmit').removeAttr('disabled');
	$('#mailpageForm').find('input[name^=recipient], textarea').val('');
	$('#popupmessageInfo').hide();
	PopupMessage().show('popupmessage');
	return false;
}
*/

function resizeImage(url, width, height) {
	var parts = url.split('?');
	var args = parseGetParameters(url, true);
	args['width'] = width;
	args['height'] = height;
	return $.makeURL(parts[0], args);
}

function parseGetParameters(url, noEnv) {
	return $.parseGetParameters(url, noEnv);
};



//called on ajax callbacks to add ajax ability to the new content
function processContent(context) {
	context = $(context || this);
	// Create ajax forms
	context
		.find('form:not(.processed)')
			.addClass('processed')
			.args({output: 'json', retrieve: 'data', data: ['missing', 'validated']})
			.ajaxForm({dataType: 'json', success: ajaxFormReply, beforeSubmit: beforeFormSubmit});
}


//caroussel
function handleOverflow(helper) {
	var content, hY, cY, currentLeft;
	if (!helper.length) return;
	$('img', helper).imageReady(goOnThen);

	function goOnThen() {
		var ul = helper.find('ul');
		helper = ul.wrap('<div/>').parent().css({position: 'relative', height: ul.height()});
		helper.addClass('processed');
		hY = helper.width();
		content = helper.children(':first').css({position: 'absolute'});
		cY = content.width();
		var checkButtons = function() {
			bUp.css('display', (currentLeft < 0 ? 'block' : 'none'));
			bDown.css('display', (-(currentLeft - hY) < cY ? 'block' : 'none'));
		};
		
		currentLeft = content.position().left;
		
		if (cY > hY) {
			helper.css({overflow: 'hidden', position: 'relative', zoom: 1});
			var helperParent = helper.parent();
			var bDown = $('<img class="nextButton"/>')
				.appendTo(helperParent)
				.attr('src', rootURL + 'assets/images/buttons/next.png')
				.click(function(e) {
					currentLeft -= hY;
					if (-(currentLeft - hY) > cY) currentLeft = -cY + hY;
					content.stop().animate({left: currentLeft}, 'normal', 'easeOutCubic', checkButtons);
				});
			var bUp = $('<img class="prevButton"/>')
				.prependTo(helperParent)
				.attr('src', rootURL + 'assets/images/buttons/prev.png')
				.click(function() {
					currentLeft += hY;
					if (currentLeft > 0) currentLeft = 0;
					content.stop().animate({left: currentLeft}, 'normal', 'easeOutCubic', checkButtons);
				});
			
			checkButtons();
			
			var scrollTimeout = false;
			helper.mousewheel(function(e, delta) {
				e.preventDefault();
				currentLeft += delta * 150;
				if (currentLeft > 0) currentLeft = 0;
				if (-(currentLeft - hY) > cY) currentLeft = -cY + hY;
				content.get(0).style.left = currentLeft + 'px';
				checkButtons();
			});
		}
	}
}

//used in the lightbox
function ajaxFormReply(json, a, form) {
	$form = $(form);
	$form.find('.ajaxLoader').fadeOut('slow', function() { $(this).remove(); } );
	if (!json.validated) {
		// For the sake of the example plugin: call blur on elements
		$form.add($(':submit, :image', form)).removeAttr('disabled');
		if (json.missing && json.missing.length > 0) {
			$.each(json.missing, function() {
				var el = $('[name="' + this + '"]:not(.error)', form);
				if (el.length) {
					var error = el.metadata().error;
					if (el.is(':radio') || el.is(':checkbox')) el = $(form).find('label[for="' + el.attr('id') + '"]');
					var pos = el.position();
					if ($form.is('#mailpageForm')) {
						pos.top -= 8;
					} else {
						pos.left += el.outerWidth() + 2;
					}
					if (error) {
						var message = $('<span class="errorMessage"/>')
							.text(error)
							.appendTo(form)
							.css(pos)
							.css({
								position: 'absolute',
								cursor: 'pointer'
							}).click(function() {
								el.focus();
							});
					}
					el.addClass('error').one('focus click', function() {
						if (error) message.remove();
						$(this).removeClass('error');
					});
				}
			});
			$.scrollTo($('input, textarea', form).blur().filter('.error:first'), 500, {easing: 'easeOutCubic'});
		} else PopupMessage().lightbox(json.message);
	} else PopupMessage().lightbox(json.message);
}
//used in the lightbox
function beforeFormSubmit(a, form) {
	//$('<img class=\"ajaxLoader\" src="assets/images/ajax-loader.gif">').insertAfter($('input:submit', form)).fadeIn('fast');
	$(form).add($(':submit, :image', form)).attr('disabled','disabled');
}

//used for position banner

function getPixelsFromTop(obj){
	objFromTop = obj.offsetTop;
	while(obj.offsetParent!=null) {
		objParent = obj.offsetParent;
		objFromTop += objParent.offsetTop;
		obj = objParent;
	}
	return objFromTop;
}


function banner() {
		leftP = (document.documentElement.clientWidth/2)+487;
		document.getElementById("bannert").style.left = leftP+"px"; 
		contentBotDiv = document.getElementById("tools");
		if (contentBotDiv != null) {
		contentBottom = (getPixelsFromTop(contentBotDiv)-68);
 		document.getElementById("bannert").style.height = contentBottom+"px"; 
		document.getElementById("bannert").style.display = "block";  }
		else {
 		document.getElementById("bannert").style.height = "590px"; 
		document.getElementById("bannert").style.display = "block";  }
		 
	}
 
