$(function() {
	$.ewyseGallery.set({
		imgPath: 'assets/images/gallery/',
		maxHeight: 600,
		minHeight: 600,
		minWidth: 800,
		maxWidth: 800,
		autoMaxDimension: true,
		cacheAjaxRequests: true
	});
	
	PopupMessage().set({lightboxButton: "assets/images/gallery/close.png"});
	
	if ($.ie6()) {
		$('.pngfix').remove();
		$('#mainMenu > li').hoverClass('hover');
		$.ifixpng('assets/images/pixel.gif');
		$('#logo').ifixpng();
	}
	
	$('#mainMenu a').ajaxNav({target: '#templateLayer > div', onShow: onShow, callback: processContent, ajaxFile: rootURL, ajaxParams: {output: 'json', retrieve: 'template'}, trackGA: true, createWorkspace: true, subMenu: 'ul.subMenu a', keyNav: true, fixViewport: true});

	processContent.apply(document);
	onShow.apply(document);
});

function onShow() {
	var nav = $('div.ewyse_collection:not(.search) div.collection_navigation', this);
	nav.each(function() {
		var $$ = $(this);
		$$.find('.prevItem, .nextItem').remove();
		$('a.page', $$).ajaxNav({ajaxFile: rootURL, target: $$.prev('ul'), callback: processContent, 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({left: 20, marginLeft: -10, overflow: 'visible'});
	});
}

function processContent() {
	$('form:not(.processed)').args({output: 'json', retrieve: 'data', data: ['missing', 'validated']}).addClass('processed').ajaxForm({dataType: 'json', success: ajaxFormReply, beforeSubmit: beforeFormSubmit});

	$('a.lightbox').removeClass('lightbox').click(lightboxIt);
	
	// Create a nice gallery
	var ul = $(this).is('ul') ? $(this) : $('ul.collection_items', this);
	if (ul.length) {
		ul.each(function() {
			var $$ = $(this);
			$$.ewyseGallery('a.collection_item_viewLarger', 
				{
					mode: 'json',
					url: '?output=json&retrieve=collectionImages&view=' + $$.parents('.ewyse_collection:first').attr('id').split('_')[1],
					rewriteFunction: resizeImage
				}
			);
		});
			
		$('.collection_item_image img:not(.processed)', ul).addClass('processed').css('cursor', 'pointer').click(function() { $(this).parents('.collection_item:first').find('a.collection_item_viewLarger').trigger('click') } );
	}
}

function lightboxIt(e) {
	e.preventDefault();
	$.getJSON($.makeURL(this.href, {output: 'json', retrieve: 'content'}), function(json) {
		PopupMessage().lightbox(json.content, {onShow: processContent});
	});
}

function processReply(json) {
	if (json.result) {
		$('#mailpageForm').unbind('submit').submit(function(){return false;});
	} else $('#popupmessageSubmit').enable();
	$('#popupmessageInfo').css('color', json.result ? 'green' : 'red').html(json.message).fadeIn('fast');
	if (json.field) $('input[name="' + json.field + '"]').focus();
}

$.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 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 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 ($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');
					});
				}
			});
		} else PopupMessage().lightbox(json.message);
	} else PopupMessage().lightbox(json.message);
}

// Returns an array with either the current get-arguments or the get-arguments of the given url.
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);
}