/* Trillian for Web
 *
 * In-site registration and sign on
 *
 * Copyright (C) 2010 Cerulean Studios, LLC
 *
 * Programmer: Andy Magoon
 */

var g_profileRequest = null;
var g_minIndexHeight = 400;
var g_minIndexWidth = 990;
var g_registering = false;
var g_registering_timeout = null;
var g_network = 'astra';
var g_networkun, g_networkpw;
var g_initfocuscancel = false;
var g_focused = null;
var g_un, g_pw;
var au,ap,np,ae,sqe,sqc,sa;
var g_fbname;
var g_fbwatch = {handler: false, faded: false, chatfaded: false, loginfaded: false, lswtimer: false};

if ($.browser.opera && location.href.indexOf("https:")!=-1) location.href = location.href.replace(/https:/, "http:");
if (navigator.appName.indexOf("Microsoft") != -1)
{
	var reJsHost = (("https:" == document.location.protocol) ? "https://api-secure." : "http://api.");
	document.write(unescape("%3Cscript src='" + reJsHost + "recaptcha.net/js/recaptcha_ajax.js' type='text/javascript'%3E%3C/script%3E"));
	var g_reincluded = true;
	var fbJsUrl = (("https:" == document.location.protocol) ? "https://ssl.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" : "http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/en_US");
	document.write(unescape("%3Cscript src='" + fbJsUrl + "' type='text/javascript'%3E%3C/script%3E"));
	var g_fbincluded = true;
} else {
	var g_reincluded = false;
	var g_fbincluded = false;
}


$(document).ready(function() { 
	include("/chat/chat.css", "css");
});

function onResizeIE(e)
{
	return;
	if (g_mode=="register") g_minIndexHeight=400;
	if ($(window).height() < g_minIndexHeight) 
	{
		$("div.background-simple").height(g_minIndexHeight);
	   	$("body").css("overflow-y", "scroll");
	} else {
		$("div.background-simple").css("height", "100%");
	   	$("body").css("overflow-y", "auto");
	}
	if ($(window).width() < g_minIndexWidth)
	{
		$("div.background-simple, div#background-flow-short").width(g_minIndexWidth);
		$("body").css("overflow-x", "scroll");
	} else {
		$("div.background-simple, div#background-flow-short").css("width", "100%");
	   	$("body").css("overflow-x", "auto");
	}
	return;
}
function onResizeOpera(e)
{
	if (g_chatVisible) return;
	if ($(e).width() > g_minIndexWidth) 
	{
	   $("body").css("overflow-x", "hidden");
	}
	else 
	{
	   $("body").css("overflow-x", "scroll");
	}
	if ($(e).height() > g_minIndexHeight)
	   $("body").css("overflow-y", "hidden");
	else
	   $("body").css("overflow-y", "scroll");
	fixOpera();
}

function chat_login(un, pw)
{
	if ($.browser.msie) setTimeout(function(){onResizeIE($(window))}, 100);
	window.scrollTo(0,0);
	$("body").children().remove().end().load("/chat/chat.html", function() {
		$("#login-loading").show(1,function() {
			if ($.browser.msie)
			{
				setTimeout(function() {
					ui_login(un, pw);
				},500);
			} else {
				ui_login(un, pw);
			}
		});
	});
}

function invalidUser(a_un, a_pw, a_network)
{ 
	switch (a_network)
	{
		case "facebook":
			if (!g_fbname)
			{
				return("You must connect with Facebook before continuing");
			}
			return false;
		case "msn":
			if (a_pw == "" || a_un == "")
			{
				$("input.password[rel="+a_network+"]").focus();			
				return("Please enter both Windows Live email and password.");
			}
			if (!isValidEmail(a_un))
			{
				$("input.username[rel="+a_network+"]").focus();			
				return("Invalid entry.  Please enter a valid Windows Live email.");
			}
			break;
		case "jabber":
			if (a_pw == "" || a_un == "")
			{
				$("input.password[rel="+a_network+"]").focus();			
				return("Please enter both Jabber JID and password.");
			}
			if (!isValidEmail(a_un))
			{
				$("input.username[rel="+a_network+"]").focus();			
				return("Invalid entry.  Please enter a valid Jabber JID.");
			}
			break;
		case "myspace":
			if (a_pw == "" || a_un == "")
			{
				$("input.password[rel="+a_network+"]").focus();			
				return("Please enter both MySpaceIM email and password.");
			}
			if (!isValidEmail(a_un))
			{
				$("input.username[rel="+a_network+"]").focus();			
				return("Invalid entry.  Please enter a valid MySpaceIM email.");
			}
			break;
		case "google":
			if (a_pw == "" || a_un == "")
			{
				$("input.password[rel="+a_network+"]").focus();			
				return("Please enter both Google Talk username and password.");
			}
			if (a_un.indexOf("@") == -1)
			{
				a_un += "@gmail.com";
				$("input.username[rel="+a_network+"]").val(a_un);
			}
			if (!isValidEmail(a_un))
			{
				$("input.username[rel="+a_network+"]").focus();			
				return("Invalid entry.  Please enter a valid Google Talk username.");
			}
			break;
		case "aim":
			if (a_un.indexOf(" ") != -1)
			{
				a_un = a_un.replace(/ /g,"");
				$("input.username[rel="+a_network+"]").val(a_un);
			}
			if (a_pw == "" || a_un == "")
			{
				$("input.password[rel="+a_network+"]").focus();			
				return("Please enter both AIM Screen Name and password.");
			}
			if (a_un.search(/^[0-9]/) != -1)
			{
				$("input.username[rel="+a_network+"]").focus();			
				return("Invalid entry.  Your AIM Screen Name cannot start with a number.");
			}
			if (a_un.indexOf("@") != -1)
			{
				if (!isValidEmail(a_un))
				{
					return("Invalid entry.  The email address you've entered is not valid.");
				}
			}
			break;
		case "yahoo":
			if (a_pw == "" || a_un == "")
			{
				$("input.password[rel="+a_network+"]").focus();			
				return("Please enter both Yahoo! ID and password.");
			}
			if (a_un.indexOf("@yahoo.com") != -1)
			{
				a_un = a_un.replace("@yahoo.com", "");
				$("input.username[rel="+a_network+"]").val(a_un);
			}
			break;
		case "icq":
			a_un = a_un.replace(/[^\d]/g, "");
			$("input.username[rel="+a_network+"]").val(a_un);
			if (a_pw == "" || a_un == "")
			{
				$("input.password[rel="+a_network+"]").focus();			
				return("Please enter both ICQ UIN and password.");
			}
			if (a_un.length < 6)
			{
				$("input.username[rel="+a_network+"]").focus();			
				return("Invalid entry.  You must enter your ICQ UIN as 6 or more numbers, no letters or symbols.");
			}
			break;
		case "astra":
			if (a_pw == "" || a_un == "")
			{
				$("input.password[rel="+a_network+"]").focus();			
				return("Please enter both Trillian Username and password.");
			}
			if (isValidEmail(a_un))
			{
				$("input.username[rel="+a_network+"]").focus();			
				return("Invalid entry.  Trillian Usernames do not use an email addresses.  Please try again.");
			}
			if (!isValidUsernameForSignin(a_un))
			{
				$("input.username[rel="+a_network+"]").focus();			
				return("Invalid entry.  Trillian Usernames must start with a letter, contain between 6 and 64 numbers/letters, no symbols other than period or underscore.");
			}
			break;
		default:
			if (a_pw == "" || a_un == "")
			{
				$("input.password[rel="+a_network+"]").focus();			
				return("Please enter both username and password.");
			}
			if (isValidEmail(a_un))
			{
				$("input.username[rel="+a_network+"]").focus();			
				return("Invalid entry.  Please enter a valid email address.");
			}
			break;
	}	
	
	if (a_un && a_pw == "")
	{
		$("input.password[rel="+a_network+"]").focus();			
		return("Please type both a username and password.");
	}
		
	if (a_un == "" || a_pw == "")
	{
		$("input.username[rel="+a_network+"]").focus();			
		return("Please type both a username and password.");
	}

	return false;
}

function show_register() {
	g_mode = 'register';  
	document.title = "Trillian";
	if (!g_reincluded)
	{
		g_reincluded = true;
		var reJsHost = (("https:" == document.location.protocol) ? "https://api-secure." : "http://api.");
		include(reJsHost + "recaptcha.net/js/recaptcha_ajax.js", "js");
	}
	$("#container").css("min-height", "400px");
	$("div#register-content-1").find("div.error-row").hide();
	$("div#custom-question-row").hide();
	$("input#register-username, input#email, input#register-password, input#verify, input#security_question_custom, input#security_answer").bind("change", function(){
		$(this).removeClass("error");
	});

	$("input#register-username, input#email").keypress(function(a_event){ if (a_event.which == 13) show_register_2(); });

	$("input#register-password, input#verify, input#security_question_custom, input#security_answer").keypress(function(a_event){ if (a_event.which == 13) show_register_3(); });
	
	$("a#btn-register-1-cancel").click(function()
	{
		hide_register();
	});

	$("input#btn-register-1-next").click(function()
	{
		show_register_2();
	});

	$("a#btn-register-2-back").click(function()
	{
		show_register_1();
	});

	$("input#btn-register-2-submit").click(function()
	{
		show_register_3();
	});

	$("select#security_question_enum").bind("change", function(){
			if ($(this).val() == "0")
			{
				$("div#custom-question-row").show();
				$("input#security_question_custom").focus();
			} else {
				$("div#custom-question-row").hide();
				$("input#security_answer").focus();
			}
	});	
	$("select#security_question_enum").bind("keyup", function(){
			if ($(this).val() == "0")
			{
				$("div#custom-question-row").show();
			} else {
				$("div#custom-question-row").hide();
			}
	});	
$("#login-register").show(1,function() {
		if ($.browser.msie)
		{
			setTimeout(function() {
				ui_login($("#register-username").val(), $("#register-password").val());
			},2000);
		} else {
			ui_login($("#register-username").val(), $("#register-password").val());
		}
	});
	$("div#register-content-1").show();
	$("div#register-content-1").height("400px");
	setTimeout(show_recaptcha, 1000);
	if (g_network != "astra")
	{
		setTimeout(function(){$("input#email").focus();}, 500);
	} else {
		setTimeout(function(){$("input#register-username").focus();}, 500);
	}
	fixOpera();
	setTimeout(fixOpera, 500);
	impress(g_network);
	if ($.browser.msie) setTimeout(function(){onResizeIE($(window))}, 100);
}

function show_register_1() 
{ 
	$("div#register-content-2").hide();
	$("div#register-content-1").show();
	fixOpera();
}
function show_register_2()
{
	$("div#register-content-1").find("input.card-input").removeClass("error");
	$("div#register-content-1").find("div.error-row").hide();
	var invalids_page1=0;
	if (!$("input#terms").attr("checked"))
	{
		invalids_page1++;
		$("input#terms").focus();
		$("div#terms-error").show();
	}
	if ($("input#recaptcha_response_field").val().length < 1)
	{
		invalids_page1++;
		$("input#recaptcha_response_field").focus();
		$("div#captcha-error").show();
	}
	if (!isValidEmail($("input#email").val()))
	{
		invalids_page1++;
		$("div#email-error").show();
		$("input#email").addClass("error").focus();
	}
	if (!isValidUsername($("input#register-username").val()))  
	{
		invalids_page1++;
		$("div#username-error").show();
		$("input#register-username").addClass("error").focus();
	}
	if (!invalids_page1) {
		$("div#register-content-1").hide();
		$("div#register-content-2").show();
		$("input#register-password").focus();
	}
	fixOpera();
	setTimeout(fixOpera, 500);
	if ($.browser.msie) setTimeout(function(){onResizeIE($(window))}, 100);

	au = $("input#register-username");
	ap = $("input#register-password");
	np = $("input#register-password");
	ae = $("input#email");
	sqe = $("select#security_question_enum");
	sqc = $("input#security_question_custom");
	sa = $("input#security_answer");
}

function show_register_3()
{
	if (!g_ready)
	{
		alert("Trillian for Web's registration process requires Flash, but our Flash object has not finished loading.  Check to make sure you don't have it blocked then try again, or visit //register for a non-Flash form.");
		return;
	}
	if (g_registering)
	{
		return;
	}
	$("div.error-row").hide();
	$("input.card-input").removeClass("error");
	var invalids_page2=0;
	if ($("input#security_answer").val().length < 3)
	{
		invalids_page2++;
		$("input#security_answer").addClass("error").focus();
		$("div#answer-error").show();
	}
	if ($("select#security_question_enum").val() == "0" && $("input#security_question_custom").val().length < 3)
	{
		invalids_page2++;
		$("select#security_question_enum").addClass("error");
		$("input#security_question_custom").addClass("error").focus();
		$("div#custom-error").show();
	}
	if ($("select#security_question_enum").val() == "-1")
	{
		invalids_page2++;
		$("select#security_question_enum").addClass("error").focus();
		$("div#question-error").show();
	}
	if ($("input#register-password").val() != $("input#verify").val())
	{
		invalids_page2++;
		$("input#verify").addClass("error").focus();
		$("div#password-error").show();
		
	}
	if ($("input#register-password").val().length < 8 || $("input#register-password").val().length > 32)
	{
		invalids_page2++;
		$("input#register-password, input#verify").addClass("error");
		$("div#password-error").show();
		$("input#register-password").focus();
	}
	if (!invalids_page2)
	{	
		var cm = 1;
		var ch = Recaptcha.get_challenge();
		var re = Recaptcha.get_response();
		var v = g_version;
		var p = "Web";
		var querystring = "au="+au.val();
		querystring += "&ap="+encodeURIComponent(ap.val());
		querystring += "&np="+encodeURIComponent(np.val());
		querystring += "&ae="+ae.val();
		querystring += "&sqe="+sqe.val();
		querystring += "&sqc="+encodeURIComponent(sqc.val());
		querystring += "&sa="+encodeURIComponent(sa.val());
		querystring += "&cm="+cm;
		querystring += "&ch="+ch;
		querystring += "&re="+re;
		querystring += "&v="+v;
		querystring += "&p="+p;
		g_registering = true;
		g_registering_timeout = setTimeout(register_timeout, 40000);
		$("input#btn-register-2-submit").removeClass("green").addClass("gray");
		$("div#register-content-2").hide(); 
		$("#register-loading").show();
		//alert(querystring);
		gkRegister(querystring, "https://www.ceruleanstudios.com/client/signup/");
	}
	if ($.browser.msie) setTimeout(function(){onResizeIE($(window))}, 100);
	fixOpera();
	setTimeout(fixOpera, 500);
}

function gatekeeper_error(in_data)
{
	$("#register-loading").hide();
	clearTimeout(g_registering_timeout);
	g_registering = false;
	alert("Error trying to register.  Please wait a minute before trying again.  (\"" + in_data + "\")");
	$("div#register-content-2").show(); 
	$("input#btn-register-2-submit").removeClass("gray").addClass("green");
	if ($.browser.msie) setTimeout(function(){onResizeIE($(window))}, 100);
}

function register_timeout()
{
	if (g_registering)
	{
		g_registering = false;
		alert("The request timed out.  Please wait a minute before trying again.");
	}
	$("div#register-content-1, div#register-content-2").show(); 
	$("input#btn-register-2-submit").removeClass("gray").addClass("green");
	if ($.browser.msie) setTimeout(function(){onResizeIE($(window))}, 100);
}

function gatekeeper_result(in_data)
{
	clearTimeout(g_registering_timeout);
	g_registering = false;
	$("input#btn-register-2-submit").removeClass("gray").addClass("green");
	updateStatus("","");
	//alert(in_data);
	var l_data=parseXML(in_data);
	var l_xml=$(l_data);
	$(l_xml).find("gatekeeper").each(function(){
		$(this).find("failure").each(function(){
			var ask = $(this).attr("ask");
			switch (ask)
			{
				case "confirmation":
					gatekeeper_success();
					break;
				case "captcha":
					// show captcha error 
					$("#register-loading").hide();
					Recaptcha.reload();
					show_register_1();
					$("input#recaptcha_response_field").focus();
					$("div#captcha-error").show();
					updateStatus("Invalid entry.","");
					break;
				case "astra":
					// show astra account already taken 
					Recaptcha.reload();
					$("#register-loading").hide();
					$("input#register-username").addClass("error").focus();
					$("div#username-taken-error").show();
					updateStatus("Invalid entry.","");
					show_register_1();
					break;
				default:
					$("#register-loading").hide();
					alert($(this).text());
					Recaptcha.reload();
					updateStatus("Please try again.","");
					show_register_1();
					break;
			}
		});
		$(this).find("success").each(function(){
			var ask = $(this).attr("ask");
			gatekeeper_success();
		});
	});
	if ($.browser.msie) setTimeout(function(){onResizeIE($(window))}, 100);
	fixOpera();
}

function gatekeeper_success()
{
	updateStatus("Registration Complete!","");
	g_un = au.val();
	g_pw = ap.val();
	setTimeout(gatekeeper_signin, 1000);
	fixOpera();
	registered(g_network);
}

function gatekeeper_signin()
{
	signIn(au.val(), ap.val());
	if (g_network != 'astra')
	{
		findFlash("chat").mediumLogin(g_network, g_networkun, g_networkpw);
	}
}

function hide_register() 
{ 
	document.location.reload(true);
}

function show_recaptcha()
{
	try {
		Recaptcha.create("6Ldr9wEAAAAAACie7CCLhJjCGSB8-0FzKDiZQ9Zc", 'recaptcha_div', {
		    theme: "clean", 
		    callback: recaptcha_loaded
		});
	} catch(e) {
		setTimeout(show_recaptcha, 1000);
	}
	
}

function recaptcha_loaded()
{
	$("input#recaptcha_response_field").attr('tabindex', 3).keypress(function(a_event){ if (a_event.which == 13) show_register_2(); });
	$("table#recaptcha_table").css("border-right-width", "0px");
	if ($.browser.msie) $("div#recaptcha_div").height(140).parent().height(140);
	if (!$("input#register-email").val()) $("input#register-email").focus();
	if (!$("input#register-username").val()) $("input#register-username").focus();
	fixOpera();
}

function showAll()
{
	document.location.reload(true);
}

function impress(a_network)
{
	switch (a_network) { case 'astra': var a=12; break; case 'msn': var a=13; break; case 'yahoo': var a=14; break; case 'aim': var a=15; break; case 'facebook': var a=16; break; case 'google': var a=17; break; case 'icq': var a=18; break; case 'myspace': var a=19; break; case 'jabber': var a=20; break; default: return false; }
	$.ajax({url: "/client/ad/v1/?impression/3/3/" + a});
	return true;
}

function registered(a_network)
{
	switch (a_network) { case 'astra': var a=12; break; case 'msn': var a=13; break; case 'yahoo': var a=14; break; case 'aim': var a=15; break; case 'facebook': var a=16; break; case 'google': var a=17; break; case 'icq': var a=18; break; case 'myspace': var a=19; break; case 'jabber': var a=20; break; default: return false; }
	$.ajax({url: "/client/ad/v1/?click/3/3/" + a});
	return true;
}

function facebookAuthorizationRequest()
{
	setTimeout(fbStart, 100);
}

window.receivedmessage = function(a_val)
{
	alert('received message ' + a_val);
}

function fbStart()
{
	window.name = "Trillian";
	if (!g_fbincluded) 
	{
		g_fbincluded = true;
		var fbJsUrl = (("https:" == document.location.protocol) ? "https://ssl.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" : "http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/en_US");
		include(fbJsUrl, "js");
		setTimeout(fbStart, 1000);
		return;
	}
        var api = "567a2525dcc3c21f62a3f6d3fc7cc498";
        var xdc = "/chrome/facebook_xd_receiver.html";
        fbStartDialogWatch();
        FB.Bootstrap.requireFeatures(["Connect"], function()
        {
                FB.Facebook.init(api, xdc);
                FB.ensureInit(function() {
			//FB.Debug.logLevel = 6;
			if ($.browser.webkit && $.browser.version >= "534.10")
			{
				fbStartLocalStorageWatch();
				FB.dynData.site_vars.use_postMessage=1;
			}
                        if ($.browser.opera)
                        {
                                FB.Connect.showPermissionDialog("xmpp_login", askedpermission);
                        } else {
                                FB.Connect.requireSession(initted, cancelled, isUserActionHint=false);
                        }
                });
        });
}

function waitInitted()
{
	setTimeout(initted, 1000);
}

function cancelled()
{
	fbStopDialogWatch();
	setTimeout(function(){if (g_ready) findFlash("chat").facebookAuthorizationResult(false, {});}, 100);
}

function initted()
{
	FB.Connect.get_status().waitUntilReady( function( status ) {
		checkpermission();
	});
}

function checkpermission()
{
	FB.Facebook.apiClient.users_hasAppPermission("xmpp_login", gotpermission);
}
	
function askedpermission()
{
	setTimeout(function(){FB.Facebook.apiClient.users_hasAppPermission("xmpp_login", permissionresponse);}, 1000);
}

function permissionresponse(a_hasPermission)
{
	if ($.browser.msie) $("div.background").height($("div#container").height());
	if (a_hasPermission) 
	{
		setTimeout(fbsuccess, 1000);
		return true;
	}
	fbStopDialogWatch();
	setTimeout(function(){if (g_ready) findFlash("chat").facebookAuthorizationResult(false, {});}, 100);
}

function gotpermission(a_hasPermission)
{
	if (a_hasPermission) 
	{
		fbsuccess();
		return true;
	}
	FB.Connect.showPermissionDialog("xmpp_login", askedpermission);
}
	
function fbsuccess()
{
	var l_uid = FB.Facebook.apiClient.get_session().uid;
	var l_base_domain = FB.Facebook.apiClient.get_session().base_domain;
	var l_expires = FB.Facebook.apiClient.get_session().expires;
	var l_secret = FB.Facebook.apiClient.get_session().secret;
	var l_session_key = FB.Facebook.apiClient.get_session().session_key;
	var l_sig = FB.Facebook.apiClient.get_session().sig;
	var l_json = '{"session_key":"'+l_session_key+'", "uid":"'+l_uid+'", "expires":'+l_expires+', "secret":"'+l_secret+'","sig":"'+l_sig+'"}';
	if (g_ready) 
	{
		findFlash("chat").facebookAuthorizationResult(true, l_json);
	} else {
		FB.Facebook.apiClient.users_getInfo(l_uid,["name"],fbgotinfo);
	}
	fbStopDialogWatch();
}
function fbgotinfo(a_info, a_exception)
{
	if ($.browser.msie) $("div.background").height($("div#container").height());
	var l_name = a_info[0]['name'];
	g_fbname = l_name;
	$("input.facebookhelper, input.username[rel=facebook]").val(l_name);
	$("div.facebookbutton").fadeOut('fast');
	login();
}	

function fbStartLocalStorageWatch()
{
	if (g_fbwatch.lswtimer) return;
	try {
		localStorage.setItem("facebook_packet_string", null);
	}catch(e){
	}
	g_fbwatch.lswtimer = setInterval(fbLocalStorageWatch, 100);
}

function fbStopLocalStorageWatch()
{
	clearInterval(g_fbwatch.lswtimer);
	g_fbwatch.lswtimer = false;
}

function fbLocalStorageWatch()
{
	try { FB.XdComm.Server.singleton.unregisterDataHandler = function(a){ /* noop */ } } catch (e) { }
	try { 
		var l_packetstring = localStorage.facebook_packet_string;
	} catch(e) {
		fbStopLocalStorageWatch();
		return;
	}
	if (l_packetstring)
	{
		if (l_packetstring.length>5 && l_packetstring != "undefined") 
		{
			fbStopLocalStorageWatch();
			setTimeout(function(){FB.XdComm.Server.singleton.onReceiverLoaded(l_packetstring)}, 1000);
			localStorage.setItem("facebook_packet_string","-1");
			return;
		} 
	} else {
		return;
	}
	
}

function fbStartDialogWatch()
{
	if (g_fbwatch.handler) return;
	g_fbwatch.handler = setInterval(fbDialogWatch, 250);
}

function fbStopDialogWatch()
{
	clearInterval(g_fbwatch.handler);
	g_fbwatch.handler = false;
	$(".fb_popupContainer").remove();
	setTimeout(function(){if (g_fbwatch.faded) fbDialogWatch();}, 250);
}
function fbDialogWatch()
{
	if (g_fbwatch.faded) 
	{
		// Currently faded
		if (!$("table.fb_popup").length)
		{
			// Dialogs gone
			if (g_fbwatch.loginfaded)
			{
				// We faded login
				$("div#login-loading").show();
				g_fbwatch.loginfaded = false;
			}
			if (g_fbwatch.chatfaded && g_chatVisible)
			{
				// We faded chat
				if ($.browser.mozilla && ($.browser.version > '1.8' && $.browser.version < '1.9') || ($.browser.msie && $.browser.version >= '8.0'))
				{
					// FF2 fix
					document.getElementById('chat').style.width = '100%';
				} else {
					// Move onscreen
					$("div#index-chat").css("left", 0);
				}
				g_fbwatch.chatfaded = false;
			}
			if (!$.browser.mozilla || $.browser.version <= '1.8' || $.browser.version >= '1.9')
			{
				$("div#container").fadeTo('fast', 1);
			}
			g_fbwatch.faded = false;
		}
	} else {
		// Do we need to fade?
		if ($("table.fb_popup").length)
		{
			// Yes
			// Is login visible?
			if ($("div#login-loading").is(":visible"))
			{
				g_fbwatch.loginfaded = true;
				$("div#login-loading").hide();
			}
			// Is chat visible?
			if ($("div#index-chat").is(":visible") && g_chatVisible)
			{
				g_fbwatch.chatfaded = true;
				if ($.browser.mozilla && ($.browser.version > '1.8' && $.browser.version < '1.9') || ($.browser.msie && $.browser.version >= '8.0'))
				{
					// FF2 fix
					document.getElementById('chat').style.width = 1;
				} else {
					// Move offscreen and fade
					$("div#index-chat").css('left', -5000);
				}
			}
			if (!$.browser.mozilla || $.browser.version <= '1.8' || $.browser.version >= '1.9')
			{
				$("div#container").fadeTo(0, 0.9, function(){
					$("div#container").fadeTo(2500, 0.5);
				});
			}
			// Mark that we are currently faded
			g_fbwatch.faded = true;
		}
	}
}

function parseXML(a_xml)
{ 
	if(window.ActiveXObject && window.GetObject) 
	{ 
		var dom = new ActiveXObject('Microsoft.XMLDOM'); 
		dom.loadXML(a_xml); 
		return dom;
	}
	if(window.DOMParser)
		return new DOMParser().parseFromString(a_xml,'text/xml'); 
	throw new Error('No XML parser available'); 
} 

function isValidEmail(a_email){
	if (a_email.length < 6) return false;
	if (a_email.indexOf('..') != -1) return false;
	validRegExp = /^[^@ ]+@[^@]+\.+[a-z.]{2,}$/i;
	if (a_email.search(validRegExp) == -1) return false; 
	return true; 
}

function isValidUsername(a_username)
{
	if (a_username.length < 6) return false;
	if (a_username.length > 64) return false;
	if (a_username.indexOf('..') != -1) return false;
	validRegExp = /^[a-zA-Z][a-zA-Z0-9._]{1,62}[a-zA-Z0-9]$/;
	if (a_username.search(validRegExp) == -1) return false;
	return true;
}

function isValidUsernameForSignin(a_username)
{
	if (a_username.length < 3) return false;
	if (a_username.length > 64) return false;
	if (a_username.indexOf('..') != -1) return false;
	validRegExp = /^[a-zA-Z_][a-zA-Z0-9._-]{1,62}[a-zA-Z0-9.]$/;
	if (a_username.search(validRegExp) == -1) return false;
	return true;
}

function proto()
{
	if ("https:" == document.location.protocol) return "https:";
	return "http:";
}

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 include(a_filename, a_filetype)
{
	if (a_filetype=="js")
	{
		var l_file=document.createElement('script')
		l_file.setAttribute("type","text/javascript")
		l_file.setAttribute("src", a_filename)
	}
	else if (a_filetype=="css")
	{
		var l_file=document.createElement("link")
		l_file.setAttribute("rel", "stylesheet")
		l_file.setAttribute("type", "text/css")
		l_file.setAttribute("href", a_filename)
	}
	if (typeof l_file!="undefined")
		document.getElementsByTagName("head")[0].appendChild(l_file)
}


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-simple").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-simple, 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 = "2px";
		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").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").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;
		$("div#login-loading").hide();
		if (g_profileRequest)
		{
			findFlash("chat").showProfile(proto() + "//www.trillian.im/",g_profileRequest);
			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()
{
	var l_device = "WEB";
	signIn(g_un, g_pw, 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,1000);
}

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;
	g_un = a_user;
	g_pw = a_pass;
	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.trillian.im/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() {}

