jQuery.fn.reverse = [].reverse;

// redaxo url
var url;
// current object
var path;
// name and path of breadcrumb item (array)
var breadcrumb;
// json object
var data = {contents:[0]};
// redaxo language
var lang = 0;
// article id to be loaded
var newId;
// positions of content containers
var xpos;
// project open true false;
var prop = false;
// count of loaded background images
var backid = 3;
// is loading
var active = false;
// first run
var kickoff = true;
// flash plugin
var flashloaded = false;
// loading text animation
var loadingtext = "Loading...";
var mixobj;
var from = 0;
var to = 0;
var ctrl = 0;
var l = 0;
var str1 = "";
var str2 = "";
var str3 = "";
var textindex = 0;
var loadanimation = false;

/* ########### CONTENT ########### */ 

function load_content()
{
	//console.log("loadContent");
	//console.log(id[0],id[1]);
	
	loadanimation = true;
	loading_text();
	
	$.ajax({
		dataType: 'json',
		success: function (dt){
			//console.log(dt);
			data = dt;
			document.title = "Julia Lein - "+data.name;
			load_backgroundimage();
		},
		url: 'index.php?article_id='+newId[0]+'&json=1'
	});
	
}

function build_teaser()
{
	if(data.contents.length>0)
	{
		xpos = [0];
		show_content(0,1);
	}
	else set_inactive();
};

function build_teaserimage()
{
	if(data.contents.length>1) show_content(1,2);
}

function show_content(s,l)
{
	for(i=s; i<l; i++)
	{
		switch(data.contents[i]['type'])
		{
			case "text":
				
				var below = '<div class="content contentsize" style="left:'+xpos[i]+'px;"></div>';
				var beneath = '<div class="control controlsize" style="left:'+xpos[i]+'px;">'+data.contents[i]['content']['text']+'</div>';
				if(i < 1)
				{
					$('#belowtitle').append(below);
					$('#beneathtitledescription').append(beneath);
					$('#beneathtitlemenu').html(data.contents[i]['content']['link']);
					
					$('#belowtitle').height(0);
					$('#beneathtitle').height(0);
					$('#belowtitle').delay(200).animate({height:440},{queue:true, duration:500, easing:"cubicEaseOut"});
					$('#beneathtitle').delay(200).animate({height:440},{queue:true, duration:500, easing:"cubicEaseOut", complete:build_teaserimage});
					xpos.push(xpos[i]);
				}
				else
				{
					$('#belowcontentcontainer').append(below);
					$('#beneathcontentcontainer').append(beneath);
					if(i == 1)
					{
						$('#belowcontent').height(0);
						$('#beneathcontent').height(0);
						$('#belowcontent').animate({height:440},{queue:true, duration:500, easing:"cubicEaseOut"});
						$('#beneathcontent').animate({height:440},{queue:true, duration:500, easing:"cubicEaseOut", complete:set_inactive});
					}
					xpos.push(xpos[i]+330);
				}
				break;
			case "image":
				var imgwidth = parseInt(data.contents[i]['content']['width']);
				var imgheight = parseInt(data.contents[i]['content']['height']);
				var below = '<div class="content" style="position:absolute;left:'+xpos[i]+'px;width:'+imgwidth+'px;height:'+imgheight+'px;" id="image'+i+'"></div>';
				$('#belowcontentcontainer').append(below);
				var beneath = '<div class="control" style="position:absolute;left:'+xpos[i]+'px;width:'+imgwidth+'px;height:'+imgheight+'px;" id="loading'+i+'"><span class="loadingtext">&nbsp;loading...&nbsp;</span></div>';
				$('#beneathcontentcontainer').append(beneath);
				
				var $thumbdiv = $('<div class="thumbnail"></div>');
				var $thumb = $(new Image()).attr({src: 'index.php?rex_resize=50c__50h__'+data.contents[i]['content']['image'], id: "thumb"+i, name: "image"+i}).appendTo($thumbdiv);
				$('#beneathtitleimages').append($thumbdiv);
				$thumbdiv.bind('click',project_thumbnail_click);
				var $img = $(new Image()).attr({src: 'files/'+data.contents[i]['content']['image']+no_cache(), id: "image"+i, name: "loading"+i}).appendTo($('#image'+i));
				$img.load(function()
				{
					set_inactive();
					$('#'+$(this).attr("name")).empty();
				});
				if(i == 1 && data.contents.length>2)
				{
					$('#loading'+i).bind("mouseover", project_over);
					$('#loading'+i).bind("mouseout",project_out);
					$('#loading'+i).bind("click", open_project);
				}
				xpos.push(xpos[i]+imgwidth+10);
				break;
			case "video":
				var video1 = data.contents[i]['content']['video1'];
				var video2 = data.contents[i]['content']['video2'];
				var video3 = data.contents[i]['content']['video3'];
				var poster = data.contents[i]['content']['image'];
				var vidwidth = parseInt(data.contents[i]['content']['width']);
				var vidheight = parseInt(data.contents[i]['content']['height']);
				
				var $thumbdiv = $('<div class="thumbnail"></div>');
				var $thumb = $(new Image()).attr({src: 'index.php?rex_resize=50c__50h__'+poster, id: "thumb"+i, name: "image"+i}).appendTo($thumbdiv);
				$('#beneathtitleimages').append($thumbdiv);
				$thumbdiv.bind('click',project_thumbnail_click);
				
				var below = '<div class="content" style="position:absolute;left:'+xpos[i]+'px;width:'+vidwidth+'px;height:'+vidheight+'px;" id="image'+i+'"></div>';
				$('#belowcontentcontainer').append(below);
				
				var beneath = '<div class="control video-js-box vim-css" style="position:absolute;left:'+xpos[i]+'px;width:'+vidwidth+'px;height:'+vidheight+'px;" id="video'+i+'"></div>';
				$('#beneathcontentcontainer').append(beneath);
				
				var video = '<video class="video-js" width="'+vidwidth+'" height="'+vidheight+'" controls="controls" poster="files/'+poster+'" preload="none"><source src="files/'+video1+'" type="video/mp4" /><source src="files/'+video2+'" type="video/ogg" /><source src="files/'+video3+'" type="video/webm" /><object width="'+vidwidth+'" height="'+vidheight+'" type="application/x-shockwave-flash" data="swf/flashmediaelement.swf"><param name="movie" value="swf/flashmediaelement.swf" /><param name="flashvars" value="controls=true&amp;file=../files/'+video1+'" /></object></video>';
				$('#video'+i).append(video);
				
				xpos.push(xpos[i]+vidwidth+10);
				break;
		}
	}
	VideoJS.setupAllWhenReady();
}

function clear_content()
{
	$('.content').each(function(){
		$(this).remove();
	});
	$('.control').each(function(){
		$(this).remove();
	});
	$('#beneathtitlemenu').empty();
	$('#beneathtitleimages').empty();
}

/* ########### BACKGROUND ########### */ 

function load_backgroundimage()
{
	if(data.background != '')
	{
		var bgarray = data.background.split(",");
		stop_loading();

		$div = $('<div class="bgpic" style="z-index:'+backid+'"></div>');
		$div.css({opacity:0});

		$('#bg').append($div);
		var $img = $(new Image()).attr({src: 'files/'+bgarray[0]+no_cache(), id: "bg"+backid}).appendTo($div);
		backid++;

		$img.load(function()
		{
			loadanimation = false;
			resize_window();
			$(this).parent().animate({opacity:1},{queue:true, duration:500, easing:"cubicEaseOut", complete:clear_background});
		});
	}
	else
	{
		stop_loading();
		loadanimation = false;
		build_teaser();
	}
}

function clear_background()
{
	for (var i=$('#bg').children.length-2; i >= 0; i--)
	{
		$('#bg div:eq('+i+')').remove();
	}
	build_teaser();
}

/* ########### PROJECT ########### */ 

function project_over()
{
	$(this).html('<span class="loadingtext">&nbsp;Click to open...&nbsp;</span>');
}

function project_out()
{
	$(this).empty();
}

function open_project()
{
	prop = true;
	
	$('#loading1').unbind("mouseover", project_over);
	$('#loading1').unbind("mouseout", project_out);
	$('#loading1').unbind("click", open_project);
	$('#loading1').empty();
	
	$('#beneathtitlemenu').html('<span class="markedtext"><a href="javascript:project_images();">&nbsp;Images&nbsp;</a></span>');
	
	close_navigation(true);
	
	$('#beneath').animate({left: 80}, {queue:true, duration:300, easing:"cubicEaseOut"});
	$('#below').animate({left: 80}, {queue:true, duration:300, easing:"cubicEaseOut", complete:show_project});
}

function show_project()
{
	show_content(2,data.contents.length);
	resize_window();
	$('#scrollbar').show();
	$('#arrow').animate({width: "toggle"}, {queue:true, duration:300, easing:"cubicEaseOut"});
}

function close_project()
{
	prop = false;
	
	var w = Math.floor($(window).width());
	
	$('#scrollbar').hide();
	$('#scrollbar').css("left", "80px");
	
	for (var i=$('.content').length-1; i > 1; i--) {
		$('.content:eq('+i+')').remove();
		$('.control:eq('+i+')').remove();
	}
	
	$('#loading1').bind("mouseover", project_over);
	$('#loading1').bind("mouseout", project_out);
	$('#loading1').bind("click", open_project);
	
	$('#arrow').animate({width: "toggle"}, {queue:true, duration:300, easing:"cubicEaseOut"});
	
	$('#beneath').animate({left: w/2-165}, {queue:true, duration:300, easing:"cubicEaseOut"});
	$('#below').animate({left: w/2-165}, {queue:true, duration:300, easing:"cubicEaseOut"});
	
	$("#belowcontentcontainer").stop().animate({left: 0}, {queue:false, duration:500, easing:"cubicEaseOut"});
	$("#beneathcontentcontainer").stop().animate({left: 0}, {queue:false, duration:500, easing:"cubicEaseOut", complete:project_open_link});
	
	$('#navigation').show();
	$('#navigation ul li:first').animate({width: "toggle"}, {queue:true, duration:200, easing:"cubicEaseOut", complete:open_navigation});
}

function project_open_link()
{
	resize_window();
	
	for (var i=$('#beneathtitleimages').children().length-1; i >0; i--) {
		$('#beneathtitleimages div:eq('+i+')').remove();
	};
	
	$('#beneathtitlemenu').html(data.contents[0]['content']['link']);
	$('#beneathtitledescription').animate({left: 0}, {queue:true, duration:300, easing:"cubicEaseOut"});
	$('#beneathtitleimages').animate({left: 320}, {queue:true, duration:300, easing:"cubicEaseOut"});
}

function project_images()
{
	$('#beneathtitledescription').animate({left: -320}, {queue:true, duration:300, easing:"cubicEaseOut"});
	$('#beneathtitleimages').animate({left: 0}, {queue:true, duration:300, easing:"cubicEaseOut"});
	$('#beneathtitlemenu').html('<span class="markedtext"><a href="javascript:project_description();">&nbsp;Description&nbsp;</a></span>');
}

function project_description()
{
	$('#beneathtitledescription').animate({left: 0}, {queue:true, duration:300, easing:"cubicEaseOut"});
	$('#beneathtitleimages').animate({left: 320}, {queue:true, duration:300, easing:"cubicEaseOut"});
	$('#beneathtitlemenu').html('<span class="markedtext"><a href="javascript:project_images();">&nbsp;Images&nbsp;</a></span>');
}

function project_thumbnail_click()
{
	var newPos = parseInt($('#'+$('img',this).attr("name")).css("left"));
	var contentW = parseInt($(".content").last().css("left"));
	var prozent = newPos/contentW;
	
	$("#scrollbar").stop().animate({left: (330*prozent)+80}, {queue:false, duration:500, easing:"cubicEaseOut"});
	$("#belowcontentcontainer").stop().animate({left: newPos*-1}, {queue:false, duration:500, easing:"cubicEaseOut"});
	$("#beneathcontentcontainer").stop().animate({left: newPos*-1}, {queue:false, duration:500, easing:"cubicEaseOut"});
}

/* ########### BREADCRUMB ########### */ 

function breadcrumb_mouseover()
{
	$(this).css("color", "#000");
	$(this).css("background-image", "url(img/white.png)");
}

function breadcrumb_mouseout()
{
	$(this).css("color", "#fff");
	$(this).css("background-image", "url(img/grey.png)");
}

function breadcrumb_click()
{
	if(active) return;
	active = true;
	var id = ($(this).index()-2)/2;
	if(id < 0)
	{
		navigation_set_root();
		clear_navigation();
		newId = 1;
		clear_content();
		load_content();
	}
	else
	{
		newId = breadcrumb[id]["url"];
		path = breadcrumb[id]["parent"];
		for(i = breadcrumb.length; i>id+1; i--)
		{
			breadcrumb.pop();
		}
		close_navigation(false);
		clear_content();
		load_content();
	}
}

function breadcrumb_behaviour()
{
	$('.breadcrumb').bind('mouseenter', breadcrumb_mouseover);
	$('.breadcrumb').bind('mouseleave', breadcrumb_mouseout);
	if(!isiPad()) $('.breadcrumb').bind('click', breadcrumb_click);
	else $('.breadcrumb').bind('touchstart', breadcrumb_click);
}

/* ########### NAVIGATION ########### */ 

function build_navigation()
{
	$('#navigation').css("visibility", "hidden");
	if(breadcrumb.length > 0)
	{
		var span = '<span class="breadcrumb">home</span>';
		$('#navigation ul li').append(span);
		
		for(i=0; i<breadcrumb.length; i++)
		{
			span = '<span class="breadcrumbdivider">/</span><span class="breadcrumb">'+breadcrumb[i]["name"]+'</span>';
			$('#navigation ul li').append(span);
		}
		breadcrumb_behaviour();
	}
	
	for(i=0; i<path.length; i++)
	{
		var li = '<li class="rootcat"><span class="root_black">'+path[i].category+'</span><span class="root_white">'+path[i].category+'</span><div class="root_alpha"></div></li>';
		$('#navigation ul').append(li);
	}
	if(kickoff)
	{
		setTimeout("open_navigation()", 1000);
		kickoff = false;
	}
	else open_navigation();
}

function navigation_behaviour()
{
	if(!isiPad()) $('.root_alpha').bind('click', navigation_click);
	else $('.root_alpha').bind('touchstart', navigation_click);
}

function navigation_mouseenter()
{
	if(!isiPad()) $(this).parent().find('.root_white').animate({width: "show"}, {queue:true, duration:200, easing:"cubicEaseOut"});
}

function navigation_mouseleave()
{
	if(!isiPad()) $(this).parent().find('.root_white').animate({width: "hide"}, {queue:true, duration:200, easing:"cubicEaseOut"});
}

function navigation_click()
{
	if(active) return;
	active = true;
	newId = getIDs(path[$(this).parent().index()-1].url);
	if(path[$(this).parent().index()-1].sub.length)
	{
		path = path[$(this).parent().index()-1].sub;
		breadcrumb.push({"name":$(this).parent().find('.root_white').html().toLowerCase(),"parent":path,"url":newId});
		clear_navigation();
	}
	clear_content();
	load_content();
}

function open_navigation()
{
	$('.root_alpha').each(function(){
		$(this).width($(this).parent().find('.root_black').width()+10);
	});
	
	$('.root_white').hide();
	$('.root_black').hide();
	$('#navigation').css("visibility", "visible");
	
	var delay = 200;
	var delayindex = 0;
	
	$('.root_black').each(function(){
		$(this).stop(true, true).delay(delay*delayindex).animate({width: "toggle"}, {queue:true, duration:300, easing:"cubicEaseOut", complete: function(){
			$(this).parent().find('.root_alpha').bind('mouseenter', navigation_mouseenter);
			$(this).parent().find('.root_alpha').bind('mouseleave', navigation_mouseleave);
			if(!isIE()) if($(this).parent().find('.root_alpha').is(':hover') === true && !isiPad()) $(this).parent().find('.root_alpha').trigger('mouseenter');
		}});
		delayindex++;
	});
	delayindex++;
	setTimeout('navigation_behaviour()', delay*delayindex);
}

function close_navigation(all)
{
	var delay = 100;
	var delayindex = 0;
	
	$('.root_black').reverse().each(function(){
		$(this).stop(true, true).delay(delay*delayindex).animate({width: "toggle"}, {queue:true, duration:200, easing:"cubicEaseOut"});
		delayindex++;
	});
	delayindex++;
	
	if(!all) setTimeout('clear_navigation()', delay*delayindex);
	else $('#navigation ul li:first').stop(true, true).delay(delay*delayindex).animate({width: "toggle"}, {queue:true, duration:200, easing:"cubicEaseOut", complete:hide_navigation});
}

function clear_navigation()
{
	$('.root_alpha').unbind('mouseenter', navigation_mouseenter);
	$('.root_alpha').unbind('mouseleave', navigation_mouseleave);
	if(!isiPad()) $('.root_alpha').unbind('click', navigation_click);
	else $('.root_alpha').unbind('touchstart', navigation_click);
	
	$('.breadcrumb').unbind('mouseover', breadcrumb_mouseover);
	$('.breadcrumb').unbind('mouseout', breadcrumb_mouseout);
	if(!isiPad()) $('.breadcrumb').unbind('click', breadcrumb_click);
	else $('.breadcrumb').unbind('touchstart', breadcrumb_click);
	
	$('#navigation ul').empty();
	$('#navigation ul').append('<li></li>');
	
	build_navigation();
}

function hide_navigation()
{
	$('#navigation').hide();
}

function navigation_set_root()
{
	path = navigation.navigation;
	breadcrumb = new Array();
}

function arrow_enter()
{
	$(this).css("background-image", "url(img/pink.png)");
}

function arrow_leave()
{
	$(this).css("background-image", "url(img/grey.png)");
}

/* ########### LOADING ########### */ 

function loading_text()
{
	l = loadingtext.length;
	to = l;
	text_numbers();
}

function text_numbers(){
	if(textindex < l){
		str3 += " ";
		write_text(str3);
		textindex++;
		text_numbers();
	}
	else 
	{
		text_mixture();
	}
}

function text_mixture()
{
	if(!loadanimation)
	{
		mixobj.hide();
		return;
	}
	if(from == 1) mixobj.show();
	if(from <= l) 
	{
		str1 = "";
		str2 = loadingtext.substr(0,from);
		for (var i = 0; i<l; i++) 
		{
			str1 = str1+String.fromCharCode(33+Math.round(Math.random()*90));
		}
		var intString = str2 + str1.substr(0,from)+str3.substr(0,to);
		write_text(intString.substring(0,l));
		if (ctrl >= 3) 
		{
			from++;
			to--;
			ctrl = 0;
		}
		else 
		{
			ctrl++;
		}
		setTimeout("text_mixture()", 50);
	}
	else {
		textindex = 0;
		setTimeout("flicker()", 50);
	}
}

function write_text(txt){
	mixobj.html(txt);
}

function flicker()
{
	if(!loadanimation)
	{
		mixobj.hide();
		return;
	}
	if(textindex < l)
	{
		mixobj.toggle();
		textindex++;
		setTimeout("flicker()", 50);
	}
	else
	{
		mixobj.hide();
		from = 0;
		to = l;
		setTimeout("text_numbers()", 200);
	}
}

/* ########### LOAD ASSETS ########### */ 

function remove_white()
{
	$('#white').remove();
	$('#preloader').remove();
	mixobj = $("#loading");
	navigation_set_root();
	build_navigation();
}

function fade_out_white()
{
	resize_window();
	$('#white').animate({opacity:0}, {queue:false, duration:500, easing:"cubicEaseOut", complete:remove_white});
}

function load_inital_image()
{
	var $img = $(new Image()).attr({src: 'files/'+backgroundimage+no_cache(), id: "back"}).appendTo($('.bgpic'));
	$img.load(function()
	{
		move_logo();
	});
}

function load_tint()
{
	var $img = $(new Image()).attr({src: 'img/tint.png'+no_cache(), id: "tintmask"}).appendTo($('#tint'));
	$img.load(function()
	{
		load_inital_image();
	});
}

function move_logo()
{
	loadanimation = false;
	$('#preloader').stop().delay(1000).animate({opacity:0}, {queue:true, duration:300, easing:"cubicEaseOut"});
	$('#logo').stop().delay(1000).animate({left:Math.floor($(window).width())-70}, {queue:true, duration:500, easing:"cubicEaseOut", complete:fade_out_white});
}

/* ########### DOCUMENT READY ########### */ 

$(document).ready(function()
{
	mixobj = $("#introloading");
	loadanimation = true;
	loading_text();
	$('.root_alpha').hover();
	$('#scrollbar').hide();
	$('#arrow').hide();
	$('#arrow').bind("mouseenter", arrow_enter);
	$('#arrow').bind("mouseleave", arrow_leave);
	$('#scrollbar').draggable({
		axis: 'x',
		containment: [80,0,410,0],
		drag: function(event, ui)
		{
			var offset = $('#scrollbar').offset();
			var prozent = (offset.left-80)/330;
			var contentW = $(".content").last().css("left");
			var newPos = ((parseInt(contentW)*prozent)*-1);
			$("#belowcontentcontainer").stop().animate({left: newPos}, {queue:false, duration:500, easing:"cubicEaseOut"});
			$("#beneathcontentcontainer").stop().animate({left: newPos}, {queue:false, duration:500, easing:"cubicEaseOut"});
		}
	});
	load_tint();
});

/* ########### RESIZE ########### */ 

function resize_window()
{
	var w = Math.floor($(window).width());
	var h = Math.floor($(window).height());
	
	var ws = Math.ceil(w / 13.75);
	var hs = Math.ceil(h / 9.25);
	
	$('#tint img').width(w);
	$('#tint img').height(h);
	
	$('#tint_top img').width(w);
	$('#tint_top img').height(hs);
	
	$('#tint_bottom img').width(w);
	$('#tint_bottom img').height(hs);
	
	$('#tint_left img').height(h-(hs*2));
	$('#tint_left img').width(ws);
	$('#tint_right img').height(h-(hs*2));
	$('#tint_right img').width(ws);
	
	$('#tint_bottom').offset({left: 0,top: h-hs});
	$('#tint_left').offset({left: 0,top: hs});
	$('#tint_right').offset({left: w-ws,top: hs});
	$('#tint_middle').offset({left: ws,top: hs});
	
	$('#bg').height(h);
	$('#bg').width(w);
	
	$('#arrow').css("top", (h/2)-18+"px");
	
	var p = 793/1200;
	
	if ((h/w) > p){
	    $('.bgpic img').height(h);
	    $('.bgpic img').width(h/p);
	} else {
	    $('.bgpic img').width(w);
	    $('.bgpic img').height(w*p);
	}
	
	var bgH = $('.bgpic img').height();
	var bgW = $('.bgpic img').width();
	if(bgH > h) $('.bgpic').css("margin-top", (h-bgH)+"px");
	else $('.bgpic').css("margin-top", "0px");
	if(bgW > w) $('.bgpic').css("margin-left", (w-bgW)+"px");
	else $('.bgpic').css("margin-left", "0px");
	
	$('#logo').css("left", (w-70)+"px");
	$('#loading').css("left", (w-275)+"px");
	
	$('#beneath').css("top", h/2-220);
	$('#below').css("top", h/2-220);
	$('#scrollbar').css("top", h/2+230);
	
	if(!prop)
	{
		$('#beneath').css("left", w/2-165);
		$('#below').css("left", w/2-165);
		$('#beneathcontent').width(w-(w/2+170));
		$('#belowcontent').width(w-(w/2+170));
	}
	else
	{
		$('#beneathcontent').width(w-390);
		$('#belowcontent').width(w-390);
	}
}

$(window).resize(function() {
	resize_window();
});

/* ########### HELPER ########### */ 

function set_inactive()
{
	active = false;
}

function isiPad()
{
    return ((navigator.platform.indexOf("iPhone") != -1) || (navigator.platform.indexOf("iPod") != -1) || (navigator.platform.indexOf("iPad") != -1));
}

function no_cache()
{
	var str;
	if(isIE == "false") str = "?"+new Date().getTime();
	else str = "";
	return str;
}

function isIE(){
	var bool;
	if($.browser.msie && $.browser.version.substr(0,1) < 9) bool = true;
	else bool = false;
    return bool;
}

function stop_loading()
{
	if (window.stop !== undefined) {
	   window.stop();
	} else if (document.execCommand !== undefined) {
	   document.execCommand("Stop", false); 
	}
}

function getIDs(str)
{
	var id = str.match(/[0-9]\w*/g);
	return id;
}

$('a[rel*=external]').live('click', function()
{
	window.open($(this).attr('href'));
	return false;
});
