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

function addEffects() {
	$('ul.collection_items li').shadow({margin: 'left right top bottom'});
	$('div.search ul a').fancyHover();
}

function init() {
	addEffects();
	
	if ($.ie6()) {
		$.ifixpng('assets/images/pixel.gif');
		$('#logo').ifixpng();
	}

	$('div.shadowWrapper').shadow({margin: 'left right top bottom'});

	$.ewyseGallery.set({
		imgPath: 'assets/images/gallery/',
		borderSpace: 25,
		maxHeight: 600,
		minHeight: 600,
		minWidth: 800,
		maxWidth: 800,
		autoMaxDimension: true
	});
	
	$('input.jq_example, textarea.jq_example').example(function() {
			return $(this).metadata().empty;
	});
	
	$('#menu a:not(.activeItem), #subMenu a:not(.activeItem)')
		.addClass('fade')
		.each(function () {
			var $a = $(this).css('position', 'relative').prepend('<span style="display: none;" class="hover">' + $(this).text() + '</span>');
			var $span = $('> span.hover', this).css({
													opacity: 0,
													position: 'absolute',
													left: 0,
													top: 0,
													display: 'block',
													height: $a.outerHeight(),
													width: $a.width(),
													paddingLeft: $a.css('paddingLeft'),
													paddingRight: $a.css('paddingRight')
												});
			$(this).hover(function () {
				$span.stop().animate({opacity: 1}, 300, 'easeout');
			}, function () {
				$span.stop().animate({opacity: 0}, 500, 'easein');
			});
		});

	$('div.gallery > ul a, div.downloads > ul a, div.horizontaal_kader > ul a, div.verticaal_kader > ul a').fancyHover();

	if (sfeerCollectie > 0) $.getJSON('?output=json&retrieve=collectionImages&doc_id=' + sfeerCollectie, function (json) {
		if (json.images.length > 1) {
			($.sfeerbeelden = {
				images: json.images,
				index: 0,
				img: $('#topImageLayer > img.sfeer'),
				showNext: function() {
					$.sfeerbeelden.index = $.sfeerbeelden.index < ($.sfeerbeelden.images.length - 1) ? $.sfeerbeelden.index + 1 : 0;
					preload($.sfeerbeelden.images[$.sfeerbeelden.index], showImage);
				},
				setTimeout: function() {
					if ($.sfeerbeelden.images.length > 1) window.setTimeout($.sfeerbeelden.showNext, 5000);
				}
			}).setTimeout();
		}
	});
	
		// Create a nice gallery
	$('div.assets.ewyse_collection').each(function() {
		$('a[href*="doc_id="]', this).ewyseGallery({
			rewriteFunction: resizeImage,
			mode: 'json',
			url: '?output=json&retrieve=collectionImages&view=' + $(this).attr('id').split('_')[1]
		});
	});
	
	var nav = $('div.collection_navigation');
	if (nav.length) {
		nav.find('.prevItem, .nextItem').remove();
		$('a.page', nav).ajaxNav({ajaxFile: rootURL, target: $('ul.collection_items'), keyNav: true, fade: false, callback: addEffects, onShow: fixSearch, fixViewport: true, createViewport: true, createWorkspace: true, classActive: 'activePage', ajaxParams: {output: 'json', retrieve: 'pane', pane: 'centreCollectionPane'}, find: 'ul'});
		$viewport = nav.parents('.ewyse_collection').find('.ajaxNav_viewport');
		$viewport.css('height', $viewport.height() + 40);
	}
}

$.fn.fancyHover = function() {
	this.addClass('fade').children(':not(.nextButton)').css({zIndex: 2, position: 'relative'}).end()
		.prepend('<span class="hover" />').each(function () {
			var $a = $(this).css('position', 'relative');
			var button = $a.find('img.nextButton').css({display: 'block', opacity: 0});
			var $span = $('> span.hover', this).css({
													opacity: 0,
													position: 'absolute',
													left: 0,
													top: 0,
													height: $a.outerHeight(),
													width: $a.outerWidth(),
													zIndex: 1
												});
			$(this).hover(function () {
				$span.add($a.find('img.nextButton')).stop().fadeTo(500, 1);
			}, function () {
				$span.add($a.find('img.nextButton')).stop().fadeTo(300, 0);
			});
		});
}

function fixSearch() {
	var indices = $('.collection_item_index', this);
	var elems = $('.searchInfo strong');
	elems[0].innerHTML = $(this).parents('.ewyse_collection:first').find('.activePage').text();
	elems[1].innerHTML = indices.slice(0, 1).text() + ' - ' + indices.slice(-1).text();
}

function showImage(img) {
	$.sfeerbeelden.img.fadeOut(1000, function() { $(this).remove(); });
	$.sfeerbeelden.img = $(img).css({display: 'none'}).appendTo('#topImageLayer').fadeIn(1000);
	$.sfeerbeelden.setTimeout();
}

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;
};

$.fn.args = function(args) {
	return this.each(function() {
		if (/FORM|A/.test(this.nodeName)) {
			var oldArgs = parseGetParameters(this.href || this.action, true);
			args = $.extend({}, oldArgs, args);
			this[this.nodeName == 'FORM' ? 'action' : 'href'] = $.makeURL(rootURL, args);
		}
	});
}

function processContent() {
	$('form:not(.processed)').args({output: 'json', retrieve: 'content'}).addClass('processed').ajaxForm({dataType: 'json', success: ajaxFormReply, beforeSubmit: beforeFormSubmit});
}

function ajaxFormReply(json, a, form) {
	$form = $(form);
	$form.find('.ajaxLoader').fadeOut('slow', function() { $(this).remove(); } );
	if (!json.validated) {
		$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 (error) {
						var message = $('<span class="errorMessage"/>')
							.text(error)
							.appendTo(form)
							.css({
								position: 'absolute',
								left: pos.left + el.outerWidth() + 2,
								top: pos.top,
								cursor: 'pointer'
							}).click(function() {
								el.focus();
							});
					}
					el.addClass('error').one('focus click', function() {
						if (error) message.remove();
						$(this).removeClass('error');
					});
				}
			});
		} else PopupMessage().lightbox(json.message);
	} else PopupMessage().lightbox(json.message);
}

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');
}

function parseGetParameters(url, noEnv) {
	if (!url) {
		if (noEnv) return {};
		url = window.location.href;
	}
	var array = {};
	if ((index = url.indexOf('?')) !== -1) {
		var args = url.substring(index + 1).split(/&amp;|&/);
		for (var i = 0; i < args.length; i++) {
			var arg = args[i].split('=');
			array[arg[0]] = (typeof(arg[1]) != 'undefined') ? arg[1] : '';
		}
	}
	return array;
};

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);
}

