/* ***************************************************************** */
/*                                                                   */
/* IBM Confidential                                                  */
/*                                                                   */
/* OCO Source Materials                                              */
/*                                                                   */
/* (C) Copyright IBM Corp. 2003, 2008                                */
/*                                                                   */
/* The source code for this program is not published or otherwise    */
/* divested of its trade secrets, irrespective of what has been      */
/* deposited with the U.S. Copyright Office.                         */
/*                                                                   */
/* ***************************************************************** */

var clientDebugWindow = false;

var STlinksVersion="Sametime8.5";

function getSTlinksVersion()
{
	return STlinksVersion;
}

var ICON_WIDTH=13;
var ICON_HEIGHT=16;
var autoLogin=false;
var ll_is=new browserInfo();
var ll_IDs=new Object();
var ll_linksCount=0;
var ll_linkTxt=new Object();
var ll_tip=new Object();
var ll_status=new Object();
var ll_desc=new Object();
var ll_options=new Object();
var ll_namesRes=";";
var ll_namesNoRes=";";
var llApplet,urlMain,urlPages,ns_appPath;
var STHost="";
var ll_displayNamesToSet = new Object();
var llAppletFound=false;
var llAppletStarted=false;
var sticn=new Object();
sticn[0]="offline";
sticn[0x8]="meeting";
sticn[0x20]="active";
sticn[0x40]="away";
sticn[0x60]="away";
sticn[0x80]="dnd";
sticn[0x208]="meetingMobile";
sticn[0x220]="activeMobile";
sticn[0x260]="awayMobile";
sticn[0x280]="dndMobile";
var ll_statusTip;
var countPlaces=new Array();
var STLANGS="en,zh,sv,pt,no,nl,ko,ja,it,fr,fi,es,de,da,zh_TW,pl,ru,pt_BR,cs,el,hu,tr,ar,he,iw";
// ca,th,sl,sk,ro,hr,kk
var STDEF_LANG="en";
var ll_loggedIn=false;

//flag that indicates if the web page need to pass the reverse proxy for using the sametime 
//server - do not change this variable.
var isRProxy=false;
// flag to support IPv6 for stlinks if the sametime server accepts connections to only IPv6 addresses
var enableIPv6=false;


/* flag to indicate whether stlinks is case-sensitive. do not change
unless appropriate server configuration is in place. default value is true.
if you set to this to false, sametime.ini [Config] will need to be updated with
AWARENESS_CASE_SENSITIVE=0 and also append
-DAWARENESS_CASE_SENSITIVE=0 to STLINKS_VM_ARGS
*/
var STlinksCaseSensitive=true;

//The following parameters need to be changed by the
//administrator in the case of a FIPS environment
var isFIPS_env = false;
var stFIPSKeyStore = "stkeystore.p12";
var stKeyStorePwd = "sametime";
var allowSelfSignedCerts = true;

//The following parameters need to be changed by the administrator
// in case of reverse proxy environment
//var ll_RProxyName="https://proxy.ibm.com";
//var ll_AffinityId="st1";

//var ll_TimeToSleep=1000;

// isTAM_env flag is sent to the STLinks applet.
// Possible values: 	false - for working in the not-TAM environment
//       		true - for working in the TAM environment

var isTAM_env = false;

// racingConnTimeout - Timeout between racing connections in milliseconds. The value is sent to the STLinks applet.
var racingConnTimeout = 500;

/* for TAM environment should be
 isTAM_env = true;
 racingConnTimeout = 5000;
*/

/*
05/08/2005
Debug code begin
*/
function debugMessage(type,objId,msg)
{
	this.m_type= type;
	this.m_objId = objId;
	this.m_msg = msg;
}

function systemObj(root)
{
	this.m_root = root;
	this.m_debugMode = false;
	this.m_debugwindow = null;
	this.m_DebugStringContainer = new Array();
	
	this.out = function(objId,msg)	
	{
		if (this.m_debugMode)	
		{
			try
			{
				this.m_debugwindow.system.out(objId,msg);
			}
			catch(err){}
		}
		else
		{
			this.m_DebugStringContainer.push(new debugMessage("out",objId,msg));
		}
	};
	
	this.error = function(objId,msg)
	{
		if ( this.m_debugMode == true )	
		{
			try
			{
				this.m_debugwindow.system.error(objId,msg);
			}
			catch(err){}
		}
		else
		{
			this.m_DebugStringContainer.push(new debugMessage("error",objId,msg));
		}
	};
	
	this.objectToString = function(objId,o)
	{
		try
		{
			this.out(objId,"Parsing object begin");
			for ( key in o)
			{
				if ( typeof(o[key]) !="function" )
				{
					this.out(key,typeof(o[key]) + " " + o[key]);
				}
				else 
				{
					this.out(key,typeof(o[key]) );
				}
			}
		
			this.out(objId,"Parsing object end");
		}
		catch(err){}
	};

	this.setDebugMode = function(flag)
	{
		this.m_debugMode = flag;
		if (flag)	
		{
			this.m_debugwindow = window.open("","debugWindow","scrollbars=yes,resizable=yes,menubar=no,status=no,directories=no,width=300,height=500");
			if ( typeof( this.m_debugwindow.system ) == "undefined" )
			{
				if (this.m_root != "")
				{
					this.m_debugwindow = window.open(this.m_root + "/log.htm","debugWindow","scrollbars=yes,resizable=yes,menubar=no,status=no,directories=no,width=300,height=500");
				}
			}
			if (this.m_DebugStringContainer.length >0)
			{
				for (var i = 0 ; i < this.m_DebugStringContainer.length ; i++)	
				{
					var tmpMsg = this.m_DebugStringContainer[i];
					switch(tmpMsg.m_type)
					{
						case "out":
							this.out(tmpMsg.m_objId,tmpMsg.m_msg);
						break;
						
						case "error":
							this.error(tmpMsg.m_objId,tmpMsg.m_msg);
						break;
					}
				}
			}
		}
	};
}

/* Debug code end */

///////////   Automatic Away Code /////////////////////////////////////

var g_nInterval = 600;
var g_nIntervalCounter = 0;
var g_fIsFirstTime = false;
var g_strLoginName = "";
var g_strLastToolTip = null;
var g_nLastMouseX = -1;
var g_nLastMouseY = -1;
var g_fIsAAActive = true;
var g_fIsSTDebug = false;
var g_stfIsAutoawayActivated = false;
var g_stfIsAutoawayManager = false;
var g_stfIsAutoawayOn = false;
var g_fIsFocus = true;
var g_isHasDummyParent = false;
var g_isAutoawayRunning = true;

//SPR- Auto-away will fail after modifying status message on Mozilla and Firefox (AM)
//addEvents (document, "onfocus", OnWindowFocus);
//addEvents (document, "onblur", OnWindowBlur);


function SetAutoawyInterval (nInterval) 
{
	g_nInterval = nInterval;
}

function addEvents (objAttachTo, strEventName, objFunction)
{
	try {
		var strEventPrefix = strEventName.substring(0, 2);
	
		if (strEventPrefix == "on") {
			strEventName = strEventName.substring(2, strEventName.length);
		}

		// Mozilla
		if (objAttachTo.addEventListener) {
			objAttachTo.addEventListener (strEventName, objFunction, true);
		}// IE
		else if (objAttachTo.attachEvent) {
			objAttachTo.attachEvent("on"+strEventName, objFunction);
		}
	}
	catch (e) {
		//alert ("stlinks.js addEvents() error: "+e.message);
	}
}

function log (strMessage)
{
	var strPreviousMsg = document.getElementById("txtDebug").value;
	strMessage = strPreviousMsg+"\n"+strMessage;
	document.getElementById("txtDebug").value = strMessage;
}


function STStartAutoawy () 
{
	try {
		if (g_nInterval != 0 && !g_stfIsAutoawayOn) {
			addEvents (document, "onmousemove", OnMouseMove);
			addEvents (document, "onmousedown", OnMouseMove);
			addEvents (document, "onkeypress", OnMouseMove);

			if (parent.frames.length != 0) {
				for (var i = 0; i < parent.frames.length; i++) {
					var nodeFrame = parent.frames[i];

					for (var j = 0; j < nodeFrame.frames.length; j++) {
						var nodeChildFrame = nodeFrame.frames[j];

						addEvents (nodeChildFrame, "onmousemove", OnMouseMove);
						addEvents (nodeChildFrame, "onmousedown", OnMouseMove);
						addEvents (nodeChildFrame, "onkeypress", OnMouseMove);
					}

					addEvents (nodeFrame, "onmousemove", OnMouseMove);
					addEvents (nodeFrame, "onmousedown", OnMouseMove);
					addEvents (nodeFrame, "onkeypress", OnMouseMove);
				}
			}

			g_stfIsAutoawayOn = true;
		}
	}
	catch (e) {
		//alert (e);
	}
}

function internal_ActiveAutoAway (fIsActive)
{
	g_stfIsAutoawayManager = fIsActive;
	STActivateThread ();
}

function STActivateThread ()
{
	if (g_stfIsAutoawayOn && g_stfIsAutoawayManager && !g_stfIsAutoawayActivated) {
		window.setTimeout (strSTAWFunction, 100);
		
		g_stfIsAutoawayActivated = true;
	}	
}

function LoginNameFixUp (strName) {
	try
	{
		system.out("STLinks","LoginNameFixUp :" + strName);
	}
	catch(err)
	{}
	var arName = strName.split ("%s");
	return arName[1];
}

function GetIntervalCounter () {

	var nIntervalCounter = 0;
	try {
		nIntervalCounter = window.parent.opener.g_nIntervalCounter;
		
		if (typeof(nIntervalCounter) != "undefined") {
			g_nIntervalCounter = nIntervalCounter;
		}
		else {
			nIntervalCounter = g_nIntervalCounter;
		}
	}
	catch (e) {
		nIntervalCounter = g_nIntervalCounter;
	}

	return nIntervalCounter;
}

var strSTAWFunction = function() {
	try {
		if (g_stfIsAutoawayManager) {
			var nStatus = STLinksMyStatus();

			if (GetIntervalCounter() > g_nInterval) {
				if (!g_fIsFirstTime && (nStatus != 128 && nStatus != 96 && nStatus != 8)) { 
					g_strLastToolTip = STLinksMyStatusMessage();
					STLinksSetMyStatus (64, LoginNameFixUp(TIP_AUTOAWAY));

					g_fIsFirstTime = true;
				}
			}
			else if (GetIntervalCounter() <= g_nInterval){			
				if (g_fIsFirstTime) {

					STLinksSetMyStatus(32, g_strLastToolTip);
					g_fIsFirstTime = false;
				}
			}

			if (g_fIsSTDebug) {
				document.getElementById("txtSTDebug").value = GetIntervalCounter();
			}

			g_nIntervalCounter++;
			
			if (g_isAutoawayRunning) {
				window.setTimeout (strSTAWFunction, 1000);
			}
		}
	} 
	catch (e){}
};

function getFatherObject ()
{
	var nodeFather = this.parent.opener;

	if (typeof nodeFather == "undefined") {
		nodeFather = this.parent;
	}
	else {
		try {
			var frameFather = nodeFather.parent;
	
			if (typeof frameFather != "undefined") {
				nodeFather = frameFather;
			}
		}
		catch(e){ }
	}

	return nodeFather;
}

function handleHasParent () 
{
	if (getFatherObject().g_fIsAAActive) {
		getFatherObject().zeroAutoawayCounter();
	}
	else {
		getFatherObject().g_fIsAAActive = true;
	}			
}

function handleHasNoParent ()
{
	if (g_fIsAAActive) {
		g_nIntervalCounter = 0;
	}
	else {
		g_fIsAAActive = true;
	}
}

function handleHasDummyParent ()
{
	if (g_fIsFocus && !g_isHasDummyParent) {
		g_isHasDummyParent = true;
		internal_ActiveAutoAway (true);
	}

	handleHasNoParent ();
}

function OnWindowFocus ()
{
	g_fIsFocus = true;
	g_isAutoawayRunning = true;
}

function OnWindowBlur ()
{
	g_fIsFocus = false;

	if (g_isHasDummyParent) {
		g_isHasDummyParent = false;
		g_isAutoawayRunning = false;
		
	}
}

function OnMouseMove (e) 
{	
	if (typeof (window.parent.opener) != "undefined") {
		try {
			handleHasParent ();
		}
		catch (e) {
			handleHasDummyParent ();
		}

	}
	else {
		handleHasNoParent ();
	}
}

function ccc ()
{
	var fIsTryFail = false;

	try {
		if (typeof (window.parent.opener.g_fIsAAActive) != "undefined") {
			if (window.parent.opener.g_fIsAAActive) {
				window.parent.opener.g_nIntervalCounter = 0;
			}
			else {
				window.parent.opener.g_fIsAAActive = true;
			}
		}
		else {
			if (g_fIsAAActive) {
				g_nIntervalCounter = 0;
			}
			else {
				g_fIsAAActive = true;
			}
		}
	} 
	catch (err) {
		fIsTryFail = true;
	}

	if (fIsTryFail) {
		try {
			var nLastMouseX = -1;
			var nLastMouseY = -1;
			var chLastChar = 0;
			
			if (ll_is.ie) {
				nLastMouseY = window.event.clientY;
				nLastMouseX = window.event.clientX;
				chLastChar = window.event.keyCode;
			}
			else {
				nLastMouseY = e.pageX;
				nLastMouseX = e.pageY;
				chLastChar = e.which;
			}

			var fIsMouse = false;

			if (
				nLastMouseX != g_nLastMouseX &&
				nLastMouseY != g_nLastMouseY &&
				g_nLastMouseX != -1 &&
				g_nLastMouseY != -1
				
			){
				g_nIntervalCounter = 0;
				fIsMouse = true;
			}
			
			if (
				chLastChar != 0 &&
				!fIsMouse
			){
				g_nIntervalCounter = 0;
			}

			g_nLastMouseX = nLastMouseX;
			g_nLastMouseY = nLastMouseY;
		}
		catch (e) {
			//alert ("error :: "+e.message);
		}
	}
}


function
SetPauseActivity (
){
	try {
		window.parent.opener.g_fIsAAActive = false;
	}
	catch (e) {
		g_fIsAAActive = false;
	}
}

///////////   Automatic Away Code /////////////////////////////////////

function browserInfo()
{
	var agent = navigator.userAgent.toLowerCase();
	this.major = parseInt(navigator.appVersion);
	this.ns = ((agent.indexOf('mozilla')!=-1) && ((agent.indexOf('spoofer')==-1) && (agent.indexOf('compatible') == -1)));
	this.ns6 = (agent.indexOf('netscape6')!=-1);
	this.ie = (agent.indexOf("msie") != -1);
	this.dom = ((agent.indexOf("msie") != -1) || (agent.indexOf("gecko")!=-1));
	this.win = (agent.indexOf("win")!=-1);
	this.nowin = (agent.indexOf("linux")!=-1 || agent.indexOf("sun")!=-1 || agent.indexOf("aix")!=-1 || agent.indexOf("mac")!=-1);
}

function escapeUnicodeMessage (strMessage) 
{
	try
	{
		system.out("STLinks","escapeUnicodeMessage  :" + strMessage);
	}
	catch(err)
	{}
	var strMSG = "";

	while (strMessage.match(/&#(\d+);/)) {
		var nCode = RegExp.$1;
		eval ("nCode=\"\\u" + convertToHex(nCode) + "\"");
		strMessage = strMessage.replace(/&#(\d+);/i, nCode);
	}

	try
	{
		system.out("STLinks","escapeUnicodeMessage  RESULT:" + strMessage);
	}
	catch(err)
	{}
	return strMessage;
}

function convertToHex (strCode)
{
	var strHex = "0000";

	try {
		var nDecimal = parseInt(strCode);
		strHex = nDecimal.toString(16);

		for (var i = strHex.length; i < 4; i++) {
			strHex = "0"+strHex;
		}
	}
	catch (e) {}

	return strHex;
}

function unicodeEscape(s)
{
	var ret = "";
	for(var i = 0 ; i < s.length ; i++)
		ret += s.charCodeAt(i).toString(16) + ",";
	return ret.substr(0, ret.length-1);	
}

function fromUnicode(s)
{
	var uniChars = s.match(/&#(\d{2,4});/g);
	if (uniChars == null)
		return s;
	for (var i = 0; i < uniChars.length; i++) {
		var c = uniChars[i];
		var code = c.substring(2,c.length-1);
		s = s.replace(c,String.fromCharCode(code))
	}
	return s;
}

function llOption(options,name,defVal)
{
	var a = (options.replace(/ /g,'')).split(";");
	for (var i=0; i<a.length; i++) {
		var pair = a[i].split('\:');
		if (pair[0].toLowerCase() == name.toLowerCase())
			return pair[1];
	}
	return defVal;	
}

function writeSametimeLink(id, txt, bResolve, options)
{
	try
	{
		system.out("STLinks","writeSametimeLink(" + id + "," +  txt + "," +  bResolve+ "," +  options + ")");
	}
	catch(err){}
	
	document.write(prepareSametimeLink(id,txt,bResolve,options));
}

function prepareSametimeLink(linkId, linkText, bResolve, options)
{
	try
	{
		system.out("STLinks","prepareSametimeLink(" + linkId + "," + linkText + "," +  bResolve + "," +  options + ")");
	}
	catch(err){}
	
	linkId = fromUnicode(linkId);
   
   if(!STlinksCaseSensitive) {
      linkId = linkId.toLowerCase();
   }
   
	var s = linkId.replace(/;/g,";;") + ";";
	if (bResolve == false) {
		if (ll_namesNoRes.indexOf(";"+s)==-1)
			ll_namesNoRes += s;
		if (ll_loggedIn)
			watchNames("",s);
	} 
	else if (ll_namesRes.indexOf(";"+s)==-1) {
		ll_namesRes += s;
		if (ll_loggedIn)
			watchNames(s,"");
	}			
	return prepareSametimeLinkNW(linkId, linkText, options);
}

function updateLinkStatus(linkId, stat, desc)
{
	try
	{
		system.out("STLinks","updateLinkStatus(" + linkId + "," +  stat + "," +  desc + ")");
	}
	catch(err){}
	
	ll_status[linkId] = stat;
	ll_desc[linkId] = desc;
	for(var tagId in ll_IDs[linkId]) {
		if (document.getElementById(tagId) != null) {
			var uname = ll_linkTxt[tagId];
			updateLinkHtml(tagId,linkId,stat, STLinksStatusTip(uname, stat, desc));
		}
	}
}

function offlineAllLinks()
{
	try
	{
		system.out("STLinks","offlineAllLinks()");
	}
	catch(err){}
	for(var id in ll_IDs)
		updateLinkStatus(id, 0); 
}

function onSTLinkClicked(linkId,tagId,event)
{
	try
	{
		system.out("STLinks","onSTLinkClicked(" + linkId + ","+ tagId + "," + event + ")");
	
		var browserInfo =  navigator.userAgent.toLowerCase();
		var isFirefox = browserInfo.indexOf('firefox');
		if ( typeof( STLinkClicked ) != "undefined")
		{
			system.out("STLinks","user STLinkClicked function is implemented ");	
			STLinksSetDisplayName(linkId, ll_linkTxt[tagId]);
			STLinkClicked(linkId, ll_linkTxt[tagId], ll_status[linkId], event);
			

		}	
		else if (llApplet!=null)
		{
			system.out("STLinks","onSTLinkClicked is NOT implemented , call: llApplet.createIm");		
			STLinksSetDisplayName(linkId, ll_linkTxt[tagId]);
			llApplet.createIm(linkId);
		}
	}
	catch(err){
		system.error("onSTLinkClicked",err.message)	;
	}
}

function LinkStatus(styleName, isLink)
{
	try
	{
		system.out("STLinks","Constructor: LinkStatus(" + styleName + "," +  isLink + ")");
	}
	catch(err){}
	
	this.styleName = styleName;
	this.isLink = isLink;
}

function getHREF(linkId, tagId, bOnline, bOfflineLink, bTip_NS)
{
	try
	{
		system.out("STLinks","getHREF(" + linkId + "," +  tagId + "," +  bOnline + "," +  bOfflineLink + "," +  bTip_NS + ")");
	}
	catch(err){}
	
	if (!bOnline && !bOfflineLink)
	{
		try
		{
			system.out("STLinks","getHREF(), !bOnline && !bOfflineLink, return ''");
		}
		catch(err){}
		return ""
	}
	else {
		// Jan 12, 2005
		// The problem was that if the username looks like "user1\, user" then the backslash is removed, and only comma remains
		linkId=linkId.replace(/\\/g, "\\\\");
		var act= "onSTLinkClicked('" + linkId.replace(/'/g, "\\'").replace(/"/g, "&quot;") + "','" + tagId +"',event)";
		var s =" href=\"javascript:" + act + "\" onclick=\"" + act + ";return false;\" oncontextmenu=\"return false\"";
		
		try
		{
			system.out("STLinks","getHREF(), return " + s);
		}
		catch(err){}
		return s;
	}
}

function getLinkTag(linkId, linkText, tagId, options)
{
	var tip = STLinksStatusTip(linkText, ll_status[linkId], ll_desc[linkId]);
	try
	{
		system.out("STLinks","getLinkTag(" + linkId + "," +  linkText + "," +  tagId + "," +  options+ ")");
		system.out("STLinks","getLinkTag(),tip = " + tip);
	}
	catch(err){}
	
	return '<SPAN ID="' + tagId + '">' + getInnerTag_IE(linkId, tagId, ll_status[linkId], tip, options) + '</SPAN>';
}

function getImgTag(statusType, tip, tagId)
{
	return "<img" + 
		((typeof tagId != "undefined") ? " name=" + tagId : "")  + 
		" border=0 align=absmiddle alt='" + tip.replace(/'/g, "&#039;") + 
		'\' src="'+ getImgUrl(statusType) +'" width=' + ICON_WIDTH + ' height=' + ICON_HEIGHT +">";
}

function getImgUrl(statusType)
{
	return urlPages + "/../img/" +
		((typeof sticn[statusType] == "undefined") ? sticn[0] : sticn[statusType]) + ".gif";
}

function updateLinkHtml(tagId,linkId,statusType,tip)
{
	var opt = ll_options[tagId];
	document.getElementById(tagId).innerHTML = getInnerTag_IE(linkId,tagId,statusType,tip,opt);
	try
	{
		system.out("STLinks","updateLinkHtml(" + tagId + "," + linkId + "," + statusType + "," + tip + ")");
	}
	catch(err){}
}

function getInnerTag_IE(linkId,tagId,statusType,tip,options)
{
	var styleName = statusType == 0 ? options.offlineStyle : options.onlineStyle;
	var s = '<nobr><A ' + getHREF(linkId, tagId, (statusType != 0), options.bOfflineLink) + 
		" title='"+tip.replace(/'/g, "&#039;")+"'" + ' CLASS="' + styleName + '">';
	if (!options.bText)
		s += getImgTag(statusType, tip);
	else if (!options.bIcon)
		s += ll_linkTxt[tagId];
   else s+= getImgTag(statusType, tip) + getIconSpace(options.iconSpace) + '<span dir="ltr">' + ll_linkTxt[tagId] + '</span>';
	return s + '</A></NOBR>';
}

function getIconSpace(n)
{
	var s = "<span class=iconSpace>";
	for (var i=0; i<n; i++)
		s += "&nbsp;";
	return s+"</span>";
}

function STLinksSetDisplayName(userName, displayName)
{
	if (llAppletStarted) {
		llApplet.setDisplayName(userName, displayName);
	}
	else {
		ll_displayNamesToSet[userName] = displayName;
	}
}

function showSendDeniedMsg(err, userName)
{
	if (typeof ERR_MSG[err] == "undefined") {
		alert(escapeUnicodeMessage (ERR_MSG["SEND_DENIED"]));
	}
	else { 
		alert(escapeUnicodeMessage (ERR_MSG[err].replace(/%s/gi, userName)));
	}
}

function showLogoutMsg(reason)
{
	alert(escapeUnicodeMessage (ERR_MSG["LOGOUT"]));
}

function fireEvent (cmd)
{
	try
	{
		system.out("STLinks","fireEvent (" + cmd + ")");
	}
	catch(err){}
	setTimeout(cmd,1);
}

// 	This function polls command string per time. 
// Applet puts the command using JSExecute command
function pollApplet()
{
	try {
		llApplet = document.applets["STLinksApp"];
		var cmd = "" + llApplet.getCommand();
		llAppletFound = true;
		
		if (cmd != "") {
			if (!ll_is.dom) {
				cmd = cmd.replace(/\\/g, "\\\\");
				cmd = cmd.replace(/"/g, "\\\"");
				eval(eval('"' + cmd + '"'));
			}
			else {
				setTimeout(cmd,1);
			}
		}
	}
	catch (e){}
}

function appletStarted()
{
	if (typeof ll_TimeToSleep != "undefined")
		llApplet.setTimeToSleepBeforeExit(parseInt(ll_TimeToSleep));
	// Nov 06, 2005:
	// Added printing of stlinks version
	// This will not work with Microsoft JVM
	// Nov 20, 2005: Added one more catch so it will work for Microsoft JVM
	try 
	{
		llApplet.debugPrintln("The stlinks js version is " + getSTlinksVersion());
    }
    catch (e) 
    {
		try 
		{
			llApplet.debugprintln("The stlinks js version is " + getSTlinksVersion());
		}
		catch (e) 
		{
		}
    }

	if ( autoLogin )
		llApplet.autoLogin();
	if (typeof STLinksAppletStarted == "function")
		STLinksAppletStarted();
		
	llAppletStarted = true;
	// set the display name that were gathered while the applet hasn't been
	// started yet
	for (userName in ll_displayNamesToSet) {
		llApplet.setDisplayName(userName, ll_displayNamesToSet[userName]);
	}
}

function appletLoggedOut (reason)
{
	try
	{
		system.out("STLinks","appletLoggedOut (" + reason + ")");
	}
	catch(err){}
	ll_loggedIn=false;
	for (var i=0; i<countPlaces.length; i++)
		st_placeCount(countPlaces[i].id,0);
	if (typeof STLinksLoggedOut=="function")
		STLinksLoggedOut(reason);
}

function appletLoggedIn(userId,displayName)
{
	try
	{
		system.out("STLinks","appletLoggedIn(" + userId + "," + displayName+ ")");
	
		ll_loggedIn=true;
		system.out("STLinks","appletLoggedIn step 1");
		try{
			
			if ( typeof(top.stlinksAppletUp ) == "function")
			{
				system.out("STLinks","appletLoggedIn step 1.1");
				top.stlinksAppletUp();
			}
		}
		catch(err)
		{
			system.error("appletLoggedIn, internal try",err.message)	;
		}
		system.out("STLinks","appletLoggedIn step 2");
		watchNames(ll_namesRes, ll_namesNoRes);
		for (var i=0; i<countPlaces.length; i++)
			llApplet.enterPlace(countPlaces[i].id,false,countPlaces[i].bDelay);
	
	
		system.out("STLinks","appletLoggedIn step 3");
		if (typeof STLinksLoggedIn == "function")
			STLinksLoggedIn(userId,displayName);
		system.out("STLinks","appletLoggedIn step 4");	
		if (!ll_is.dom) setTimeout("nsPlacesRefresh()",5000);	
		g_strLoginName = displayName;
		system.out("STLinks","appletLoggedIn step 5");	
		//SPR - WBLU7BA7TH 
		setTimeout("resetMyStatus()",4000);
	}
	catch(err)
	{
		system.error("appletLoggedIn",err.message)	;
	}
}

function resetMyStatus()
{	//SPR- ELEE74DB7W default status message not appearing on client UIMs
		if (STLinksMyStatus() == 32)
		STLinksSetMyStatus("32", TIP_ACTIVE_INIT);
}

var c_nsRefresh=0;
function nsPlacesRefresh()
{
	if (c_nsRefresh++<8)
	{
	 	setTimeout("nsPlacesRefresh()",5000);
	}
	for (var i=0;i<countPlaces.length;i++)
	{
		if (countPlaces[i].count!=0) st_placeCount(countPlaces[i].id,countPlaces[i].count);
	}
}

function userStatusChanged(userId,displayName,statusType,statusDesc,groupName)
{
	try
	{
		system.out("STLinks","userStatusChanged(" + userId + "," + displayName + "," + statusType + "," + statusDesc + "," + groupName + ")");
	}
	catch(err){}
//	var w = (typeof top.updateLinkStatus == "function") ? top : this;
//	w.updateLinkStatus(userId,statusType,statusDesc);
	updateLinkStatus(userId,statusType,statusDesc);
	if (typeof STLinksUserStatusChanged == "function")
		STLinksUserStatusChanged(userId,displayName,statusType,statusDesc,groupName); 
}

var lastOpenedImWinName = "";
var lastOpenedImWin = null;

function openImWindow (partnerId, partnerName, away, mobile, isSecured, winIndex, winName, isRecovery, inMeeting)
{
	if (winName == lastOpenedImWinName)
    {
		try 
		{
			if (lastOpenedImWin && lastOpenedImWin.open && !lastOpenedImWin.closed) 
			{
				return;
            }
        }
        catch (e) 
        {
        }
    }

	partnerName=unicodeEscape(partnerName);
	partnerId=unicodeEscape(partnerId);

	try
	{
		system.out(	"STLinks",
				"openImWindow (" + 
				"partnerId=" + partnerId + "," +
				"partnerName=" + partnerName + "," + 
				"away=" + away + "," + 
				"mobile=" + mobile + "," + 
				"isSecured="+ isSecured + "," + 
				"winIndex="+winIndex + "," + 
				"inMeeting="+inMeeting + "," + 
				"winName="+winName + ")"
			);
	}
	catch(err){}
	
	var isAnonymousAccessInfo = false;

	try {
		isAnonymousAccessInfo = appletFrame.llApplet.anonymousAccessInfo();
	}
	catch (e) {
		try {
			isAnonymousAccessInfo = appletFrame.llApplet.anonymousaccessinfo();
		}
		catch (e1) {}
	}

        lastOpenedImWinName = winName;
	lastOpenedImWin= open(urlPages+"/chatWindow.html?winType=IM&urlMain="+urlMain+"&PartnerName="+partnerName+
		"&partnerId="+partnerId+"&isSecured="+isSecured+(away ? "&away=1" : "")+(mobile ? "&mobile=1" : "")+
                (isRecovery ? "&isRecovery=1" : "") + (inMeeting ? "&inMeeting=1" : "")+ 
		"&meetings=" + (STLinksMeetingsEnabled() ? "1" : "0"), "IM_" + winName,
		"width="+WIN_IM_WIDTH+",height="+ WIN_IM_HEIGHT +
		",resizable=" + (!ll_is.dom? "no" : "yes") +
		",status=no,menubar=no,scrollbars=no,location=no,directories=no,top="+winIndex*20+",left="+winIndex*20);
	SetPauseActivity();
}

function openInviteWin(invitorName,chatId,isSecured,winIndex)
{
	try
	{
		system.out(	"STLinks",
				"openInviteWin(" + 
				"invitorName=" + invitorName + "," + 
				"chatId" + chatId + "," +
				"isSecured=" + isSecured + "," + 
				"winIndex=" + winIndex + ")"
			);
	}
	catch(err){}
	open(urlPages + "/chatWindow.html?winType=INVITE&urlMain="+urlMain+"&chatId="+chatId+"&invitor="+unicodeEscape(invitorName)+"&isSecured="+isSecured,"_blank","width="+WIN_INVITE_WIDTH+",height="+WIN_INVITE_HEIGHT+",status=no,resizable=yes,menubar=no,location=no,scrollbars=no,directories=no,top="+winIndex*20+",left="+winIndex*20);		
	SetPauseActivity();
}

function openAnnounceWin(name,id,allowResponse,winIndex)
{
	try
	{
		system.out("STLinks","openAnnounceWin(" + name + "," + id + "," + allowResponse + "," + winIndex + ")" );
	}
	catch(err){}
	open(urlPages + "/chatWindow.html?winType=ANNOUNCE&isSecured=0&urlMain="+urlMain+"&announcerId="+unicodeEscape(id)+"&announcerName="+unicodeEscape(name)+'&response='+allowResponse,"_blank","width="+WIN_INVITE_WIDTH+",height="+WIN_INVITE_HEIGHT+",status=no,resizable=yes,menubar=no,location=no,scrollbars=no,directories=no,top="+winIndex*20+",left="+winIndex*20);		
	SetPauseActivity();
}

function openStatusWindow()
{
	open(urlPages+"/changeStatus.html?urlMain="+urlMain,"_blank","width=330,height=290,status=no,menubar=no,scrollbars=no,resizable=yes,location=no,directories=no,top=100,left=100" );
}

function openNwayWindow(chatId,winIndex)
{
	try
	{
		system.out("STLinks","openNwayWindow(" + chatId + "," + winIndex + ")" );
	}
	catch(err){}
	var isAnonymousAccessInfo = "";

	try {
		isAnonymousAccessInfo = llApplet.anonymousAccessInfo();
	}
	catch (e) {
		try {
			isAnonymousAccessInfo = llApplet.anonymousaccessinfo();
		}
		catch (e1) {}
	}

	open(urlPages + "/chatWindow.html?winType=NWAY&isSecured=1&urlMain="+urlMain+"&chatId="+chatId+
	"&meetings=" + (STLinksMeetingsEnabled() ? "1" : "0") +isAnonymousAccessInfo, "_blank",
		"width="+WIN_NWAY_WIDTH+",height="+WIN_NWAY_HEIGHT+",status=no,menubar=no,scrollbars=no,resizable=yes,location=no,directories=no,top="+winIndex*20+",left="+winIndex*20); 
}

function openMeetingWin(url, winLeft, winTop, winW, winH, upgrade)
{
	try
	{
		system.out("STLinks","openMeetingWin(" + URL + "," +  winLeft + "," + winTop + "," + winW + "," + winH + "," +  upgrade + ")");
	}
	catch(err){}
	var newURL=url;
	if (llApplet.isUsingRProxy())
	{
		newURL = llApplet.getRProxyNameAndPort();
		var temp = url;
		if (url.indexOf("http")!=-1)
		{
			temp = url.substring(url.indexOf('/')+2);
			temp = temp.substring(temp.indexOf('/'));
		}
		newURL+=temp;
	}
	open(newURL, "_blank", "resizable=" + (!ll_is.dom ? "no" : "yes")+ 
			",status=no,menubar=no,scrollbars=no,location=no,directories=no,left=" + winLeft + ",top=" + winTop + ",width=" + winW + ",height=" + winH );
}

function alphanum(s){return escape(s).replace(/%/g,"_").replace(/\./g,"_").replace(/\//g,"_")};

function openPlaceWin(id, title)
{
	try
	{
		system.out("STLinks","openPlaceWin(" + id + "," + title + ")");
	}
	catch(err){}
	if (!ll_loggedIn) {
		alert(escapeUnicodeMessage (ERR_MSG["LOGOUT"]));
	}
	else open(urlPages + "/chatWindow.html"+"?winType=PLACE&urlMain="+urlMain+"&placeId="+unicodeEscape(id)+"&title="+unicodeEscape(title)+"&isSecured=1",alphanum(id),"width="+WIN_PLACE_W+",height="+
		WIN_PLACE_H+",status=no,resizable=yes,menubar=no,location=no,scrollbars=no,directories=no,top=100,left=100");		
}

function openPlaceChat(id, title)
{
	try
	{
		system.out("STLinks","openPlaceChat(" + id + "," + title + ")");
	}
	catch(err){}
	
	if (!ll_loggedIn) {
		alert(escapeUnicodeMessage (ERR_MSG["LOGOUT"]));
	}
	else open(urlPages + "/chatWindow.html"+"?winType=PLACE_CHAT&urlMain="+urlMain+"&placeId="+unicodeEscape(id)+"&title="+unicodeEscape(title)+"&isSecured=1",alphanum(id)+"chat","width="+WIN_PCHAT_W+",height="+
		WIN_PCHAT_H+",status=no,resizable=" + (ll_is.dom ? "yes" : "no") + ",menubar=no,location=no,scrollbars=no,directories=no,top=100,left=100");		
}

function writeSTLinksApplet(loginName, key, byToken, organization)
{
	try
	{
		system.out("STLinks","writeSTLinksApplet(" + loginName + "," +  key + "," + byToken + "," + organization + ")");
	}
	catch(err)
	{}
	
	if (! ll_platform())
		return;
	
	if (typeof(byToken) == "undefined")
		byToken = true; // the key is assumed to be a token

	if (g_fIsSTDebug) 
			document.writeln('<input type="text" id="txtSTDebug"><textarea id="txtDebug"></textarea>');
	
	var isTunneling = (typeof HTTP_TUNNELING_PORT != "undefined");

	var appletTag = prepareSTLinksApplet({
		server: STHost,
		port: (isTunneling ? HTTP_TUNNELING_PORT : undefined),
		username: loginName,
		password: (! byToken ? key : undefined),
		token: (byToken ? key : undefined),
		org: organization
	});

	document.writeln('<span style="position:absolute;left:0;top:0;visibility:hidden">' + appletTag + '</span>');
	
	try 
	{
		g_strLoginName = window.parent.opener.g_strLoginName;
	} 
	catch (err) 
	{}

	autoLogin = (loginName != null);

	if (g_nInterval != 0)
		STStartAutoawy();

	StartPolling();
}

function writePlaceCounter(placeId, title, bDelay)
{
	try
	{
		system.out("STLinks","writePlaceCounter(" + placeId + "," +  title + "," +  bDelay + ")");
	}
	catch(err){}
	var tag="ST_PLACE_"+countPlaces.length;
	document.write('<SPAN ID="' + tag + '">--</span>');
	p=new Object();
	p.id=placeId;
	p.title=title;
	p.bDelay=(typeof bDelay == "undefined")?false:bDelay;
	p.count=0;
	countPlaces[countPlaces.length++]=p;
	if (ll_loggedIn)
		llApplet.enterPlace(p.id,false,p.bDelay);
}

function st_placeCount(placeId,count)
{
	var ind=-1;
	for (var i=0;i<countPlaces.length;i++)
		if (countPlaces[i].id==placeId)
			ind=i;
	if (ind==-1) return;
	countPlaces[ind].count=count;	
	var s = (count==0) ? "--" : "<a href='javaScript:' onClick=\"openPlaceWin('" + placeId.replace(/(['"])/g,"\\$1") + "','" + countPlaces[ind].title.replace(/(['"])/g,"\\$1") + "');return false;\">" + count + "</a>";
	var tagId = "ST_PLACE_"+ind;
	document.getElementById(tagId).innerHTML = s;
}

function st_userJoined(id,name,placeId)
{
	try
	{
		system.out("STLinks","st_userJoined(" + id + "," + name + "," + placeId + ")");
	}
	catch(err){}
	if (typeof STLinksUserEnteredPlace != "undefined")
		STLinksUserEnteredPlace(id,name,placeId);
}

function st_userLeft(id,name,placeId)
{
	try
	{
		system.out("STLinks","st_userLeft(" + id + "," + name + "," + placeId + ")");
	}
	catch(err){}
	if (typeof STLinksUserLeftPlace != "undefined")
		STLinksUserLeftPlace(id,name,placeId);
}
function st_leftPlace(){};

function STLinksLogin(name, key, byToken, organization)
{
	try
	{
		system.out("STLinks","STLinksLogin(" + name + "," +  key + "," +  byToken + "," +  organization+ ")");
	}
	catch(err){}
	if (typeof organization == "undefined")
		organization="";
	llApplet.login(name, key, byToken, organization);
}

function STLinksLogout()
{
	try
	{
		system.out("STLinks","STLinksLogout()");
	}
	catch(err){}
	llApplet.logout();
}

function setSTLinksURL(main,lang,pages)
{
	try
	{
		system.out("STLinks","setSTLinksURL:" + main + "," + lang + "," + pages);
	}
	catch(err){}
	main = main.replace(/ *(.*)/i, "$1");
	if (typeof ll_RProxyName != "undefined")
	{
		var host = ll_RProxyName.substring(ll_RProxyName.indexOf('/')+2);
		if (host==document.location.hostname)
			isRProxy = true;
	}
	if (!isRProxy)
	{
		if ((main.search(/^https?:\/\//i) == -1) && (main.charAt(0) != '/'))
			main = "http://" + main;
	}
	urlMain=main;
	if ((typeof TUNNELING_ADDRESS != "undefined") && (TUNNELING_ADDRESS != "")) {
		if (urlMain.charAt(0) == '/')
			urlMain = "http://"+TUNNELING_ADDRESS+urlMain;		
		else urlMain = urlMain.replace(/ *(https?:\/\/)?[^\/]*\/(.*)/i, "$1" + TUNNELING_ADDRESS + "/$2");
	}
/*
	if (!isRProxy && ll_is.ns && urlMain.indexOf("http")!=-1)
	{
		var host = urlMain.substring(urlMain.indexOf('/')+2);
		if (host.indexOf(':')!=-1)
			host = host.substring(0,host.indexOf(':'));
		else if (host.indexOf('/')!=-1)
			host = host.substring(0,host.indexOf('/'));
		if (host!=document.location.hostname)
		{
			STHost = host;
			if (ns_appPath == null)
				ns_appPath = "sametime/stlinks";
			urlMain=document.location.protocol + "//" + document.location.host + "/" + ns_appPath;
		}
	}
*/
	if (isRProxy)
	{
		urlMain = urlMain.replace(/ *(.*)/i, "$1");
		var rel = urlMain;
		if (rel.indexOf("http")!=-1){
			rel = rel.substring(rel.indexOf('/')+2);
			rel = rel.substring(rel.indexOf('/')+1);
		}
		if (rel.substring(0,1) == "/")
		{
			rel = rel.substring(rel.indexOf('/')+1);
		}
		var affIdTest = rel.substring(0,rel.indexOf('/'));
		if (affIdTest == ll_AffinityId)
			rel = rel.substring(rel.indexOf('/')+1);
		urlMain = document.location.protocol + "//" + document.location.host;
		if (ll_AffinityId != "") 
			urlMain += "/" + ll_AffinityId;
		urlMain += "/" + rel;
	}
	if ((typeof lang == "undefined") || (lang == ""))
		lang=STDEF_LANG;
	else {
		if (STLANGS.toLowerCase().indexOf(lang.toLowerCase()) == -1) {
			lang=lang.substring(0,2);
			if (STLANGS.indexOf(lang) == -1)
				lang=STDEF_LANG;
		}
	}
	if (typeof pages == "undefined")
		urlPages=urlMain;
	else urlPages=pages;
	urlPages += "/" + lang;
	if (location.hostname.indexOf('.') == -1)
		urlPages = urlPages.replace(/(https?:\/\/)?(\w+)\.([^\/:]*)([\/:].*)/i, "$1$2$4");
		
	document.write('<SCRIPT src="' + urlPages + '/res.js"><\/SCRIPT>');
	document.write('<SCRIPT src="' + urlMain + '/hostInfo.js"><\/SCRIPT>');
	try
	{
		system = new systemObj( urlMain );
		system.setDebugMode( clientDebugWindow );
	}
	catch(er)
	{}
}

function StartPolling()
{
	try
	{
		system.out("STLinks","StartPolling()");
	}
	catch(err){}
	setInterval( "pollApplet()", 200);
}

function ll_platform()
{
	if (ll_is.ns && (ll_is.major >= 5) && !ll_is.ns6)
		return (ll_is.win || ll_is.nowin);
	else if (ll_is.ie && (ll_is.major >= 4))
		return ll_is.win;
	else return false;
}

function watchNames(resNames, noResNames)
{
	try
	{
		system.out("STLinks","watchNames: " + resNames + "," +  noResNames);
	}
	catch(err){}

	llApplet.watchUsers(resNames, true);
	llApplet.watchUsers(noResNames, false);
}

function privateGroupsResult(success, result)
{
	try
	{
		system.out("STLinks","privateGroupsResult: " + success + "," +  result);
	}
	catch(err){}

	if (success == 1) {
		if (typeof STLinksPrivateGroupsReceived != "undefined")
			STLinksPrivateGroupsReceived(result);
	}
	else if (typeof STLinksPrivateGroupsFailed != "undefined")
			STLinksPrivateGroupsFailed(result);
}

function STLinksStatusTip(uname, stat, desc)
{
	try
	{
		system.out("STLinks","STLinksStatusTip: " + uname + "," +  stat + "," +  desc );
	}
	catch(err){}
	var strStatus = "";

	if (stat == 0) {
		strStatus = TIP_OFFLINE.replace(/%s/gi, uname);
	}
	else if (stat == 64) {
		strStatus = TIP_AUTOAWAY.replace(/%s/gi, uname);
	}
	else if ((stat == 32) && (desc == "")) {

		if (g_strLastToolTip != null) {
			if (g_strLastToolTip != "") {
				strStatus = g_strLastToolTip;
			}
			else {
				strStatus = TIP_ACTIVE.replace(/%s/gi, uname);
			}
		}
		else {
			strStatus = TIP_ACTIVE.replace(/%s/gi, uname);
		}
	}
	else if (desc.indexOf("undefined") >= 0) {
		if (g_strLastToolTip != null) {
			strStatus = uname+":"+g_strLastToolTip;
		}
		else {
			var str = TIP_ACTIVE.replace(/%s/gi, "");
			strStatus = desc.replace(/undefined/gi, str);
		}
	}
	else {
		strStatus = uname + ": " + desc;
	}
	
	try
	{
		system.out("STLinks","STLinksStatusTip: strStatus=" + strStatus);
	}
	catch(err){}
	return strStatus;
}

function STLinksPageLoaded()
{
	try
	{
		system.out("STLinks","STLinksPageLoaded(), top.watchNames");
	}
	catch(err){}
	top.watchNames(ll_namesRes, ll_namesNoRes);
}

function STLinksMyStatus()
{
	/*
	try
	{
		system.out("STLinks","STLinksMyStatus: " +  llApplet.getStatusType());
	}
	catch(err){}
	*/
	return llApplet.getStatusType();
}

function STLinksMyStatusMessage()
{
	try
	{
		system.out("STLinks","STLinksMyStatusMessage - begin ");
	}
	catch(err){}
	
	var statusDesc = "";
	statusDesc  = llApplet.getStatusDesc();
	var strStatus = new String(statusDesc).toString();
	if (strStatus.indexOf("undefined") >= 0)
	{
		statusDesc = LoginNameFixUp(TIP_ACTIVE);
	}
	
	try
	{
		system.out("STLinks","STLinksMyStatusMessage: " + statusDesc);
	}
	catch(err){}
	
	return statusDesc;
}

function STLinksGetStatusType(){ return STLinksMyStatus(); }
function STLinksGetStatusDesc(){ return STLinksMyStatusMessage(); }

function STLinksSetMyStatus (stat, desc)
{
	try
	{
		system.out("STLinks","STLinksSetMyStatus : " + stat + "," + desc);
	}
	catch(err){}
	llApplet.setStatus(stat, desc);
}

function STLinksWatchGroups(groups)
{
	try
	{
		system.out("STLinks","STLinksWatchGroups: " + groups );
	}
	catch(err){}
	
	llApplet.watchGroups(groups);
}

function STLinksWatchUsers(users, bResolve)
{
	try
	{
		system.out("STLinks","STLinksWatchUsers: " + users + "," + bResolve);
	}
	catch(err){}

	llApplet.watchUsers(users, bResolve);
}

function STLinksResetList()
{
	try
	{
		system.out("STLinks","STLinksResetList()");
	}
	catch(err){}

	llApplet.resetList();
	ll_status = new Object();
	ll_desc = new Object();
}

function STLinksGetPrivateGroups()
{
	try
	{
		system.out("STLinks","STLinksGetPrivateGroups()");
	}
	catch(err){}
	llApplet.getPrivateGroups();
}

function STLinksAddToContactList(userName,group)
{
	try
	{
		system.out("STLinks","STLinksAddToContactList(" + userName + ","+ group + ")");
	
	}
	catch(err)
	{}
	
	llApplet.addToPrivateGroup(userName,group);
	
}

function STLinksCreateIM(partnerName)
{
	try
	{
		system.out("STLinks","STLinksCreateIM(" + partnerName + ")");
	
	}
	catch(err)
	{}
	try {
		llApplet.createIm(partnerName);
	}
	catch (e) {
		try {
			llApplet.createim(partnerName);
		}
		catch (e1) {}
	}
}

function STLinksCreateMeeting(invitees,tools,topic,msg)
{
	try
	{
		system.out("STLinks","STLinksCreateMeeting:" + invitees + "," + tools + "," + topic + "," + msg);
	
	}
	catch(err)
	{}
	llApplet.createMeeting(invitees,tools,topic,msg,false);
}

function STLinksEnterPlace(placeId, bDelay)
{
	try
	{
		system.out("STLinks","STLinksEnterPlace:" + placeId + "," + bDelay );
	}
	catch(err)
	{}
	llApplet.enterPlace(placeId, false, (typeof bDelay == "undefined")?false:bDelay);
}

function STLinksLeavePlace(placeId)
{
	try
	{
		system.out("STLinks","STLinksLeavePlace:" + placeId);
	}
	catch(err)
	{}
	llApplet.leavePlace(placeId, false);
}

function STLinksMeetingsEnabled()
{
	try
	{
		system.out("STLinks","STLinksMeetingsEnabled:" + llApplet.meetingsEnabled() );
	}
	catch(err)
	{}
	return llApplet.meetingsEnabled();
}

function STLinksAudioEnabled()
{
	try
	{
		system.out("STLinks","STLinksAudioEnabled:" + llApplet.audioEnabled() );
	}
	catch(err)
	{}
	return llApplet.audioEnabled();
}

function STLinksVideoEnabled()
{
	try
	{
		system.out("STLinks","STLinksVideoEnabled:" + llApplet.videoEnabled() );
	}
	catch(err)
	{}
	return llApplet.videoEnabled();
}

function STLinksStartCall(invitees, bResolve)
{
	try
	{
		system.out("STLinks","STLinksStartCall:" + invitees + "," + bResolve );
	}
	catch(err)
	{}
	llApplet.startCall(invitees, bResolve);
}

function setSTLinksNSCodeBase(codeBase)
{
	try
	{
		system.out("STLinks","setSTLinksNSCodeBase:" + codeBase );
	}
	catch(err)
	{}
	ns_appPath=codeBase;
}

function AddToContactListFailed(result)
{
	try
	{
		system.out("STLinks","AddToContactListFailed:" + result );
	}
	catch(err)
	{}
	
	if (typeof STLinksAddToContactListFailed != "undefined")
		STLinksAddToContactListFailed(result);
}

function prepareSametimeLinkNW(linkId, linkText, options, useSavedStatus)
{
	try
	{
		system.out("STLinks","prepareSametimeLinkNW:" + linkId + "," +  linkText + "," + options);
	}
	catch(err)
	{}
	
	if (typeof linkText =="undefined")
		linkText = linkId;
	if (typeof options == "undefined")
		options = "";
	var opt = new Object;
	opt.bText=(llOption(options,"text","yes").toLowerCase() == "yes");
	opt.bIcon=(llOption(options,"icon","yes").toLowerCase() == "yes");
	if (!opt.bText && !opt.bIcon)
		return;
	opt.bOfflineLink=(llOption(options,"offlineLink","no").toLowerCase() == "yes");
	opt.onlineStyle=llOption(options,"onlineStyle","online");
	opt.offlineStyle=llOption(options,"offlineStyle","offline");
	opt.iconSpace=llOption(options,"iconSpace",1);
	if (isNaN(parseInt(opt.iconSpace)))
		opt.iconSpace=1;
	if (!ll_platform()) {
		if (opt.bText)
			return(linkText); 
		else return "";
	}
	else {	
		if(!ll_IDs[linkId]){
			ll_IDs[linkId] = new Object();

			if ((typeof useSavedStatus == "undefined") || (useSavedStatus == false)) { 
				ll_status[linkId] = 0;
				ll_desc[linkId] = "";
			}
		}
		var tagId = "";
		var currTime = (new Date()).getTime();
		for(var oldTagId in ll_IDs[linkId]) {
			if (document.getElementById(oldTagId) != null)
				ll_IDs[linkId][oldTagId] = 0;
			else {
				if ((ll_IDs[linkId][oldTagId] == 0) || (currTime - ll_IDs[linkId][oldTagId] > 20000)) {
					tagId = oldTagId;
					break;
				}
			}
		}
		if (tagId == "")
			tagId = "LLZ_" + ll_linksCount++;
		ll_IDs[linkId][tagId] = currTime;
		ll_options[tagId] = opt;
		ll_linkTxt[tagId] = linkText;
		return getLinkTag(linkId,linkText,tagId,opt);
	}
}

function prepareSTLinksApplet(args)
{
	// NOTE: typically a call to ll_platform() would be made to make sure this is a supported
	// platform, but let's just let this function return the applet tag regardless if there's
	// an edge case that needs the tag generated.
	
	var applet = {
		attr: {
			codebase: eval(getVar("args['codebase']", urlMain)),
			name: eval(getVar("args['applet']", 'STLinksApp')),
			code: eval(getVar("args['class']", 'com.lotus.sametime.stlinks.client.STLinksApplet.class')),
			width: eval(getVar("args['width']", 10)),
			height: eval(getVar("args['height']", 10))
		},
		param: {
			archive: eval(getVar("args['archive']", 'stlinks.jar')),
			CaseSensitive: STlinksCaseSensitive,
			partnerName: 'main' + ((new Date).getTime() % 100000)
		}
	};
	
	if (ll_is.dom)
		applet.attr['mayscript'] = null;
   
	if (typeof(args['server']) != 'undefined' && args['server'] != '')
		applet.param['STHost'] = args['server'];
		
	//this is because only 1.6 JVM supports 'java_arguments' inside applet as a parameter
	applet.param['enableipv6'] = enableIPv6 ;
	
	if (typeof(args['port']) != 'undefined' && parseInt(args['port']) != 0)
		applet.param['port'] = args['port'];

	if (typeof(args['username']) != 'undefined') 
	{
		applet.param['loginName'] = args['username'].replace(/"/g, "&quot;");
		
		if (typeof(args['password']) != 'undefined') 
			applet.param['password'] = args['password'];
		else if (typeof(args['token']) != 'undefined')
			applet.param['token'] = args['token'];
	}
	
	if (typeof(args['org']) != 'undefined')
		applet.param['organization'] = args['org'].replace(/"/g, "&quot;");

	// Set reverse proxy URL
	if (isRProxy)
	{
		var proxyUrl = window.location.protocol + "//" + window.location.host;
		
		if (typeof(ll_AffinityId) != 'undefined' && ll_AffinityId != "")
			proxyUrl += "/" + ll_AffinityId;
			
		applet.param['RProxy'] = proxyUrl;
	}

	// send TAM_env and racingConnTimeout parameters to the applet
	if (typeof(isTAM_env) != 'undefined')
		applet.param['TAM_env'] = isTAM_env;

	if (typeof(racingConnTimeout) != 'undefined')
		applet.param['RacingTimeout'] = racingConnTimeout;
	
	// FIPS should be OFF by default
	if (eval(getVar('isFIPS_env', false)))
	{
		applet.param['FIPSEnabled'] = 'true';
		applet.param['stFIPSKeyStore'] = eval(getVar('FIPS_KEYSTORE_FILE', 'stkeystore.p12'));
		applet.param['stKeyStorePwd'] = eval(getVar('FIPS_KEYSTORE_PASSWORD', 'sametime'));
		applet.param['allowSelfSignedCerts'] = eval(getVar('FIPS_SELF_SIGNED_CERT', 'false'));
		applet.param['archive'] += eval(getVar('FIPS_JDK', ',sslite140-v3.16.zip'));
	}

	// Convert to HTML applet tag
	var attrs = '';
	var params = '';

	for (x in applet['attr'])
	{
		attrs += ' ' + x;

		if (applet['attr'][x] != null)
			attrs += '="' + applet['attr'][x] + '"';
	}
	
	for (x in applet['param'])
		params += '<param name="' + x + '" value="' + applet['param'][x] + '">\n';
	
	return '<applet' + attrs + '>\n' + params + '</applet>';
}

//-----------------------------------------------------------------------
//
//-----------------------------------------------------------------------
function dumpMap(map)
{
	var tmp = '';
	
	if (typeof map != "undefined")
	{
		tmp += ': ';
		
		for (x in map)
			tmp += x + '="' + map[x] + '" ';
	}
	
	return tmp;
}

//-----------------------------------------------------------------------
// This is a helper function to test and return a default value for 
// a varible. It's the equivelent of doing:
//
//		typeof(foo) != "undefined" ? foo : 'bar'
//
//	usage:
//		eval(getVar('foo')) returns null if foo isn't defined
//		eval(getVar('foo', 'bar')) returns 'bar' if foo isn't defined, otherwise the value of foo
//-----------------------------------------------------------------------
function getVar(varName, defaultValue)
{
	var a = 'null';
	
	if (typeof(defaultValue) == 'string')
		a = '"' + defaultValue + '"';
	else
		a = defaultValue;
	
	return 'typeof(' + varName +') != "undefined" ? ' + varName + ' : ' + a;
}

//-----------------------------------------------------------------------
// This is a helper function to avoid the pitfalls of
// misspelling "undifined" :)
//
//	usage:
//		eval(isdef('myVar'))
//-----------------------------------------------------------------------
function isdef(varName)
{
	return 'typeof(' + varName +') != "undefined"';
}

try
{
	system = new systemObj("");
	system.setDebugMode( clientDebugWindow );
}
catch(er)
{}
