// JavaScript Document
var homeImage;

if (window['loadFirebugConsole']) window.loadFirebugConsole();
else 
{
	if (!window['console']) {
		window.console = {};
		window.console.info = function(s){};
		window.console.log = function(s){};
		window.console.warn = function(s){};
		window.console.error = function(s){};
	}
}

$(document).bind('ready', function()
{
	$('#content').draggable({ handle: '#asylum' });
	$('#sticky').draggable({ handle: '#sticky_header' });
	
	$('#hideshow').bind('click', toggleUserInterface );
	$('#download').bind('click', download );
	$('a.btnStickyClose').bind('click', hideSticky );
	
	checklinks();
	
	homeImage = $("#activefile").html();
	$("#dyn").load('/media/', { show:"next", current:homeImage }, checklinks );
	
	// load the sticky from the blog
	$.get("feed.php", null, onFeedXMLLoaded);
	
	$.historyInit(onHistoryChange);
});

var fileExtension = function( file )
{
	return file.substring( file.lastIndexOf(".") + 1 );
};

/**
 * @function onHistoryChange
 * 
 * This function is called when:
 *  1. after calling $.historyInit();
 *  2. after calling $.historyLoad();
 *  3. after pushing "Go Back" button of a browser
 */
var onHistoryChange = function(hash)
{
	if (hash)
	{
		var extension = fileExtension( hash );
		// if($.browser.msie) hash = encodeURIComponent(hash); // fix bug with high-ASCII chars on IE.
		switch( extension )
		{
			case "htm": case "html": case "php":
				$("#main").load(hash, null, showMainPane);
				switchBackdrop( homeImage );
				showUserInterface();
				checklinks();
				break;
				
			case "mov": case "flv":
				switchBackdrop( hash );
				hideUserInterface();
				break;
				
			case "jpg": case "jpeg":
				switchBackdrop( hash );
				showUserInterface();
				break;
		}
	}
	else
	{
		switchBackdrop( homeImage );
		showUserInterface();
		hideMainPane();
	}
};

var decode = function( str )
{
	var r = "";
	var c = str.split(":");
	for( var i in c ) r += String.fromCharCode(Math.sqrt(parseInt(c[i],10) + 4017));
	return r;
}

var showStickySIFR = function()
{
	if(typeof sIFR != "undefined")
	{
		var rustysHand = { src: 'flash/RustysHand.swf' };
		sIFR.activate(rustysHand);
		sIFR.replace(
			rustysHand, 
			{
				selector: 'body #sticky p',
				wmode:"transparent",
				css: [ '.sIFR-root { color:#666666; } a:link { background-color:#fff; text-decoration:none; }' ]
			}
		);
	};
};

var onFeedXMLLoaded = function( data )
{
	$("#sticky p").html(data);
	showSticky();
	checklinks();
};

var download = function(e)
{		
	file = $('#activefile').html();
	
	if(file.length > 0)
	{
		var i = file.lastIndexOf(".");
		var ext = file.substring(i+1);
		
		if(ext == 'flv' || ext == 'mov')
		{
			//open a window with the videoplayer
			var mov = file.replace('.'+ext, '.mov');
			window.open(mov, 'video');
		}
		else
		{
			//it's not an FLV, just open an window with the file in it
			window.open(file);
		}	
	}
	
	e.preventDefault();
}

var onMainXClick = function()
{
	hideMainPane();
	return false;
};

var showMainPane = function(responseText, textStatus, XMLHttpRequest)
{
	if (textStatus=="error") {
		$("#main").html("<h3>Error</h3><p>This page could not be retrieved.");
		// alert("Error: "+responseText);
	}
	
	// mailto link
	$("#hfds92a").each(function(){
		var e = decode("7008:8083:6387:8304:79:5392:9208:10624:7647:9672:7864:6387:7008:7647:7864:9208:-1901:5784:8304:-1901:9672:7432");
		$(this).html('<a href="mailto:'+e+'">'+e+'</a>');
	});
	
	$("#main").slideDown("normal", function(){
		$("#main").css("overflow", "");
	});
	
	checklinks();
	
	$("#main").append('<a id="mainx" class="x" onclick="return onMainXClick();">x</a>');
	
	checkInputs();
};

var hideMainPane = function()
{
	$('#mainx').remove();
	$("#main").slideUp("slow", function() { 
		$('a.content').removeClass('active');
		checklinks();
	});
};

var toggleUserInterface = function()
{
	var menuVisible = ($('#user-interface').css('display')!="none");
	
	if (menuVisible) hideUserInterface();
	else showUserInterface();
	
	return false;
}

var hideUserInterface = function()
{
	$('#user-interface').hide();
	$('#hideshow').html('show menu');
}

var showUserInterface = function()
{
	$('#user-interface').show();
	$('#hideshow').html('hide menu');
}

var loadAndShowMenuItem = function(e)
{
	var elem = $(this);
	var mv = $('#main').css('display');
	if(mv != 'none')
	{
		$('#mainx').remove();	
		$('#main').css('overflow', 'hidden');
		showMainPane();
	}
	$('a.content').removeClass('active');
	elem.addClass('active');
	
	$.historyLoad( elem.attr('href').replace(/^.*#/, '') );
	
	checklinks();
	
	return false;
}

var killLinkClick = function(e)
{
	e.preventDefault(); 
	e.stopPropagation();
	return false;
}

var getRelativeHref = function( jElt ) 
{
	var absHref = jElt.href;
	var windowHref = window.location.href;
	var urlParts = windowHref.split("/");
	var newUrlParts = [ urlParts[0], urlParts[1], urlParts[2] ];
	var urlWithoutPath = newUrlParts.join("/");
	return absHref.replace(urlWithoutPath, "");
}

var onBackdropLinkClick = function(e)
{
	var elem = $(this);
	var link = getRelativeHref(elem[0]);
	var title = elem.attr('title');
	
	$.historyLoad( link.replace(/^.*#/, '') );
	
	e.preventDefault();	
	return false;
};

var checklinks = function(){
	
	var contentlinks = $('a.content');
	contentlinks.each(function(i)
	{
		$(this).unbind('click');
		if(!$(this).hasClass('active')) $(this).bind('click', loadAndShowMenuItem);
		else $(this).bind('click', killLinkClick);
	});
	
	$('a.backdrop').each(function(i)
	{
		var elem = $(this);
		elem.unbind('click');
		elem.bind('click', onBackdropLinkClick);	
	});
	
	$("a[rel=external]").attr('target', '_blank');
}

var hideSticky = function(){
	$('#sticky').hide();
	return false;
}

var showSticky = function(){
	$('#sticky').show();
}

var isFFMac = function() 
{
	return $.browser.mozilla && navigator.platform.toLowerCase().indexOf('mac') != -1;
}

var pops = function(img, x, y, txt, txtx, txty)
{
	var popLabel = "";
	if(txt && txt.length > 0)
	{
		if(!txtx) txtx = 0;
		if(!txty) txty = 0;
		popLabel = '<p style="left:'+txtx+'px;top:'+txty+'px;">'+txt+'</p>';
	}
	
	var thePop = '<div id="pops" style="position:absolute;left:'+x+'px;top:'+y+'px;">' + 
					'<img src="'+img+'" />' + 
					popLabel +
				 '</div>';
	
	//beautiful FF Mac hack to avoid floating scrollbar
	if (isFFMac()) $('#main').css({'overflow': 'hidden', 'padding-right': '35px'});
	
	$("#content").append(thePop)
}

var unpop = function()
{
	if ($('#pops'))
	{
		$('#pops').remove();
		if (isFFMac()) $('#main').css({'overflow': 'auto', 'padding-right': '20px'});
	}
}

var checkInputs = function(){

	$('input').each(function(i)
	{
		var n = $(this);
		n.bind('focus', function(e)
		{
			if(n.val() == n.attr('title')) n.val('');
		});
		
		n.bind('blur', function(e)
		{
			if(n.val()=='') n.val( n.attr('title') );
		});
	});
	
	$('textarea').each(function(i)
	{
		n = $(this);
		n.bind('focus', function(e)
		{
			if(n.val() == n.attr('title')) n.val("");
		});
		
		n.bind('blur', function(e)
		{
			if(n.val() == '') n.val( n.attr('title') );
		});
	});
}

var switchBackdrop = function(link, title)
{
	var file = link.substring(link.indexOf("/")+1);
	var i = file.lastIndexOf(".");
	var ext = file.substring(i+1);
	if (!title) title = link;
	
	$('#activefile').html( link );
	$('#download').attr("href", link);
	
	if(ext == 'jpg' || ext == 'gif' || ext == 'png' )
	{
		$('#backdrop').html('<img src="'+ link +'" alt="'+ title +'" />');
		$('#download').hide();
	}
	else
	{
		hideUserInterface();
		
		var so = new SWFObject("/flash/videoPlayer.swf", "flashvid", "100%", "100%", 9, "#000000");
		so.addParam("wmode", "opaque");
		so.addVariable("video", link);
		so.addVariable("debug", "false");
		so.write("backdrop");
		
		$('#download').show();
	}
	
	$("#dyn").load('/media/', { show:"next", current:link }, checklinks );
}

var formsend = function(form)
{
	var formEmail = $(form.email).val();
	var formName = $(form.name).val();
	var formURI = $(form.uri).val();
	var formComment = $(form.comment).val();
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	
	if(!filter.test(formEmail))
	{
		alert('please fill out a valid email-address');
		return false;
	}
	else if(formName.length == 0 || formName == 'NAME')
	{
		alert('please fill out a name');
		return false;
	}
	else
	{
		$('#main form button[type=submit]').css('display', 'none');
		var params = {
			name: formName,
			email: formEmail,
			uri: formURI,
			comment: formComment
		};
		
		$("#main").load($(form).attr("action"), params, showMainPane);
	}
}