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;
var g_suspend = false;

var g_mode = 'login';
var g_version = -1;
var g_minHeight = 200;
var g_minWidth = 1000;

/* 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";
	document.getElementById("index-chat").style.minHeight = "400";
	$("div#background-flow-short").hide();
	if ($.browser.mozilla && $.browser.version > '1.8' && $.browser.version < '1.9')
	{
	        $("div.background").hide();
	}
	if (!$.browser.msie)
	{
		$("div#container").css("min-height", 0);
	}
	
	g_chatVisible = true;
	g_chatLoading = false;
	g_loggingIn = false;
}

function hideChat()
{
	if ($.browser.mozilla && $.browser.version > '1.8' && $.browser.version < '1.9')
	{
	        $("div.background, div#background-flow-short").show();
	}

	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 document.getElementById(a_movie);
	}
	else 
	{
		return document[a_movie];
	}
}

function updateStatus(a_status, a_percent)
{
	switch (g_mode)
	{
		case 'register':
			$("#register-status").html(a_status);
			if (a_percent && a_percent < 100)
				$("#btn-register-2-submit").val("Loading (" + a_percent + "%)");
			else
				$("#btn-register-2-submit").val("Start");
			$("#register-percent").html(a_percent);
			break;
		case 'login': default:
			$("#login-status").html(a_status);
			$("#login-percent").html(a_percent);
			break;
	}
}

/* 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";

	var l_attributes = {
		id: "chat",
		name: "chat"
	}
	
	swfobject.embedSWF("http://trillian.cachefly.net/trillian.im/chat/trillian-2.0.0.616.swf", "chat", "100%", "100%", "10.0.0", null, l_flashvars, l_params, l_attributes);

	if (navigator.appName.indexOf("Microsoft") != -1) 
	{
		document.getElementById("index-chat").style.width = "2";
		document.getElementById("index-chat").style.marginLeft = "0px";
	}
}

function removeFlash()
{
	document.getElementById("index-chat").innerHTML = '';
}

function hideLoadingFlash()
{
	switch (g_mode)
	{
		case 'register':
			document.getElementById("register-loading").style.display = "none";
			break;
		case 'login': default:
			document.getElementById("login-loading").style.display = "none";
			break;
	}
}

function showLoadingFlash()
{
	switch (g_mode)
	{
		case 'register':
			document.getElementById("register-loading").style.display = "block";
			break;
		case 'login': default:
			document.getElementById("login-loading").style.display = "block";
			break;
	}
}

function badpassword()
{
	g_invalidLogin = true;
	setTimeout(function() 
	{
		alert("Invalid username or password.");
		$("input.password[rel=astra]").val("");
		close();
	}, 10);
}

function license_invalid()
{
	g_invalidLogin = true;
	setTimeout(function() 
	{
		alert("You must be a pro customer to use the Web IM product.");
		$("input.password[rel=astra]").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)
{
	switch (g_mode)
	{
		case 'register':
			updateStatus("Preloading", a_value);
			break;
		case 'login': default:
			updateStatus("Loading", a_value);
			break;
	}

}

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(proto() + "//www.trillian.im/",g_profileRequest);
			hideLoadingFlash();
			showChat();
		}
		else
		{
			if (navigator.appName.indexOf("Microsoft") != -1) 
			   document.getElementById("index-chat").style.marginLeft = "-120%";
			switch (g_mode)
			{
				case 'register':
					updateStatus("Ready","");
					setTimeout(gray_submit, 100);
					g_version = findFlash("chat").version();
					break;
				case 'login': default:
					g_version = findFlash("chat").version();
					updateStatus("Signing in...","");
					setTimeout(ready_login, 100);
					break;
			}
		}


		/* The flash may not get valid stage coordinates, so tell it to
		 * update until it does
		 */
		flashStageUpdate();
	}
}
function gray_submit()
{
	$("input#btn-register-2-submit").removeClass("gray").addClass("green");
}

function ready_login()
{
	l_username = $("input.username[rel=astra]").val();
	l_password = $("input.password[rel=astra]").val();
	var l_device = "WEB";
	signIn(l_username, l_password, l_device);
}

function signIn(a_username, a_password, a_device)
{
	updateStatus("Signing in...","");
	findFlash("chat").login(a_username, a_password, a_device);
	flashStageUpdate();
}

function gkRegister(a_querystring, a_url)
{
	updateStatus("Registering...","");
	var l_results = findFlash("chat").gatekeeper(a_url, a_querystring);
}

function setSuspend(a_suspend)
{
	g_suspend = a_suspend;
}

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();
		getalerts();
	}
}

function onClose()
{
	if (g_profileRequest)
	{
		document.location = "/";
		return;
	}

	updateStatus("Signing out...","");
	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 (g_mode == 'login')
	{
		if (!a_user || !a_pass || !a_user.length || !a_pass.length)
		{
			alert("Please enter both a username and a password.");
			setTimeout(onClose,10);
			return;
		}
	}

	document.title = "Trillian for 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 getalerts()
{
	$.ajax({url: proto() + "//www.ceruleanstudios.com/alerts/alerts.php?version="+g_version+"&beta=1&pro=0&platform=web"});
	return true;
}

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_string = null;

	if (g_suspend == true)
	{
		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%20closed%20since%20" + l_time + "";

		l_string = "c=sessionSuspend&status=away&statusmsg=" + l_status + "&xsession=" + g_sessionID;
	}
	else
	{
		l_string = "c=sessionLogout&xsession=" + g_sessionID;
	}

	var l_hmac = hex_hmac_sha1(g_nonce,l_string);
	l_string += "&xhmac=" + l_hmac;

	try { 
		jQuery.ajax({
			url:    proto() + '//www.trillian.im/chat/octopus.php/' + g_server,
			data:   l_string,
			type:    'post',
			async:   false
		});      
		$("#chat").fadeOut();
		return true;
	} catch(e) { }
}

window.onbeforeunload = function(a_event) 
{
	if (g_sessionID == null || g_sessionID == "") return;
	if (g_nonce == null || g_nonce == "") return;
	if (g_server == null || g_server == "") return;
	if (g_suspend == true) return;

	var l_event = a_event || window.event;

	// For IE and Firefox
	if (l_event) 
	{
		l_event.returnValue = "You are still connected to Trillian.  Leaving will disconnect you.";
	}

	// For Safari
	return "You are still connected to Trillian.  Leaving will disconnect you.";
};

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();
	}
}

function proto()
{
	if ("https:" == document.location.protocol) return "https:";
	return "http:";
}

/* Redeclare the destructive fixResize() to override default.js's 
 */

function fixResize() {}

