

var transitionDuration = 1000,
	crossfadeDuration = 1000,
	slideDuration = 1500,
	hostingHash = "#home",
	hostingHashEN = "#home-en",
	ajaxMode = true,
	generalPageTitle = " – The Circle at Zurich Airport";
var completeEvents={},
	currBackgroundImages,
	outroDuration = transitionDuration,
	introDuration = transitionDuration,
	nextPageContents,
	triggeredLink="",
	startpageOutro,
	isContentsLayoutLarge = true,
	searchQuery = "",
	domainPath = location.host == "localhost" ? "/thecircle":"";
	
var useBGCrossfade = true;




// $('img.photo',this).imagesLoaded(myFunction)
// execute a callback when all images have loaded.
// needed because .load() doesn't work on cached images

// mit license. paul irish. 2010.
// webkit fix from Oren Solomianik. thx!

// callback function is passed the last image to load
//   as an argument, and the collection as `this`


$.fn.imagesLoaded = function(callback){
  var elems = this.filter('img'),
      len   = elems.length;
      
  elems.bind('load',function(){
      if (--len <= 0){ callback.call(elems,this); }
  }).each(function(){
    
	// cached images don't fire load sometimes, so we reset src.
     if (this.complete || this.complete === undefined){
        var src = this.src;
        // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
        // data uri bypasses webkit log warning (thx doug jones)
        this.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
        this.src = src;
		
    } else if( this.complete==false ) {
		$(this).trigger("load");
	} 
  }); 

  return this;
};



$.fn.scaleToFullscreen = function(){
  var elems = this.filter('img');      
  elems.each( function(){
		if( $(this).width()>0 && $(this).height()>0 ){
			$(this).css("height", $(window).height() );
			$(this).css("width", "auto" );
			if( $(window).width() > $(this).width() ){
				$(this).css("width", $(window).width() );
			 	$(this).css("height", "auto" );
			}
		}
	} );
	return elems;
};


function removeFilter(){
	if ($.browser.msie) {
		$("#drawer,#contentWrap,#left,#right,#logo").css("filter","").removeAttr("filter");
	}
}
	

$(document).ready(function() {

	useBGCrossfade = $.browser.msie && $.browser.version < 9;
	initPage();
	
});

function initPage () {
	
	// delete value in search input submit
	$("#footerRight input").val("");
  
  	// don't show anything on startup	
	$("#currPage,#drawer,#line").hide();


	if( ajaxMode ){
		
		// set startpage priviledges or reset startpage classes
		var hash = window.location.hash || hostingHash;
		if( hash == hostingHash || hash == hostingHashEN ){
			triggeredLink = hash;
		}else{
			$("body").removeClass("startseite").removeClass("contentLarge");
			$(".level_1 li.startseite.active").removeClass("active");
		}
				
		// make home link interactive
		var homeLink = $("#footer .mod_navigation .level_1 li span.startseite");
		var dlink = convertHashToDeepLink(hostingHash).substr(1);
		homeLink.replaceWith("<a href='"+dlink+"' class='startseite'>"+homeLink.text()+"</a>");
		$("#logo a").addClass("startseite").click(handleFooterNavClick);
		
		// enable AJAX interactivity
		completeEvents.animation = true;
		ajaxifyPage( [ 
			$("#left .mod_navigation .level_1 li a"), 
			$("#left .mod_changelanguage li a"),
			$("#footer .mod_navigation .level_1 li a"),
			$(".mod_newslist p.more a"),
			$("#logo a") 
		] );
		
		if( doesHashlinkBelongsToFooter(hash) ){
			$("body").addClass("contentLarge");			
		}
	}else{
		initGallery();
		hoverTeaser();
		playIntro();		
	}
	
	initSearchfield();
	initNavigation();	
	initLightbox();
	
	if ($.browser.webkit) {
	    $("body").addClass('webkit')
	}
  	
  	
  	
}

function initGallery() {

	if( $("#galerie a").size()==0 ){
		return false;
	}
	
	$("#galerie a").click( function(e){
		e.preventDefault();
		
		$("#galerie a").removeClass("active");
		$(this).addClass("active");

		// set captions
		$("#right .tncaption").addClass('invisible').hide();
		if($(this).parent().parent().find('div.tncaption').text() != "Background") {
			$(this).parent().parent().find('div.tncaption').hide().removeClass('invisible').fadeIn("slow");
		}
		
		// load new image
		toggleContent(true,false);
		var fadeTime = 1000;
		//fadeOutGalleryImages(fadeTime);
		var img = $("<img class='galleryImg' src='"+$(this).attr("href")+"' />").appendTo("#background").hide()
			.load( function(){ 
				$(this).fadeIn(fadeTime); 
				$(this).scaleToFullscreen().show();				 
			} );
	} );
	
}


function fadeOutGalleryImages(fadeTime) {
	if(!fadeTime){
		fadeTime = 1000;
	}
	$("#background .galleryImg").fadeOut(fadeTime,function(){ $(this).detach() });
}


function initNavigation() {
	
	// set event listeners for arrows
	$("#pfeile").click( function(){ 
		
		// toggle between slide in/out of content
		toggleContent(true); 
		
		// reopening hides gallery image
		if( $("#galerie a").size() && $("#drawer").hasClass("open") ){
			fadeOutGalleryImages();
			$("#right .tncaption:not(.invisible)").fadeOut(1000);
		}
	} );
	
	// set event listeners for main navigation
	$("#left .mod_navigation .level_1 a").click( handleMainNavClick );
	
	// set event listeners for footer navigation
	$("#footer .mod_navigation .level_1 a").add("#logo a").click( handleFooterNavClick );
}

function handleMainNavClick(e) {
	
	var hash = window.location.hash,
		triggerSelector;
		
	if(e){
		// prevent click action
		e.preventDefault();	
		
		// if( $(this, ".mod_changelanguage") && $("body").hasClass("contentLarge") ){
			// alert("LARGE")
			// handleFooterNavClick.apply();
		// }	
		
		triggerSelector = $(this);
		triggeredLink = $(this).attr("href");
		if( triggeredLink == hash ){
			return false;
		}
	}else{
		triggeredLink = hash;
		triggerSelector = getItemByHashlink( triggeredLink ).trigger("click");		
	}
		
	completeEvents = {};
	// console.log("**********CLICK LEFT NAV");
		
	// load ajax contents
	if(ajaxMode){
		
		// set previous indicators as classes
		setIndicatorClasses();
	
		// load current image in previous image container
		createPrevImage();

		// load hash url
		location.href = triggeredLink;
		if( $.browser.msie && $.browser.version < 8 ){
			handleHashChange();
		}
	}
	
	// play outro	
	playOutroToOneColContent( triggerSelector );
	
}

function handleFooterNavClick(e) {
	
	
	var hash = window.location.hash || hostingHash,
		triggerSelector;
		
	if(e){
		// prevent click action
		e.preventDefault();	
		triggerSelector = $(this);
		triggeredLink = $(this).attr("href");
		if( triggeredLink == hash ){
			return false;
		}
	}else{
		triggeredLink = hash;
		triggerSelector = getItemByHashlink( triggeredLink ).trigger("click");
	}

	completeEvents = {};
	// console.log("**********CLICK FOOTER NAV");
	
	// load ajax contents
	if(ajaxMode){
		
		// set previous indicators as classes
		setIndicatorClasses();
		
		// load current image in previous image container
		createPrevImage();
		
		// load hash url
		location.href = triggeredLink;
		if( $.browser.msie && $.browser.version < 8 ){
			handleHashChange();
		}
	}


	// play outro		
	playOutroToLargeContent( triggerSelector );
	
	
}

function handleSearchResultClick (e) {
  
	e.preventDefault();	
  	triggeredLink = $(this).attr("href");
  	completeEvents = {};
  	completeEvents.isSearchResult = true;
  	
  	
  	// load hash url
	location.href = triggeredLink;
	if( ($.browser.msie && $.browser.version < 8) ){
		handleHashChange();
	}
  	
}


function handleSearchSubmit(e) {
	
	
	// prevent click action
	e.preventDefault();	
	
	triggeredLink = "#suchresultate";
	triggerSelector = $(this);
	//console.log( triggerSelector );
	
	searchQuery = $("#footer input[name=keywords]").val();
	
	completeEvents = {};
	// console.log("**********CLICK FOOTER NAV");
	
	// load ajax contents
	if(ajaxMode){
		
		// set previous indicators as classes
		setIndicatorClasses();
		
		// load current image in previous image container
		createPrevImage();
		var originalHash = location.hash;
		if( originalHash != triggeredLink ){
			location.href = triggeredLink;
		}
		
		// load hash url
		if( ($.browser.msie && $.browser.version < 8)  || originalHash == triggeredLink ){
			handleHashChange();
		}
		
		
	}

	// play outro		
	playOutroToLargeContent( triggerSelector );
}

function pseudoFadeOutForIE ( complete, isLargeContent ) {
	$("<div class='fadeOutIE' />").insertAfter("#drawer").css({"z-index":450, position:"absolute",top:0});
	$("#background .prevImg img").clone().scaleToFullscreen().appendTo(".fadeOutIE");
	removeFilter();

	$(".fadeOutIE").hide().fadeIn( outroDuration, function(){
		if( complete != undefined ){
			complete();
			$("#drawer,#line").hide();
			startpageOutro = function( completeFunc ){ 
				completeFunc(); 
			};
		}else{
			startpageOutro = function( completeFunc ){ 
				if( !isLargeContent ){
					$("body").removeClass("contentLarge");
				}
				$("body").removeClass("startseite"); 
				completeFunc(); 
			}
			
		}
		
		
		handleAnimationComplete();
		$(".fadeOutIE").detach();
	} );
}


function pseudoFadeInForIE ( useWhiteBG ) {
	$("<div class='fadeInIE' />").insertAfter("#drawer").css({"z-index":250, position:"absolute",top:0});
	if( useWhiteBG ){
		$(".fadeInIE").css({ background:"#FFFFFF", width:"100%", height:"100%" });
		$("#background .currImg img").show().scaleToFullscreen();
	}else{
		$("#background .currImg img").clone().scaleToFullscreen().appendTo(".fadeInIE");
	}
	
	
	// switch to logo for black background
	$("#logo img").attr("src","tl_files/Layoutbilder/logo_home.png");
	$("#contentWrap,#content,#drawer").show();
	$("#line").css("left","230px").hide().fadeIn(introDuration);
	removeFilter();
	$("#drawer").css({left:0,width:''});
	
	$(".fadeInIE").show().fadeOut( outroDuration, function(){
		removeFilter();
		$(".fadeInIE").detach();
	} );
}


function playOutroToOneColContent( triggerSelector ) {
	
	fadeOutGalleryImages( outroDuration );
	
	// if initial position is the start page, the drawer gets opened 	
	if( $("body").hasClass("startseite") ){			
		
				
		if( useBGCrossfade ){
			pseudoFadeOutForIE();
			return false;
		}	
		
		
		startpageOutro = function( complete ){
			
			$("#line").fadeOut( outroDuration );
			$("#drawer").fadeOut( outroDuration,function(){
				// remove current identification classes
				$("body").removeClass("startseite").removeClass("contentLarge");
				complete();				
			});
			
		};
		
	// if initial position is a contentLarge page, the drawer gets collapsed 	
	}else if( $("body").hasClass("contentLarge") ){						
		
		var complete = function(){
			// remove current identification classes
			handleAnimationComplete();
			$("body").removeClass("startseite").removeClass("contentLarge");
		};
		
		// do content fadeout
		fadeOutContentOnly( function(){ 
			toggleContent(true,true,complete); 			
		} );
			
	
	// otherwise only content gets faded out	
	}else{	
		
		if( !$("#drawer").hasClass("open") ){
			toggleDrawer( true );
		}
				
		// do content fadeout
		fadeOutContentOnly( handleAnimationComplete );

	}
	
}


function toggleDrawer ( doSlideIn, doFullWidthFill ) {
 
  
  // define complete function
  var completeFunc = function(){  		
  	$("#pfeile .close").css("display", doSlideIn ? "block" : "none");
	$("#pfeile .open").css("display", doSlideIn ? "none" : "block");				
	$("#pfeile").fadeIn( introDuration );  		
  };
  
  
  // if no fullwidth fill is set, perform slide in/out toggle 
  if( doFullWidthFill == undefined )
  {
  	
  	if( doSlideIn == undefined )
  	{
  		doSlideIn = !$("#drawer").hasClass("open");
  	} 
  	if( doSlideIn )
  	{
  		$('#drawer').addClass("open");		
		$("#currPage .inside").text("");
		$("#currPage").hide();
		$("#pfeile").hide();
		
  	} else {
  		
  		$('#drawer').removeClass("open");	
  	}
  	var options = {queue:false,duration:transitionDuration };
  	$("#line").animate({ left: doSlideIn ? "230px" : "46px" },options);
  	$("#contentWrap").animate({ opacity: doSlideIn },options);
  	$("#drawer").animate( { left: doSlideIn ? "0px" : "-620px" }, $.extend(options,{complete:completeFunc}) );
  	  	
  // otherwise perform fullwidth toggle
  } else {
  	
  	if( $("#drawer").hasClass("open") )
  	{
	  $("#pfeile").fadeOut( outroDuration );
	}
	var options = {queue:false,duration: $("body").hasClass("contentLarge") ? transitionDuration : slideDuration };
	$("#line").animate({ left: doFullWidthFill ? "0px" : "230px" },options);
  	$("#drawer").animate( { left: doFullWidthFill ? "0px" : "-750px", width: doFullWidthFill ? "750px" : "100%" }, $.extend(options,{complete:completeFunc}) );
  	
  }  
  return doSlideIn;
}


function animateDrawerTo ( positionIndex, isAnimation, completeFunction ) {
 	
 	isAnimation = isAnimation == undefined ? false : isAnimation;
 	
 	// set default states = drawer is invisible and hidden on the browsers left border
	var lineState = 		{ left:0 },
		drawerState = 		{ left:"-750px", width:750 },
		contentWrapState = 	{ opacity:0 };
		
 	
 	var completeFunc = function(){ 
 		if( completeFunction != undefined ){ completeFunction(); } 		
 	};
 	if( positionIndex == 1 || positionIndex == 2 ){
  		var doSlideIn = positionIndex == 2;
  		completeFunc = function(){  		
  			$("#pfeile .close").css("display", doSlideIn ? "block" : "none");
			$("#pfeile .open").css("display", doSlideIn ? "none" : "block");				
			$("#pfeile").fadeIn( introDuration );  	
			if( !doSlideIn ){				
				var txt = ajaxMode ? $(".mod_navigation li.active span").text() : $(".mod_navigation li.active span.active").text();
				$("#currPage .inside").text( txt );
				if( $.browser.msie ){// && $.browser.version < 8 ){
					$("#currPage").show();
				}else{
					$("#currPage").fadeIn(transitionDuration);
				};				
			};	
			if( completeFunction != undefined ){
 				completeFunction(); 
 			}
  		}; 		
 	}else{
 		if( $("#drawer").hasClass("open") ){
	  		$("#pfeile").fadeOut( outroDuration );
		}
 	}
 	
 	// reset previous states					
 	$('#drawer').removeClass("open");	
 	$("#currPage .inside").text("");
	$("#currPage").hide();
 	
 	// set states by position index ( 0 = invisible, 4 = fullscreen )
 	switch( positionIndex ){
  	
  		case 1: // drawer is collapsed for better background image view
  			
  			lineState.left = 46;
  			drawerState.left = "-620px";
  			contentWrapState.opacity = 0;  			
  			
  			break;
  	
  		case 2: // drawer is exapanded / open
  			
  			lineState.left = 230;
  			drawerState.left = 0;
  			drawerState.width = 750;
  			contentWrapState.opacity = 1;
  			
  			$('#drawer').addClass("open");		
			$("#pfeile").hide();
  			
  			break;  	
  	
  		case 3: // drawer is over full width
  			
  			lineState.left = 230;
  			drawerState.left = 0;
  			drawerState.width = "100%";
  			contentWrapState.opacity = 1;
  			
  			$("#pfeile").hide();
  			
  			break;	
  			
  		default: // default state = invisible
  				
	}
  
  	if( isAnimation ){
  		// do animate line, drawer and (opacity of) contentWrap
  		var options = {queue:false,duration:transitionDuration };
  		$("#line").animate( lineState, options );
  		$("#contentWrap").animate( contentWrapState, options);
  		$("#drawer").animate( drawerState, $.extend(options,{complete:completeFunc}) );
  	}else{
  		// set css styles w/o animation
  		$("#line").css( lineState );
  		$("#contentWrap").css( contentWrapState );
  		$("#drawer").css( drawerState );
  		completeFunc();
  	}
  
  	
  
}



function isLanguageChange (selector) {
	//console.log( selector );
	return selector.parent().hasClass("lang-en") || selector.parent().hasClass("lang-de");
}


function playOutroToLargeContent( triggerSelector ) {
	
	fadeOutGalleryImages();
	
	var onComplete = function(){		
		
		setFooterClasses( triggerSelector );
		completeEvents.animation=true;
		handleOutroComplete();
		
	};
	
		
	// if initial position was a oneCol page, set drawer to full width
	if( hasOneCol() && !isLanguageChange( triggerSelector ) ){	
		
		if( triggerSelector.hasClass("startseite") ){
			
			toggleContent(true,true,onComplete,false);
			fadeOutContentOnly();
			
		}else{
			toggleContent(true,true,onComplete,true);
			$("#line").fadeOut(outroDuration);
			$("#right").hide();
			$("#content").fadeOut(outroDuration );
			
		}
		
		
		
	// if initial position was the startpage	
	}else if( $("body").hasClass("startseite") ){
		
		
		if( useBGCrossfade ){
			
			var isNextPageStartpage = triggerSelector.hasClass("startseite") || isLanguageChange( triggerSelector );
			if( isNextPageStartpage ){
				pseudoFadeOutForIE( function(){} );					
			}else{
				pseudoFadeOutForIE( undefined,true );		
			}
			return false;	
		}		
		
		$("#drawer").fadeOut(outroDuration);
		$("#line").fadeOut(outroDuration,onComplete);
	
	// if initial position was contentLarge	
	}else if( $("body").hasClass("contentLarge") ){
		
		var isStartpageClicked = triggerSelector.hasClass("startseite");// || isLanguageChange( triggerSelector );
		
		// fade out contents / REVIEW THIS:
		fadeOutContentOnly( isStartpageClicked ? undefined : onComplete )
		
		if( isStartpageClicked ){
			toggleContent(true,true,onComplete,false);
		}
	
		
	}
	
}


function fadeOutContentOnly ( complete ) {
  
	$("#line").fadeOut(outroDuration);
	$("#right").fadeOut(outroDuration);
	$("#content").fadeOut(outroDuration, complete );
  
}


function handleAnimationComplete() {
	if(!ajaxMode){
		location.href = triggeredLink;
	}else{	
		// console.log("ANIMATION COMPLETE (LEFT)");
		completeEvents.animation=true;
		handleOutroComplete();
	}	
}

function setFooterClasses( selector ) {
	
	// is language change?
	var isStartPageLangChange = isLanguageChange( selector ) && isHostingHash();
	
	// remove body indicators
	$("body").removeClass("startseite").removeClass("contentLarge");
	
	// add indicators
	if( selector.hasClass("startseite") || isStartPageLangChange ){
		$("body").addClass("startseite").addClass("contentLarge");
	}else{
		$("body").addClass("contentLarge");
	}
	
}

function isHostingHash() {
	return window.location.hash == hostingHash || window.location.hash == hostingHashEN;
}

function setIndicatorClasses() {
	$("body").removeClass("prevPageWasLargeContent").removeClass("prevPageWasStartpage");
	if( $("body").hasClass("startseite") ){
		$("body").addClass("prevPageWasStartpage");
	}else if( $("body").hasClass("contentLarge") ){
		$("body").addClass("prevPageWasLargeContent");
	}
}

function createPrevImage() {
	// REVIEW THIS:
	$("#background .prevImg").show()
	var currImg = $("#background .currImg").children();
	$("#background .prevImg").empty();
	currImg.clone().appendTo( "#background .prevImg" );
}

function handleOutroComplete( isAjaxComplete ) {
	
	
	if( !completeEvents.xcount ){
		//completeEvents.xcount = 1;
		completeEvents.xcount = [ isAjaxComplete?"ajax":"animation" ];
	}else{
		completeEvents.xcount.push( isAjaxComplete?"ajax":"animation" );
	}
	
	var str="";
	for( prop in completeEvents  ){
		if( prop != "xcount" ){
			str += prop +" - ";
		}
		
	};
	//str += "COMPLETES:"+completeEvents.xcount;
	
	
	// if( !completeEvents.ajax ){
	// 		location.href = triggeredLink;
	// 	}
	//alert( completeEvents.ajax +" // "+ completeEvents.animation )
	
	// if startpage outro is defined and ajax data is loaded, 
	// first crossfade the background image and fadeout old content, then fadein new content (startpageOutro's complete function)
	if( completeEvents.isSearchResult && completeEvents.ajax ){
		
		// set previous indicators as classes
		setIndicatorClasses();
		
		// load current image in previous image container
		createPrevImage();
		
		completeEvents.isSearchResult = undefined;
		if( isContentsLayoutLarge ){
			playOutroToLargeContent( getItemByHashlink( location.hash ) );
		}else{			
			playOutroToOneColContent( getItemByHashlink( location.hash ) );
		}

		
	}else if( startpageOutro && completeEvents.ajax ){
				
		
		// replace image and start crossfade
		replaceTargetPageContent("#background .currImg");
		crossfadeBGimages();
		
		// start fadeout of contents
		startpageOutro( function(){
			
			// replace current with new loaded contents
			replaceAllPageContents();
			
			// play intro
			playIntro();
			
		} );
		startpageOutro = undefined;
		completeEvents = {};
		
	}
	
	// otherwise if animation complete and ajax data is loaded, replace all content and play intro
	else if( completeEvents.ajax && completeEvents.animation ){
		
		//reset event control object
		completeEvents = {};
		
		// replace current with new loaded contents
		replaceAllPageContents();
		
		// play intro
		playIntro();
	}
	
}


/*** AJAX METHODS --BEGIN ***/

function ajaxifyPage( linkSelectors ) {
	
	if( typeof( linkSelectors ) == "string" ){
		linkSelectors = [ linkSelectors ];
	}
	
	// convert navigation's deep links to hash links
	var selector,
		deeplink;
	for (var i=0; i < linkSelectors.length; i++) {
		selector = linkSelectors[i];
		ajaxifyNavigation( selector );
	};
		
	// listen to and trigger hashchange event
	if ("onhashchange" in window) {
  		$(window).bind("hashchange", handleHashChange )
	  		.trigger("hashchange");
	}

	
}

function ajaxifyNavigation( selector ) {
	var deeplink;
	return selector.each( function(){
		deeplink = $(this).attr("href");
		if( deeplink === undefined || deeplink.substr(0,1) == "#" ){
			return false;
		}else{
			$(this).attr("href", convertDeepToHashLink( deeplink ) );			
		}		
	} );
	
}

function handleHashChange(e) {
	

	var hash = window.location.hash || hostingHash;
	
	// handle browser's back button trigger
	if( triggeredLink=="" ){
		if( doesHashlinkBelongsToFooter(hash) ){
			handleFooterNavClick();
		}else{
			handleMainNavClick();
		}
	}
	
	// load pages content via ajax request	
	loadPage( hash, listenToLoadedBG )
	
	// reset triggered hashlink to enable backbutton use
	triggeredLink = "";
}

function doesHashlinkBelongsToFooter( hashlink ) {
	var xpath = ".level_1 li a[href$=\""+hashlink+"\"]";
	if( $(xpath).size()==0 ){
		var actives = $("li.active span.active");
		for (var i=0; i < actives.size(); i++) {
			if( $( actives[i], "#footer").size()>0  ){
				continue;
			}else{
				return false;
			}
		};
		return false;
				
	}else if( $( xpath, "#footer").size()>0 ){			
		return true;
	}else{
		return false;
	}
}

function getItemByHashlink( hashlink ) {
	var xpath = ".level_1 li a[href$=\""+hashlink+"\"]";
	return $( xpath );
}


function loadPage( hashlink, complete ) {
	
	var deeplink = convertHashToDeepLink( (hashlink || hostingHash) );
	var params = {};
	if( hashlink == "#suchresultate" ){
		params.keywords = searchQuery;
	}
	var jqxhr = requestPageContents( deeplink,{ "#content":"main", "#right":"right", "#background .currImg":"Background","#left":"left","#footer":"footer" }, complete, params );	
}

function requestPageContents( pageURL, mappings, complete, parameters ) {
	
	var sections = [],
		requestURL;
	for( selectorID in mappings ){
		sections.push( mappings[ selectorID ] );
	}
	
	var strParameters = "";
	if( parameters != undefined ){
		for( param in parameters ){
			strParameters += "&"+param+"=" +escape(parameters[param]);
		}
	}
	
	
	requestURL = domainPath + pageURL + "?request=" + escape(sections.join(",")) + strParameters;
	//console.log( "REQ: "+requestURL )
	return $.ajax({
		url: requestURL,
		context: document.body,
		dataType: "html",
		success: function(data){
			
			_gaq.push(['_trackPageview', pageURL]);
			var sectionContent;
			nextPageContents = {};
			for( selectorID in mappings ){
				sectionContent = $(data).find("div#ajaxSection_" + mappings[ selectorID ] ).children();
				nextPageContents[ selectorID ] = sectionContent;
			}
			if( complete != undefined ){
				complete( data );				
			}
	  	}
	});
	
}

function replaceAllPageContents() {
	for( selectorID in nextPageContents ){
		replaceTargetPageContent( selectorID );
	}
}

function replaceTargetPageContent(selectorID) {
	var sectionContent = nextPageContents[ selectorID ];
	if( sectionContent ){
		$( selectorID ).empty().append( sectionContent );
	}	
}

function convertDeepToHashLink( deeplink ) {
	var httpPrefix = "http://";
	var hasHttpPrefix = deeplink.substr(0,httpPrefix.length) == httpPrefix;
	var hashlink = "";
	var pathParts = hasHttpPrefix ? deeplink.substr(httpPrefix.length).split("/") : deeplink.split("/");
	
	// if string is slash separated, check if first part does contain dots e.g. www.google.com
	if( pathParts.length > 1 )
	{
		if( hasHttpPrefix ){
			
			hashlink = pathParts.slice(1,pathParts.length-1).join("/");
			if( hashlink.length ){
				hashlink += "/";
			}
		}else{
			
			hashlink = pathParts.slice(0,pathParts.length-1).join("/") + "/";
			
		}
		hashlink += pathParts[pathParts.length-1].split(".html")[0];
		
	}
	
	// else use hardlink without html term
	else{
		hashlink = deeplink.split(".html")[0];
	}
	
	return "#" + hashlink;
}

function convertHashToDeepLink( hashlink ) {
	var splits = hashlink.split("#");
	if( splits.length == 2 ){
		return splits.join("/") + ".html";
	}else if( splits.length > 2 ){
		return hostingHash;
	}
	
}

function crossfadeBGimages( completeFunc ) {
	
	// fade out previous image to show current image
	currBackgroundImages = $("#background img");
	if( currBackgroundImages.size()>0 ){
		//currBackgroundImages.hide();
		currBackgroundImages.scaleToFullscreen().show();
		$("#background .prevImg").fadeOut(crossfadeDuration, completeFunc);
	}

	// use previous image as current image if no image is available
	if( $("#background .currImg img").size()==0 ){
		$("#background .currImg").append( $("#background .prevImg").children() );
	}
	// else if( $("#background .currImg img").size()==1 ){
	// 		$("#background .currImg img").show();
	// 	}
	
}





/*** AJAX METHODS --END ***/


function playIntro() {
	
	
	if($("#newsletter-singup-form").size()>0){
  		
  		$("#newsletter-singup-form p.submit a").click(function(e){
  			e.preventDefault();
  			$("#newsletter-singup-form input").add("#newsletter-singup-form select").removeClass("error");//.css({ background:"#FFF", border:"" })
  			$(".errorMsg:visible").slideUp(500);
  			var cssLabelError = { color:"red" };
  			var arrErrorMsg = [];
  			//var cssFieldError = { border:"1px solid red", background: "#FFCEBC" };
  			var blnNoErrors = true;
  			if( $("#newsletter-singup-form select[name=Anrede]").val() == "#DEL#" ){
  				$("#newsletter-singup-form select[name=Anrede]").addClass("error");//.css(cssFieldError);
  				//$("#newsletter-singup-form label[for=Anrede]").css(cssLabelError); 
  				blnNoErrors = false;
  				arrErrorMsg.push( "Anrede" );
  			}
  			if( $("#newsletter-singup-form input[name=Vorname]").val() == "" ){
  				$("#newsletter-singup-form input[name=Vorname]").addClass("error");//.css(cssFieldError);
  				//$("#newsletter-singup-form label[for=Vorname]").css(cssLabelError); 
  				blnNoErrors = false;
  				arrErrorMsg.push( "Vorname" );
  			}
  			if( $("#newsletter-singup-form input[name=Name]").val() == "" ){
  				$("#newsletter-singup-form input[name=Name]").addClass("error");//.css(cssFieldError);
  				//$("#newsletter-singup-form label[for=Name]").css(cssLabelError); 
  				blnNoErrors = false;
  				arrErrorMsg.push( "Name" );
  			}
  			
  			// check email address' validation
  			var strEmail = $("#newsletter-singup-form input[name=Email]").val();
  			var blnIsValid = (/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/).test(strEmail);
  			if( !blnIsValid ){
  				$("#newsletter-singup-form input[name=Email]").addClass("error");//.css(cssFieldError);
  				//$("#newsletter-singup-form label[for=Email]").css(cssLabelError); 
  				blnNoErrors = false;
  				arrErrorMsg.push( "Email" );
  			}
  			if( blnNoErrors ){
  				document.onlineForm.submit();
  				//alert("SUBMIT");
  			}else{
  				var strError = $("#newsletter-singup-form .error_msg").text();
  				//alert(strError);
  				for (var i=0; i < arrErrorMsg.length; i++) {
					$(".error_"+arrErrorMsg[i]).slideDown(500);
				};
  			}
  			
  		});
  		
  	}
	
	if( $("body").hasClass("no-ajax") ){
		$("body").removeClass("no-ajax").addClass("ajax");
	}
	
	if(ajaxMode){
		
		// console.log( "––––––––––––––PLAY INTRO" );
		initGallery();
		hoverTeaser();
		initLightbox();
		
		addClassToFloatedImages();
		listenToMediaHover();
		initSearchfield();
		
		if($(".mod_changelanguage li").hasClass("lang-en")) {
			$("#logo a").attr("href",hostingHash);
		}else{
			$("#logo a").attr("href",hostingHashEN);
		}
		
		
		// detect main navigation
		ajaxifyNavigation( $("#left .mod_navigation .level_1 li a") ).click( handleMainNavClick );    
		ajaxifyNavigation( $("#left .mod_changelanguage li a") ).click( $("body").hasClass("contentLarge") ? handleFooterNavClick : handleMainNavClick );    
		ajaxifyNavigation( $("#footer .mod_navigation .level_1 li a") ).click( handleFooterNavClick );    
		// detect subnavigations
		ajaxifyNavigation( $(".mod_customnav .level_1 li a") );    
		// pressnews
		ajaxifyNavigation( $(".mod_newslist .layout_short h2 a") ).click( handleFooterNavClick );
		ajaxifyNavigation( $(".mod_newslist .layout_short p.more a") ).click( handleFooterNavClick );
		// news
		ajaxifyNavigation( $(".mod_newslist .layout_latest h2 a") ).click( handleMainNavClick );
		ajaxifyNavigation( $(".mod_newslist .layout_latest p.more a") ).click( handleMainNavClick );
		// search results
		ajaxifyNavigation( $(".mod_search h2 a") ).click( handleSearchResultClick );
		
		if( !$("body").hasClass("startseite") ){
			$("#drawer").show();
		}
		
		// make subnavigation clickable
		$(".mod_customnav li a").click( handleFooterNavClick );
		
		// add active class' describing class as wrapper class 
		var pageTitle;
		var activeItem;
		if( $(".mod_navigation li.active").size()>0 ){
			activeItem = $(".mod_navigation li.active");
		}else{
			activeItem = $(".mod_navigation li.trail");
		}
		if( activeItem.size()>0 ){
			
			var classes = activeItem.attr("class").split(" "),
				pageClass;
			pageTitle = activeItem.text();
			for (var i=0; i < classes.length; i++) {
				if( classes[i] != "active" ){
					pageClass = classes[i];
					break;
				}
			};
			$("#wrapper").attr("class","").addClass(pageClass);
			
		}else{
			$("#wrapper").attr("class","");						
		}
		document.title = (pageTitle || "Home") + generalPageTitle;
				
		
		var isStartpage = $("body").hasClass("startseite"),
			numBGImages = $("#background img").size();
		
		
		
		// play intro animation
		if( useBGCrossfade && isStartpage )
		{
			
			// if initial startpage is loaded
			if( numBGImages == 1 ){
				
				pseudoFadeInForIE( true );
			
			}
			
			// first crossfade, then do IE pseudo fadeout
			else{
				
				crossfadeBGimages( pseudoFadeInForIE );	
			}
			
		}
		else
		{
			
			// generate intro animation
			fadeInNewContent();		
			
			//crossfade background images	
			crossfadeBGimages();	
		}
		
		
		
	
	}
}

function fadeInNewContent () {
  
  
	// CASE: oneColPage / largeContentPage -> startpage
	if( $("body").hasClass("startseite") ){
			
		// switch to logo for black background
		$("#logo img").attr("src","tl_files/Layoutbilder/logo_home.png");
		
		$("#contentWrap,#drawer").show();
		$("#line").css("left","230px");
		$("#drawer").css({left:0,width:''});
		
		fadeInContentOnly( removeFilter );
		
	}else{	
		
		// switch to logo for black background
		$("#logo img").attr("src","tl_files/Layoutbilder/logo.png");
		
		
		// CASE: startpage -> oneColPage / largeContentPage
		if( $("body").hasClass("prevPageWasStartpage") ){

			// initial position
			toggleContent(false,false,undefined,false);
			$("#drawer").show();
			$("#line").hide().fadeIn( introDuration );//css("opacity",1);
			
			// slide in drawer
			var isFullwidthDisplay = $("body").hasClass("contentLarge")?true:undefined;
			toggleContent(true,true,removeFilter,isFullwidthDisplay);
		
		
		// CASE: oneColPage -> largeContentPage	
		}else if( $("body").hasClass("contentLarge") && !$("body").hasClass("prevPageWasLargeContent") ){
			
			toggleContent(false,true,undefined,true);
			fadeInContentOnly( removeFilter );			
		
		// CASE: oneColPage -> oneColPage or largeContentPage -> largeContentPage		
		}else{
			
			$("#contentWrap,#drawer").css({opacity:1});
			fadeInContentOnly( removeFilter );
			$("#drawer").addClass("open");
			
		}
	
	}
  
}


function fadeInContentOnly (complete) {
  	
  	$("#line").fadeIn(introDuration);
  	$("#content").hide().fadeIn(introDuration);
	$("#right").hide().fadeIn(introDuration,complete);
}


function hasOneCol() {
	return !$("body").hasClass("contentLarge") && !$("body").hasClass("startseite");
}

$(window).resize(function() {
	if( currBackgroundImages != undefined ){
		currBackgroundImages.scaleToFullscreen().show();
	}	
});



function toggleContent ( isAnimation, isSlideIn, completeCallback, isFullWidth ) {
	
	// only show arrows if drawer is open
	if( isSlideIn != $("#drawer").hasClass("open") ){
		$("#pfeile").hide();
	}
	
	// set default slide action if not set	
	if( isSlideIn == undefined ){
		isSlideIn = $('#drawer').hasClass("open") ? false : true;
	}
	
	var width, left;
	if( isFullWidth != undefined ){
		width = isFullWidth ? "100%" : "750px";
		left = isFullWidth ? "0px" : "-750px";
		if( $("#drawer").hasClass("open") ){
			$("#pfeile").fadeOut();
		}
	}else{
		left = isSlideIn ? 0 : -620;
		if( $("body").hasClass("contentLarge") && isSlideIn ){
			left = "0px";
			width = "750px";
		}
	}	
	
	if( isSlideIn==true ){
		$('#drawer').addClass("open");		
		$("#currPage .inside").text("")
		$("#currPage").hide();
	}else{
		$('#drawer').removeClass("open");		
	}
	
	var slideState = {	left:left };
	if( width!=undefined ){
		slideState.width = width; 
	}
	var lineState = { left: (isSlideIn && isFullWidth!=false) ? 230 : 46 };
	
	if( isSlideIn && isFullWidth==undefined && !$("body").hasClass("contentLarge") ){
		//$('#line').css({ left:0 });		
	}
	
	var contentState = { opacity:isSlideIn ? 1 : 0 };
	var completeFunc = function() {
		
		//$("#subnavi").fadeIn("fast");	
		
		if( isFullWidth==undefined ){
			
			$("#pfeile .close").css("display", isSlideIn ? "block" : "none");
			$("#pfeile .open").css("display", isSlideIn ? "none" : "block");				
			$("#pfeile").fadeIn(introDuration);		
			
			if( !isSlideIn ){
				
				var txt = ajaxMode ? $(".mod_navigation li.active span").text() : $(".mod_navigation li.active span.active").text();
				$("#currPage .inside").text( txt );
				if( $.browser.msie ){// && $.browser.version < 8 ){
					$("#currPage").show();
				}else{
					$("#currPage").fadeIn(transitionDuration);
				}
				
			}
		}
		
		if( completeCallback ){
			completeCallback();
		}
	};

	if( isAnimation ){
		var duration = $("body").hasClass("contentLarge") || isFullWidth != undefined ? transitionDuration : slideDuration;
		var opt = {queue:false,duration:duration };
		$('#line').animate(lineState, opt );
		$("#contentWrap").animate(contentState,opt);
		$('#drawer').animate(slideState,$.extend(opt,{ complete:completeFunc }) );
	}else{
		$('#drawer').css( slideState );
		$('#line').css( lineState );
		$("#contentWrap").css( contentState );
		completeFunc();
	}	
	
}

function handleImageLoadComplete() {
	
	completeEvents.ajax = true;
	handleOutroComplete(true);
	
}

function listenToLoadedBG( data ) {
	
	isContentsLayoutLarge = $(data).hasClass("contentLarge");
	
	currBackgroundImages = $("#background img");
	// console.log("WAIT FOR "+currBackgroundImages.length+" IMAGES");
	if( currBackgroundImages.size()==0 ){
		// console.log("NIX IMG")
		handleImageLoadComplete();
		return false;
	}
	
	// REVIEW THIS:
	var prevImg = $("#background .prevImg img");
	if(ajaxMode){
		prevImg.css("visibility","visible");
	}else{		
		if( prevImg.size()>0 ){
			scaleImages( prevImg.css("visibility","visible") );
		}
	}
		
	currBackgroundImages.imagesLoaded( function(){ 

		if(ajaxMode){
			handleImageLoadComplete();
		}else{
			// crossfade background images if possible
			currBackgroundImages.scaleToFullscreen(); 
			if( currBackgroundImages.size()==2 ){
				prevImg.fadeOut(introDuration);
			}
		}
		
	} );
	
}

function initSearchfield() {
	$("#ctrl_2_submit").attr('value', '');
	if( !searchQuery ) {
		if($(".mod_changelanguage li").hasClass("lang-en")) {
			$("input[name=keywords]").val("SUCHEN")
		} else {
			$("input[name=keywords]").val("SEARCH")
		}
	}else{
		$("input[name=keywords]").val(searchQuery)
	}
	$("input[name=keywords]").click( function() {
		$(this).attr('value', '');
	});
	$("form#f1").submit( handleSearchSubmit );
}

function hoverTeaser() {
	$("#teaser .ce_text:first h3").addClass("aktiv");
	$("#teaser h3").hover( function() {
		$("#teaser .ce_text h3").removeClass("aktiv")
		$(this).addClass("aktiv");
		$("#teaser .ce_text p").hide();
		$(this).parent().find("p").show();
	});
}

function listenToMediaHover () {
   $("#wrapper.medien .downloadarchivItem .image_container img").hover( 
       function() {
           $(this).animate({height: '120px', width: '160px', left: '-=50px', top: '-=38px'}, 100);
       },
       function() {
           $(this).animate({height: '45px', width: '60px', left: '+=50px', top: '+=38px'}, 100);
       }
   );
};

function addClassToFloatedImages () {
// add class to floated images
	$("#content img").each( function() {
		if( $(this).css("float") == "right") {
			$(this).addClass("rightImage");
		}
	});
}

function initLightbox() {

   $(".image_container").each( function() {
       $(this).find(".hyperlink_img[rel='lightbox']").lightBox();
       $(this).find(".ce_hyperlink[rel='lightbox']").lightBox();
   })

}

