var countryHomepage = false;

// run jquery in compatibility mode
// until prototype is removed
jQuery.noConflict();

// document startup functions to integrate unobtrusive usability enhancements
jQuery(document).ready(function($) {
	// --- lightbox ---
	$('a.lightbox').lightBox();

	// --- add tabindex attributes to make elements keyboard-focusable. This breaks validation, that's why it's done here. ---
	$('#leftFrontpage div#mainTeaser, #article div#mainTeaser, #article .block div.blockOpener').attr('tabindex', '0');

	// --- panels ---
	if( $(".panel").size() > 0 ) {
		$(".panel").addClass('closed');
		$(".panel .content, .panel .blockImage").hide().attr('aria-hidden',true);
		$(".panel").each(function() {
			// assign aria-controls
			var ariaControls = "";
			if( $(this).find(".blockImage") ) {
				ariaControls += $(this).find(".blockImage").attr('id');
			}
			if( $(this).find(".content") ) {
				ariaControls += (ariaControls == "") ? "" : " ";
				ariaControls += $(this).find(".content").attr('id');
			}
			$(this).find("h2 a.panelToggler").attr("aria-controls", ariaControls)
				.prepend('<span class="panel-helper-hint element-invisible">'+cbm_t9n['open_panel']+': </span>');
		});
		$(".panel:last").css('margin-bottom', '33px');
		$(".panel h2 a.panelToggler").click(function (e) {
			e.preventDefault();
			var panel = $(this).parents(".panel");
			panel.toggleClass('closed');
			panel.find(".blockImage").slideToggle("fast");
			panel.find(".content").slideToggle("fast", function() {
				if( $(this).parent().hasClass('closed') ) {
					// panel was just closed
					$(this).parent().next('a.closePanel').remove();
					$(this).parent().find('h2 a.panelToggler span.panel-helper-hint').text(cbm_t9n['open_panel']+': ');
					$(this).parent().find('.content, .blockImage').attr('aria-hidden', true);
					$(this).parent().find('h2 a.panelToggler').focus();
				} else { // panel was just opened
					// add close panel link if panel height is larger than 1/3 of viewport height
					if( $(this).parent().innerHeight() > ( $(window).height() / 3 ) && cbm_t9n['close_panel'] ) {
						$(this).parent().after('<a href="#" class="closePanel">' + cbm_t9n['close_panel'] + '</a>');
					}
					$(this).parent().find("h2 a.panelToggler").find('span.panel-helper-hint').text(cbm_t9n['close_panel']+': ');
					$(this).parent().find(".content, .blockImage").attr('aria-hidden', false);
				}
			});
		});
		$('#article a.closePanel').live('click', function() {
			$(this).prev('div.panel').find('h2 a.panelToggler').click();
			return false;
		} );
		$(".panel .paneldt").click(function () {
			$(this).parent().find(".content").slideToggle("fast");
			$(this).parent().find(".blockImage").slideToggle("fast");
			$(this).parent().toggleClass('closed');
		});
	}

	// --- print link ---
	$("#printThisJS").css('display', 'block');

	// --- homepage infobox for CBM logo ---
	if( $(".cbmFrontpage .infotext").size() > 0 ) {

		// show infotext only one time a day
		if( $.cookie('cbmInfotextShown') != 'yes' ) {
			$(".cbmFrontpage .infotext").show();
			$.cookie('cbmInfotextShown', 'yes', {expires: 1, path: '/'});
		} else {
			$(".cbmFrontpage .infotext .infotextContent").css('width', 0);
			$(".cbmFrontpage .infotext").css('width', 0);
			$(".cbmFrontpage .infotext").show();
		}

		// remove logo title attribute since it disturbs the infotext experience
		$("#logo a").attr('title', '');

		$(".cbmFrontpage .infotext .infotextText").css('marginTop',
			parseInt($(".cbmFrontpage .infotext .infotextText").css('marginTop'))
				+ ( ( 74 - $(".cbmFrontpage .infotext .infotextText div").height() ) / 2 ) + 'px'
		);

		// bind custom events for show/hide to infobox
		$(".cbmFrontpage .infotext").bind('slideIn', function() {
			$(this).css('display', 'none').removeClass('element-invisible');
			$(".cbmFrontpage .infotext, .cbmFrontpage .infotext .infotextContent").stop(true, true);
			clearTimeout( infotextTimer );
			if( parseInt($(".cbmFrontpage .infotext").css('width')) == 0 ) {
				$(".cbmFrontpage .infotext").animate({width: '238px'}, 400, null, function() {
					$(".cbmFrontpage .infotext .infotextContent").animate({width: '238px'}, 200);
				});
			}
		} );
		$(".cbmFrontpage .infotext").bind('slideOut', function() {
			$(".cbmFrontpage .infotext, .cbmFrontpage .infotext .infotextContent").stop(true, true);
			$(".cbmFrontpage .infotext .infotextContent").animate({width: 0}, 200);
			setTimeout(function() {
				$(".cbmFrontpage .infotext").animate({width: 0}, 400, function() {
					$(this).addClass('element-invisible').css('display', '');
				});
			}, 150);
		} );

		infotextTimer = setTimeout(function() {
			$(".cbmFrontpage .infotext").trigger('slideOut');
		}, 5000);

		$("#logo").bind('mouseenter focusin', function() {
			$(".cbmFrontpage .infotext").trigger('slideIn');
		});
		$("#logo").bind('mouseleave focusout', function() {
			$(".cbmFrontpage .infotext").trigger('slideOut');
		});
	}

	// --- mainpage teaser / picture slideshow with controls ---
	if( $(".mainTeaser").position() != null ) {
		$(".mainTeaser").css({'display': 'none', 'position': 'absolute', 'margin': '0px'});
		$(".pictureframe_1").css('display', 'block');
		currentTeaser = 1;
		teaserObject = $(".mainTeaser");
		var teaserCount = $(".mainTeaser").length;
		if( teaserCount > 1 ) {
			$("#mainTeaser").append('<a class="pager-prev" href="#" title="'+ cbm_t9n['previous'] +'" tabindex="0"></a>'
				+'<a class="pager-next" href="#" title="' + cbm_t9n['next'] + '" tabindex="0"></a>'
				+'<a class="play-pause pause" href="#" title="' + cbm_t9n['pause_slideshow'] + '" tabindex="0"></a>');

			mainTeaserChange = setInterval("currentTeaser = showTeaser( 'next', currentTeaser );", 10000);
			mainTeaserPager = mainTeaserPaused = false;

			$('#mainTeaser a.pager-next, #mainTeaser a.pager-prev, #mainTeaser a.play-pause').hide();

			$("#mainTeaser").bind('mouseenter focusin', function() {
				// stop the slideshow and show the pagers
				clearInterval( mainTeaserChange );
				clearTimeout( mainTeaserPager );
				$(this).find('a.pager-next, a.pager-prev, a.play-pause').fadeIn('fast');
			});
			$("#mainTeaser").bind('mouseleave focusout', function() {
				// run the slideshow and hide the pagers
				if( mainTeaserPaused != true ) {
					clearInterval( mainTeaserChange );
					mainTeaserChange = setInterval("currentTeaser = showTeaser( 'next', currentTeaser );", 10000);
				}
				mainTeaserPager = setTimeout(function() {
					$("#mainTeaser").find('a.pager-next, a.pager-prev, a.play-pause').fadeOut();
				}, 700);
			});

			$("#mainTeaser .pager-next").click(function () {
				currentTeaser = showTeaser( 'next', currentTeaser, 500 );
				return false;
			});

			$("#mainTeaser .pager-prev").click(function () {
				currentTeaser = showTeaser( 'prev', currentTeaser, 500 );
				return false;
			});

			$("#mainTeaser .play-pause").click(function (e) {
				if( $(this).hasClass('pause') ) {
					// pause the animation
					mainTeaserPaused = true;
					$(this).removeClass('pause').addClass('play').attr('title', cbm_t9n['start_slideshow']);
				} else if( $(this).hasClass('play') ) {
					// re-enable the animation
					mainTeaserPaused = false;
					$(this).removeClass('play').addClass('pause').attr('title', cbm_t9n['pause_slideshow']);
				}
				e.preventDefault();
			});
		}
	}

	// --- homepage "From CBM [...]" box - enable clicking on the whole box ---
	if( $(".cbmFrontpage .fromCBMContent").size() > 0 ) {
		$(".cbmFrontpage .fromCBMContent").css('cursor', 'pointer').click(function() {
			if( $(this).find('h3 a').is('a[target="_blank"]') ) {
				window.open( $(this).find('h3 a').attr('href') );
			} else {
				$(this).find('h3 a').click();
			}
		});
	}

	// --- worldwide menu ---
	if( $("#worldwideButton").position() != null ) {
		$("#worldwideButton a").mouseenter( function() {
			if( $.browser.msie ) {
				$("#worldwideBox").show();
			} else {
				$("#worldwideBox").fadeIn("fast");
			}
			$("#worldwideButton").addClass('hover');
			return false;
		});
		$("#worldwideBox").mouseleave(function() {
			if( $.browser.msie ) {
				$("#worldwideBox").hide();
				$("#worldwideButton").removeClass('hover');
			} else {
				$("#worldwideBox").fadeOut("fast", function(){
					$("#worldwideButton").removeClass('hover')
				});
			}
			return false;
		});

		$left = $("#worldwideButton").position().left;
		$width = (290 - $("#worldwideButton").width())/2;
		$("#worldwideBox").css('left', ($left+203)-$width );
	}

	// --- donate menu ---
	$("#donateButton a").mouseenter(function() {
		if( $.browser.msie ) {
			$("#donateBox").show();
		} else {
			$("#donateBox").fadeIn("fast");
		}
		$("#donateButton").addClass('hover');
		// $("#donateBox").width( $("#donateButton").outerWidth() + $("#donateButton").css( 'border-width' ) );
		// $("#donateBox").width( $("#donateButton").outerWidth() );

		return false;
	});
	$("#donateBox").mouseleave(function() {
		if( $.browser.msie ) {
			$("#donateBox").hide();
			$("#donateButton").removeClass('hover');
		} else {
			$("#donateBox").fadeOut("fast", function(){
				$("#donateButton").removeClass('hover')
			});
		}
		return false;
	});
	$("#donateBox select").mouseleave(function(e) {
		e.stopPropagation(); // stop event propagation for selects inside the box
	});
	$("#mainNavigation").append( $("#donateBox") ); // attach donate box to correct parent

	// --- block opener image with caption, keyboard-navigation-enabled and screenreader-accessible ---
	if( $(".blockOpener").position() != null ) {
		$(".blockOpener .caption").addClass('element-invisible');
		$(".blockOpener").bind('mouseenter focusin', function() {
			if($(this).find('.caption').hasClass('element-invisible')) {
				$(this).find('.caption').css('display', 'none').removeClass('element-invisible');
			}
			$(".blockOpener .caption").animate({"height": "toggle", "opacity": "toggle"}, "fast");
		});
		$(".blockOpener").bind('mouseleave focusout', function() {
			$(".blockOpener .caption").animate({"height": "toggle", "opacity": "toggle"}, "fast", function() {
				$(this).addClass('element-invisible').css('display', '');
			});
		});
	}

	// --- marginal map ---
	marginalMapTimer = false;
	$("#marginalColumn #map").hover(
		function() { // over
			clearTimeout( marginalMapTimer );

			height = $(this).css('height');
			width = $(this).css('width');

			var classString = $(this).attr("class");
			var classes = classString.split(' ');

			if( classes.length == 2 ) {
				if( classes[0].indexOf("map-zoom-width-") == 0
				&& classes[1].indexOf("map-zoom-height-") == 0
				&& ! isNaN( parseInt( classes[0].substring( "map-zoom-width-".length ) ) )
				&& ! isNaN( parseInt( classes[1].substring( "map-zoom-height-".length ) ) )
				) {
					width = parseInt( classes[0].substring( "map-zoom-width-".length ) ) + "px";
					height = parseInt( classes[1].substring( "map-zoom-height-".length ) ) + "px";
				}
			}

			if( !$(this).hasClass('large') ) {
				map.enlargeView( width, height );
			}
		},
		function() { // out
			marginalMapTimer = setTimeout( function(){
				if( jQuery(".frontpage #marginalColumn #map").size() == 1 ) {
					map.shrinkView( '97.5%', '97%' );
				} else {
					map.shrinkView( '99.5%', '99.5%' );
				}
			}, 700 );
		}
	);

	// --- marginal teaser ---
	$("#marginalColumn .teaserImage").css('display', 'none');
	$("#marginalColumn .teaserImage:first").css('display', 'block');
	$("#marginalColumn .teaser").mouseenter(function() {
		var teaserImage = $(this).find(".teaserImage");
		if( teaserImage.length > 0 ) {
			$("#marginalColumn .teaserImage").css('display', 'none');
			teaserImage.css('display', 'block');
		}
	});

	// --- search field ---
	$('#searchInput').click(function() {
		$('#searchInput').attr('value', '');
	});

	// --- emergency layout ---
	if( $('#emergencyTicker').size() > 0 ) {
		$('#emergencyTicker').addClass('emergencyTickerDynamic');
		$('.emergencyTickerContent div').vTicker({
			speed: 500,
			pause: 5500,
			showItems: 1,
			mousePause: true,
			height: 25,
			direction: 'up'
		});
	}

	// --- newsroom ---
	if( $('.newsroomWrapper').size() > 0 ) {
		// tabs
		$('#countryLivestreamNews h2')
			.wrapAll('<div class="newsroomBoxNav" />')
			.addClass('inactive')
			.css('cursor', 'pointer')
			.first().removeClass('inactive');
		$('#countryLivestreamNews ol').hide()
			.first().show()
			.next('div.furtherLinks').show()
			.nextAll('div.furtherLinks').hide();

		$('#countryLivestreamNews h2 a').click(function(e) {
			e.preventDefault();
			$('#countryLivestreamNews h2').addClass('inactive');
			$(this).parent('h2').removeClass('inactive');
			var classname = $(this).parent('h2').attr('class');
			$('#countryLivestreamNews ol, #countryLivestreamNews div.furtherLinks').hide();
			$('#countryLivestreamNews ol.'+classname+', #countryLivestreamNews div.'+classname).fadeIn('fast');
			$(this).parents('.newsroomBox').trigger('checkScrollerState');
			$(this).parents('.newsroomBox').find('.newsroomBoxScrollerHolder a').attr(
				'aria-controls', $('#countryLivestreamNews ol.'+classname).attr('id')
			);
		});

		// scrolling
		$('.newsroomBox').not('.newsroomBoxStatic').find('ol').css({height: 300, overflow: 'hidden'});
		$('.newsroomBox').not('.newsroomBoxStatic').each(function() {
			var boxId = $(this).find('ol').attr('id');
			$(this).append('<div class="newsroomBoxScrollerHolder"><a class="newsroomBoxScrollDown" '
				+'role="scrollbar" aria-controls="'+boxId+'" tabindex="0"></a></div>');
			$(this).find('ol:first').before('<div class="newsroomBoxScrollerHolder"><a class="newsroomBoxScrollUp" '
				+'role="scrollbar" aria-controls="'+boxId+'" tabindex="0"></a></div>');
			$(this).find('ol').each(function() {
				$(this).find('li:first').addClass('ontop');
			});
		});

		// custom event for scroller state
		$('.newsroomBox').not('.newsroomBoxStatic').bind('checkScrollerState', function() {
			$(this).find('.newsroomBoxScrollDown:hidden').show();
			$(this).find('.newsroomBoxScrollUp:hidden').show();

			if( $(this).find('ol:visible li.ontop').prev('li').size() == 0 ) {
				$(this).find('.newsroomBoxScrollUp').fadeOut('fast');
			}

			var height = $(this).find('ol:visible li.ontop').outerHeight();
			$(this).find('ol:visible li.ontop').nextAll('li').each(function() {
				height += $(this).outerHeight();
			});
			if( height <= parseInt( $(this).find('ol:visible').css('height') ) ) {
				$(this).find('.newsroomBoxScrollDown').fadeOut('fast');
			}
		});
		$('.newsroomBox').not('.newsroomBoxStatic').trigger('checkScrollerState');

		$('.newsroomBoxScrollDown').click(function() {
			var thisList = $(this).parents('.newsroomBox').find('ol:visible');
			var height = 0;
			height += $(thisList).find('li.ontop').outerHeight();
			$(thisList).find('li.ontop').nextAll('li').each(function() {
				if( ( height + $(this).outerHeight() ) > parseInt( $(this).parents('ol').css('height') ) ) {
					$(this).prevAll('li').removeClass('ontop');
					$(this).prev('li').addClass('ontop')
					height -= $(this).prev('li').outerHeight();
					return false;
				}
				height += $(this).outerHeight();
			});
			$(thisList).find('li:first').animate(
				{ marginTop: '-='+parseInt( height ) },
				400,
				function() {
					$(this).parents('.newsroomBox').trigger('checkScrollerState');
				}
			);
			return false;
		});
		$('.newsroomBoxScrollUp').click(function() {
			var thisList = $(this).parents('.newsroomBox').find('ol:visible');
			var height = 0;
			height += $(thisList).find('li.ontop').outerHeight();
			$(thisList).find('li.ontop').prevAll('li').each(function() {
				if( ( height + $(this).outerHeight() ) > parseInt( $(this).parents('ol').css('height') ) ) {
					height -= $(thisList).find('li.ontop').outerHeight();
					$(this).nextAll('li').removeClass('ontop');
					$(this).next('li').addClass('ontop');
					return false;
				}
				height += $(this).outerHeight();
			});

			if( Math.abs( parseInt( $(thisList).find('li:first').css('margin-top') ) ) <= height ) {
				height = Math.abs( parseInt( $(thisList).find('li:first').css('margin-top') ) );
				$(thisList).find('li').removeClass('ontop');
				$(thisList).find('li:first').addClass('ontop');
			}

			$(thisList).find('li:first').animate(
				{ marginTop: '+='+parseInt( height ) },
				400,
				function() {
					$(this).parents('.newsroomBox').trigger('checkScrollerState');
				}
			);
			return false;
		});

	}

	// --- list below maps ---
	if( $('#article div.mapList').size() > 0 ) {
		$('#article div.mapList div.mapListContent').hide()
			.prevAll('h2').addClass('closed');

		$('#article div.mapList h2 a').click( function() {
			$(this).parents('h2').toggleClass('closed')
				.nextAll('.mapListContent').slideToggle();
			return false;
		} );
	}

	// --- gallery grid-view ---
	if( $('#article .galleryGridContainer').size() > 0 ) {
		$('#article .galleryGridContainer dl dd').each(function() {
			if( $(this).height() > 55 ) {
				$(this).wrapInner('<div class="masked"></div>');
				$(this).append('<div class="mask"></div>');
			}
		});
		$('#article .galleryGridContainer').addClass('galleryGridContainerDynamic');

		$('#article .galleryGridContainer dl').hover(
			function() { // over
				if( $(this).find('dd .mask').size() > 0 ) {
					$(this).find('dd .mask').fadeOut(100);
					$(this).find('dd').css('overflow','visible');
				}
			},
			function() { // out
				if( $(this).find('dd .mask').size() > 0 ) {
					$(this).find('dd .mask').fadeIn(100);
					$(this).find('dd').css('overflow','hidden');
				}
			}
		);

		// set a descending z-index to fix a bug in IE6+7
		var initialZIndex = $('#article .galleryGridContainer dl').size() + 10;
		$('#article .galleryGridContainer dl').each(function() {
			$(this).css('z-index', initialZIndex);
			initialZIndex--;
		});
	}

	// --- article topic navigation ---
	if( $('#content .articleTopicReference').size() > 0 ) {
		var prevNextLinks = $('.articleTopicReference li.previousNext a');
		if ($('.articleTopicReference li.previousNext a.next').size() > 0) {
			prevNextLinks.not('.next').find('span.labelText').addClass('element-invisible');
		} else {
			if ($('.articleTopicReference li.previousNext a.previous').size() > 0) {
				// only prev link
				$('#content .articleTopicReference li.prevInfowindow').addClass('prevInfowindowNoNext');
			}
		}
		prevNextLinks.bind('mouseenter focusin', function() {
			prevNextLinks.stop(true, true);
			if ($(this).hasClass('previous')) {
				if ($('.articleTopicReference li.previousNext a.next').size() > 0) {
					prevNextLinks.find('span.labelText').not('.element-invisible').addClass('element-invisible');
					$(this).find('span.labelText.element-invisible').removeClass('element-invisible');
				}
				$('#content .articleTopicReference li.prevInfowindow').show();
			} else {
				$('#content .articleTopicReference li.nextInfowindow').show();
			}
		});
		prevNextLinks.bind('mouseleave focusout', function() {
			prevNextLinks.stop(true, true);
			if ($(this).hasClass('previous')) {
				if ($('.articleTopicReference li.previousNext a.next').size() > 0) {
					prevNextLinks.find('span.labelText').not('.element-invisible').addClass('element-invisible');
					prevNextLinks.not('.previous').find('span.labelText').removeClass('element-invisible');
				}
				$('#content .articleTopicReference li.prevInfowindow').hide();
			} else {
				$('#content .articleTopicReference li.nextInfowindow').hide();
			}
		});
		$('#content .articleTopicReference li.topicOverview').bind('mouseenter focusin', function() {
			$('#content .articleTopicReference li.topicOverviewInfowindow').show();
		});
		$('#content .articleTopicReference li.topicOverview').bind('mouseleave focusout', function() {
			$('#content .articleTopicReference li.topicOverviewInfowindow').hide();
		});
	}

	// --- add GA events to elements ---
	addAnalyticsEvents();

	// --- activate gallery if one is present on page ---
	if( window.activateGallery ){
		activateGallery();
	}
});

function addAnalyticsEvents() {
	// add download event
	jQuery('.fileDownload').each( function() {
		jQuery(this).click( function() {
			_gaq.push(['_trackEvent', 'Media', 'Download', this.href.substring( this.href.lastIndexOf( '/' )+1 ) ]);
		} );
	});

	// add event for donate button on top
	jQuery('#donateLink').click( function() {
		_gaq.push(['_trackEvent', 'Donation', 'Donate button to MA', this.href ]);
	});

	// add event for donate button's link to landing page
	jQuery('#landingPageLink').click( function() {
		_gaq.push(['_trackEvent', 'Donation', 'Donate button to Donate page', this.href ]);
	});

	// add event for donate links on landing page
	jQuery('.donationPageMALink').each( function() {
		jQuery(this).click( function() {
			_gaq.push(['_trackEvent', 'Donation', 'Donate page to MA', this.href ]);
		} );
	});

	// add event for worldwide button on country pages
	jQuery('.linkMemberAssociation').each( function() {
		jQuery(this).click( function() {
			_gaq.push(['_trackEvent', 'External link', 'Member Association', this.href ]);
		} );
	});

	// add event for "from cbm [country]" box on mainpage
	jQuery('.memberAssociationsFrontpage').each( function() {
		jQuery(this).click( function() {
			_gaq.push(['_trackEvent', 'External link', 'Member Association homepage box', this.href ]);
		} );
	});

	// add event for "did you know..." box in left column
	jQuery('#didYouKnow a').click( function() {
		_gaq.push(['_trackEvent', 'External link', 'Did you know...', this.href ]);
	} );

	// add event to all links with target="_blank" (except in .donateHeadImage)
	jQuery('#article a[target="_blank"]').click( function() {
		if( jQuery(this).parents('.donateHeadImage').size() == 0 ) {
			_gaq.push(['_trackEvent', 'External link', 'in content', jQuery(this).attr('href') ]);
		}
	} );

	// add event for newsroom links
	jQuery('.newsroomWrapper .livestream li a').click( function() {
		_gaq.push(['_trackEvent', 'External link', 'Newsroom - Livestream', this.href ]);
	} );
	jQuery('.newsroomWrapper .country li a').click( function() {
		_gaq.push(['_trackEvent', 'External link', 'Newsroom - from your country', this.href ]);
	} );
	jQuery('#marginalColumn #newsroomLinks a').click( function() {
		_gaq.push(['_trackEvent', 'External link', 'Newsroom - Link box', this.href ]);
	} );
	jQuery('#marginalColumn #newsroomStayInTouch a').click( function() {
		_gaq.push(['_trackEvent', 'External link', 'Newsroom - Stay in touch', this.href ]);
	} );

	// add event for "follow us" links on homepage and in footer
	jQuery('#rightFrontpage .followUs a').click( function() {
		_gaq.push(['_trackEvent', 'External link', 'Follow us', this.href ]);
	} );
	jQuery('#footer .followUs a').click( function() {
		_gaq.push(['_trackEvent', 'External link', 'Follow us', this.href ]);
	} );

	// track clicks on accessibility view switch and topic navigation
	jQuery('#topNavigation li#accessibilityView a').click(function(e) {
		e.preventDefault();

		if( typeof _gaq != 'undefined' ) {
			if( jQuery('body').hasClass('regularLayout') ) {
				_gaq.push(['_trackEvent', 'Website action', 'Accessibility view - turn on', this.href ]);
			} else {
				_gaq.push(['_trackEvent', 'Website action', 'Accessibility view - turn off', this.href ]);
			}
		}

		setTimeout('window.location = "' + jQuery(this).attr('href') + '"', 150);
	});
	jQuery('#content .articleTopicReference ul li a').click(function(e) {
		e.preventDefault();

		if( typeof _gaq != 'undefined' ) {
			if( jQuery(this).closest('li').hasClass('topicOverview') ) {
				_gaq.push(['_trackEvent', 'Website action', 'Topic navigation - More-link', this.href ]);
			} else if( jQuery(this).hasClass('previous') ) {
				_gaq.push(['_trackEvent', 'Website action', 'Topic navigation - Previous-link', this.href ]);
			} else if( jQuery(this).hasClass('next') ) {
				_gaq.push(['_trackEvent', 'Website action', 'Topic navigation - Next-link', this.href ]);
			}
		}

		setTimeout('window.location = "' + jQuery(this).attr('href') + '"', 150);
	});
}

function showTeaser( direction, currentTeaser, duration ) {
	var teaserLength = jQuery('.mainTeaser').length;

	if( !direction ) {
		var direction = 'next';
	}

	if( direction == 'prev' ) {
		if( currentTeaser >= 2 ) {
			nextTeaser = currentTeaser-1;
		} else {
			nextTeaser = teaserLength;
		}
	} else {
		if( currentTeaser < teaserLength ) {
			nextTeaser = currentTeaser+1;
		} else {
			nextTeaser = 1;
		}
	}

	if( !duration ) {
		var duration = 2000;
	}

	return switchTeaser( currentTeaser, nextTeaser, duration );
}

function switchTeaser( current, next, duration ) {
	jQuery('.pictureframe_'+current).fadeOut( duration );
	jQuery('.pictureframe_'+next).fadeIn( duration );
	return nextTeaser;
}

// object for mapping and map handling
function CBMMap( containerId ) {

	if( ! containerId ) {
		containerId = 'map';
	}
	this.container = document.getElementById( containerId );
	this.closeContainer = document.getElementById( containerId + 'Close' );
	this.enlargeContainer = document.getElementById( containerId + 'Enlarge' );
	this.centerLat = null;
	this.centerLong = null;
	this.center = null;
	this.zoom = 3;
	this.mapType = 3;
	this.KMLoverlays = new Array();
	this.controls = false;

	this.exclude = false;

	this.map = null;
	this.mgr = null;
	this.typeControl = null;
	this.zoomControl = null;

	//Call this function when the page has been loaded
	this.init = function()
	{
		// init map
		this.center = new GLatLng( this.centerLat, this.centerLong );
		this.map = new google.maps.Map2( this.container );
		this.map.setCenter( this.center, this.zoom );

		// configure map types
		this.mapTypes = new Array( '', G_NORMAL_MAP, G_SATELLITE_MAP, G_PHYSICAL_MAP );
		this.map.removeMapType( G_HYBRID_MAP );
		for( i=1; i<this.mapTypes.length; ++i ) {
			this.map.addMapType( this.mapTypes[ i ] );
		}
		this.map.setMapType( this.mapTypes[ this.mapType ] );

		// add overlays
		for( i=0; i<this.KMLoverlays.length; ++i ) {
			this.map.addOverlay( new GGeoXml( this.KMLoverlays[ i ] ) );
		}

		// add controls
		this.typeControl = new GMapTypeControl();
		this.zoomControl = new GSmallMapControl;
		if( this.controls ) {
			this.map.addControl( this.zoomControl );
			this.map.addControl( this.typeControl );
		}

		// prevent gmaps infowindow links open in new window
		GEvent.addListener(this.map, "infowindowopen", function() {
			var infoWindow = jQuery(this.getInfoWindow().getContentContainers());
			jQuery("a", infoWindow).attr("target", "_self").addClass("cbmMapInfoWindowLink");
		});

		// enable mouse-wheel zoom
		this.map.enableScrollWheelZoom();
	}

	this.addKMLOverlay = function( url ) {
		this.KMLoverlays.push( url );
	}

	this.enlargeView = function( width, height ) {
		jQuery(this.container).addClass('large');
		jQuery(this.container).css('position', 'absolute');
		jQuery(this.container).css('width', width);
		jQuery(this.container).css('height', height);
		this.closeContainer ? jQuery(this.closeContainer).show() : null;
		this.enlargeContainer ? jQuery(this.enlargeContainer).hide() : null;

		this.map.addControl( this.zoomControl );
		this.map.addControl( this.typeControl );

		this.map.checkResize();
		this.map.setCenter( this.center, this.zoom + 1 );
	}

	this.shrinkView = function( width, height ) {
		jQuery(this.container).removeClass('large');
		jQuery(this.container).css('position', 'relative');
		jQuery(this.container).css('width', width);
		jQuery(this.container).css('height', height);
		this.closeContainer ? jQuery(this.closeContainer).hide() : null;
		this.enlargeContainer ? jQuery(this.enlargeContainer).show() : null;

		this.map.removeControl( this.zoomControl );
		this.map.removeControl( this.typeControl );

		this.map.checkResize();
		this.map.setCenter( this.center, this.zoom );
	}

	this.addClusteredMarkers = function( markerTypes, clusterGridSize, exclude ) {

		this.clusterGridSize = clusterGridSize;

		if( exclude && typeof exclude != 'undefined' ) {
			this.exclude = exclude;
		}

		// JSONP request to solve same-origin-policy problems
		jQuery.getJSON(
			'http://www.cbm.org/mapdata.json.php?callback=?',
			{'types': markerTypes},
			function( data ) {

				var markers = [];

				jQuery.each( data, function( i, item ) {
					if( map.exclude == false || !item.container || map.exclude != item.container ) {
						var icon = new GIcon(G_DEFAULT_ICON);
						icon.image = item.icon.image;
						icon.iconSize = new GSize(item.icon.width, item.icon.height);
						icon.iconAnchor = new GPoint(item.icon.anchorLeft, item.icon.anchorTop);

						var iconX = parseInt(item.icon.width);
						var iconY = parseInt(item.icon.height);
						icon.imageMap = [0,0, iconX,0, iconX,iconY, 0,iconY];

						var latlng = new GLatLng(item.coordinates.lat, item.coordinates.lon);
						var marker = new GMarker(latlng, {icon: icon});
						marker.title = item.title;
						var description = item.description;
						GEvent.addListener(marker, 'click', function() {
							marker.openInfoWindowHtml(
								'<div style="min-height: 60px; margin-bottom: -20px;"><strong style="display: block; margin-bottom: 8px;">'
									+item.title+'</strong>'+description+'<div style="clear:right;"></div></div>',
								{maxWidth: 250}
							);
						});
						markers.push(marker);
					}
				});

				if( map.clusterGridSize > 0 ) {
					// clustered mode
					var clusterStyle = [
						{url: 'http://www.cbm.org/_resources/images/icons/flag_cluster.png', height: 33, width: 51, opt_anchor: [5,null], opt_textColor: '#FFFFFF'},
						{url: 'http://www.cbm.org/_resources/images/icons/flag_cluster.png', height: 33, width: 51, opt_anchor: [5,null], opt_textColor: '#FFFFFF'},
						{url: 'http://www.cbm.org/_resources/images/icons/flag_cluster.png', height: 33, width: 51, opt_anchor: [5,null], opt_textColor: '#FFFFFF'}
					];
					var markerCluster = new MarkerClusterer( map.map, markers, {styles: clusterStyle, gridSize: map.clusterGridSize} );
				} else {
					// non-clustered mode
					jQuery.each( markers, function( index, marker ) {
						map.map.addOverlay( marker );
					});
				}
			}
		);
	}

	this.addCurrentProgrammeAtMapCenter = function( title ) {
		var flag = new GIcon(G_DEFAULT_ICON);
		flag.image = "http://www.cbm.org/_resources/images/icons/flag_yellow.png";
		flag.shadow = "";
		flag.iconSize = new GSize(32, 32);
		flag.iconAnchor = new GPoint(3, 26);

		var markerOptions = { 'title': title, clickable: false, icon: flag, zIndexProcess: function () {return GOverlay.getZIndex(this.centerLat) + 100000000;} };
		var center = new GLatLng( this.centerLat, this.centerLong );

		var marker = new GMarker( center, markerOptions );
		this.map.addOverlay( marker );
	}
}
