if ($.browser.safari) $(window).load(init);
else $(init);

if (!window.console) {
	window.console = {
		log: function() {}
	};
}

function init() {
	$('body').removeClass('nonJS').addClass('js');

	// 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) {}

	// 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, div.templateTop div.tl, div.templateTop div.tr, div.subMenuWrapper div.helper1, div.subMenuWrapper div.helper2, ul.subMenu span.helper3').ifixpng();
	
	$('#country_selector select').selectbox({'hideFirstItem' : true});
    $('#country_selector input[type=submit]').hide();
    $('#country_selector .selectbox-wrapper li').click(function(){
        location = $(this).attr('id');
    });
	
	// Make the overflow of mediabar elements elements look nicer, instead of the regular scrollbar
	$('div.mediaBar div.collection_innerWrapper:not(:has(div.collection_navigation))').prettyOverflow({innerWrap: true});
	
	// In case of an active submenu, show a different arrow
	$('ul.subSubMenu.level1 > li.level1.activeItem:has(ul.level2) > a > span.helper2').css({backgroundImage: 'url(assets/menu/subsub-right-active.gif)'});
	
	// Create JS foldouts to make the lists easier to use
	$('div.fold_out, .downloads').utsFoldout();
	
	// Initialise the popupmessage
	PopupMessage().set({lightboxButton: 'assets/gallery/close.png', width: 946, shadow: {}});
	// Show stuff in lightboxes?
	$('#divContent a.lightbox').lightbox({onShow: processForm});
	
	$('input.jq_example').example(function() { return $(this).metadata().empty; });
	
	// Create the homepage FX
	$('#homepageImages').utsHomepageEffects();
	
	// Initialise the fancy gallery
	$.ewyseGallery.set({
		imgPath: 'assets/gallery/',
		maxHeight: 467,
		minHeight: 467,
		minWidth: 697,
		maxWidth: 697,
		autoMaxDimension: true,
		fitImage: false,
		cacheAjaxRequests: true,
		flashparams: {height: 330}
	});
	
	// Dynamically load tab lists with ajax
	$('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, div.ewyse_inner_collection').filter(':not(.mediaBar, .collections)').find('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,
					callback: processContent,
					classActive: 'activePage',
					ajaxParams: {retrieve: 'pane', output: 'json', pane: paneId},
					find: '#' + id + ' ul:first',
					buttons: buttons
				});
				keyNav = false;
			});
		}
		$('div.mediaBar', this).each(function() {
			var self = $(this), nav = self.find('div.collection_navigation'), id = this.id, pages;
			self.find('img').imageReady(function() {
				pages = $('a.page', nav);
				if (pages.length) pages.ajaxNav({
					target: nav.prev(),
					preload: true,
					hash: false,
					keyNav: false,
					createWorkspace: 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();
		});
	});
	
	$('form.collection_selectbox_form').each(function() {
		var form = $(this);
		$('input', this).filter('.submit, .image').remove();
		$('select.collection_selectbox', this).selectbox().change(function(){ form.submit(); });
	});
	
	processContent(document);
}

function processContent(context) {
	context = context || this;
	$('div.assets').filter('.ewyse_inner_collection, .ewyse_collection').each(function() {
		var self = $(this), json = self.find('div.collection_navigation').length > 0, collections = $('ul.collection_items:not(.processed)', this).addClass('.processed');
		if (collections.length) {
			// This will be the ajax part... we have several pages of images
			if (json) {
				var parts = this.id.split('_'), urlArgs = {output: 'json', retrieve: 'collectionImages'};
				// A view ID is preferable; more information on how to show the collection. Otherwise we can get the collection itself
				urlArgs[parts[0] == 'colView' ? 'view' : 'doc_id'] = parts[1];
				collections.ewyseGallery('a', {
					mode: 'json',
					rewriteFunction: resizeImage,
					url: $.makeURL(rootURL, urlArgs)
				});
			} else {
				collections.ewyseGallery('a', {rewriteFunction: resizeImage});
			}
		}
	});
	/*
	$('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',
			rewriteFunction: resizeImage,
			url: $.makeURL(rootURL, {output: 'json', extra: ['vote_id'], retrieve: 'collectionImages', view: self.parents('div.ewyse_collection').attr('id').split('_').pop()})
		});
		return this;
	});
	*/
}

function processForm(context) {
	$('form#applicationForm:not(.processed), form#congressForm:not(.processed)', context)
		.addClass('processed')
		.args({output: 'json', retrieve: 'data', data: ['missing', 'validated', 'error']})
		.ajaxForm({dataType: 'json', success: ajaxFormReply, beforeSubmit: beforeFormSubmit, timeout: 60000})
		.find(':submit').click(function(e){
			$('div#lightboxContent > div').prepend('<div class="please_wait"><div class="please_wait_inner">Your personal data is being transmitted, please wait</div></div>');
			$('div.please_wait')
			.width(($('div.please_wait').parent().parent().parent().width())+'px')
			.height(($('div.please_wait').parent().parent().parent().height()-60)+'px')
			.find('div.please_wait_inner').css({
				'height' : $('div.please_wait').height(),
				'line-height' : $('div.please_wait').height()+'px'
			});
		});
}

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 ajaxFormReply(json, a, form) {
	$form = $(form);
	$form.find('.ajaxLoader').fadeOut('slow', function() { $(this).remove(); } );
	setTimeout("$('div.please_wait').fadeOut('slow', function() { $(this).remove(); } )", 1000);
	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;
					textarea = $(form).find('textarea#' + el.attr('id'));
					input = $(form).find('input#' + el.attr('id'));
					sel = $(form).find('select#' + el.attr('id'));
					
					if (el.is('textarea')) {
						var css = textarea.position();
						css.left += textarea.outerWidth() + 5;
					} else if (el.is('select')) {
						var css = sel.position();
						css.left += sel.outerWidth() + 5;
					} else {
						var css = input.position();
						css.left += input.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 PopupMessage().lightbox(json.message);
	} else PopupMessage().lightbox(json.message);
}

$.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;
}

function openLinkInLightbox(href, options) {
	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);
	});
}

function beforeFormSubmit(a, form) {
	$(form).add($(':submit, :image', form)).attr('disabled','disabled');
}

(function($){
	$.fn.utsFoldout = function() {
		return this.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;
				});
			});
		});
	};
	
	$.fn.utsHomepageEffects = function() {
		function func() {
			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();
			
			function func2() {
				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() {
					
				});
			}
			
			items.each(func2);
		}
		
		return this.each(func);
	};
})(jQuery);