//Global Vars

var startscreenDuration = 500;
var startscreenFade = 500;
var startscreenFadeIn = 500;
var loadingFadeIn = 200;
var loadingFadeOut = 500;

var fadespeedDetails = 300; //animation speed (ms)

var globalIsIE7 = false;
if (jQuery.browser.msie && jQuery.browser.version.substr(0, 1) == 7) {
	fadespeedDetails = 0;
	startscreenFadeIn = 0;
	loadingFadeIn = 0;
	loadingFadeOut = 0;
	globalIsIE7 = true;
}

var globalIsIE8 = false;
if (jQuery.browser.msie && jQuery.browser.version.substr(0, 1) == 8) {
	fadespeedDetails = 0;
	startscreenFadeIn = 0;
	globalIsIE8 = true;
}

var animatespeedPanel = 850; //animation speed (ms)
var animatespeedExtender = 400; //animation speed (ms)
var newPanelWrapperWidth = 0;
var pageWidth = 0;
var automaticAnimation;
var easingMethod = "easeOutQuint";

var blinkPreNext = 300;

// Global states and vars
var globalStartScreenOnceFaded = 0; //indicates if startscreen is faded
var globalJSON =""; // Global Closure for JSON file
var globalReloadPanel = true; //boolean value that indicates if panel has to be reloaded
var globalPagetypeLoad = "";
var globalSubnavParent = "";

var globalAmountPages = "";
var globalNewWrapperWidth = "";
var globalPageWidth = "";

// Global closures


// ----------------------------------------------------------------------- //
// --- INITIAL FUNCTION LOADING THE START PAGE AND EXTRACTING THE HASH --- //
// ----------------------------------------------------------------------- //

jQuery(document).ready(function() {
	if (!(jQuery.browser.msie && jQuery.browser.version.substr(0, 1) <= 6)) {
		// On load, load JSON File and call all docreadys
		jQuery.getJSON('json/pages.json', function(pages) {
			globalJSON = pages; //projects is global closure for json file
			jQuery.history.init(callback);
		});
	}
});


function callback(hash) {
	var isStart = jQuery("body").hasClass("index");

	if(isStart==true) { // Is physical start page?
	
		// Does start page have hash value?
		var whatsDaHash = window.location.hash;
		whatsDaHash = whatsDaHash.replace( '#', '');
		
		// If not, set hash to "index" for index.phtml
		/*
		if (whatsDaHash=="") {
			whatsDaHash="index";
		}
		*/
		
		// Start content operations dependend on hash value
		if (whatsDaHash!="") {
			docready(whatsDaHash);
		}
		
		if (whatsDaHash=="") {
			whatsDaHash="index";
		}
		
		// History-Eintrag 
		jQuery.history.load(whatsDaHash);
		

		// Econda	
		var emospro = {};
		emospro.content = globalJSON.pagedata[whatsDaHash].emosPageContent;
		emospro.pageId = globalJSON.pagedata[whatsDaHash].emosPageId;
		emospro.siteid = 'www.salient.de'; 
		window.emosPropertiesEvent(emospro); // Senden der Werte an econda	
		
		
	}else{	// if no, cut last part of url without ".phtml" and call start page with hash value			
		var pathname = window.location.pathname;
		var lastslash = pathname.lastIndexOf('/');
		lastslash++;
		var lastdot = pathname.lastIndexOf('.');
		var newLocationBeginning = pathname.substring(0,lastslash);
		var newhash = pathname.substring(lastslash,lastdot);
		var newUrl = newLocationBeginning + "index.phtml#" + newhash;
		window.location.replace(newUrl);
	}
}

// --------------------------------------------------- //
// --- CONTENT OPERATIONS DEPENDEND AND HASH VALUE --- //
// --------------------------------------------------- //

function docready(hashvalue) {

	// --------------------------- //
	// --- TYPE OF PAGE LOADED --- //
	// --------------------------- //
	/*
	jQuery.each(globalJSON.pagedata, function(key, pagevalue) {
		if (pagevalue.pageidentifier == hashvalue) {
			globalPagetypeLoad = pagevalue.pagetypeload;
			globalSubnavParent = pagevalue.subnavParent;
		}
	});
	*/
	
	globalPagetypeLoad = globalJSON.pagedata[hashvalue].pagetypeload;
	globalSubnavParent = globalJSON.pagedata[hashvalue].subnavParent;
	
	// --------------------- //
	// --- START ELEMENT --- //
	// --------------------- //
	
	if (globalPagetypeLoad=="index") {
		if (globalStartScreenOnceFaded==0) {  //dont show startscreen again once panel faded in
			// Fade in of start cloud
			jQuery("#top, #below, #bottom, .page-prev, .page-next").css({"visibility":"hidden"});
			window.setTimeout(function() {
				jQuery(".startscreen").css('visibility','visible').hide().fadeIn(startscreenFadeIn);
			}, 400);
			
			// Click 'play'
			jQuery("#play-start").unbind("click");
			jQuery("#play-start").bind("click", function() {
				jQuery("#top, #below, #bottom, .page-prev, .page-next").css('visibility','visible').hide().fadeIn(startscreenFadeIn);
				blink();
				globalStartScreenOnceFaded = 1; //dont show startscreen again once panel faded in
				return false;
			});
		}else if (hashvalue!="") {
			jQuery("#top, #below, #bottom, .page-prev, .page-next").css({"visibility":"visible"});
		}
		
	}else if (globalPagetypeLoad!="") {
		jQuery("#top, #below, #bottom, .page-prev, .page-next").css({"visibility":"visible"});
	}else{
		jQuery("#top, #below, #bottom, .page-prev, .page-next").css({"visibility":"hidden"});
	}
	
	// ------------------------------------------------------------------------------------- //
	// --- Top Navigation and Opening and Closing of Extender Stage & loading of content --- //
	// ------------------------------------------------------------------------------------- //

	// open Extender Content on load if pagetype is "topcontent"
	if (globalPagetypeLoad=="topcontent") {
		openExtenderContent(hashvalue); // ""= no clicked element; false=order to NOT load content via ajax, but to use the natively loaded content
	}
	
	if (globalPagetypeLoad=="index") { //TODO: maybe make an exception if "in focus" is clicked
		closeExtenderContent();
	}
	
	// open Extender Content on click - if the same hash, dont reload content
	jQuery("#top li a").unbind("click");
	jQuery("#top li a").bind("click", function() {

		globalReloadPanel = false;  //for all top navi: dont reload panel
		
		var pageidentifier = jQuery(this).parent().attr("id");
		var firstminus = parseInt(pageidentifier.indexOf('-'));
		firstminus++;
		var hash = pageidentifier.substring(firstminus);
		var currentHash = window.location.hash;
		currentHash = currentHash.replace( '#', '');
		
		if (hash!=currentHash) {
			hash = hash.replace(/^.*#/, '');
			jQuery.history.load(hash);
		}else{
			openExtenderContent(hash);
		}
			
		return false;
	});
	
	jQuery("#bottom a").unbind("click");
	jQuery("#bottom a").not(".lang").bind("click", function() {
	
		globalReloadPanel = false; //for all bottom navi: dont reload panel
		
		var pageidentifier = jQuery(this).attr("id");
		var firstminus = parseInt(pageidentifier.indexOf('-'));
		firstminus++;
		var hash = pageidentifier.substring(firstminus);
		hash = hash.replace(/^.*#/, '');
		// moves to a new page.
		// pageload is called at once.
		jQuery.history.load(hash);
		
		jQuery(document).scrollTop(0);
		return false;
	});

	// close extender content //
	// does not change hash value, because which hash value should it be?
	jQuery(".close-extender").live("click", function() {
		closeExtenderContent();
		return false;
	});

	// Click on Logo - Start Page
	jQuery("#logo").unbind("click");
	jQuery("#logo").bind("click", function() {

		globalReloadPanel = true; //for click on logo: reload panel
		
		var hash = "index"
		hash = hash.replace(/^.*#/, '');
		jQuery.history.load(hash);

		return false;
	});


	// ----------------------------- //
	// --- Panel Content Loading --- //
	// ----------------------------- //
		
	if ((globalPagetypeLoad == "panelcontent") || (globalPagetypeLoad == "panelmain")) { // Panel Content loaded - first reset - show LoadingScreen - then loadPanel with initial value "noclickedelement"
		globalReloadPanel = true;
		//jQuery("#wrapper").animate({"margin-left": "0px"}, {duration: animatespeedPanel, easing: easingMethod});
		showLoading();
		loadPanel("noclickedelement", hashvalue);
		/*window.setTimeout(function() {
			showLoading();
			loadPanel("noclickedelement", hashvalue);
			window.setTimeout(function() {
				
			}, loadingFadeIn); 
		}, animatespeedPanel);*/
	}else if (globalPagetypeLoad == "topcontent") { // Check if Panel needs to be loaded (with start value) - normally with topcontent, panel has no special content, so if it is not yet loaded, startcontent is needed
		checkIfPanelNeedsLoad(hashvalue);		
	}else if (globalPagetypeLoad == "index") { // Check if Panel needs to be loaded (with start value)
		checkIfPanelNeedsLoad(hashvalue);
	}
	
	
	// TODO: If make this panel reload every time
	// TODO: on load: remove href attribute to not confuse
	// do not klapp ein topcontent on click
	
	jQuery(".panel-navigation li a").live("click", function() { // on click, load with new hash value
		/*if (this.id=="nav-index") {
			return false;
		}else{*/
			var hash = this.id;
			var firstminus = parseInt(hash.indexOf('-'));
			firstminus++;
			hash = hash.substring(firstminus);
			hash = hash.replace(/^.*#/, '');
			jQuery.history.load(hash);
			return false;
		// }
	});
	
	// ----------------------------------------------------------------- //
	// --- Init "Show" and "Close" Buttons of details of panel pages --- //
	// ----------------------------------------------------------------- //

	jQuery(".close-details, .backgroud-img").live("click", function() { // .live() is needed because ajax loads content dynamically
		showLevelOne(fadespeedDetails);
		return false;
	});

	jQuery(".show-details").live("click", function() { // .live() is needed because ajax loads content dynamically
		showLevelTwo(fadespeedDetails);
		return false;
	});

	// ---------------------------------- //
	// --- Extend Project Detail Card --- //
	// ---------------------------------- //
	
	jQuery(".wider").live("click", function() {
		if (jQuery(this).hasClass("open")) {
			jQuery(this).parent().parent().find(".card-right-wrapper").animate({"width":"351px"},{duration: animatespeedPanel, easing: easingMethod});
			jQuery(this).removeClass("open");
		}else{
			jQuery(this).parent().parent().find(".card-right-wrapper").animate({"width":"765px"},{duration: animatespeedPanel, easing: easingMethod});
			jQuery(this).addClass("open");
			
			/* if card is on the right side, move card to the left if it opens */
			var currentpos = jQuery(this).parent().parent().parent().attr("currentpos");
			var thisAttribute = jQuery(this).attr("id");
			var thisIndex = thisAttribute.substring(5);
			if (currentpos==thisIndex) {
				jQuery(this).addClass("justopened");
				jQuery(".card-next").trigger("click");
			}
		}
		return false;
	});

}

// ----------------------------- //
// --- Open extender content --- //
// ----------------------------- //

function openExtenderContent(pageidentifier) {

	if (globalSubnavParent != "") {
		jQuery("#nav-"+globalSubnavParent).addClass("selected");
		jQuery("#top li").not("#nav-"+globalSubnavParent).removeClass("selected");
	}else{
		jQuery("#nav-"+pageidentifier).addClass("selected");
		jQuery("#top li").not("#nav-"+pageidentifier).removeClass("selected");
	}

	var checkId= "nav-" + pageidentifier;
	jQuery("#top li").each(function() {
		var thisId = jQuery(this).attr("id");
		if (thisId==checkId) {
			jQuery(this).addClass("selected");
		}
	});

	// Continue if complete...
	jQuery.ajax({
		url: 'html/' + pageidentifier + '.txt', //works only if identifiers are always the same as the urls (without ".phtml")
//		contentType: 'text/html',
		dataType: 'html',
		mimeType: 'text/html',
		success: function(data) {
			var assemblycontent = jQuery(data).html();
			jQuery("#extender-content *").remove();
			jQuery('#extender-content').append(assemblycontent);
			
			//measure new height and open content (or: if opened, set new height)
			var extenderheight = jQuery("#extender-content").height();
			
			jQuery("#extender-content").css({"bottom":"50px"});
			
			var newheight = parseInt(extenderheight) + (parseInt(jQuery("#extender-content").css("bottom")) * 2);
			
			jQuery("#extender-stage").stop().animate({"height":newheight}, {duration: animatespeedExtender, complete: function() {
				jQuery("#extender-content").css({"bottom":"auto","top":"50px"}); // when opened, relate to top instead of bottom, so that content does not jump when height is changed
			
			}});
			jQuery("#extendergap").stop().animate({"height":"20px"}, {duration: animatespeedExtender});
			
			//init subnavi
			jQuery(".subnavi a").bind("click", function() {
			
				globalReloadPanel = false; //for all top navi say: dont reload panel
				
				var pageidentifier = jQuery(this).parent().attr("id");
				//openExtenderContent(pageidentifier);
				var firstminus = parseInt(pageidentifier.indexOf('-'));
				firstminus++;
				var hash = pageidentifier.substring(firstminus);
				hash = hash.replace(/^.*#/, '');
				// moves to a new page.
				// pageload is called at once.
				jQuery.history.load(hash);
				
				return false;
			});
		}
	});
}

// ------------------------------- //
// --- Update Extender Content --- //
// ------------------------------- //

function updateExtender() { //this function has to be called after .text or .extender-exchangable changed
	var extenderheight = jQuery("#extender-content").height();
	var newheight = parseInt(extenderheight) + (parseInt(jQuery("#extender-content").css("top")) * 2);
	jQuery("#extender-stage").css({"height":newheight+"px"});
}

// ------------------------------ //
// --- Close Extender Content --- //
// ------------------------------ //

function closeExtenderContent() {
	jQuery("#extender-content").css({"bottom":"50px","top":"auto"});
	jQuery("#extender-stage").stop().animate({"height":"0"}, {duration: animatespeedExtender, easing: easingMethod, complete: function() {
		jQuery("#top li").removeClass("selected");
	}});
	jQuery("#extendergap").stop().animate({"height":"0px"}, {duration: animatespeedExtender});
}

// ----------------------------------------- //
// --- Check if Panel needs to be loaded --- //
// ----------------------------------------- //

function checkIfPanelNeedsLoad(hashvalue) {
	if (globalReloadPanel==true) {
		jQuery("#wrapper").animate({"margin-left": "0px"}, {duration: animatespeedPanel, easing: easingMethod});
		loadPanel("noclickedelement", hashvalue);
	}
}

// ------------------ //
// --- load Panel --- //
// ------------------ //

function loadPanel(clickedelement, hashvalue) {

	var pageidentifier= "";
	if (clickedelement != "noclickedelement") {
		jQuery(".panel-navigation li").removeClass("selected");
		jQuery(clickedelement).parent().addClass("selected");
		pageidentifier = jQuery(clickedelement).attr("id");
	}else{
		//pageidentifier = jQuery("body").attr("id");
		pageidentifier = hashvalue;
	}

	jQuery(".panel-navigation li.selected ul").remove(); //remove static light navigation and make it dependend on the loaded project list

	var assemblycontent = new Array(); //assemble all new content in this array
	var projectincludes = new Array();
	
		var pagevalue = globalJSON.pagedata[pageidentifier];
			
			var tabCategory = "im-fokus"; //default panel is "im fokus"
			if (usedlanguage=="en") {
				tabCategory = "in-focus";
			}
			
			if (pagevalue.pagetypeload=="panelcontent") {
				tabCategory = pagevalue.subnavParent;
			} else if (pagevalue.pagetypeload=="panelmain") {
				tabCategory = pageidentifier;
			}
			
			jQuery(".panel-navigation li").removeClass("selected");
			jQuery(".panel-navigation li a#nav-" + tabCategory).parent().addClass("selected");
			
					var tab = globalJSON.tabdata[tabCategory];
				
					var amountincludes = tab.projectincludes.length - 1; // -1 because index starts at 0
					var index = 0;
		
					jQuery.each(tab.projectincludes , function(key2, include) {
						var localindex = index;
						
						//store all includes with their identifier in array
						projectincludes.push(include.identifier);
						jQuery.ajax({
							url: 'html/' + include.identifier + '.txt', //works only if identifiers are always the same as the urls (without ".html")
							dataType: 'html',
							mimeType: 'text/html',
							success: function(data) {
								assemblycontent[localindex] = jQuery(data).find("#wrapper").html();							
								if (localindex == amountincludes) { //after the last array element is filled, go over array, check if one is not filled yet. If so, repeat checking... if all are filled, append everything
									// function to check if all content is there
									function checkContent() {
										var contentloaded = 1; //default set true
										var checkindex = 0;		
										jQuery.each(assemblycontent, function(key, value) {
										
											if (value.length == 0) { 
												contentloaded = 0;
											}
											
											if (checkindex == amountincludes) {
												if (contentloaded == 1) {
													window.clearInterval(checkInterval);
													appendator();
												}
											}
											checkindex++;
										});
										
									}
									
									// function to append eveything to html
									function appendator() {
									
										var appendhtml = "";
										var appendindex= 0;
										jQuery.each(assemblycontent, function(key, valueHere) {
											appendhtml = appendhtml + valueHere;
											if (appendindex == amountincludes) {
												jQuery("#wrapper *").remove();
												jQuery("#wrapper").css({"margin-left": "0px"});
												jQuery.each(assemblycontent, function(key, valueHere) {
													jQuery('#wrapper').append(valueHere);
												});
												delete assemblycontent;
												initCarouselL1(pageidentifier);
											}
											appendindex++;
										});	
										
									}
									var checkInterval = window.setInterval(checkContent, 200);
								}
							}
						});
						index++;
					}); 


	// --- INIT CAROUSEL L1 --- //
	// do this only if ajaxing and building is complete... //
	
	function initCarouselL1(pagejumper) {
		globalAmountPages = jQuery(".panel-page").length;
		if(globalAmountPages>1) {
		
			//set width of panel wrapper
			globalPageWidth = parseInt(jQuery(".panel-page:first").width());
			globalNewWrapperWidth = (globalAmountPages  + 1) * globalPageWidth;
			jQuery("#wrapper").css({"width": globalNewWrapperWidth + "px"});
		
			//copy first page to last position, necessary for carousel function
			var first = jQuery(".panel-page:first").clone();
			first.appendTo(jQuery('#wrapper'));
			
			//build up all ids
			var index=1;
			var lastElement = globalAmountPages + 1;
			jQuery(".panel-page").each(function() {
				if (index != lastElement) {
					jQuery(this).attr("id","page"+index);
					index++;
				}
			});
			
			//build lights list
			
			var lights = "<ul>";
			var linkTitle;
			var index = 1;
			
			
			jQuery.each(projectincludes, function(key, value) {
			
				var linkTitle = "";
				jQuery.each(globalJSON.projectdata, function(key, prvalue) {
					if (prvalue.projectidentifier == value) {
						linkTitle = prvalue.projecttitle;
					}
				});

/*
				var linkTitle = "";
				var prvalue = globalJSON.projectdata[value];
				linkTitle = prvalue.projecttitle;
*/				
				if (index==1) {
					lights = lights + '<li><a id="light' + (index++) + '" href="#" class="selected"><span class="tooltip">' + linkTitle + '</span></a></li>';
				}else{
					lights = lights + '<li><a id="light' + (index++) + '" href="#"><span class="tooltip">' + linkTitle + '</span></a></li>';
				}
			});

			lights = lights + "</ul>";
			// TODO: Write in title and href attributes to "a" (read out from json object??)
			jQuery(lights).appendTo('.panel-navigation li.selected');
			
			// build light navigation
			jQuery(".panel-navigation li ul a").bind("click",function() {
				jQuery(".panel-navigation li ul a").not(this).removeClass("selected");
				jQuery(this).addClass("selected");
				var activeId = jQuery(this).attr("id")
				var thisindex = parseInt(activeId.substring(5));
				jQuery(".panel-page").removeClass("active");
				jQuery("#page"+thisindex).addClass("active");
				jumpToPage(thisindex);
				return false;
			});
			
			//are set on display:none on default
			jQuery(".page-prev, .page-next").show();
			
			//panel navigation previous
			jQuery(".page-prev").unbind("click");
			jQuery(".page-prev").click("click",function() {
				previousPage();
				if(automaticAnimation) {clearInterval(interval)}; //in case interval is started
				return false;
			});
		
			//panel navigation next
			jQuery(".page-next").unbind("click");
			jQuery(".page-next").click("click",function() {
				jQuery(this).show();
				nextPage();
				if(automaticAnimation) {clearInterval(interval)}; //in case interval is started
				return false;
			});
			

			/* Weseley Swipes */
			jQuery(function(){
				// This prevents scrolling
				jQuery('.panel-page img').swipe(function(e, info){
					if (info.direction === 'left') {
						nextPage();
					}
				});
				jQuery('.panel-page img').swipe(function(e, info){
					if (info.direction === 'right') {
						previousPage();
					}
				})
			});
			
			//finally, set first element as active/selected (TODO: not always the case)
			jQuery("#page1").addClass("active");
			
			// this function autmatically displays next carousel page (however i don't think that we need this)
			//var automaticAnimation = window.setInterval(nextPage,15000);
		
			if (pagejumper!="") {
				jumpToPage(pagejumper);
			}
		}else{
			jQuery("#wrapper .panel-page").addClass("active");
			jQuery(".page-prev, .page-next").hide();	
		}
		
		hideLoading();
		
		//init Tooltips
		initTooltips(".page-prev");
		initTooltips(".page-next");
		initTooltips(".show-details");
		initTooltips(".close-details");		
		
		// init internal links
		jQuery('.internal-more-link a').bind("click", function() {
			globalReloadPanel = false; //for all bottom navi: dont reload panel
			
			var pageidentifier = jQuery(this).attr("id");
			var firstminus = parseInt(pageidentifier.indexOf('-'));
			firstminus++;
			var hash = pageidentifier.substring(firstminus);
			hash = hash.replace(/^.*#/, '');
			// moves to a new page.
			// pageload is called at once.
			jQuery.history.load(hash);
			
			jQuery(document).scrollTop(0);
			return false;
		});	
	}

}

// --------------------------------------------------------------------- //
// --- Carousel L1 Access functions (prevPage, nextPage, jumpToPage) --- //
// --------------------------------------------------------------------- //

function previousPage() {
	var active = jQuery(".panel-page.active");
	var activeId = jQuery(".panel-page.active").attr("id");
	var thisindex = activeId.substring(4);
	if(thisindex==1) { //carousel: jump backwards to last element
		active.removeClass("active");
		jQuery(".panel-navigation li.selected ul a").removeClass("selected");
		jQuery("#page"+globalAmountPages).addClass("active");
		jQuery("#light"+globalAmountPages).addClass("selected");
		jQuery("#wrapper").css({"margin-left":((-globalNewWrapperWidth)+globalPageWidth)+"px"});
		jQuery("#wrapper").stop().animate({"margin-left":((-globalNewWrapperWidth)+globalPageWidth+globalPageWidth)+"px"},{duration: animatespeedPanel, easing: easingMethod});
		showLevelOne(fadespeedDetails);
	}else{
		jumpToPage(thisindex-1);
	}
}

function nextPage() {
	var active = jQuery(".panel-page.active");
	var activeId = jQuery(".panel-page.active").attr("id");
	var thisindex = parseInt(activeId.substring(4));
	if(thisindex==globalAmountPages) { //carousel: jump forward to first element
		active.removeClass("active");
		jQuery(".panel-navigation li.selected ul a").removeClass("selected");
		jQuery("#light1").addClass("selected");
		jQuery("#page1").addClass("active");
		jQuery("#wrapper").stop().animate({"margin-left":((-globalNewWrapperWidth)+globalPageWidth)+"px"},{duration: animatespeedPanel, easing: easingMethod, complete: function() {
			jQuery("#wrapper").css({"margin-left":"0px"});
		}});
		showLevelOne(fadespeedDetails);
	}else if (thisindex==1) {
		jQuery("#wrapper").stop().css({"margin-left":"0px"}); //this prevents a rolling back from last element if you click too fast
		jumpToPage(thisindex+1);
	}else{
		jumpToPage(thisindex+1);	
	}
}

function jumpToPage(page) { //page can be an index number or the class name of one panel-page

	//checks if page is a name or a number, if it is a name, then find the according number within the id
	var purenumber = String(parseInt(page));
	var noNumber = isNaN(purenumber);
	if (noNumber==true) {
		jQuery(".panel-page").each(function() {
			if (jQuery(this).hasClass(page)) { //if there are several with same class name, only first one is taken.
				page = jQuery(this).attr("id").substring(4);
			}
		});
	}
	
	// move to page
	if (jQuery("#page"+page).length) { //do stuff only if page really exists, in case a not-existing name or number is provided
		jQuery(".panel-page").removeClass("active");
		jQuery("#page"+page).addClass("active");
		jQuery(".panel-navigation li.selected ul a").removeClass("selected");
		jQuery("#light"+page).addClass("selected");
		var newpos = -(page * globalPageWidth) + globalPageWidth;
		jQuery("#wrapper").animate({"margin-left":newpos}, {duration: animatespeedPanel, easing: easingMethod});
		showLevelOne(fadespeedDetails); //fade out details, if necessary
	}
}

// -------------------------------------- //
// --- Loading Panel: Fade In and Out --- //
// -------------------------------------- //

function showLoading() {
	jQuery(".loading").fadeTo(loadingFadeIn,0.65);
}

function hideLoading() {
	jQuery(".loading").fadeTo(loadingFadeIn,0, function() {
		jQuery(".loading").hide();
	}); 
}


// --------------- //
// --- Blinker --- //
// --------------- //

function blink() {
	window.setTimeout(function() {
		jQuery(".page-prev, .page-next").addClass("blinker");
		window.setTimeout(function() {
			jQuery(".page-prev, .page-next").removeClass("blinker");
			window.setTimeout(function() {
				jQuery(".page-prev, .page-next").addClass("blinker");
				window.setTimeout(function() {
					jQuery(".page-prev, .page-next").removeClass("blinker");
					initIdleMover();
				}, blinkPreNext);
			}, blinkPreNext);
		}, blinkPreNext);
	}, 1400);
}

// ------------------------ //
// --- Panel Idle Mover --- //
// ------------------------ //

function initIdleMover() {

	var idleMover = window.setInterval(function() {
		nextPage();
	}, 18000);
	
	jQuery("#panel a, .panel-navigation a, #top a, #logo").bind("click", function() {
		window.clearInterval(idleMover);
	});
	
}

// ------------------- //
// --- CAROUSEL L2 --- //
// ------------------- //

function initCarouselL2() {

	var thisDetails = jQuery(".active .details"); //this is the one we need
	
	/* wider buttons need index to check if current card is on right side. if so, move card to left when wider is clicked */
	var widerindex = 0;
	jQuery(".active .wider").each(function() {
		jQuery(this).attr("id","wider"+widerindex);
		widerindex++;
	});
		
	if(thisDetails.hasClass("initialized")) { //init only if details were not initialized yet, does not have to be done everytime these details are displayed, or do they?
		return;
	}else{
	
		var amountDetailCards = thisDetails.find(".card").length;
		var sliderWrapperWidth = 414 * (amountDetailCards + 1);
		thisDetails.find(".slider-wrapper").css({"width":sliderWrapperWidth+"px"});

		var amountCards = thisDetails.find(".card").length;
		
		if(amountCards>1) {
		
			thisDetails.find(".slider-wrapper").attr("currentpos","1");
			
			thisDetails.find(".card-prev").bind("click", function() {						
				var currentpos =  parseInt(thisDetails.find(".slider-wrapper").attr("currentpos"));
				var newpos = currentpos-1;
				if (newpos==1) {
					var newml = -((newpos-1) * 411);
					thisDetails.find(".slider-wrapper").animate({"margin-left":newml+"px"},{duration: animatespeedPanel, easing: easingMethod});
					thisDetails.find(".slider-wrapper").attr("currentpos",newpos);
					thisDetails.find(".card-right-wrapper").animate({"width":"351px"},{duration: animatespeedPanel, easing: easingMethod});
					thisDetails.find(".wider").removeClass("open");
					thisDetails.find(".card-prev").hide();
					thisDetails.find(".card-next").show();
				}else{
					var newml = -((newpos-1) * 411);
					thisDetails.find(".slider-wrapper").animate({"margin-left":newml+"px"},{duration: animatespeedPanel, easing: easingMethod});
					thisDetails.find(".slider-wrapper").attr("currentpos",newpos);
					thisDetails.find(".card-right-wrapper").animate({"width":"351px"},{duration: animatespeedPanel, easing: easingMethod});
					thisDetails.find(".wider").removeClass("open");
					thisDetails.find(".card-next").show();
				}
				return false;
			});
			
			thisDetails.find(".card-next").bind("click", function() {
			
				var currentpos = parseInt(thisDetails.find(".slider-wrapper").attr("currentpos"));
				var newpos = currentpos+1;
				if (newpos==amountCards) {
					var newml = -((newpos-1) * 411);
					thisDetails.find(".slider-wrapper").animate({"margin-left":newml+"px"},{duration: animatespeedPanel, easing: easingMethod});
					thisDetails.find(".slider-wrapper").attr("currentpos",newpos);
					
					var justopened = thisDetails.find(".wider").hasClass("justopened");
					if(justopened==false) {
						thisDetails.find(".card-right-wrapper").animate({"width":"351px"},{duration: animatespeedPanel, easing: easingMethod});
						thisDetails.find(".wider").removeClass("open");
					}
					thisDetails.find(".wider").removeClass("justopened");
					
					thisDetails.find(".card-next").hide();
					thisDetails.find(".card-prev").show();
					
				}else{
				
					var newml = -((newpos-1) * 411);
					thisDetails.find(".slider-wrapper").animate({"margin-left":newml+"px"},{duration: animatespeedPanel, easing: easingMethod});
					thisDetails.find(".slider-wrapper").attr("currentpos",newpos);
					
					var justopened = thisDetails.find(".wider").hasClass("justopened");
					if(justopened==false) {
						thisDetails.find(".card-right-wrapper").animate({"width":"351px"},{duration: animatespeedPanel, easing: easingMethod});
						thisDetails.find(".wider").removeClass("open");
					
					}
					thisDetails.find(".wider").removeClass("justopened");
					
					thisDetails.find(".card-prev").show();
				}
				return false;
			});
		}else{
		//only one card:
			thisDetails.find(".card-next, .card-prev").hide();
			thisDetails.find(".card-right-wrapper").css({"width":"765px"});
		}
		thisDetails.addClass("initialized");
	}
}

// -------------------------------------------- //
// --- Switching between Teaser and Details --- //
// -------------------------------------------- //

function showLevelOne(ms) {
	jQuery(".level1").customFadeIn({duration: ms, easing: "jswing"});
	jQuery(".level2").customFadeOut({duration: ms, easing: "jswing", complete: function() {
		
		//reset details
		var thisDetails = jQuery(".active .details");
		thisDetails.find(".slider-wrapper").attr("currentpos","1");
		thisDetails.find(".slider-wrapper").css({"margin-left":"0px"});
		var amountCards = thisDetails.find(".card").size();
		thisDetails.find(".wider").removeClass("open");
		thisDetails.find(".card-prev").hide();
		if (amountCards>1) {
			thisDetails.find(".card-next").show();
			thisDetails.find(".card-right-wrapper").css({"width":"351px"});
		}
		
	}});
	jQuery(".page-prev, .page-next").css({"visibility":"visible"}); //fade out buttons: not display:none because this is reserved for wether there is only one or more pages.
	jQuery(".panel-page .background-img").unbind("click");
	
}

function showLevelTwo(ms) { //fade In dependend on active state of panel page
	jQuery(".level2").customFadeIn({duration: ms, easing: "jswing"});
	jQuery(".active .level1").customFadeOut({duration: ms, easing: "jswing"});
	jQuery(".page-prev, .page-next").css({"visibility":"hidden"});
	jQuery(".panel-page .background-img").bind("click", function() { // click on background image: close-details
		showLevelOne(fadespeedDetails);
	});
	initCarouselL2();
}

// ------------------------- //
// --- MACHER - OVERLAYS --- //
// ------------------------- //
	
jQuery(document).ready(function() {
	jQuery(".leader-clickarea").live("click", function() {
		var thisID = jQuery(this).attr("id");
		var nameID = thisID.substring(10);
		jQuery(this).parent().find("#overlay-"+nameID).fadeIn(400);
		return false;
	});
	
	jQuery(".close-leader").live("click", function() {
		jQuery(this).parent().fadeOut(400);
		return false;
	});
});

// -------------------- //
// --- CONTACT FORM --- //
// -------------------- //

jQuery(document).ready(function() {

	// --- CONTACT FORM --- //
	
	var justclicked = 0;
	jQuery("#submit-btn").live("click", function() {
		evalForm();
		return false;
	});  
	
	function evalForm() {
		var index = 1;
		var amountRecs = jQuery(".req").size();
		var allValid = true;
		jQuery(".req").each(function() {
			var that = jQuery(this);
			//validate
			
			var thatValue = jQuery(this).val();
			var thatID = that.attr("id");
			
			if (thatID=="anrede") {
				var standardVal = that.find("option.standard").val();
				if(thatValue==standardVal) {
					allValid = false;
					jQuery(this).parent().find(".error").css({"display":"block"});
				}else{
					jQuery(this).parent().find(".error").hide();
				}
			} else if (thatID=="email") {
				var validateEmail = echeck(thatValue);
				if(validateEmail==true) {
					jQuery(this).parent().find(".error").hide();
				}else{
					allValid = false;
					jQuery(this).parent().find(".error").css({"display":"block"});
				}
			} else if (thatValue=="") {
				allValid = false;
				jQuery(this).parent().find(".error").css({"display":"block"});
			} else{
				jQuery(this).parent().find(".error").hide();
			}

			if (index==amountRecs) {
			
				var extenderheight = jQuery("#extender-content").height();
				jQuery("#extender-content").css({"bottom":"50px"});
				var newheight = parseInt(extenderheight) + (parseInt(jQuery("#extender-content").css("bottom")) * 2);
				
				jQuery("#extender-stage").animate({"height":newheight}, {duration: animatespeedExtender, complete: function() {
					jQuery("#extender-content").css({"bottom":"auto","top":"50px"}); // when opened, relate to top instead of bottom, so that content does not jump when height is changed
				}});
				jQuery("#extendergap").animate({"height":"20px"}, {duration: animatespeedExtender});
			
				if (allValid==true) {
					var anliegen = jQuery("input#anliegen").val();
					var anrede = jQuery("select#anrede").val();  
					var vorname = jQuery("input#vorname").val();
					var name = jQuery("input#name").val();  
					var email = jQuery("input#email").val();  
					var firma = jQuery("input#firma").val();
					if (firma=="") firma="-";
					var tel = jQuery("input#tel").val(); 
					if (tel=="") tel="-";
					var sonstiges = jQuery("textarea#sonstiges").val();
					if (sonstiges=="") sonstiges="-";
		
					var dataString = 'anliegen='+ anliegen + '&anrede='+ anrede + '&vorname='+ vorname + '&name='+ name + '&email=' + email + '&firma=' + firma + '&tel=' + tel + '&sonstiges=' + sonstiges; 
					
					jQuery.ajax({  
						type: "POST",  
						url: "../script/email.php",
						data: dataString,  
						success: function() {  
							jQuery("#contact-form").fadeOut(200);
							jQuery("#confirmation").fadeIn(200);
						}  
					});
					
				}
			}
			index++;
		});
	}
	
	
	function echeck(str) {
	
		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   return false
		}
	
		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr) {
		   return false
		}
	
		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr) {
			return false
		}
	
		 if (str.indexOf(at,(lat+1))!=-1) {
			return false
		 }
	
		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot) {
			return false
		 }
	
		 if (str.indexOf(dot,(lat+2))==-1) {
			return false
		 }
		
		 if (str.indexOf(" ")!=-1){
			return false
		 }
	
		 return true					
	}
});

// ---------------- //
// --- TOOLTIPS --- //
// ---------------- //
	
jQuery(document).ready(function() {
	
	var isiPad = navigator.userAgent.match(/iPad/i) != null;
	var isiPhone = navigator.userAgent.match(/iPhone/i) != null;
	var isiPod = navigator.userAgent.match(/iPod/i) != null;

	if ((isiPad != true) && (isiPhone != true) && (isiPod != true)) {
		if (globalIsIE7 != true) {	
			if (globalIsIE8 != true) {	
			
				jQuery(document).mousemove(function(e) {
				
					var winWidth = jQuery(window).width();
					var mouseX ="";
					var mouseY ="";
					
					var distance = winWidth - e.pageX;
					if (distance < 300) {
						jQuery("#tooltip").addClass("fromright");
						mouseX = distance + 12;
						mouseY = e.pageY + 15 - jQuery(document).scrollTop();
						jQuery("#tooltip").css({left: "auto", right:mouseX, top:mouseY});
					}else{
						jQuery("#tooltip").removeClass("fromright");
						mouseX = e.pageX + 15;
						mouseY = e.pageY + 15 - jQuery(document).scrollTop();
						jQuery("#tooltip").css({right: "auto", left:mouseX, top:mouseY});
					}
				});
				
				var aktiv = "";
				jQuery(".panel-navigation li ul a, .page-prev, .page-next, .show-details, .close-details, .close-extender").live("mouseenter", function() {
					var that = jQuery(this);
					aktiv = window.setTimeout(function() {
						var tooltiptext = jQuery(that).find("span.tooltip").text();
						jQuery("#tooltip").text(tooltiptext);
						jQuery("#tooltip").fadeIn(260);
					},250);
				});
					
				jQuery(".panel-navigation li ul a, .page-prev, .page-next, .show-details, .close-details, .close-extender").live("mouseleave", function() {
					jQuery("#tooltip").fadeOut(240);
					window.clearTimeout(aktiv);
				});
				
				jQuery(".show-details, .close-details, .close-extender").live("click", function() {
					jQuery("#tooltip").fadeOut(240);
					window.clearTimeout(aktiv);
				});
				
			}
		}
	}
});

// -------------------------- //
// --- EXCHANGING TOOLTPS --- //
// -------------------------- //

function initTooltips(ttSelector) {
	if (globalIsIE7 != true) {
	if (globalIsIE8 != true) {
		var thisTitle = jQuery(ttSelector).attr("title");
		if (typeof thisTitle !== 'undefined' && thisTitle !== false) {
			jQuery(ttSelector).removeAttr("title");
			jQuery(ttSelector).append('<span class="tooltip">' + thisTitle + '</span>');
		}
	}
	}
}


// -------------------------------------------- //
// --- Removing hrefs from panel navigation --- //
// -------------------------------------------- //

jQuery(document).ready(function() {
	jQuery(".panel-navigation > li > a").attr("href","#");
});


// ---------------------- //
// --- STARTANIMATION --- //
// ---------------------- //

var faderLetters = 100;

if (jQuery.browser.msie && jQuery.browser.version.substr(0, 1) <= 8) {
	faderLetters = 0;
}
jQuery(document).ready(function() {

	jQuery(".textblock").each(function() {
	
		var defaultWidth = jQuery(this).find(".default img").attr("width");
		var defaultHeight = jQuery(this).find(".default img").attr("height");
		var hoverWidth = jQuery(this).find(".hover img").attr("width");
		var hoverHeight = jQuery(this).find(".hover img").attr("height");
		var originalColor = jQuery(this).css("background-color");
		
		jQuery(this).attr("save-width",defaultWidth);
		jQuery(this).attr("save-height",defaultHeight);
		jQuery(this).attr("save-color",originalColor);
		
		jQuery(this).find(".hover").css({
			"visibility":"visible",
			"display":"none"
		});
		
		var that = jQuery(this);
		
		var isiPad = navigator.userAgent.match(/iPad/i) != null;
		var isiPhone = navigator.userAgent.match(/iPhone/i) != null;
		var isiPod = navigator.userAgent.match(/iPod/i) != null;

		if ((isiPad==true) || (isiPhone==true) || (isiPod==true)) {	
		
			that.bind("touchstart", function() {
			
				var unhoverobj = jQuery(".touched");
				if (unhoverobj.length > 0) {
					var oldwidth = unhoverobj.attr("save-width");
					var oldheight = unhoverobj.attr("save-height");
					var oldcolor = unhoverobj.attr("save-color");
					unhoverobj.find(".default").fadeIn(faderLetters);
					unhoverobj.find(".hover").fadeOut(faderLetters);
					unhoverobj.animate({
						backgroundColor: oldcolor,
						width: oldwidth + "px",
						height: oldheight + "px"
					});
					unhoverobj.removeClass("touched");
				}

				that.animate({
					width: hoverWidth + "px",
					backgroundColor: "#e86e0a",
					height: hoverHeight + "px"
				}, 200, function() {
					that.addClass("touched");
				});
				that.find(".hover").fadeIn(faderLetters);
				that.find(".default").fadeOut(faderLetters);
				
				
				/* Move Cloud */
				
				var parentID = that.parent().attr("id");
				var cloudbuster = 50;
				
				if (parentID=="cell1") cloudbuster = 53;
				if (parentID=="cell2") cloudbuster = 43;
				if (parentID=="cell4") cloudbuster = 50;
				if (parentID=="cell6") cloudbuster = 43;
				if (parentID=="cell7") cloudbuster = 53;
				if (parentID=="cell8") cloudbuster = 43;
				
				jQuery(".cloud").stop().animate({
					"left":cloudbuster + "%",
					"top":"47%"
				}, 200);
			});	
			
		}else{
		
			that.bind("mouseenter", function() {
				that.stop().animate({
					width: hoverWidth + "px",
					backgroundColor: "#e86e0a",
					height: hoverHeight + "px"
				}, 200);
				
				that.find(".hover").fadeIn(faderLetters);
				that.find(".default").fadeOut(faderLetters);
				
				var parentID = that.parent().attr("id");
				var cloudbuster = 50;
				
				if (parentID=="cell1") cloudbuster = 53;
				if (parentID=="cell2") cloudbuster = 43;
				if (parentID=="cell4") cloudbuster = 50;
				if (parentID=="cell6") cloudbuster = 43;
				if (parentID=="cell7") cloudbuster = 53;
				if (parentID=="cell8") cloudbuster = 43;
				
				jQuery(".cloud").stop().animate({
					"left":cloudbuster + "%",
					"top":"47%"
				}, 200);	
			});	
			
			that.bind("mouseleave", function() {
				that.stop().animate({
					backgroundColor: originalColor,
					width: defaultWidth + "px",
					height: defaultHeight + "px"
				}, 200);
				
				that.find(".default").fadeIn(faderLetters);
				that.find(".hover").fadeOut(faderLetters);
				
				jQuery(".cloud").stop().animate({
					"left":"50%",
					"top":"50%"
				}, 200);
			});	
		}
		
	});
});


