if ($.browser.safari) $(window).load(init);
else $(init);

if (!window.console) {
	window.console = {
		log: function() {}
	};
}

function init() {
	$('body').removeClass('nonJS').addClass('js');

	if (sfeerCollectie > 0) $.getJSON('?retrieve=collectionImages&output=json&doc_id=' + sfeerCollectie, function (json) {
		if (json.images && json.images.length > 0) {
			var images = json.images;
			($.sfeerbeelden = {
				images: images,
				index: 0,
				img: $('#topImageLayer > img'),
				showNext: function() {
					$.sfeerbeelden.index = $.sfeerbeelden.index < ($.sfeerbeelden.images.length - 1) ? $.sfeerbeelden.index + 1 : 0;
					preload($.sfeerbeelden.images[$.sfeerbeelden.index], showImage);
				},
				setTimeout: function() {
					window.setTimeout($.sfeerbeelden.showNext, 8000);
				}
			}).setTimeout();
		}
	});

	$.ewyseGallery.set({
		imgPath: 'assets/gallery/',
		maxHeight: 467,
		minHeight: 467,
		minWidth: 697,
		maxWidth: 697,
		autoMaxDimension: true,
		fitImage: false,
		cacheAjaxRequests: true,
		flashparams: {height: 330}
	});
	
	$.ifixpng('assets/pixel.gif');
	$('#logo img').ifixpng();
	
	PopupMessage().set({lightboxButton: 'assets/images/close.png', width: 946 });

	$('.siteWidth #shadow').shadow({
			sides: 'bottom left right',
			corners: 'bl br',
			wrap: 'outside'
		});
	
	slider($("span.readMore"));
	
	$("#blok_blok_1 a, #blok_blok_2 a").lightbox({onShow: processForm});
	//$('.image_lightbox').lightbox({onShow: processContent});

	try {
		document.execCommand("BackgroundImageCache", false, true);
	}
	catch (err) {}
	
	$('input.jq_example').example(function() {
		return $(this).metadata().empty;
	})
}

function showImage(img) {
	
	$.sfeerbeelden.img.fadeOut(1000, function() { $(this).remove(); });
	$.sfeerbeelden.img = $(img).css({display: 'none'}).appendTo('#topImageLayer').center().fadeIn(1000, function() {
	});
	$.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.src = img.src;
};

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

function processForm(context) {
	$('form#inschrijvingForm:not(.processed), form#maillijstForm:not(.processed)', context)
		.addClass('processed')
		.args({output: 'json', retrieve: 'data', data: ['missing', 'validated', 'error']})
		.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;
					selectbox = $(form).find('select#' + el.attr('id'));
					input = $(form).find('input#' + el.attr('id'));
					
					if (el.is('select')) {
						var css = selectbox.position();
						css.left += selectbox.outerWidth() + 5;
					} else {
						var css = input.position();
						css.left += input.outerWidth() + 5;
					}
					css.position = 'absolute';
					css.cursor = 'pointer';
					if (error) {
						var message = $('<span class="errorMessage"/>')
							.text(error)
							.appendTo(el.parent())
							.css(css)
							.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);
}

$.fn.lightbox = function(options) {
	this.filter('a:not(.processedLink)').addClass('processedLink').each(function() {
		$(this).bind('click', function(e) {
			e.preventDefault();
			openLinkInLightbox(this.href, options);
		});
	});
	return this;
}

function openLinkInLightbox(href, options) {
	var base = href.split('?')[0], args = parseGetParameters(href);
	$.extend(args, {output: 'json', retrieve: 'content'});
	var url = $.makeURL(base, args);
	$.getJSON(url, function(json) {
		try { pageTracker._trackPageview(json.name); } catch (e) { if (window.console) console.log("Tracking error in AJAX page '" + json.name + "': " + e); }
		PopupMessage().lightbox(json.content, options);
	});
}

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

function beforeFormSubmit(a, form) {
	$(form).add($(':submit, :image', form)).attr('disabled','disabled');
}

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 slider(start) {
	var speed = 500;
	if ($.ie6()) {
		speed = '';	
	}

	/* initieel gesloten */

	start.append("[read more]").css("cursor", "pointer").addClass("slidedown");	

	start.bind("click", function() {
		if ($(this).hasClass("slidedown")) {
			$(this).prev().slideDown(speed);			
			$(this).empty().append("[read less]").removeClass("slidedown").addClass("slideup");
		}
		else if ($(this).hasClass("slideup")) {
			$(this).prev().slideUp(speed);
			$(this).empty().append("[read more]").removeClass("slideup").addClass("slidedown");
		}
	});
}

// Returns an array with either the current get-arguments or the get-arguments of the given url.
function parseGetParameters(url, noEnv) {
	var array = {}, index, args, arg, i, key;
	if ((url || (!noEnv && (url = window.location.search))) && (index = url.indexOf('?')) !== -1) {
		args = url.substring(index + 1).split(/&amp;|&/);
		for (i = 0; i < args.length; i++) {
			arg = args[i].split('=');
			// Remove the first entry; it's our key in this pair
			key = arg.shift();
			// If the value also contains unencoded '=' signs, we save the value by rejoining the remainings
			arg = arg.join('=');
			array[key] = (typeof(arg) != 'undefined') ? decodeURIComponent(arg) : '';
		}
	}
	return array;
};