var g_ready = false;
var g_invalidLogin = false;
var g_loggingIn = false;

var g_flashing = false;
var g_flashTextCurrently = false;
var g_flashText = null;
var g_flashOldTitle = null;

var g_chatVisible = false;
var g_chatLoading = false;

var g_nonce = null;
var g_sessionID = null;
var g_server = null;

/* Helper functions
 */

function flashStageUpdate()
{
	if (findFlash("chat") && findFlash("chat").stageUpdate() == null)
		setTimeout(flashStageUpdate,100);
}

function showChat()
{
	/* Hide overflow
 	 */
	if (navigator.appName.indexOf("Microsoft") != -1) 
		document.body.style.overflowY = "hidden";

	/* Set us visible
	 */
	document.getElementById("index-chat").style.visibility = "visible";

	/* Set us up, we are initially 1x1 off screen so we are hidden
	 */
	document.getElementById("index-chat").style.left = "0px";
	document.getElementById("index-chat").style.top = "0px";
	document.getElementById("index-chat").style.width = "100%";
	document.getElementById("index-chat").style.height = "100%";
	document.getElementById("index-chat").style.marginLeft = "0px";
        document.getElementById("index-chat").style.marginTop = "0px";

	g_chatVisible = true;
	g_chatLoading = false;
	g_loggingIn = false;
}

function hideChat()
{
	document.getElementById("index-chat").style.visibility = "hidden";
	g_chatVisible = false;

	/* Show overflow
 	 */
	if (navigator.appName.indexOf("Microsoft") != -1) 
		document.body.style.overflowY = "auto";
}

function findFlash(a_movie) 
{
	if (navigator.appName.indexOf("Microsoft") != -1) 
	{
		return window[a_movie];
	}
	else 
	{
		return document[a_movie];
	}
}

function updateStatus(a_status)
{
	$("#astra-status").html(a_status);
}

/* Flash related functions
 */
function loadFlash()
{
	var l_flashvars = {};
	l_flashvars.allowscriptaccess = "always";

	var l_params = {}
	l_params.bgcolor = "#000000";
	l_params.allowscriptaccess = "always";
	l_params.swliveconnect = "true";

	swfobject.embedSWF("http://trillian.cachefly.net/trillian.im/chat/trillian-1.0.0.621.swf", "chat", "100%", "100%", "10.0.0", null, l_flashvars, l_params);
}

function removeFlash()
{
	document.getElementById("index-chat").innerHTML = '';
}

function hideLoadingFlash()
{
	document.getElementById("login-loading").style.display = "none";
}

function showLoadingFlash()
{
	document.getElementById("login-loading").style.display = "block";
}

function badpassword()
{
	g_invalidLogin = true;
	setTimeout(function() 
	{
		alert("Ungültiger Benutzername oder Kennwort.");
		$("#astra-password").val("");
		close();
	}, 10);
}

function license_invalid()
{
	g_invalidLogin = true;
	setTimeout(function() 
	{
		alert("Sie müssen Inhaber einer Pro Lizenz sein, um das Web IM Produkt nutzen zu können.");
		$("#astra-password").val("");
		close();
	}, 10);
}

/* Window flashing
 */
function flashTitle()
{
	if (g_flashing)
	{
		if (g_flashTextCurrently)
			document.title = g_flashOldTitle;
		else
			document.title = "*" + g_flashText + "*";

		g_flashTextCurrently = !g_flashTextCurrently
		setTimeout(flashTitle,1000);
	}
}

/* Events from the flash
 */

function progress(a_value)
{
	updateStatus("Loading (" + a_value + "%)...");
}

function onReady()
{
	/* Only do it once.  Other sub-swf's may also tell us later, and we do not want to reshow the login
	 */
	if (!g_ready)
	{
		g_ready = true;
		if (g_profileRequest)
		{
			findFlash("chat").showProfile("http://www.trillian.im/",g_profileRequest);
			hideLoadingFlash();
			showChat();
		}
		else
		{
			updateStatus("Anmelden...");
			l_username = document.getElementById("astra-username").value;
			l_password = document.getElementById("astra-password").value;

			var l_device = "WEB";
			findFlash("chat").login(l_username,l_password, l_device);
		}


		/* The flash may not get valid stage coordinates, so tell it to
		 * update until it does
		 */
		flashStageUpdate();
	}
}

function setServer(a_server)
{
	g_server = a_server;
}

function setNonce(a_nonce)
{
	g_nonce = a_nonce;
}

function setSessionID(a_id)
{
	g_sessionID = a_id;
}

function ready()
{
	setTimeout(onReady,100);
}

function startFlash(a_text)
{
	g_flashText = decodeURIComponent(a_text);
	if (!g_flashing)
	{
		g_flashTextCurrently = false;
		g_flashOldTitle = document.title;
		g_flashing = true;
		setTimeout(flashTitle,1000);
	}
}

function stopFlash()
{
	if (g_flashing)
	{
		document.title = g_flashOldTitle;
		g_flashing = false;
	}
}

function success()
{
	if (g_invalidLogin) return;
	if (g_chatVisible) return;

	if (!g_chatLoading)
	{
		g_chatLoading = true;
		showChat();
	}
}

function onClose()
{
	if (g_profileRequest)
	{
		document.location = "/";
		return;
	}

	updateStatus("Abmelden...");
	hideChat();
	removeFlash();
	g_ready = false;
	g_invalidLogin = false;
	g_loggingIn = false;
	showAll();
}

function userAlert(a_text)
{
	setTimeout(function() { alert(a_text); },10);
}

function close()
{
	g_nonce = null;
	g_sessionID = null;
	g_server = null;

	setTimeout(onClose,10);
}

/* Events from the html
 */

function ui_login(a_user, a_pass)
{
	if (g_loggingIn) return;
	
	if (!a_user || !a_pass || !a_user.length || !a_pass.length)
	{
		alert("Bitte geben Sie sowohl Ihren Benutzernamen, als auch Ihr Kennwort ein.");
		return;
	}

	document.title = "Trillian für Web";
	g_loggingIn = true;
	loadFlash();
}

function sleep(a_time)
{
	var l_date = new Date();
	var l_current = null;
	do 
	{ 
		l_current = new Date(); 
	}
	while(l_current-l_date < a_time);
}

function onUnload()
{
	if (g_sessionID == null || g_sessionID == "") return;
	if (g_nonce == null || g_nonce == "") return;
	if (g_server == null || g_server == "") return;

	try {
		findFlash("chat").silence();
	} catch(e) { } 

	var l_date = new Date();
	var l_min = l_date.getMinutes();
	var l_hour = l_date.getHours();

	var l_timezone = (l_date.getTimezoneOffset()/60) * -1;
	var l_timezoneString = "%28GMT%20";
	if (l_timezone > 0)
		l_timezoneString += "%2B" + l_timezone + "%29";
	else l_timezoneString += "" + l_timezone + "%29";
	var l_time = (l_hour > 12 ? l_hour-12 : (l_hour != 0) ? l_hour : "12") + "%3A" + (l_min > 10 ? l_min : ("0" + l_min)) + "%20" + (l_hour >= 12 ? "PM" : "AM") + "%20" + l_timezoneString;
	var l_status = "Browser%20geschlossen%20seit%20" + l_time + " Uhr";

	var l_string = "c=sessionSuspend&status=away&statusmsg=" + l_status + "&xsession=" + g_sessionID;
	var l_hmac = hex_hmac_sha1(g_nonce,l_string);
	l_string += "&xhmac=" + l_hmac;

	jQuery.ajax({
		url:    'http://www.trillian.im/chat/octopus.php/' + g_server,
		data:   l_string,
		type:    'post',
		async:   false
	});      
}

function onLoad()
{
	var hasReqestedVersion = DetectFlashVer(10, 0, 0);
	if (!hasReqestedVersion)
	{
		if (g_profileRequest)
		{
			document.getElementById("index-getflash").style.display = "block";
		}
		else
		{
			document.getElementById("index-login").style.display = "none";
			document.getElementById("index-getflash").style.display = "block";
		}
	}
	else if (g_profileRequest)
	{
		showLoadingFlash();
		loadFlash();
	}
}
