/* common scripts */

// color animation
// color vars
var prof = "#babbbf";
var free = "#424240";
var meta = "#ada9a3";

// infobox width // 1px fix
var infow = "339px"; 

// image
var imgPos = 0;
var imgArray = new Array();

// slideshow
var curImg = 0;

// loader
var loader = false;
var delay = 0;

// lang change
var newHash = true;

$(document).ready(function(){
	
	// get hash
	var hash = window.location.hash; 

	// redirect to start
	redirect(hash);	
	
    // load different content on pageload
    //or trigger start-slideshow      
    if(hash) {
    
    	url = hash.split('~');    	
    	theHref = "index.php?article_"+url[1];
    	colorScheme = url[3].replace("topic=","");	
    	loadContent(theHref,colorScheme);    	
 	    $("#wrapper").stop().fadeIn(800,"easeInOutQuad");
    
    } else {   // start-page?
   	
   		// get images, preload and shuffle
    	for(i=0;i<$(".imgArray a").length;i++) {
    	    imgArray[i] = $(".imgArray a").eq(i).attr("href");
    	}
		preload(imgArray);   		
   		imgArray.shuffle();	
   		
	    slideShowId = setInterval("slideShow()", 4500);
	    
	    $("#info").css({top:"-3000px"});
	    $("#navi").css({display: "none"});
	    
	    // get navi and info on startup
	    $("#content").css({cursor:"pointer"}).click(function() {
	    	$("#navi").css({display: "block"});
	    	$("#navilink").css({display: "none"});
	    	$("#info").css({display: "none",top:"0"}).fadeTo(800,1);
	    	naviIn();
	    	$('#content').css({cursor:"default"}).unbind('click');
	    });   
	
		// check for first image to load and blend in site
		start();
		 
    }
        
	// load content on hash-change also
	$(window).bind('hashchange', function(){
		if(newHash == true) {
			hash = window.location.hash;
			if(!hash) {
				hash = "~id=1~lang=0~topic=home";
			}	
    		url = hash.split('~');    	
    		theHref = "index.php?article_"+url[1];
    		colorScheme = url[3].replace("topic=","");    	
    		loadContent(theHref,colorScheme);    	
    	} else {
    		newHash = true;
    	}
	});	
	
	// resize frame
	adjustSize($("#frame"),1);	

	// resize on resize
	$(window).resize(function() {
		adjustSize($("#frame"),200);
	});  		
	
	// arrowclick
	$('#arrowL a,#arrowR a').click(function(){    
    	nextImage($(this),imgArray);
    	return false;
    });		
	
	// hovers and ajax
	init();
	
});

// slideshow
function slideShow() {
	
    $("#image img:last").attr("id","firstImg");
	
	if(curImg < ($(".imgArray a").length - 1)) {
		curImg++;
	} else {
		curImg = 0;
	}
	
	var theImgSrc = imgArray[curImg].split('~');	
	$("#firstImg").clone().attr("id","secImg").prependTo("#image").attr("src",theImgSrc[0]).attr("class",theImgSrc[2]);
	$("#firstImg").fadeTo(800,0,"easeInOutQuad");
	window.setTimeout(function() {
		$("#firstImg").remove();
	}, 2200);
	
}

// check for first image to load
function start() {
	var theImgSrc = imgArray[0].split('~');
	$("#image img").attr("src",theImgSrc[0]).attr("class",theImgSrc[2]);
	var img = new Image(); 				
 	$(img).load(function () {
 	    $(this).hide();
 	    $("#frame").show();
 	    $("#wrapper").fadeIn(800,"easeInOutQuad");
 	    hideLoader();
 	    clearInterval(loadDel);
 	})
 	.attr("src", theImgSrc[0]);
 	// blend in Loader after 1,5 sec	
 	loadDel = setInterval(function() {
		if(delay == 1) { 
			showLoader();
		}
		delay++;
	}, 150);
}

// intiate hovers and ajax
function init() {
	// hover navi
	$("#navi").hover(
		function() {
			naviIn();
		},
		function() {
			naviOut();
		}
	);
		
	// hover info
	$("#info").hover(
		function() {
			infoIn();
		},
		function() {
			infoOut();
		}
	);
	
	// navi-rollover 
	$("#free,#prof,#meta").hover(
		function() {
			subnaviIn($(this));
		},
		function() {
			if($("body").hasClass("meta")) {
				subnaviOut($(this));
			}
		}
	);
	
	// ipad gestures
	$("#content").touchwipe({
	     wipeLeft: function() {
	     	if(($("body").hasClass("prof") || $("body").hasClass("free")) && !$("body").hasClass("building")) {
	     		nextImage($("#imagelink"),imgArray);
	     	}
	     },
	     wipeRight: function() {
	     	if(($("body").hasClass("prof") || $("body").hasClass("free")) && !$("body").hasClass("building")) {
	     		nextImage($("#arrowL a"),imgArray);
	     	}
	     },
	     min_move_x: 20,
	     min_move_y: 20,
	     preventDefaultEvents: true
	});
    
    // load meta Content on click
    $('ul#meta li a').click(function(){    
    	loadIt($(this).attr('href'),"meta");
    	setActive($(this));
    	return false;      	  
    });     
    
    // load work Content on click
    $('ul.works ul ul a').click(function(){  
    	var colorScheme = $(this).parents("ul.works").attr("id");  
    	loadIt($(this).attr('href'),colorScheme);
    	setActive($(this));
    	$("#logo").stop().fadeTo(200,1);
    	return false;      	  
    }); 
	
	// subnavi
	$("ul#free a.topics").click(function() {
		return false;
	});	
	$("ul#free a.topics").mouseover(function() {
		toggleSub($(this));		
	});	
	$("ul#prof a.topics").click(function() {
		toggleSub($(this));
		return false;
	});	
	
	// thumb- and imageclick
	$('#thumbs a,#imagelink').click(function(){
		// imagenavigation
    	nextImage($(this),imgArray);
    	return false;
    });
    
    $('#imagelink').click(function(){
		// ipad enabling
		infoOut();
		naviOut();
    });
}

// preload images
function preload(imgArray) {
	imgPos = 0;
	for (i=0;i<imgArray.length;i++) {
		var theSrc = imgArray[i].split('~');
		var img = new Image(); 				
 		$(img).load(function () {
 			$(this).hide();		   
 		})
 		.attr("src", theSrc[0]);		
	}
}

// mix array randomly
function arrayShuffle(){
  var tmp, rand;
  for(var i =0; i < this.length; i++){
    rand = Math.floor(Math.random() * this.length);
    tmp = this[i]; 
    this[i] = this[rand]; 
    this[rand] =tmp;
  }
}
Array.prototype.shuffle = arrayShuffle;

// next image
function nextImage(theLink,imgArray) {
	
	// arrows for images or for text?
	if($("body").hasClass("meta")) { 
		var theBox = $("#infobox .active");
		var activeBox = theBox.find(".textBlocks").not(".hidden");
		var nextID = theBox.find(".textBlocks").index(activeBox)+1;
		if(theLink.parent().attr("id") == "arrowR") {
			if (activeBox.next(".textBlocks").length) {
				var nextBox = activeBox.next();
				nextID++;
				var nextPag = theBox.find(".page"+nextID);
			} else {
				var nextBox = theBox.find(".textBlocks:first");
				var nextPag = theBox.find(".page1");
			}        		
		} else {
			if (activeBox.prev(".textBlocks").length) {
				var nextBox = activeBox.prev();
				nextID--;
				var nextPag = theBox.find(".page"+nextID);
			} else {
				var nextBox = theBox.find(".textBlocks:last");
				var nextPag = theBox.find(".page:last");
			}  
		}
		
		theBox.find(".page").removeClass("active");
		nextPag.addClass("active");	
		activeBox.slideUp(300, function(){
			activeBox.addClass("hidden");
			nextBox.slideDown(300).removeClass("hidden");
		});
		
	} else {
		if(theLink.parent().attr("id") == "arrowL") {
			aDir = "back";
		} else {
			aDir = "next";
		}
		// thumb or arrow?
		if(theLink.parent().parent().attr("id") == "arrows" || theLink.attr("id") == "imagelink" ) {
			tDir = "arrow";
		} else {
			tDir = theLink.index();
			if(tDir<imgPos) {
				aDir = "back";
			}
		}	
		buildFrame(imgArray,aDir,tDir);
	}
}

// duplicate frame and insert new image
function buildFrame(imgArray,aDir,tDir) {
	$("body").addClass("building");
	// clicking the same thumb?
	if(imgPos != tDir) {
		// clone frame		
		$("#frame").clone().attr("id","imgFrame").insertAfter("#logo").hide();
		// prevent wrong image to show
		$("#imgFrame .image img").hide();
				
		// get right image
		if(tDir == "arrow") {
			if(aDir == "next") {		
				if(imgPos < imgArray.length-1) {
					imgPos = imgPos+1;
				} else {
					imgPos = 0;
				}		
			} else {
				if(imgPos == "0") {
					imgPos = imgArray.length-1;
				} else {
					imgPos = imgPos-1;
				}		
			}
		} else {
			imgPos = tDir;					
		}
		
		var theSrc = imgArray[imgPos].split('~');
		$("#imgFrame .image img").attr("src", theSrc[0]).attr("alt", theSrc[1]).attr("class", theSrc[2]).show();
		
		//animate Frames
		imgAni(aDir,imgPos);
	}
}

//animate Frames
function imgAni(aDir,imgPos) {

	// blend in logo
	$("#logo").css({width: "340px"});

	// get widths
    var winWn = $(window).width();
    
    // prepare body
    $('#arrows').stop().hide();
    
    // prepare and animate
	if (aDir == "next") {
    	var newleft = "-"+winWn+"px";
    	var startleft = winWn+"px";
    	
    } else {
    	var newleft = winWn+"px";
    	var startleft = "-"+winWn+"px";    
    }
    	
    $("#frame").stop().animate({left: newleft},400, function(){
        $(this).empty().remove();
        $('#arrows').fadeTo(600,1); 
		$('#thumbs a').removeClass("active");
		$('#thumbs a').eq(imgPos).addClass("active");	
		$("body").removeClass("building");
        init();
    });
    adjustSize($("#imgFrame"),1);
    checkText($("#imgFrame"),imgPos);
    window.setTimeout(function() {
    	$("#imgFrame").css({left: startleft}).show().animate({left: "0"},1000,"easeOutExpo",function(){   
        	if($("body").hasClass("free") || $("body").hasClass("prof")) {
				$("#logo").css({width: "0px"});
			}
    	}).attr("id","frame");  
    },100);
    		
}

// check for pagina and language
function checkText(obj,imgN) {
	
	// show right text for right image
	obj.find(".infobox").find(".textBox").addClass("hidden");
	var textBox = ".num"+(imgN+1);
	obj.find(".infobox").find(textBox).removeClass("hidden");
	obj.find(".infobox").find(".numAll").removeClass("hidden");
	// only show texts if available
	if(obj.find(".infobox").find(textBox).find(".pagina").prev().length == 0 && obj.find(".infobox").find(textBox).find(".pagina").length) {
		$("#info").css({display: "none"});
	} else {
		$("#info").css({display: "block"});	
	}
	
	// check language
	var lang = window.location.hash.split('~');
	if(lang[2] == "lang=1" && $("#en").length > 0) {
		$("#en").show().addClass("active");
		$("#de").hide().removeClass("active");
		$(".enmore,.lang .de").removeClass("hidden");
		$(".demore,.lang .en").addClass("hidden");			
	}
	
	// language links
	if($("#en").length > 0) {
		$(".lang").removeClass("hidden");
	}
	$(".lang span").click(function() {
		changeLang($(this));
	});

	// pagination
	obj.find(".page").click(function(){
		pagiNate($(this));
	});	
	
}

// pagination
function pagiNate(el) {
	if(!el.hasClass("active")) {
		var paRent = el.parent(".pagina");
		var blockId = el.html();
		$(paRent).children(".page").removeClass("active");
		el.addClass("active");	
		paRent.parent(".bigText").children(".textBlocks").not(".hidden").slideUp(300, function(){
			paRent.parent(".bigText").children(".textBlocks").addClass("hidden");
			paRent.parent(".bigText").children(".block"+blockId).slideDown(300).removeClass("hidden");
		});
	}
}	

// change language
function changeLang(obj) {
	hash = window.location.hash;
	if(obj.hasClass("de")) {		
		hash = hash.replace("lang=1","lang=0");
		$("#en").removeClass("active").slideUp(300, function(){
			$("#de").slideDown(300).addClass("active");		
		});
		$(".demore,.lang .en").removeClass("hidden");	
		$(".enmore,.lang .de").addClass("hidden");
	} else {
		hash = hash.replace("lang=0","lang=1");
		$("#de").removeClass("active").slideUp(300, function(){
			$("#en").slideDown(300).addClass("active");
		});
		$(".enmore,.lang .de").removeClass("hidden");
		$(".demore,.lang .en").addClass("hidden");
	}
	newHash = false;
	window.location.hash = hash;
}

// more Text
function moreText(obj) {

	// which language?
	if(obj.parent().hasClass("demore")) {
		var langInfo = $("#de");
	} else {
		var langInfo = $("#en");
	}
	
	// read on
	if (obj.index()==0) {
		obj.addClass("hidden");
		obj.next().removeClass("hidden");
		if(langInfo.children("div").length > 2) {
			obj.next().next().removeClass("hidden");
		}
		langInfo.children("div.shown")
			.slideUp(300).removeClass("shown")
			.next().slideDown(300).addClass("shown");
	// back
	} else if (obj.index()==1) {
		if(langInfo.children("div.shown").index() == 1) {
			obj.addClass("hidden");
			obj.next().addClass("hidden");	
			obj.prev().removeClass("hidden");		
		} else {
			obj.next().removeClass("hidden");
		}
		langInfo.children("div.shown")
			.slideUp(300).removeClass("shown")
			.prev().slideDown(300).addClass("shown");
	// next
	} else if (obj.index()==2) {
		if(langInfo.children("div.shown").index() == langInfo.children("div").length-2) {
			obj.addClass("hidden");
		}
		langInfo.children("div.shown")
			.slideUp(300).removeClass("shown")
			.next().slideDown(300).addClass("shown");		
	}
	// alert(obj.index());
}


// resize function
function adjustSize(obj,speed) {

	// minimal frame:  580x754px margin: 15px 90px 30px 40px ratio: 1.3
	// minimal window: 625x980px
	// imageheight: 638x840px (standardsize) ratio: 1.317
	
	// get height and width of window
	var winW = $(window).width();
	var winH = $(window).height();
	
	// min size: 980/625px -> ratio: 1.568
	var ratio = winW/winH;	
	
	// frame-sizing depending on minimal window (ratio)
	if (ratio > 1.568) {
		var frameheight = parseInt(((winH-580)*0.2)+580); // mind. height	
	} else {
		var frameheight = parseInt((((winW/1.568)-580)*0.2)+580);
	}
	
	// getting width by ratio of frame
	var framewidth = frameheight*1.3;
	
	// positioning frame
	var marginleft = parseInt((((winW-framewidth)*0.1)+40));
	var margintop = parseInt(((winH-frameheight)*0.45));
	
	// positioning arrows
	var arrowl = parseInt((marginleft*0.6)-30);
	var arrowr = parseInt((marginleft*0.6)-20);	
	var arrowt = parseInt(margintop+((frameheight-580)*0.45));	
	
	// resizing and positioning content
	var imgS = obj.children("#image").children("img").attr("class");
	if (!imgS) {
		imgS = "w850_h638";
	}	
	var imgS = imgS.split('_');	
	var imgw = imgS[0].substr(1);
	var imgh = imgS[1].substr(1);
	var imgratio = imgw/imgh;
		
	// minimal size
	if (winH < 625 || winW < 980) {
		frameheight = "580";
		framewidth = "754";
		arrowt = "30";
	}
	// positioning minimal size
	if (winH < 625) {
		margintop = "15";
	}	
	if (winW < 980) {
		marginleft = "40";
		arrowl = "0";
		arrowr = "0";
		var wrapperwidth = "980";
	} else {
		var wrapperwidth = winW;
	}
	
	var wrapperheight = parseInt(margintop)+parseInt(frameheight)+10; // 10px margin at bottom
	
	// sizing images and info-position
	// checking for hochformat
	if (imgratio > 1.316) { 
		var contentw = parseInt(((frameheight-30)*imgratio)+30);
	} else {
		var contentw = framewidth;
	}	
	
	framewidth = contentw;
	
	var infow = contentw - 415; // Infowrapper width
	var infob = contentw - 730;	// Infobox position (705 = boxposition+margin+width#infobox + 15px border )		
	var imgheight = frameheight-30; // remove padding
	
		
	// animating elements
	if (speed==1) { // speed == 1 -> no-resize-animation
	
		obj.css({
			marginTop: margintop+"px",
			marginLeft: marginleft+"px",
			height: frameheight+"px",
			width: framewidth+"px",
			overflow: "visible",
			display: "none"
		});	
				
		obj.children(".image").children("img").css({
			height: imgheight+"px"
		});
		
		$("#arrowL").css({
			top: arrowt+"px",
			left: arrowl+"px"
		});
		
		$("#arrowR").css({
			top: arrowt+"px",
			right: arrowr+"px"
		});
		
		$("#logo").css({
			left: marginleft+"px",
			top: arrowt+"px"
		});	
		
		$("#wrapper").css({
			width: wrapperwidth+"px",
			height: wrapperheight+"px"
		});
	
		obj.find(".info").css({
			width: infow+"px"
		});		
		
		obj.children(".content").css({
			height: frameheight+"px",
			width: contentw+"px",
			overflow: "visible"
		});		
		
	} else {
	
		obj.stop().animate({
			marginTop: margintop+"px",
			marginLeft: marginleft+"px",
			height: frameheight+"px",
			width: framewidth+"px"
		}, speed).css({overflow: "visible"});	
	
		obj.children(".image").children("img").stop().animate({
			height: imgheight+"px"
		}, speed);
		
		$("#arrowL").hide().css({
			top: arrowt+"px",
			left: arrowl+"px"
		}).fadeIn(speed);
		
		$("#arrowR").hide().css({
			top: arrowt+"px",
			right: arrowr+"px"
		}).fadeIn(speed);
		
		$("#logo").hide().css({
			left: marginleft+"px",
			top: arrowt+"px"
		}).fadeIn(speed);
		
		$("#wrapper").stop().animate({
			width: wrapperwidth+"px",
			height: wrapperheight+"px"
		}, speed);
	
		obj.find(".info").stop().animate({
			width: infow+"px"
		}, speed);		
		
		obj.children(".content").stop().animate({
			height: frameheight+"px",
			width: contentw+"px",
			overflow: "visible"
		}, speed, function(){
			$("body").css({overflow:"auto"});
		});	
		
		$("body").css({overflow:"hidden"});
		
	}
	
	$("#naviwrapper").css({
		height: frameheight+"px"
	});	
	
	$("#infowrapper").css({
		height: frameheight+"px"
	});
	
	obj.find(".infobox").css({
		right: infob+"px"
	});	
	
}

// hover navi 
function naviIn() {
	// ipad enabling
	infoOut();
	$("#naviwrapper").stop().animate({width: "495px"},600, "easeOutExpo");
	$("#menu").stop().fadeTo(600, 1);
	// replacing navilink
	$("#navilink").stop().fadeTo(300,0);
}

function naviOut() {
	$("#naviwrapper").stop().animate({width: "0px"},600, "easeOutExpo");
	$("#menu").stop().fadeTo(600, 0);
	$("#navilink").stop().fadeTo(1000, 0.7);
}

// hover info 
function infoIn() {
	// ipad enabling
	naviOut();
	$("#infowrapper").stop().animate({width: "100%"},600, "easeOutExpo");
	$("#infobox").stop().fadeTo(600, 1);
	$("#infolink").stop().fadeTo(300,0);
}

function infoOut() {
	$("#infowrapper").stop().animate({width: "0px"},600, "easeOutExpo");
	$("#infobox").stop().fadeTo(600, 0);
	$("#infolink").stop().fadeTo(1000, 0.7);
}

// hover subnavi
function subnaviIn(obj) {
	obj.children("li").children("ul").stop().fadeTo(200,1);
	$("ul#menu li ul").not(obj).not("ul#menu li ul li ul").not("ul#menu li ul li ul li ul").children("li").children("ul").stop().fadeTo(200,0);
	if($("body").hasClass("meta") && (obj.attr("id") == "free" || obj.attr("id") == "prof")) {
		$("#logo").stop().fadeTo(300,0.2);
	}
}

function subnaviOut(obj) {
	obj.children("li").children("ul").stop().fadeTo(200,0);
	if($("body").hasClass("meta")) {
		$("#logo").stop().fadeTo(500,1);
	}
}

function toggleSub(obj) {
	obj.parent("li").parent("ul")
		.children("li").children("a.topics")
		.not(obj).parent("li").removeClass("opened").children("ul").slideUp(200);
	if(obj.parent("li").hasClass("opened")) {
		obj.parent("li").children("ul").slideUp(200);
		obj.parent("li").removeClass("opened");
	} else {
		obj.parent("li").children("ul").slideDown(200);
		obj.parent("li").addClass("opened");
	}
}

// color animation

function changeColor(colorScheme,speed) {
	if (colorScheme == "free") {
		newColor = free;
	} else if (colorScheme == "meta") {
		newColor = meta;
	} else {
		newColor = prof;
	}
	$("body").stop().animate({backgroundColor: newColor},speed).removeClass("home free prof meta").addClass(colorScheme);
}

