$(init);

var currentURL = window.location.protocol + '//' + window.location.host + window.location.pathname;

if (!window.console) {
	window.console = {
		log: function() {}
	};
}

function init() {
	if ($.browser.msie){
		try {
			document.execCommand("BackgroundImageCache", false, true);
		}
		catch (err) {}
	}

	PopupMessage().set({lightboxButton: 'assets/images/buttons/close.gif', width: 616});
	
	$('body').removeClass('nonJS').addClass('js');
	
	$.ewyseGallery.set({
		imgPath: 'assets/images/gallery/',
		maxHeight: 540,
		minHeight: 540,
		minWidth: 720,
		maxWidth: 720,
		autoMaxDimension: true,
		flashvars: {skin: rootURL + 'stijl.swf'},
		flashparams: {height: 330}
	});
	
	$('.divHomeProjectBox').projectSlideBox();
	
	processDocument(document);
}

$.fn.projectSlideBox = function() {
	this.addClass('playing').find('.project:first-child').addClass('selected');
	
	this.find('.controls .right, .controls .left').click(function(e) {
		e.preventDefault();
		
		var currentProject = $(this).closest('.project'),
			projectArea = currentProject.parent(),
			projects = projectArea.find('.project'),
			height = currentProject.height(),
			scrollTop = projectArea.parent().scrollTop(),
			projectAreaHeight = projectArea.height(),
			self = $(this);
			
			projectArea
				.fadeOut(function(){
					projectArea.fadeIn();
					projects.removeClass('selected');
					
					if(self.hasClass('right')) {
						if(projectAreaHeight > (scrollTop + height)) {
							projectArea.parent().scrollTop(scrollTop + height);
							currentProject.next().addClass('selected');
						} else {
							projectArea.parent().scrollTop(0);
							projectArea.find('.project:first-child').addClass('selected');
						}
					} else {
						if(scrollTop > 0) {
							projectArea.parent().scrollTop(scrollTop - height);
							currentProject.prev().addClass('selected');
						} else {
							projectArea.parent().scrollTop(projectAreaHeight - height);
							projectArea.find('.project:last-child').addClass('selected');
						}
					}
				});
	});
	
	this.find('.controls .play').click(function(e) {
		e.preventDefault();
		$('.divHomeProjectBox').toggleClass('playing');
		if($('.divHomeProjectBox').hasClass('playing')) {
			setTimeout('projectBoxSlideShow();', 5000);
		}
	});
	
	setTimeout('projectBoxSlideShow();', 5000);
	
	return this;
}

function projectBoxSlideShow() {
	if($('.divHomeProjectBox').hasClass('playing')) {
		$('.divHomeProjectBox div.selected a.right').trigger('click');
		setTimeout('projectBoxSlideShow();', 5000);
	}
}


// If Internet Explorer would never have existed, our lifes would have been so much easier..
// The whole web industry would not be bending itself in a million different angles to create
// modern websites while still supporting stone age browsers which for some reason are still
// widely used. If only people at the biggest software company in the world had the slightest
// bit of vision and not just $$ signs in their eyes, the digital world would definitely be
// a better and more pleasant place. Here's a bit of code specifically for Internet Explorer,
// besides all the effort put into making standard compliant code, CSS and HTML also
// behave similarly in this browser beyond hope. Amen.
function handleInternetExplorerShortcomings() {
	// IE6 or lower
	if ($.ie6()) {
		// Fix the menu width!
		var mm = $('#mainMenu');
		mm.find('ul').css({width: mm.width() - 2});
		
		// Transparent PNGs hurray!
		$.ifixpng('assets/images/pixel.gif');
		$('#group span img, #wrap .siteHeader, .siteHeader img#logo, .siteHeader #searchButton, #labelsPage .labelList li a .front h2 ').ifixpng();
		
		// Add hover to some anchors, because "a:hover someelem" doesn't do anything in IE6... ;_;
		$('#group a').hoverIntent(function() {
			$(this).children('span').css('zIndex', 9).slideDown();
		}, function() {
			$(this).children('span').css('zIndex', '').slideUp();
		});

		// Remove &nbsp; from spans which only have it to validate, as IE doesn't understand
		// it shouldn't underline them on hover... naturally! o.O
		$('ul.tab_list > li > a > span').empty();
		//alert($('ul.tab_list span:first').height());
	}
}

// In here call everything which needs to be done on document load only
function processDocument(context) {
	handleInternetExplorerShortcomings();
	
	var context = context || this;

	// add nice rounded shadows9
	addShadows();
	
	//$("a.brochureBestellen").lightbox({onShow: processForm});
	$(".single[title='Vrijblijvende waardebepaling'] a.collection_item_url").lightbox({onShow: processForm});
	
	// Set a global AJAX loader.
	var loader = $('<div class="ajaxLoader"/>').css('opacity', 0.4).hide().appendTo('body'), loaderTimer;
	$('body').ajaxStart(function() {
		clearTimeout(loaderTimer);
		loader.fadeIn();
	}).ajaxComplete(function() {
		clearTimeout(loaderTimer);	
		loaderTimer = setTimeout(function() { loader.fadeOut(); }, 1000);
	}).ajaxError(function() {
		clearTimeout(loaderTimer);
		loaderTimer = setTimeout(function() { loader.fadeOut(); }, 1000);
	});

	// Prettify our top select box
	$('#quickNavSelect').selectbox();
	
	// Process the main menu; if there are more tabs, create a mouseover
	$('#mainMenu > li').hoverClass('hover');
	
	// Make the company list in the bottom real pretty
	$("#group").bubbleSkin().bubble();
	
	/* home page of burgland group , the tooltips */
	$('#centreCollectionPane .group_logos ul li a').Tooltip({bodyHandler: tooltipBodyHandler, fixPNG: true, showURL: false, delay: 0.3, track: true, opacity: 0.5, left: 10, top:-45});
	$('<div id="tooltipRight"></div>').prependTo($('#tooltip')).ifixpng().find('.body').ifixpng();
	$('#tooltip .body').ifixpng();
	
	$('#projectSearchForm').find('select:not(.autoSubmit)').addClass('autoSubmit').change(function() {
		$(this).parents('form:first').submit();
	});
	// the change event did not work on the radios in IE, so this will solve that:
	$('#projectSearchForm').find(':radio:not(.autoSubmit)').addClass('autoSubmit').click(function() {
		$(this).parents('form:first').submit();
	});
	
	$('#makelaarsMenu li.level1:has(ul) > a').simpleMakelaarsSlideDown();
		
	// Create the company fold out list
	$('#mainMenu a').filter(':contains(Burgland Bedrijven), :contains(Burgland bedrijven)').companyFoldOut();
	$('#sitemap a.level2').filter(':contains(Burgland Bedrijven), :contains(Burgland bedrijven)').parent().remove();
	// Process content is for possible ajax loaded content
	processContent(context);
}

function tooltipBodyHandler() {
	return '<div class="top"></div><div class="left"></div><div class="content">' + $(this).next('.bubble').html() + '</div><div class="bottom"></div>';
};

function processForm(context) {
	$('form#waardebepalingForm:not(.processed), form#brochureForm:not(.processed)', context)
		.addClass('processed')
		.args({output: 'json', retrieve: 'data', data: ['missing', 'validated', 'error']})
		.ajaxForm({dataType: 'json', success: ajaxFormReply, beforeSubmit: beforeFormSubmit});
}

$.fn.simpleMakelaarsSlideDown = function() {
	this.each(function() {
		var a = $(this), ul = a.next(), timer = false;
		a.add(ul).hoverIntent(function() {
			clearTimeout(timer);
			ul.slideDown(500, 'easeInOutCubic');
		}, function() {
			timer = setTimeout(function() { ul.slideUp(500, 'easeInOutCubic'); }, 400);
		});
	});
}

 // Process all dynamically loaded content here
function processContent(context) {
	var context = context || this, $context = $(context);
	$('#contentWrapper span.ewyseImageInContent').shadow({margin: 'none'});
	
	var homePane = $('#homepageProjectsPane');
	if (homePane.length) {
		homePane.find('ul.tab_list').ajaxifyTabList({ajaxParams: {retrieve: 'content', element: 'tab'}, find: 'div.paneContent'});
		homePane.find('a.next').projectCarrousel({autostart: true});
		homePane.find('form.statusSelect').ajaxifyHomepageProjectsSelect();
	}
	
	$("#footerMenu a:has('span:contains('Disclaimer')')", context).lightbox({onShow: processContent});

	// project tool stuff
	processProjectList(context);
	// Stuff that needs to be done with collections
	processCollections(context);

	$context.find('form.ajaxForm').ajaxFormDefault();
}

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');
}

// All JS that needs to run on the projecttool pages
function processProjectList(context) {
	var context = context || this, $context = $(context);

	$('#projectSearchbox select').selectbox();

	$(':radio.toggle:not(.jq_toggle)', context).addClass('jq_toggle').click(function(e) {
		var show = $(this).is('#giftType_terugkerend:checked');
		var input = $('input', $(this).parents('#radios:first').find('blockquote.frequency')[show ? 'slideDown' : 'slideUp']('fast')).enabled(show);
	}).triggerHandler('click');

	//if (!$('#contentWrapper > div.projectListWrapper').length) return;

	$context.find('form.ajaxForm').ajaxFormDefault();
	
	// Internet exploder can't handle the heavy shadow action
	if (!$.browser.msie) $('ul.subProjectList li, ul.mediaList li', context).shadow();

	// This function creates a nice slider for the media bar in projects
	handleOverflow(context);
	// Insert google maps
	googleMapify(context);

	// Let the pager of projects navigate with ajax, instead of page reloads
	var nav = $('div.projectListWrapper div.collection_navigation:first:not(.processed)');

	if (nav.length) {
		// Pretty stupid piece of code which could be cleaned up and abstracted of course, but it needs a prettier solution anyways
		nav.addClass('processed').find('.prevItem, .nextItem').remove();
		var buttons = {right: $('a.nextItem', nav), left: $('a.prevItem', nav)};
		if (!buttons.right.length) buttons.right = $('<a class="nextItem" href="#nada"><span>&gt;&gt;</span></a>').appendTo(nav);
		if (!buttons.left.length) buttons.left = $('<a class="prevItem" href="#nada"><span>&lt;&lt;</span></a>').prependTo(nav);
		var nav2 = $('#contentWrapper div.projectListWrapper div.collection_navigation:eq(1)');
		var buttons2 = {right: $('a.nextItem', nav2), left: $('a.prevItem', nav2)};
		if (!buttons2.right.length) buttons2.right = $('<a class="nextItem" href="#nada"><span>&gt;&gt;</span></a>').appendTo(nav2);
		if (!buttons2.left.length) buttons2.left = $('<a class="prevItem" href="#nada"><span>&lt;&lt;</span></a>').prependTo(nav2);
		buttons.left = buttons.left.add(buttons2.left);
		buttons.right = buttons.right.add(buttons2.right);
		// Now, ajaxify our project pager
		$('a.page', nav).ajaxNav({
			target: nav.next(),
			hash: false,
			preload: false,
			dimensional: false,
			keyNav: true,
			fade: false,
			callback: processContent,
			createWorkspace: true,
			classActive: 'activePage',
			ajaxParams: {output: 'json', retrieve: 'content'},
			buttons: buttons,
			find: 'ul.projectList'
		});
	}

	// Load project details with ajax
	if (context.id != 'lightbox') $('ul.projectList', $context).ajaxifyProjects();

	// Let the tabs in project details load with ajax
	$('span.projectInner ul.tab_list', context).each(function() {
		$(this).ajaxifyTabList({ajaxParams: {retrieve: 'content', project: $(this).parents('li.project').children('a.projectName').metadata().projectId, projectElement: 'tab'}, find: '>*'});
	});
	
	// Make all the media in projects show in the gallery plugin
	$('ul.mediaList', context).ewyseGallery('li.media a', {rewriteFunction: resizeImage});
	$('div.projectMediaBar', context).ewyseGallery('a', {rewriteFunction: resizeImage});
	
	$('ul.subProjectList a, a.lightbox', context).lightbox({onShow: processProjectList});	

	function slideClosed() {
		$(this).stop().animate({width: 0}, 'normal', 'easeInOutCubic');
	}
	
	$('span.extraInner:not(.slider)', context).addClass('slider').each(function() {
		var container = $(this), items = container.find('a'), timer = false;
		items.hover(function() {
			var self = $(this), span = self.children('span');
			span.css({position: 'absolute', display: 'block', right: 37, overflow: 'visible'});
			var width = span.outerWidth();
			self.stop().animate({width: width}, 'normal', 'easeInOutCubic');
			clearTimeout(timer);
			items.not(this).trigger('slideClosed');
		}, function() {
			var self = $(this);
			timer = setTimeout(function() { self.trigger('slideClosed'); }, 300);
		}).bind('slideClosed', slideClosed);
	});
}

// Process everything which needs to be done on collections (also at ajax callbacks)
function processCollections(context) {
	var context = context || this;
	$('div.sfeerbeeld', context).shadow({imagePath: 'assets/images/shadow-round/', margin: 'none'});
	
	//$('div.banner ul.collection_items', context).shadow();
	
	// Make the tabs work with AJAX
	$('#centreCollectionPane, #rightCollectionPane, #homepageCollectionPane').each(function() {
		var paneId = this.id;
		
		$('ul.tab_list', this).each(function() {
			var parentId = $(this).parents('.ewyse_collection:first').attr('id');
			$(this).ajaxifyTabList({callback: processCollections, ajaxParams: {retrieve: 'pane', pane: paneId}, find: '#' + parentId + ' div.ewyse_inner_collection:first'});
		});
		
		var nav = $('div.collection_navigation:not(.processed)', this);

		if (nav.length) {
			nav.each(function() {
				$(this).addClass('processed');
				var buttons = {right: $('a.nextItem', this), left: $('a.prevItem', this)};
				if (!buttons.right.length) buttons.right = $('<a class="nextItem" href="#nada"><span>&gt;&gt;</span></a>').appendTo(this);
				if (!buttons.left.length) buttons.left = $('<a class="prevItem" href="#nada"><span>&lt;&lt;</span></a>').prependTo(this);
				var id = $(this).parents('[id]:first').attr('id');

				$('a.page', this).ajaxNav({
					target: $(this).prev(),
					preload: false,
					dimensional: false,
					hash: false,
					keyNav: false,
					fade: false,
					callback: processContent,
					createWorkspace: true,
					classActive: 'activePage',
					ajaxParams: {retrieve: 'pane', output: 'json', pane: paneId},
					find: '#' + id + ' ul:first',
					buttons: buttons
				});
			});
		}
	});
	
	$('select', context).filter('.collection_selectbox').selectbox();
	// Make the selectbox form an ajax form.
	$('div.collection_selectbox', context).ajaxifyCollectionSelect();
	
	$('select.collection_selectbox:not(.processed)', context).addClass('processed').bind('change', function() {
		$(this).parents('form:first').submit();
	});
}

$.fn.ajaxifyHomepageProjectsSelect = function() {
	function show(toShow, toHide) {
		toHide.animate({height: 'hide'}, 'normal', 'easeInOutCubic', function() {
			toShow.animate({height: 'show'}, 'normal', 'easeInOutCubic', function() {});
			processContent(toShow.parent());
		});
	}
	
	this.filter(':not(.jq_ajaxSelect)').addClass('jq_ajaxSelect').each(function() {
		var self = $(this),
			selectBox = self.find('select'),
			map = {}, active = selectBox.val(), stack = [];
		map[active] = self.next();
		
		self.find(':submit, :image').css('display', 'none');
		self.args({retrieve: 'content', element: 'tab', output: 'json'}).ajaxForm({dataType: 'json', beforeSubmit: function() {
			var current = selectBox.val();
			if (map[current]) {
				show(map[current], map[active]);
				active = current;
				return false;
			} else stack.unshift(current);
		}, success: function(json) {
			var current = stack.pop();
			map[current] = $('div.itemsWrapper', json.content).insertAfter(map[active]).hide();
			show(map[current], map[active]);
			active = current;
		}});
	});
	return this;
}

$.fn.ajaxifyCollectionSelect = function() {
	function show(toShow, toHide) {
		toHide.animate({height: 'hide'}, 'normal', 'easeInOutCubic', function() {
			toShow.animate({height: 'show'}, 'normal', 'easeInOutCubic', function() {});
			processCollections(toShow.parent());
		});
	}
	
	this.filter(':not(.jq_ajaxSelect)').addClass('jq_ajaxSelect').each(function() {
		var self = $(this), id = self.attr('id'), form = self.find('form.collection_selectbox_form:first'),
			pane = self.parents('[id$=CollectionPane]:first').attr('id'),
			selectBox = form.find('select'),
			map = {}, active = selectBox.val(), stack = [];
		map[active] = self.find('div.ewyse_inner_collection:first');
		if (form.length && id && pane) {
			form.find(':submit, :image').css('display', 'none');
			form.args({retrieve: 'pane', pane: pane, output: 'json'}).ajaxForm({dataType: 'json', beforeSubmit: function() {
				var current = selectBox.val();
				if (map[current]) {
					show(map[current], map[active]);
					active = current;
					return false;
				} else stack.unshift(current);
			}, success: function(json) {
				var current = stack.pop();
				map[current] = $('#' + id + ' div.ewyse_inner_collection:first', json.content).insertAfter(map[active]).hide();
				show(map[current], map[active]);
				active = current;
			}});
		}
	});
	return this;
}

function googleMapify(context) {
	$('dl.locatieAttributes:not(.googleMapified)', context).addClass('googleMapified').each(function() {
		if (!window.GClientGeocoder) return;
		var $dl = $(this), address = '', hash = {}, addressHtml = '';
		// lousy address stuff code
		$.each('Straat Huisnummer Postcode Plaats'.split(' '), function() {
			var val = $('dt:contains(' + this + ')', $dl).next().text() + ' ';
			address = address + val;
			hash[this] = val;
		});
		hash['Adres'] = hash['Straat'] + ' ' + hash['Huisnummer'];
		var zoom = $.trim(hash.Straat).length > 0 ? 16 : 6;
		delete(hash['Straat']);
		delete(hash['Huisnummer']);
		
		$.each(hash, function(key, value) {
			addressHtml = addressHtml + value + "<br>";
		});
		
		(new GClientGeocoder()).getLatLng(address, function (loc) {
			if (!loc) return;
			var $gmaps = $dl.prepend('<dt class="gmapsToggle mapsLoading"/><dd class="gmapsDD"><div class="gmaps"/></dd>').find('div.gmaps'), gmaps = $gmaps.get(0);
			if (gmaps) {
				var map = new google.maps.Map2(gmaps), marker = new GMarker(loc);
				GEvent.addListener(map, "load", function(){
					setTimeout(function() {
						$dl.find('dd.gmapsDD').animate({height: $gmaps.outerHeight()}, 'normal', 'easeInOutCubic', function() {
							$gmaps.css('position', 'relative');
							$(this).css('height', 'auto');
						});
						$dl.children('dt.gmapsToggle').click(function() {
							if ($gmaps.is(':visible')) $gmaps.animate({height: 'hide'}, 'normal', 'easeInOutCubic');
							else $gmaps.animate({height: 'show'}, 'normal', 'easeInOutCubic');
						});
					}, 1000);
				});
				map.addControl(new GSmallZoomControl());
				map.addControl(new GMapTypeControl());
				//map.enableScrollWheelZoom();
				map.enableContinuousZoom();
				//GMap2.infoWindowEnabled()
				map.setCenter(loc, zoom);
				
				map.addOverlay(marker);
				GEvent.addListener(marker, 'click', function(){
					marker.openInfoWindowHtml(addressHtml);
				});
				marker.openInfoWindowHtml(addressHtml);
			}
		});
	});
}

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);
}

// Add nice rounded shadows to several elements.
function addShadows() {
	//$('.siteHeader').shadow({corners: "tl tr", sides: 'left top right', innerOverlap: true, imagePath: 'assets/images/shadow-header/'});
	$('#footerMenu').shadow({imagePath: 'assets/images/shadow-round/'});
	$('#main').shadow({corners: "bl br", sides: 'left bottom right'});
}

(function($){
	$.fn.ajaxFormDefault = function() {
		this.filter('form:not(.processed)').addClass('processed').each(function() {
			var $this = $(this), args = {output: 'json', retrieve: 'data', data: ['missing', 'validated']};
			// we have to make an exception for this special form type
			if ($this.is('#donatieForm')) args.retrieve = 'content';
			$this.args(args);
		}).ajaxForm({dataType: 'json', success: ajaxFormReply, beforeSubmit: beforeFormSubmit});
		return this;
	};
		  
	$.fn.ajaxifyTabList = function(options) {
		var options = $.extend(true, 
			{
				dimensional: false,
				preload: false,
				hash: false,
				fade: false,
				callback: processContent,
				createWorkspace: true,
				ajaxParams: {output: 'json'}
			}, options);
		this.filter(':not(.ajaxTabProcessed)').addClass('ajaxTabProcessed').each(function() {
			var self = $(this);
			self.find('a').ajaxNav($.extend({target: self.next()}, options));
		});
		return this;
	};
	
	$.fn.projectCarrousel = function(options) {
		options = $.extend(
			{
				autostart: false, 		/* Autostart the animation */
				autostartDelay: 5000,	/* Milliseconds to wait between transition */
				autoRestart: true,		/* Restart after user manually clicked */
				restartDelay: 10000		/* Milliseconds to wait before restart */
			}, options
		);
		
		this.filter(':not(.processed)').addClass('processed').each(function() {
			var timer;
			var self = $(this), timer = false, cpath = parseGetParameters(this.href)['cpath'], parts = cpath.split('_'), current = parts.pop() - 1, strippedCpath = parts.join('_') + '_', total = self.metadata().total, container = self.parent().children('div.items'), currentContent = container.children('a:first'), width = currentContent.width();
			function show(next) {
				next.css({position: 'relative', display: 'block', zIndex: 1});
				currentContent.css({position: 'absolute', zIndex: 2, width: width}).fadeOut('slow');
				currentContent = next;
			}
			
			function nextImage(e) {
				if (e && e.preventDefault) e.preventDefault();
				
				/* If the user clicked manually (i.e. there is a target for this event), stop the animation (autostart) */
				if (e && e.target) clearTimeout(timer);
				
				current++;
				if (current >= total) current = 0;
				var next = $('.item_' + current, container);
				if (!next.length) {
					$.getJSON($.makeURL(rewriteRoot, {retrieve: 'content', cpath: strippedCpath + current, output: 'json', element: 'items'}), function(json) {
						$('a.item', json.content).css({position: 'absolute', display: 'none'}).appendTo(container);
						next = $('.item_' + current, container);
						if (next.length) show(next);
					});
				} else show(next);
			}
			
			self.click(nextImage);
			
			if (options.autostart) {
				timer = setInterval(nextImage, options.autostartDelay);
				
				/* When hovering over the button, stop the autostart, and continue on mouseout */
				self.hover(
				   function() {
					   clearTimeout(timer);	
				   },
				   function() {
					   	if (options.autoRestart) {
							/* Use the same timer to wait for the restartDelay. After this delay, the autostart will continue again */
							timer = setTimeout(function() {
								timer = setInterval(nextImage, options.autostartDelay);
							}, options.restartDelay);
						}
					}
				);
			}
		});
		return this;
	};
	
	$.fn.ajaxifyProjects = function() {
		var ul = $(this).filter(':not(.ajaxifiedProjects)');
		
		if (ul.length > 0) {
			ul.addClass('ajaxifiedProjects');
			var items = $('>li', ul), active = items.filter('.activeItem');
			function show(li) {
				if (active) active.trigger('hideProject');
				if (active[0] == li[0]) active = false;
				else active = li.trigger('showProject');
			}
	
			items.each(function() {
				var li = $(this), a = $('>a.projectName', li), href = a.attr('href'), base = href.split('?')[0], hash = '#' + href.split('#').pop(), metadata = a.metadata(), projectId = metadata.projectId, content = false;
				if (li.is('.activeItem')) content = li.find('span.projectInner');
				
				li.bind('showProject', function() {
					li.addClass('activeItem');
					
					/*
					var url = $(this).find(".tab_link:contains('Investors')");
					var newUrl = $(url).parents('.ajaxNav_viewport').find('.subProjectList li a').attr('href');

					if (newUrl != 'undefined') {
						$(url).removeAttr('href').attr('href', newUrl);
						$(url).lightbox({onShow: processProjectList});
					}
					*/
					content.animate({height: 'show', queue: false}, 'normal', 'easeInOutCubic', function() {
						//window.location.hash = hash;
						$(document).scrollTo(li, 'slow', {easing: 'easeInOutCubic', offset: -40});
					});
				});
				
				li.bind('hideProject', function() {
					li.removeClass('activeItem');
					content.animate({height: 'hide', queue: false}, 'slow', 'easeInOutCubic');
				});
				
				a.add(a.next().children('a.imageLink')).click(function(e) {
					e.preventDefault();
					if (!content) {
						$.getJSON($.makeURL(base, $.extend(parseGetParameters(this.href), {retrieve: 'content', projectElement: 'innerProject', output: 'json', project: projectId})), function(json) {
							var wrapper = $('span.projectWrapper', li);
							try { pageTracker._trackPageview(json.name); } catch (e) { if (window.console) console.log("Tracking error in ajaxifyProjects: " + e); }
							content = $(json.content).css({visibility: 'hidden', position: 'absolute', clear: 'both', width: wrapper.width()}).appendTo(wrapper);
							processProjectList(content.parent());
							content.css({display: 'none', visibility: '', position: ''});
							show(li);
						});
					} else show(li);
				});
			});
		}
		return this;
	};
	
	$.fn.companyFoldOut = function() {
		var companySubmenu = false, templateCover, child, outerHeight, $this = this;
		return this.click(function(e) {
			e.preventDefault();
			var self = $(this);
			function toggleMenu() {
				if (companySubmenu.is(':visible')) {
					$this.removeClass('toggleItem');
					templateCover.fadeOut();
					child.stop().animate({top: -outerHeight}, 'normal', 'easeInOutCubic', function() { companySubmenu.hide(); });
				} else {
					$this.addClass('toggleItem');
					companySubmenu.show();
					templateCover.css('height', $('#template').height()).fadeIn();
					child.stop().animate({top: 0}, 'normal', 'easeInOutCubic');
				}
			}
			
			if (!companySubmenu) {
				templateCover = $('<div id="templateCover"/>').css({opacity: 0.8, backgroundColor: 'white', position: 'absolute', left: 0, top: 0, width: "99%", display: 'none', zIndex: 20}).appendTo('#template');
				companySubmenu = $('<div id="companySubmenu"><div id="companySubmenuInner"><div id="companySubmenuTitle">Kies een Burgland bedrijf voor meer informatie</div></div></div>').css({zIndex: 21, visibility: 'hidden'});
				var items = $('<div id="companySubmenuItems" />');
				$('#group > li').each(function() {
					var $this = $(this);
					var name = $this.attr('title');
					$('<a />').attr({title: name, href: $this.find('a').attr('href')}).text(name).appendTo(items);
				});
				child = companySubmenu.insertAfter('#mainMenu').children().append(items);
				outerHeight = child.outerHeight();
				child.css('top', -outerHeight);
				companySubmenu.css({visibility: 'visible', display: 'none'});
			};
			toggleMenu();
			return false;
		});
	};

	
	//	olivier@wharf.nl - bubble - just like a tooltip with smoother behavior (the tooltip is hoverable)
	$.fn.bubble = function(){
		var $ul = $(this);
		$ul.children(':not(.jq_bubble)').each(function(i,o){
			$(this).addClass('jq_bubble');
			var $popOut = $("span.bubble", this).css('display','none'), timeout;
			$(this).hoverIntent(function(){
				clearTimeout(timeout);
				$popOut.animate({height: 'show'}, 'normal', 'easeInOutCubic');
			},function(){
				timeout = setTimeout(function() {
					$popOut.animate({height: 'hide'}, 'normal', 'easeInOutCubic');
				}, 200);
			});
		});		

		return this;
	};
	
	$.fn.bubbleSkinGroup = function() {
		var content, src, imgname, name, bubble;
		if (!$.ie6()) $('li:not(.jq_bubbleSkin)', this).each(function(){
			$(this).addClass('jq_bubbleSkin');
			bubble = $('span.bubble', this).wrapInner('<span class="bubble_middle" />').prepend('<span class="bubble_left" />').append('<span class="bubble_right" />');
			$(bubble).children().css({display: 'block'});
			$('.bubble_middle', this).css({background: 'url(assets/images/bubble/home/bubble_bg.png) 0 0 repeat-x'});
			$('.bubble_left', this).css({background:  'url(assets/images/bubble/home/bubble_bg_left.png) 0 0 no-repeat'});
			$('.bubble_right', this).css({background: 'url(assets/images/bubble/home/bubble_bg_right.png) 0 0 no-repeat'});						
		});
		return this;
	}
	
	$.fn.bubbleSkin = function() {
		var content, src, imgname, name, bubble;
		if (!$.ie6()) $('li:not(.jq_bubbleSkin)', this).each(function(){
			$(this).addClass('jq_bubbleSkin');
			bubble = $('span.bubble', this).wrapInner('<span class="bubble_middle" />').prepend('<span class="bubble_top" />').append('<span class="bubble_bottom" />');
			$(bubble).children().css({display: 'block'});
			src = $('img', this).attr('src');
			imgname = src.substring(src.indexOf('name=') + 5, src.length - 4);
			name = imgname.toLowerCase();
			$('.bubble_middle', this).css({background: 'url(assets/images/bubble/'+name+'/bubble_bg.png)'});
			$('.bubble_top', this).css({background:  'url(assets/images/bubble/'+name+'/bubble_bg_top.png) 0 0 no-repeat'});
			$('.bubble_bottom', this).css({background: 'url(assets/images/bubble/'+name+'/bubble_bg_bottom.png) 0 0 no-repeat'});						
		});
		return this;
	}

	$.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));
			}
		});
	}

	$.fn.foldIt = function () {
		var self = $(this), headers = $('>h2', self);
		headers.bind('foldItClosed', function() {
			var h2 = $(this);
			if (h2.is('.foldItClosed')) return;
			h2.removeClass('foldItOpen').addClass('foldItClosed');
			h2.next().stop(false, true).animate({height: 'hide'}, 'normal', 'easeInOutCubic');
		}).bind('foldItOpen', function() {
			var h2 = $(this);
			headers.not(this).trigger('foldItClosed');
			if (h2.is('.foldItOpen')) return;
			h2.removeClass('foldItClosed').addClass('foldItOpen');
			h2.next().stop(false, true).animate({height: 'show'}, 'normal', 'easeInOutCubic');
		});
		
		headers.addClass('foldItOpen').css('cursor','pointer').click(function(e){
			$(this).trigger($(this).is('.foldItOpen') ? 'foldItClosed' : 'foldItOpen');
		}).eq(0).trigger('foldItOpen');
		return this;
	}

	$.fn.imageReady = function(callback, callbackParams) {
		callbackParams = callbackParams || [];
		var images = this.filter('img'), count = images.length, loaded = 0, self = this;
		images.each(function() {
			if (this.complete) loaded++;
			else $(this).one('load', function() {
				loaded++;
				if (loaded == count) callback.apply(self, callbackParams);
			});
		})
		if (loaded == count) callback.apply(self, callbackParams);
		return this;
	};
	
	// 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;
	}

})(jQuery);

function openLinkInLightbox(href, options) {
	var base = href.split('?')[0], args = parseGetParameters(href);
	$.extend(args, {output: 'json', retrieve: 'content'});
	var url = $.makeURL(base, args);
	url = encodeURI(url);
	$.getJSON(url, function(json) {
		PopupMessage().lightbox(json.content, options);
	});
}

// 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;
};

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 handleOverflow(el) {
	var helper, content, hY, cY, currentLeft;
	helper = $('div.projectMediaBarInner:not(.processed)', el);
	
	if (!helper.length) return;
	
	$('img', helper).imageReady(goOnThen);

	function goOnThen() {
		helper.css({position: 'relative'}).addClass('processed').wrapInner('<div/>');
		// In our case the parent has the correct width
		hY = helper.parent().width();
		content = helper.children(':first').css({position: 'absolute'});
		cY = content.width();
		var checkButtons = function() {
			bUp.css('display', (currentLeft < 0 ? 'block' : 'none'));
			bDown.css('display', (-(currentLeft - hY) < cY ? 'block' : 'none'));
		};
		
		currentLeft = content.position().left;
		
		if (cY > hY) {
			helper.css({overflow: 'hidden', zoom: 1});
			var helperParent = helper.parent();
			var bDown = $('<img class="nextButton"/>')
				.appendTo(helperParent)
				.attr('src', rootURL + 'assets/images/buttons/next.png')
				.click(function(e) {
					currentLeft -= hY;
					if (-(currentLeft - hY) > cY) currentLeft = -cY + hY;
					content.stop().animate({left: currentLeft}, 'normal', 'easeOutCubic', checkButtons);
				});
			var bUp = $('<img class="prevButton"/>')
				.prependTo(helperParent)
				.attr('src', rootURL + 'assets/images/buttons/prev.png')
				.click(function() {
					currentLeft += hY;
					if (currentLeft > 0) currentLeft = 0;
					content.stop().animate({left: currentLeft}, 'normal', 'easeOutCubic', checkButtons);
				});
			
			checkButtons();
			
			var scrollTimeout = false;
			helper.mousewheel(function(e, delta) {
				e.preventDefault();
				currentLeft += delta * 150;
				if (currentLeft > 0) currentLeft = 0;
				if (-(currentLeft - hY) > cY) currentLeft = -cY + hY;
				content.get(0).style.left = currentLeft + 'px';
				checkButtons();
			});
		}
	}
}

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') + '"]:not(.error)');
					if (el.is(':radio')) {
						var newEl = $([]);
						el.each(function() {
							newEl = newEl.add($(form).find('label[for="' + this.id + '"]:not(.error)'));
						});
						el = newEl;
					}
					if (el.length) {
						var pos = el.position();
						if (error) {
							var pos = el.position();
							pos.top -= 8;

							var message = $('<span class="errorMessage"/>')
								.text(error)
								.appendTo(el.parent())
								.css({
									position: 'absolute',
									left: pos.left + 20,
									top: pos.top + 7,
									cursor: 'pointer'
								}).click(function() {
									el.focus();
								});
						}
						el.addClass('error').one('focus click', function() {
							if (error) message.remove();
							el.removeClass('error');
						});
					}
				}
			});
			if (!$form.parents('#lightbox').length) $.scrollTo('.error:first', 500, {easing: 'easeOutCubic'});
		} else {
			PopupMessage().lightbox(json.message);
		}
	} else {
		if ($form.is('.postcodeCheckForm')) {
			processContent.apply($('.postCodeCheckWrapper').replaceWith(json.content));
		} else {
			PopupMessage().lightbox(json.message);
		}
	}
}

