if ($.browser.safari) $(window).load(init);
else $(init);

if (!window.console) {
	window.console = {
		log: function() {}
	};
}

function init() {
	$('body').removeClass('nonJS').addClass('js');
	
	// Hide the details menu items; they are elements that should not be accessed directly
	$('ul.subSubMenu > li.level2, div#sitemap ul.level4 > li').filter(':has(span:contains(Details))').each(function() {
		var self = $(this), text = $.trim(self.find('> a span').not('.helper1, .helper2').text()).toLowerCase();
		text = encodeURI(text.replace(/\n|\t|\r/, ''));
		if (text == 'details') {
			self.hide();
			if (self.parent().find('li.level2').length == 1) self.parent().remove();
		}
	});
	
	$.ifixpng('assets/pixel.gif');
	$('img.saleImage').ifixpng();

    $('#country_selector select').selectbox({'hideFirstItem' : true});
    $('#country_selector input[type=submit]').hide();
    $('#country_selector .selectbox-wrapper li').click(function(){
        location = $(this).attr('id');
    });
	
	// Set a global AJAX loader.
	var loader = $('<div class="ajaxLoader"/>').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);
	});
	
	try {
		document.execCommand("BackgroundImageCache", false, true);
	}
	catch (err) {}
	
	//handleOverflow();
	$('div.mediaBarInner').prettyOverflow({innerWrap: true});
	$('div.events_most_voted div.collection_innerWrapper').prettyOverflow({innerWrap: true});
	
	$('ul.subSubMenu.level1 > li.level1.activeItem:has(ul.level2) > a > span.helper2').css({backgroundImage: 'url(assets/menu/subsub-right-active.gif)'});
	
	$('div.fold_out, .downloads').each(function() {
		var container = $(this), items = container.find('li'), active = false;
		
		function set(title, fold, active) {
			if (active) {
				title.removeClass('closed').addClass('open');
				fold.slideDown('slow', 'easeOutCubic');
			} else {
				title.removeClass('open').addClass('closed');
				fold.slideUp('slow', 'easeOutCubic');
			}
		}
		
		items.each(function() {
			var li = $(this), fold = li.find('span.collection_item_content').hide(), title = li.find('span.collection_item_no_url').addClass('closed');
			
			li.bind('foldOpen', function () { set(title, fold, true); });
			li.bind('foldClosed', function () { set(title, fold, false); });
			
			title.click(function() {
				if (active) active.trigger('foldClosed');
				if (active[0] != li[0]) active = li.trigger('foldOpen');
				else active = false;
			});
		});
	});
	
	PopupMessage().set({lightboxButton: 'assets/images/sluiten.gif', width: 946, shadow: {}});	
	
	$('input.jq_example').example(function() {
		return $(this).metadata().empty;
	})
	
	/*
	$('div#superFancontentWidthShinyColourBar').each(function() {
		var self = $(this), width = self.width();
		
		function bgSlide(elem) {
			elem = elem || $(this);
			elem.css('backgroundPosition', 0);
			elem.animate({backgroundPosition: width + 'px 0px'}, 6000, 'linear', bgSlide);
		}
		
		bgSlide(self);
	});
	*/
	
	$('#homepageImages').each(function() {
		var $this = $(this), items = $this.find('span.wrap a'), firstLI = items.filter(':first').parents('li:first')
			, active = false, activeIMG = firstLI.children('img'), activeSale = false
			, activeSlideOut = false, saleWidth = $this.find('a.homeSale:first').outerWidth();
		items.each(function() {
			var self = $(this), slideOutWrapper = self.find('.payOffSlideOut'), slideOut = slideOutWrapper.children()
				, width = slideOut.outerWidth(), img = self.parents('li:first').children('img')
				, sale = img.parent().find('a.homeSale');
			self.hoverIntent(function() {
				if (this == active) return;
				active = this;
				if (activeIMG.get(0) != img.get(0)) {
					activeIMG.fadeOut('slow');
					activeIMG = img.fadeIn('slow');
				}
				
				if (activeSlideOut) {
					activeSlideOut.parent().css('overflow', 'hidden');
					activeSlideOut.stop().animate({left: -width}, 'normal', 'easeInOutCubic', function() { $(this).parent().css('visibility', 'hidden'); });
					activeSlideOut = false;
				}
				if (slideOut.length) {
					slideOutWrapper.css('visibility', 'visible');
					activeSlideOut = slideOut.stop().animate({left: 0}, 'normal', 'easeInOutCubic', function() { $(this).parent().css('overflow', 'visible'); });
				}
				
				if (activeSale) {
					var anim = {left: -saleWidth};
					if (!$.browser.msie) anim.opacity = 0;
					activeSale.animate(anim);
					activeSale = false;
				}
				if (sale.length) {
					var anim = {left: 100};
					if (!$.browser.msie) anim.opacity = 1;
					activeSale = sale.css({left: saleWidth}).animate(anim);
				}
			}, function() {
				
			});
		});
	});
	
	$.ewyseGallery.set({
		imgPath: 'assets/gallery/',
		maxHeight: 467,
		minHeight: 467,
		minWidth: 697,
		maxWidth: 697,
		autoMaxDimension: true,
		fitImage: false,
		cacheAjaxRequests: true,
		flashparams: {height: 330}
	});
	
	$('div.ewyse_collection.assets:not(.events_with_vote_number) ul, div.mediaBarInner').ewyseGallery('a', {rewriteFunction: resizeImage});
	
	
	$('ul.tab_list').each(function() {
		var self = $(this);
		self.find('a').ajaxNav({
			ajaxParams: {retrieve: 'content', module: 'documents', output: 'json'},
			dimensional: false,
			preload: false,
			hash: false,
			fade: false,
			createWorkspace: true,
			target: self.next().children()
		});
	});
	
	// only add keynav once
	var keyNav = true;
	$('#centreCollectionPane, #rightCollectionPane, #leftCollectionPane, #bottomCollectionPane').each(function() {
		var paneId = this.id;
		var navs = $('div.ewyse_collection:not(.events_with_vote_number) div.collection_navigation:not(.processed)', this);
		if (navs.length) {
			navs.addClass('processed').each(function() {
				var nav = $(this), 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 id = nav.parents('[id]:first').attr('id');
				$('a.page', nav).ajaxNav({
					target: nav.prev(),
					preload: false,
					dimensional: false,
					hash: false,
					keyNav: keyNav,
					fade: false,
					createWorkspace: true,
					classActive: 'activePage',
					ajaxParams: {retrieve: 'pane', output: 'json', pane: paneId},
					find: '#' + id + ' ul:first',
					buttons: buttons
				});
				keyNav = false;
			});
		}
		$('div.events_with_vote_number', this).each(function() {
			var self = $(this), nav = self.find('div.collection_navigation'), id = this.id;
			self.find('img').imageReady(function() {
				$('a.page', nav).ajaxNav({
					target: nav.prev(),
					preload: true,
					hash: false,
					keyNav: false,
					createWorkspace: true,
					createViewport: true,
					fixViewport: true,
					callback: processContent,
					classActive: 'activePage',
					ajaxParams: {retrieve: 'pane', output: 'json', pane: paneId},
					find: '#' + id + ' ul:first',
					buttons: {left: 'assets/buttons/prev.png', right: 'assets/buttons/next.png'}
				});
			});
			nav.hide();
		});
	});
	
	processContent(document);
}

function processContent(context) {
	context = context || this;
	$('div.events_with_vote_number ul').each(function() {
		var self = $(this);
		$('a', this).each(function() {
			var a = $(this), vote_id = parseInt(a.find('span.collection_item_vote_id').text());
			a.attr('title', 'Photo ' + vote_id + ' - if you like this photo send ' + vote_id + ' to 3535 and you can win great prizes!');
		});
		self.ewyseGallery('a', {
			jsonCallback: function(images) {
				for (var i = 0; i < images.length; i++) {
					if (images[i].vote_id) images[i].title = 'Photo ' + images[i].vote_id + ' - if you like this photo send ' + images[i].vote_id + ' to 3535 and you can win great prizes!';
				}
				return images;
			},
			mode: 'json',
			url: $.makeURL(window.location.protocol + '//' + window.location.host + window.location.pathname, {output: 'json', extra: ['vote_id'], retrieve: 'collectionImages', view: self.parents('div.ewyse_collection').attr('id').split('_').pop()})
		});
		return this;
	});
}

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);
}

// 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($){
	$.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;
	};
	
	// Needs the mousewheel plugin and the imageReady plugin
	$.fn.prettyOverflow = function(options) {
		var options = $.extend({}, options);
		this.filter(':not(.jq_prettyOverflow)').addClass('jq_prettyOverflow').each(function() {
			var helper = $(this), content, helperWidth, contentWidth, currentLeft;
			
			// Wait for images to be loaded; otherwise we don't know the width of the element
			$('img', helper).imageReady(goOnThen);
			
			function goOnThen() {
				if (options.innerWrap) helper.css({position: 'relative'}).wrapInner('<div/>');
				helperWidth = helper.parent().width();
				content = helper.children(':first').css({position: 'absolute'});
				contentWidth = content.width();
				var checkButtons = function() {
					bUp.css('display', (currentLeft < 0 ? 'block' : 'none'));
					bDown.css('display', (-(currentLeft - helperWidth) < contentWidth ? 'block' : 'none'));
				};
				
				currentLeft = content.position().left;
				
				if (contentWidth > helperWidth) {
					helper.css({overflow: 'hidden', zoom: 1});
					var helperParent = helper.parent();
					var bDown = $('<img class="nextButton"/>')
						.appendTo(helperParent)
						.attr('src', rootURL + 'assets/buttons/next.png')
						.click(function(e) {
							currentLeft -= helperWidth;
							if (-(currentLeft - helperWidth) > contentWidth) currentLeft = -contentWidth + helperWidth;
							content.stop().animate({left: currentLeft}, 'normal', 'easeOutCubic', checkButtons);
						});
					var bUp = $('<img class="prevButton"/>')
						.prependTo(helperParent)
						.attr('src', rootURL + 'assets/buttons/prev.png')
						.click(function() {
							currentLeft += helperWidth;
							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 - helperWidth) > contentWidth) currentLeft = -contentWidth + helperWidth;
						content.get(0).style.left = currentLeft + 'px';
						checkButtons();
					});
				}
			}
			
		});
		return this;
	}
})(jQuery);