$(init);
var currentURL = window.location.protocol + '//' + window.location.host + window.location.pathname;
if (!window.console) {
	window.console = {
		log: function() {}
	};
}
function init() {
	$.ewyseGallery.set({
		imgPath: 'assets/images/gallery/',
		img: {close: 'close.png'},
		maxHeight: 540,
		minHeight: 540,
		minWidth: 720,
		maxWidth: 720,
		autoMaxDimension: true,
		flashparams: {height: 330}
	});
	
	if ($.ie6()) {
		$.ifixpng('assets/images/pixel.gif');
		$('.kruis, div.clearSelection, #header img, #archive-image').ifixpng();
	}
	
	// Set a global AJAX loader.
	var loader = $('<div class="ajaxLoader"/>').hide().appendTo('body'), loaderTimer;
	$('body').ajaxStart(function() {
		clearTimeout(loaderTimer);
		loader.fadeIn();
	}).ajaxComplete(function() {
		$.resultsTooltip.hide(false, 0);
		clearTimeout(loaderTimer);
		loaderTimer = setTimeout(function() { loader.fadeOut(); }, 1000);
	}).ajaxError(function() {
		clearTimeout(loaderTimer);
		loaderTimer = setTimeout(function() { loader.fadeOut(); }, 1000);
	});

	if ($.browser.msie){
		try {
			document.execCommand("BackgroundImageCache", false, true);
		}
		catch (err) {}
	}
	
	PopupMessage().set({lightboxButton: 'assets/images/close.png', width: 946, shadow: {}});
	
	$('#home').shadow();
	
	$('body').removeClass('nonJS').addClass('js');
	
	processPage(this);
	
	$('#homepage a[href$=zoeken]').click(function(e) {
		e.preventDefault();
		var footer = $('#footer');
		footer.animate({opacity: 0}, 'fast');
		$.getJSON(this.href, {output: 'json', retrieve: 'template'}, function(json) {
			var template = $('#template').css('position', 'absolute');
			template.animate({opacity: 0}, 400, 'easeOutCubic', function() { 
				try { pageTracker._trackPageview('Zoeken (ajax)'); } catch (e) { if (window.console) console.log("Tracking error in init.js: " + e); }
				$('body').removeAttr('id');
				var content = $(json.content).css('opacity', 0).insertAfter(template).attr('id', 'template').animate({opacity: 1}, 'slow', function() { if ($.browser.msie) $(this).css('filter', ''); processPage(this); footer.animate({opacity: 1}); });
				template.remove();
			});
		});
	});
}

function processPage(context) {
	context = context || this;
	var sel = $('select#type');

	$('div.tagsPanel :checkbox').tags();
	
	$('input.jq_example').example(function() {
		return $(this).metadata().example;
	});

	processResults(context);
	
	//console.log($('#searchResults'));
	
	$('form#resultsForm:not(.jq_ajaxForm)').addClass('jq_ajaxForm').each(function() {
		var form = $(this), results = $('#searchResults'), timer;
		form.args({retrieve: 'content', output: 'json'}).ajaxForm({
			dataType: 'json',
			type: 'POST',
			success: function(json) {
				$('input.searchInput', form).triggerHandler('blur');
				results.hide();
				processResults(results.html(json.content).show().parent()); /* If this is done on results, rather than results.parent(), the paginator stops working after a search. */
			}}
		)
		form.find(':checkbox').bind('click change', function() {
			clearTimeout(timer);
			timer = setTimeout(function() {
				$('form#resultsForm').submit();
			}, 500);
		});
	});
	
	$('div.panelWrapper:not(.jq_clearbutton)').filter('.themesPanel, .typesPanel, .tagsPanel').addClass('jq_clearbutton').addClearButton();	
}

function processResults(context) {
	context = context || this;
	$('div.beeldPanel div.panelContent a.collection_item_url', context).ewyseGallery();
	var video = $('div.documentsDetails div.beeldPanel div.panelContent a:first', context);
	// Make document image clickable if there's a download
	 if (video.length) {
		title = 'Bekijk "' + $.trim(video.text()) + '"';
		img.attr('title', title).css('cursor', 'pointer').click(function() {
			video.click();
		});
	}
	
	$('form#mailpageForm:not(.processed), form.generalForm:not(.processed)', context)
		.addClass('processed')
		.args({output: 'json', retrieve: 'data', data: ['missing', 'validated', 'error']})
		.ajaxForm({dataType: 'json', success: ajaxFormReply, beforeSubmit: beforeFormSubmit});

	$('table.results a, div.contactsPanel div.panelContent a.collection_item_url, a.lightbox:not(".bijdrage"), div.kennisPanel div.panelContent a', context).lightbox({onShow: processResults});
	
	$('th.sortable', context).sortableColumns({defaultActive: {which: '.name', order: 'desc'}, target: '#resultsForm'});
	
	var nav = $('div.collection_navigation:not(.processed)', context).addClass('processed');
	if (nav.length) {
		var buttons = {right: $('a.nextItem', nav), left: $('a.prevItem', nav)};
		if (!buttons.right.length) buttons.right = $('<a href="#nade"><span>&gt;&gt;</span></a>').appendTo(nav);
		if (!buttons.left.length) buttons.left = $('<a href="#nade"><span>&lt;&lt;</span></a>').prependTo(nav);
		// <flip vernooij>
		// The pager didn't worked correctly when a search selection was made.
		// I fixed it by parsing the formvalues as get values behind every pager url.
		// This should only happen when the results are NOT shown in the lightbox.
		// I don't know or this is the best way to do it,.. but it works!
		var params;
		if($(context).attr('id')=='template'){
			
			params=$('form#resultsForm').serialize();
			params=params.replace('Zoek+op+trefwoorden+en%2Fof+mensen', '');
			params=unescape(params);
			params=params.split('&');
			var types=[];
			var themes=[];
			var tags=[];
			var search='';
			for(var i=0;i<params.length;i++){
				var t=params[i];
				t=t.split('=');
				var tm=t[1];
				t[1]=tm.replace('+', ' ');
				switch(t[0]){
					case "types[]":
						types.push(t[1]);
					break;
					case 'themes[]':
						themes.push(t[1]);
					break;
					case 'tags[]':
						tags.push(t[1]);
					break;
					case 'zoeken':
						search=t[1];
					break;
				}
			}
			params={output: 'json', retrieve: 'content', types: types, themes: themes, tags: tags, zoeken: search};
		}else{
			params={output: 'json', retrieve: 'content'}
		}
		$('a.page', nav).ajaxNav({
			target: nav.parent().prev(),
			preload: false,
			dimensional: false,
			keyNav: true,
			fade: false,
			callback: processResults,
			createWorkspace: true,
			classActive: 'activePage',
			ajaxParams: params,
			find: 'table',
			buttons: buttons
		}
	);
	}
	
	$('table.results tbody tr', context).resultsTooltip();
	var currentHelpItems = $('a.helpIcon', context).helpTooltip(), status = false;
	$('a.uitleg:not(.processedHelpLink)', context).addClass('processedHelpLink').click(function(e) {
		e.stopPropagation();
		if (!status) {
			status = true;
			currentHelpItems.trigger('showTooltip');
			$('body').one('click.showTooltip', function() {
				status = false;
				currentHelpItems.trigger('hideTooltip');
			});
		} else {
			$('body').unbind('click.showTooltip');
			status = false;
			currentHelpItems.trigger('hideTooltip');
		}
	});
	
	/* the z-indexes of each panel need to be descendant, so the helpballoons will fall over them */
	addZindex($(".panelWrapper:not('.tagsPanel, #searchResults')"));
	
	/* Add some boundaries to the amount of results shown in the panels */
	var listWrap = $('.detailsWrapper .contactsPanel .panelContent');
	slider(5, listWrap);

	var listWrap2 = $('.detailsWrapper .downloadsPanel .panelContent');
	slider(5, listWrap2);
	
	/* TODO: Not the best way, but this prevents the clicks on the anchors to go to an other page */	
	$("a.theme", context).click(
		function(e) {
			e.preventDefault();
			
			/* Get the theme_id by using an ugly regexp */
			var theme_id = $(this).attr("href").replace(/.*themes\[\]=([0-9]+).*/, "$1");

			/* Deselect all other checkboxes */
			$("div.themesPanel input:checkbox").removeAttr("checked");
			
			/* Select the one with the corresponding ID and send the change event so the form gets submitted */
			$("#theme_" + theme_id).attr("checked", "true").change();
			
			PopupMessage().hide();
		}
	);
}

function slider(maxLength, listWrap) {
	var speed = 400;
	if ($.ie6()) {
		speed = '';	
	}
	var list = listWrap.find('ul').children();
	
	if (list.length > maxLength) {
		list.filter(function(index) {			 
			 return index > maxLength; 
		}).css("display","none");
		/* initieel gesloten */
		listWrap.find(".slider:not(.processed)").append("Bekijk volledige lijst").css("cursor", "pointer").addClass("slidedown");	
		
		listWrap.find(".slider:not(.processed)").bind("click", function() {
			if ($(this).hasClass("slidedown")) {
				list.show(speed);			
				$(this).empty().append("Verberg lijst").removeClass("slidedown").addClass("slideup");
			}
			else if ($(this).hasClass("slideup")) {
				list.filter(function(index) {
					return index > maxLength; 
				}).hide(speed);
				$(this).empty().append("Bekijk volledige lijst").removeClass("slideup").addClass("slidedown");
			}
		}).addClass('processed');
	}
}

function addZindex(e) {
	var zindex = 100;
	e.each(function() {
		$(this).css("cssText", "z-index: "+(zindex)+" !important;");	/* for IE z-index needs to set !important */
		zindex-=10;
	});
}

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;
					label = $(form).find('label[for="' + el.attr('id') + '"]');
					input = $(form).find('input#' + el.attr('id'));
					if (input.length != 0) {
						var css = input.position();
						css.left += input.outerWidth() + 5;
					} else {
						var css = label.position();
						css.left += label.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 $('div.replyMessage').css('color', json.reply ? 'green' : 'red').text(json.message);
	} else $('div.replyMessage').css('color', json.reply ? 'green' : 'red').text(json.message);
}

$.fn.addClearButton = function() {
	var $button = $('<div class="clearSelection">Selectie verwijderen</div>').hoverClass('hover').click(function() {
		var fields = $(this).parent().next().find('input:checked');
		if (fields.length) {
			fields.clearFields();
			fields.each(function() {
				$(this).triggerHandler('click');
			});
		}
	});
	
	this.each(function() {
		var self = $(this).find('.panelTitleBar').append($button.clone(true));
		
	});	
	$('.clearSelection').ifixpng();
}

$.fn.sortableColumns = function(settings) {
	var items = this.filter(':not(.processed)'), target = $(settings.target), active = items.filter('.desc, .asc');
	items.addClass('processed');
	if (!active.length && settings.defaultActive && settings.defaultActive.which) active = items.filter(settings.defaultActive.which).addClass((settings.defaultActive.order || 'asc').toLowerCase());
	items.click(function() {
		var self = $(this);
		var order = self.is('.asc') ? 'desc' : 'asc';
		//if (active) active.removeClass('desc asc');

		//active = self.addClass(order);
		target.args({order: order, orderby: self.metadata().row}).submit();
	});
}

$.resultsTooltip = {
	tooltip: false,
	timer: false,
	context: false,
	status: 'hidden',
	data: {},
	
	init: function() {
		var self = this;
		if (!this.tooltip) {
			this.tooltip = $('<div class="resultsTooltip" style="display: none;"><div class="resultsTooltipInner">&nbsp;</div></div>')
				.appendTo('body')
				.hover(function () {
					self.clearTimer();
				}, function() {
					self.hide();
				});
			this.tooltip.children().shadow({imagePath: 'assets/images/tooltip-shadow/'});
		}
	},
	
	clearTimer: function() {
		clearTimeout(this.timer);
		this.timer = false;
	},
	
	show: function(content, context, options) {
		var self = this;
		options = options || {};
		
		this.data = {
			css: $(context).offset(),
			animate: {height: 'show'},
			content: content,
			context: context
		};
		
		if (!$.browser.msie) this.data.animate.opacity = 1;
		if (options.width) this.data.css.width = options.width;
		
		this.clearTimer();
		
		time = !isNaN(options.time) ? options.time : (this.status == 'show' ? 500 : 800);
		this.timer = setTimeout(function() {
			if (self.status == 'show') {
				self.hide(function() {
					self._show();
				}, 0);
			} else {
				self._show();
			}
		}, time);
	},
	
	_show: function(callback) {
		// For IE6 we don't have the q_shadow_inner element, so we need the second defined element instead
		this.tooltip.css(this.data.css).find($.ie6() ? '.resultsTooltipInner' : '.jq_shadow_inner').empty().html(this.data.content);
		this.tooltip.find('a').removeClass('processedLink').lightbox({onShow: processResults});
		this.status = 'show';
		this.tooltip.animate(this.data.animate, 'normal', 'easeOutCubic');
	},
	
	hide: function(callback, time) {
		var self = this, animate = {height: 'hide'};
		if (!$.browser.msie) animate.opacity = 0;
		if (typeof time == 'undefined') time = 300;
		this.clearTimer();

		this.timer = setTimeout(function() { self.tooltip.animate(animate, 'normal', 'easeInCubic', function() {
			self.status = 'hidden';
			if (callback) callback.apply(this);
		}); }, time);
	}
};

$.fn.resultsTooltip = function() {
	$.resultsTooltip.init();
	
	function createContent(self) {
		var content = $('<div/>').append(self.find('td.door > div').clone().addClass('contacts')).append(self.find('td.naam > div').clone().addClass('body'));
		content.find('div.description').css('display', 'block');
		return content;
	}
	
	this.filter(':not(.jq_tooltip)').addClass('jq_tooltip').each(function() {
		var self = $(this), content = false;
		self.find('*').andSelf().removeAttr('title');
		self.hover(function () {
			if (!content) content = createContent(self);
			$.resultsTooltip.show(content, this, {width: self.width() - 21});
		}, function() {
			$.resultsTooltip.hide();
		});
	});
	return this;
};

$.fn.helpTooltip = function() {
	this.filter(':not(.jq_helpTooltip)').addClass('jq_helpTooltip').each(function() {
		var self = $(this), content = false, tooltip = $(this).children('span.helpContent'), animateShow = {height: 'show'}, animateHide = {height: 'hide'}, timer;
		if (!$.browser.msie) {
			animateHide.opacity = 0;
			animateShow.opacity = 1;
		} 
		self
			.data('status', 'hidden')
			.bind('hideTooltip', function() {
				tooltip.animate(animateHide, 'normal', 'easeInCubic', function() {
					self.data('status', 'hidden');
				}); 
			}).bind('showTooltip', function() {
				clearTimeout(timer);
				if (self.data('status') != 'show') {
					self.data('status', 'show');
					tooltip.css({visibility: 'visible', display: 'none'});
					tooltip.animate(animateShow, 'normal', 'easeOutCubic');
				}
			}).click(function () {
				self.trigger('showTooltip');
			}).hover(function() {
				clearTimeout(timer);
			}, function() {
				if (self.data('status') != 'hidden') {
					timer = setTimeout(function() { 
						self.trigger('hideTooltip');
					}, 500);
				}
			});
		}).children().shadow({imagePath: 'assets/images/tooltip-shadow/'});
	return this;
};

$.fn.tags = function() {
	return this.each(function() {
		var self = $(this);
		self.bind('click change', function (e) {
			self.parent().find('[for=' + this.id + ']')[self.is(':checked') ? 'addClass' : 'removeClass']('selected');
		}).triggerHandler('click');
	});
}

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

// Show a link in a lightbox
$.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;
}

window.lastLightboxURL = false;
window.lightboxStack = [];
window.lightboxBackButton = false;
function openLinkInLightbox(href, options, doNotStack) {
	options = options || {};
	if (!doNotStack) {
		lightboxStack.push({href: href, options: options});
	}
	options.onHide = function() {
		// Get rid of the last added item; it is this current box
		window.lightboxStack.pop();
	}

	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);
		
		// Create back button
		if (!window.lightboxBackButton) {
			window.lightboxBackButton = $('<img class="vorigeButton"/>').attr({
				src: 'assets/images/vorige.png',
				alt: 'vorige'
			}).appendTo('#lightboxInner')
			.click(function() {
				// remove current element, which is the current page
				window.lightboxStack.pop();
				// get the next in the stack, which was the previous page
				var lastItem = window.lightboxStack.pop();
				openLinkInLightbox(lastItem.href, lastItem.options, doNotStack);
			});
		}
		
		window.lightboxBackButton[window.lightboxStack.length > 1 ? 'show' : 'hide']();
	});
}

// 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;|&/);
		var arrNum=0;
		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;
};