$(init);

function init() {
	$('.lightbox').click(showLinkContent);
	
	if (sfeerCollectie > 0) $.getJSON('ajax/getdata.php?type=collectionImages&id=' + sfeerCollectie, function (images) {
		if (images.length > 0) {
			($.sfeerbeelden = {
				images: 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();
		}
	});

	$('.banner_blok a').Tooltip({bodyHandler: tooltipBodyHandler, showURL: false, delay: 0, track: true, opacity: 0.9, left: 0, top: 10});
}

function tooltipBodyHandler() {
        return $(this).find('> span').html();
}


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 showLinkContent(e, callback) {
	e.stopPropagation();
	e.preventDefault();

	var params = parseGetParameters(this.href);
	params['type'] = 'content';
	$.getJSON(rootURL + 'ajax/getdata.php', params, function (data) {
		if (data) {
			// Track Google Analytics
			if (window.pageTracker && data.name) try { pageTracker._trackPageview(data.name); } catch (e) { }
			PopupMessage().lightbox(data.content, {onShow: processContent});
		}
	});
};

function processContent() {
	$('form:not(.processed)').args({output: 'json', retrieve: 'content'}).addClass('processed').ajaxForm({dataType: 'json', success: ajaxFormReply, beforeSubmit: beforeFormSubmit});
}

function ajaxFormReply(json, a, form) {
	if (json.reply === false) {
		form.add($(':submit, :image', form)).removeAttr('disabled');
		if (json.fields) $.each(json.fields, function() {
			var el = $('[name=' + this + ']:not(.error)', form);
			if (el.length) {
				var pos = el.position(), error = false;
				if (error = el.metadata().error) {
					var message = $('<span class="errorMessage"/>')
						.text(el.metadata().error)
						.appendTo(form)
						.css({
							position: 'absolute',
							left: el.width() + pos.left + 10,
							top: pos.top,
							cursor: 'pointer'
						}).click(function() {
							el.focus();
						});
				}
				el.addClass('error').one('focus', function() {
					if (error) message.remove();
					$(this).removeClass('error');
				});
			}
		});
	} else {
		setTimeout(function() {
			PopupMessage().hide();
		}, 2500);
	}
	if (form.is('#mailpageForm') || form.is('#suggestieForm')) $('.popupmessageInfo', form).css('color', json.reply ? 'green' : 'red').html(json.message).fadeIn('fast');
	else {
		$('#lightboxInner').css('width', 250);
		setLightbox('', json.message);
		PopupMessage().show('lightbox');
	}
	if (json.field) $('input[name="' + json.field + '"]', form).focus();
}

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;
};
