// $Id: global.js,v 1.152.2.2 2011-11-16 12:29:35 jrixon Exp $

// This is required by some browsers for the undefined test
var undefined;

// Check platform/browser
var agt=navigator.userAgent.toLowerCase();
var is_mac=(agt.indexOf("mac")!=-1);
var is_major=parseInt(navigator.appVersion);
var is_minor=parseFloat(navigator.appVersion);
var is_ie=((agt.indexOf("msie") != -1) && (agt.indexOf("opera")==-1));
var is_ie3=(is_ie && (is_major < 4));
var is_ie4=(is_ie && (is_major==4) && (agt.indexOf("msie 4")!=-1) );
var is_ie4up=(is_ie && (is_major >= 4));
var is_ie5=(is_ie && (is_major==4) && (agt.indexOf("msie 5.0")!=-1) );
var is_ie5_5=(is_ie && (is_major==4) && (agt.indexOf("msie 5.5") !=-1));
var is_ie5up=(is_ie && !is_ie3 && !is_ie4);
var is_ie5_5up =(is_ie && !is_ie3 && !is_ie4 && !is_ie5);
var is_ie6=(is_ie && (is_major==4) && (agt.indexOf("msie 6.")!=-1) );
var is_ie6up=(is_ie && !is_ie3 && !is_ie4 && !is_ie5 && !is_ie5_5);
var is_saf=(agt.indexOf("safari")!=-1);


// strip whitespace
var notspace=/\S/;
cleanWhitespace=function(node) {
if(node){for (var x=0; x<node.childNodes.length; x++) {var child=node.childNodes[x];/*if it's a whitespace text node=>*/if ((child.nodeType==3) && (!notspace.test(child.nodeValue))) {node.removeChild(node.childNodes[x]);x--;}/*elements can have text child nodes of their own=>*/if(child.nodeType==1) { cleanWhitespace(child);}}}
}

function init_onloads() {

	var i;
	for (i = 0; i < document.onloads.length; i++) {
		document.onloads[i]();
	}
}

sky.grabEvent.addBehaviour(
	init_onloads,
	'DOMLoaded',
	true,
	false,
	false,
	'init_onloads'
);

var Advert, State, BG, Login, Nickname, TnmtReg, TnmtPreReg, Quickplay, Focus, PhoneHome;
var reqObjs = {};
var centralReqObjs = [];

var childSandbox = {
	// the lobby child sandbox
	lobby : {
		dispLogin : function() {
			if (State) {
				// may be called by the app before this page has initialised fully
				dispLogin(false);
			}
		},
		showOverlayDialog : function(str) {
			sky.overlay.dialog(str);
		},
		hideOverlayDialog : function() {
			sky.overlay.destroy();
		},
		showGetChoiceOverlay : function(title, msg, buttons, clss) {
			sky.overlay.getChoice(title, msg, buttons, clss);
		},
		overlayButton : function(label, action, clss, id) {
			return sky.overlay.button(label, action, clss, id);
		},
		showHandHistory : function() {
			show_hand_history_air();
		},
		hideHandHistoryOnLogout : function() {
			hide_hand_history_onlogout();
		},
		hideFindPlayersOnLogout : function() {
			if(typeof FindPlayers === 'object') FindPlayers.hideOnlogout();
		},
		getStateLogin : function(prop) {
			if (State.login.hasOwnProperty(prop)) {
				return State.login[prop];
			}
			return undefined;
		},
		quickplay : function(
			name,
			qp_game_def_id,
			qp_limit_type,
			qp_reg_max,
			qp_buy_in,
			qp_tnmt_type,
			qp_avoid_nickname,
			qp_prev_game_id
		) {
			var qp_info = {
				'game_def_id':    qp_game_def_id,
				'limit_type':     qp_limit_type,
				'reg_max':        qp_reg_max,
				'buy_in':         qp_buy_in,
				'sng_type':       qp_tnmt_type,
				'avoid_nickname': qp_avoid_nickname,
				'prev_game_id':   qp_prev_game_id
			};

			return TnmtReg.showForm(
				'S',
				null,
				null,
				null,
				null,
				null,
				null,
				null,
				null,
				null,
				null,
				null,
				qp_info,
				name);
		},
		tnmtRegReq : function() {
			TnmtReg.req();
		},
		setCookie : function(cookie) {
			document.cookie = cookie;
		},
		getCookie : get_cookie,
		correctLinks : function() {
			// Add a window.open onclick to any links when:
			//  - href is non-js (doesn't start with 'javascript:' and doesn't end with '#');
			//  - doesn't already have an onclick event; and
			//  - doesn't have rel="external"
			// Clicking on these links would otherwise replace the lobby!
			var i       = 0,
				as      = document.getElementsByTagName('a'),
				a,
				len     = as.length,
				re_js   = /^javascript:/,
				re_hash = /[^#]$/;
			while (i < len) {
				a = as[i++];
				if (!re_js.test(a.href)
				 && re_hash.test(a.href)
				 && !a.onclick
				 && (!a.rel || a.rel !== 'external')
				) {
					a.onclick = function() {
						window.open(this.href);
						return false;
					};
				}
			}
		},
		openCashTable : function(tabId) {
			try {
				window.opener.State.openTable('S', 'T', tabId, {chkLogin : false, skipMaxWinCheck : true});
			} catch(e) {
				State.openTable('S', 'T', tabId, {chkLogin : false, trackWindow : false, skipMaxWinCheck : true});
			}
		},
		expectFundsReturn : function(noDelay) {
			BG.expectFundsReturn(noDelay);
		},
		phoneHome : function(action, params) {
			PhoneHome.req(action, params);
		}
	},
	// the tnmt popup child sandbox
	tnmt : {
		tnmtLobbyReq : function(gameId) {
			if (TnmtLobby.pub.gameId != gameId) {
				TnmtLobby.req(parseInt(gameId));
			}
		},
		stopComms : function() {
			TnmtLobby.stopComms();
		}
	},
	// the community popup child sandbox
	community : {
	}
};

function setup_global() {

	if (document.documentDomain != '') {
		document.domain = document.documentDomain;
	}

	if (window.parentSandboxBridge) {
		// test to see if we can set cookies directly or not
		// (all sandboxed windows need to know this)
		document.useCookieFix = false;
		set_cookie('cookieTest', 'success', '', '', '', false);
		if (get_cookie('cookieTest') != 'success') {
			document.useCookieFix = true;
		}

		if (document.isLobby) {
			window.childSandboxBridge = childSandbox.lobby;
			window.parentSandboxBridge.lobbyOnload(document.useCookieFix, document.login_cookie, document.secure_login_cookie);
		} else if (document.isTnmtLobby) {
			window.childSandboxBridge = childSandbox.tnmt;
			window.parentSandboxBridge.tnmtOnload();
		} else {
			// for now, the only non-lobby sandbox belongs to the community popup
			window.childSandboxBridge = childSandbox.community;
			window.parentSandboxBridge.communityOnload();
		}

		document._parentSandboxBridge = window.parentSandboxBridge;
	}

	if (document.cookieFix) {
		// tell the app that this document has loaded
		document.title = 'AIR~CookieFix:loaded';

		// local var to track which cookie we last handled
		var lastCookieFixId = '';

		// local function called frequently to check for new cookies
		var cookieFixFn = function() {

			setTimeout(cookieFixFn, 100);

			var re = navigator.userAgent.match(/^COOKIE:(\d+):(.+)$/);
			if (re) {
				var id = re[1];
				if (id != lastCookieFixId) {
					// actually set the cookie
					document.cookie = unescape(re[2]);

					// tell the app we've set the cookie
					document.title = 'AIR~CookieFix:' + id;

					// remember the id of the cookie we just set (we cannot
					// change userAgent here, only the app can do that)
					lastCookieFixId = id;
				}
			}
		}

		// kick off the cookie checking
		cookieFixFn();
		return;
	}

	Advert = AdvertLib();
	State = new StateClass();

	State.parseLogin();

	// click timer
	//
	sky.grabEvent.addBehaviour(
		function(el) {State.lastClick = new Date().getTime();DEBUG('clicked on ' + el.nodeName, 'red');},
		'click',
		function(el) {return true;},
		false,
		false,
		'lastClick');

	// prevent default behaviour of mousedown on the list rows in order to
	// prevent selecting of text when you double click on a row
	sky.grabEvent.addBehaviour(function(e){}, 'mousedown', function(el) {
		return sky.hasNodeName(el,'td') && el.parentNode.clickable;
	},true,true,'listRowMouseDown');

	// the above prevent default of mousedown has no effect on text selection
	// in IE so we use the IE-only technique of preventing default of its
	// onselectstart event. This is done on the whole lob_wrap div.
	if (typeof document.attachEvent != 'undefined' && document.getElementById('lob_wrap')) {
		document.getElementById('lob_wrap').attachEvent('onselectstart', function() {return false});
	}

	// clicking on list rows
	//
	sky.grabEvent.addBehaviour(listRowClick, 'click', function(el) {
		return sky.hasNodeName(el,'td') && el.parentNode.clickable;
	},true,true,'listRowClick');

	// dblclicking on list rows
	//
	sky.grabEvent.addBehaviour(listRowDblClick, 'dblclick', function(el) {
		return sky.hasNodeName(el,'td') && el.parentNode.clickable;
	},true,true,'listRowDblClick');

	// click on avatar or nickname inputs
	//
	sky.grabEvent.addBehaviour(
		function(el, evType, e) {
			var choice = document.getElementById("choice_el");
			if (choice != null) {
				choice.value = el.value;
			}
		},
		'click',
		function(el) {return sky.hasNodeName(el,'input') && (el.name == 'avatar' || el.name == 'nickname_suggest');},
		true,
		false,
		'nicknameInput');

	// click on avatar img (which pretends to be label)
	//
	sky.grabEvent.addBehaviour(
		function(el, evType, e) {
			var radio = el.firstChild.nextSibling;
			var choice = document.getElementById("choice_el");
			if (choice && radio && sky.hasNodeName(radio,'input')) {
				radio.checked = true;
				choice.value = radio.value;
			}
		},
		'click',
		function(el) {return sky.hasNodeName(el,'label') && el.firstChild && el.firstChild.id == 'avatar_img';},
		true,
		true,
		'avatarLabel');

	if (!document.openWindows) {
		document.openWindows = {};
	}

	if (typeof document.tnmtLobby === 'undefined') {
		// document.tnmtLobby keeps track of open tnmt lobbies:
		//  - max number of elements is document.max_tnmt_lobbies;
		//  - each element will have a value: { ref: window ref, id: game_id };
		//  - the array will be kept in order, with least-recently-used window at the front
		document.tnmtLobby = [];
	}

	TnmtReg = TnmtRegLib('TnmtReg');
	TnmtPreReg = TnmtPreRegLib('TnmtPreReg');
	Quickplay = QuickplayLib('Quickplay');
	PhoneHome = PhoneHomeLib('PhoneHome');

	if (!document.isAir && document.isLobby) {
		Focus = FocusLib();
		Focus.cfg(
			function(w) {
				var win = document.openWindows[w];
				if (win == null || win.closed) return false;
				win.focus();
				return true;
			},
			(document.autoFocusTables === "OLD")
		);
	}

	if (!document.isMainPage) {
		return;
	}

	State.lastClick = new Date().getTime();

	BG = BGLib('BG');
	Login = LoginLib('Login');
	Nickname = NicknameLib('Nickname');

	if (document.blank_lob_cookie) {
		set_cookie(document.lob_cookie, '', '', '/', '', '');
	}

	dispLogin();

	qp_on_load();

	if (!document.isLobby) {
		BG.doLoginUpd = true;
	}
	setTimeout(BG.poll, 2000);

	if (typeof document.check_user_agent !== 'undefined') {
		check_user_agent_func(document.check_user_agent);
	}
}

function listRowClick(el, evType) {

	if (typeof el.parentNode.parentNode.clickTR == 'function') {
		el.parentNode.parentNode.clickTR(el.parentNode);
	}
}

function listRowDblClick(el, evType) {

	if (typeof el.parentNode.parentNode.dblClickTR == 'function') {
		el.parentNode.parentNode.dblClickTR(el.parentNode);
	}
}

function pu(strURL, pu_class, win_name) {

	var strType, strWidth, strHeight, strOptions, tget;
	var pu_class = ' ' + pu_class + ' ';

	if (pu_class.match(' pu_help ')) {
		strType   = 'console';
		strWidth  = 760;
		strHeight = 500;
	} else if (pu_class.match(' pu_verisign ')) {
		strType   = 'console';
		strWidth  = 560;
		strHeight = 450;
	} else if (pu_class.match(' pu_mini_game ')) {
		strType   = 'fixed';
		strWidth  = 504;
		strHeight = 343;
	} else if (pu_class.match(' pu_small_game ')) {
		strType   = 'fixed';
		strWidth  = 810;
		strHeight = 600;
	} else if (pu_class.match(' pu_large_game ')) {
		strType   = 'fixed';
		strWidth  = 1020;
		strHeight = 600;
	} else if (pu_class.match(' pu_tnmt_lobby ')) {
		strType   = 'fixed';
		strWidth  = 850;
		strHeight = 520;
	} else if (pu_class.match(' pu_vegas_game ')) {
		strType   = 'vegas_game';
		strWidth  = 750;
		strHeight = 604;
	} else if(pu_class.match(' pu_acct_deposit ')) {
		strType   = 'elastic_simple';
		strWidth  = 800;
		strHeight = 600;
	} else {
		strType   = 'elastic';
		strWidth  = 700;
		strHeight = 400;
	}

	if (!win_name) {
		tget = 'newWin' + Math.floor(Math.random() * 20);
	} else {
		tget = win_name;
	}
	strOptions = "";

	if (strType == "console") {strOptions = "toolbar,resizable,scrollbars,height=" + strHeight + ",width=" + strWidth;}
	if (strType == "fixed")   {strOptions = "status,height=" + strHeight + ",width=" + strWidth;}
	if (strType == "elastic_simple") {strOptions = "scrollbars,resizable,location,height=" + strHeight + ",width=" + strWidth;}
	if (strType == "vegas_game") {strOptions = "resizable,height=" + strHeight + ",width=" + strWidth;}
	if (strType == "elastic") {strOptions = "toolbar,menubar,scrollbars,resizable,location,height=" + strHeight + ",width=" + strWidth;}

	return window.open(strURL, tget, strOptions);
}

function setCentre(reqObj) {

	if (State.isLobbyPage) {
		var i, obj, layout;

		if (typeof reqObj.getPageLayout == 'function') {
			layout = reqObj.getPageLayout();
		} else {
			layout = 'dflt';
		}

		if (layout == 'dflt') {
			if (document.getElementById('cntnt_c0')) {
				document.getElementById('cntnt_c0').style.display = 'none';
			}
			if (document.getElementById('cntnt_right')) {
				document.getElementById('cntnt_right').style.display = '';
			}
		} else if (layout == 'left') {
			if (document.getElementById('cntnt_c0')) {
				document.getElementById('cntnt_c0').style.display = '';
			}
			if (document.getElementById('cntnt_right')) {
				document.getElementById('cntnt_right').style.display = 'none';
			}
		} else if (layout == 'centre') {
			if (document.getElementById('cntnt_c0')) {
				document.getElementById('cntnt_c0').style.display = 'none';
			}
			if (document.getElementById('cntnt_right')) {
				document.getElementById('cntnt_right').style.display = 'none';
			}
		}

		if (document.isAir) {
			if (layout == 'centre') {
				sky.removeClass(document.getElementById('cntnt'), 'lyt2');
				sky.addClass(document.getElementById('cntnt'), 'lyt3');
				sky.addClass(document.getElementById('cntnt_middle'), 'maxwidth');
			} else {
				sky.removeClass(document.getElementById('cntnt'), 'lyt3');
				sky.addClass(document.getElementById('cntnt'), 'lyt2');
				sky.removeClass(document.getElementById('cntnt_middle'), 'maxwidth');
			}

			// Apply class to body
			var c, classes = {
				'TableList'     : 'lobby_cash',
				'TnmtList'      : 'lobby_tnmt',
				'MySelns'       : 'lobby_my_selns',
				'HandHistory'   : 'lobby_handhist',
				'CurrentLeague' : 'lobby_league'
			}
			for (c in classes) {
				if (reqObj.pub.name === c) {
					sky.addClass(document.getElementsByTagName('body')[0], classes[c]);
				} else {
					sky.removeClass(document.getElementsByTagName('body')[0], classes[c]);
				}
			}
		}

		if (State.centre && State.centre != reqObj) {
			State.centre.dispCentre(false);
		}
		reqObj.dispCentre(true);
	}

	State.centre = reqObj;
}

function refreshIcon(show) {

	var lobstate = sky.id('lobstate');
	if (!lobstate) {return;}

	if (show) {
		sky.addClass(lobstate, 'lobstate_on');
	} else {
		sky.removeClass(lobstate, 'lobstate_on');
	}
}

function chkLogin(proceedCode) {

	State.parseLogin();

	if (!State.login.logged_in) {

		if (window.parentSandboxBridge) {
			window.parentSandboxBridge.showLogin();
		} else {
			Login.showPopupForm();
		}

		return false;
	}

	if (State.login.temp_auth) {
		sky.overlay.doAlert('Temporary PIN', 'You must reset your PIN before proceeding', 'warning');
		return false;
	}

	if (State.login.temp_reg) {
		sky.overlay.doAlert('Partial registration', 'You must complete your registration before proceeding', 'warning');
		return false;
	}

	if (State.login.blocked) {
		sky.overlay.doAlert('Blocked from poker', getBlockTableXlation(), 'warning');
		return false;
	}

	if (typeof proceedCode !== 'function') return true;

	if (State.login.nickname == '') {
		Nickname.showForm('nickname', proceedCode);
		return false;
	}

	if (State.login.avatar == '') {
		Nickname.showForm('avatar', proceedCode);
		return false;
	}

	return true;
}

function idleEnter() {

	State.idle = true;

	for (objName in reqObjs) {
		reqObjs[objName].Req.idleEnter();
	}

	sky.grabEvent.addBehaviour(
		idleLeave,
		'mouseover',
		function(el) {return true;},
		false,
		false,
		'idleLeave1');

	sky.grabEvent.addBehaviour(
		idleLeave,
		'click',
		function(el) {return true;},
		false,
		false,
		'idleLeave2');
}

function idleLeave() {

	State.idle = false;

	sky.grabEvent.removeBehaviour(
		'mouseover',
		'idleLeave1');

	sky.grabEvent.removeBehaviour(
		'click',
		'idleLeave2');

	for (objName in reqObjs) {
		reqObjs[objName].Req.idleLeave();
	}

	State.lastClick = new Date().getTime();
}

function dispLogin(partial, errorMsg) {

	if (!document.isMainPage) {
		return;
	}

	if (State.loginDisp.timer != null) {
		clearTimeout(State.loginDisp.timer);
	}

	State.loginDisp.timer = setTimeout('dispLogin(true)', State.loginDisp.refresh);

	if (document.idleTimeout > 0 && !State.idle && new Date().getTime() - State.lastClick > document.idleTimeout) {
		idleEnter();
	}

	State.parseLogin();

	if (partial && State.loginDisp.logged_in != null) {
		if (State.login.logged_in == State.loginDisp.logged_in) {
			return;
		}
	}

	// Pass the logged_in state to the AIR app
	if (window.parentSandboxBridge) {
		window.parentSandboxBridge.updateStateLogin(State.login.logged_in);
	}

	State.loginDisp.logged_in = State.login.logged_in;

	var rightin_div = document.getElementById('cntnt_right_in');
	var rightout_div = document.getElementById('cntnt_right_out');
	if (rightin_div && rightout_div) {
		rightin_div.style.display  = State.login.logged_in ? '' : 'none';
		rightout_div.style.display = State.login.logged_in ? 'none' : '';
	}

	var in_div  = document.getElementById('logged_in_div');
	var out_div = document.getElementById('logged_out_div');
	var login_err_div = document.getElementById('login_err_div');

	var header_community_link = document.getElementById('header_community_link');

	var site_tabs_div = document.getElementById('site_tabs_div');
	if (site_tabs_div) {
		var site_tabs_els = site_tabs_div.childNodes;
		var site_tabs_in, site_tabs_out;
		for (var i = 0; i < site_tabs_els.length; i++) {
			if (sky.hasNodeName(site_tabs_els[i],'ul')) {
				if (!site_tabs_in) {
					site_tabs_in = site_tabs_els[i];
				} else {
					site_tabs_out = site_tabs_els[i];
					break;
				}
			}
		}
	}

	if (!in_div || !out_div || !login_err_div) {return;}

	if (State.login.logged_in) {
		// show/hide the divs
		in_div.style.display  = '';
		out_div.style.display = 'none';
		login_err_div.style.display = 'none';
		login_err_div.innerHTML = '';

		if (site_tabs_div) {
			site_tabs_in.style.display  = '';
			site_tabs_out.style.display  = 'none';
		}

		sky.addClass(sky.elems('body')[0],'logintrue');

		// show welcome text for web or AIR
		var welcome_span = document.getElementById('top_nav_welcome');
		if (welcome_span) {
			if (State.login.nickname != '') {
				welcome_span.innerHTML = ['Welcome ', State.login.first_name,
					' <span>(', State.login.nickname, ')</span>'].join('');
			} else {
				welcome_span.innerHTML = ['Welcome ', State.login.first_name].join('');
			}
		}

		// show last login date
		var last_login_span = document.getElementById('last_login');
		if (last_login_span) {
			if (State.login.last_login != '') {
				var last_login = State.login.last_login.split("_");
				last_login_span.innerHTML = '. Last login: ' + last_login[0] + ' at ' + last_login[1];
			} else {
				last_login_span.innerHTML = '&nbsp;';
			}
		}


		// display balance
		if (sky.balance && sky.balance.set) {
			sky.balance.set(State.login.disp_balance);
		}

		// show temp_auth warning
		var temp_auth_span = document.getElementById('temp_auth_span');
		if (temp_auth_span) {
			if (State.login.temp_auth) {
				temp_auth_span.style.display = '';
			} else {
				temp_auth_span.style.display = 'none';
			}
		}

		// show temp_reg warning
		var temp_reg_span = document.getElementById('temp_reg_span');
		if (temp_reg_span) {
			if (State.login.temp_reg) {
				temp_reg_span.style.display = '';
			} else {
				temp_reg_span.style.display = 'none';
			}
		}

		// show blocked warning
		var blocked_span = document.getElementById('blocked_span');
		if (blocked_span) {
			if (State.login.blocked) {
				blocked_span.style.display = '';
			} else {
				blocked_span.style.display = 'none';
			}
		}

		if (header_community_link) {
			// set the community profile link
			// (use getAttribute to prevent browser lying about a blank href)
			var profile_url = header_community_link.getAttribute('href');
			if (profile_url != '') {
				profile_url += '&plckUserId=' + State.login.cust_id;

				if (State.login.nickname != '') {
					header_community_link.onclick = function () {
						window.location = profile_url;
						return false;
					};
				} else {
					var promptText = 'Before you join in you need to create a Poker Alias.';
					header_community_link.onclick = function () {
						Nickname.showForm('nickname', function() { window.location = profile_url; }, null, promptText);
						return false;
					};
					if (document.check_nickname) {
						Nickname.showForm('nickname', null, function() { document.check_nickname = false; }, promptText);
					}
				}
				header_community_link.style.display = '';
			} else {
				header_community_link.style.display = 'none';
			}
		}

	} else {
		// show/hide the divs
		in_div.style.display  = 'none';
		out_div.style.display = '';

		if (site_tabs_div) {
			site_tabs_in.style.display  = 'none';
			site_tabs_out.style.display  = '';
		}

		sky.removeClass(sky.elems('body')[0],'logintrue');

		if (typeof errorMsg == 'string' && errorMsg != '') {
			// display login error
			login_err_div.innerHTML = errorMsg;
			login_err_div.style.display = '';
		} else if (State.login.disp_login_status != '') {
			// display login error from cookie
			login_err_div.innerHTML = State.login.disp_login_status;
			login_err_div.style.display = '';
		}

		autoUsername('main');
	}

	if (typeof(UpdPrefs) != 'undefined') {
		UpdPrefs.dispLeagueOptOut();
	}
}

// submit the login form, and remember username if specified
function submitLogin(el) {

	try {
		Login.req('main',el);
	} catch(e) {
		return true;
	}
	return false;
}

// pre-fill username and set checkbox from cookie
function autoUsername(formType) {

	// we do nothing if we can't find the dom objects or the username
	// textbox already has something in it
	var form;
	if (formType == 'main') {
		form = document.forms['fmLogin'];
	} else if (formType == 'popup') {
		form = document.forms['popupLoginForm'];
	} else {
		return;
	}
	var chk  = document.getElementById('remember_me');
	if (!form || !chk) {return;}

	var uname = form.uname;
	if (!uname || uname.value != "") {return;}

	var username = get_cookie(document.remember_me_cookie);

	if (username) {
		uname.value = username;
		chk.checked = true;
	} else {
		chk.checked = false;
	}
}

function rememberMeClk(chk) {

	// blank cookie if user unchecks
	if (!chk.checked) {
		set_cookie(document.remember_me_cookie, '', '', '/', '', '');
	}
}

// append args when moving between domains
function changeDomain(url) {

	var aff_id      = get_cookie(document.aff_cookie);
	var asset_id    = get_cookie(document.asset_cookie);
	var tealeaf_id  = get_cookie(document.tealeaf_cookie);

	var aff_arg     = document.aff_arg;
	var asset_arg   = document.asset_arg;
	var tealeaf_arg = document.tealeaf_arg;

// are there already params on the query string?
	if (aff_id != null || asset_id != null || tealeaf_id != null) {

		var join_char = '?';
		if (url.indexOf('?') != -1) {
			join_char = '&';
		}

		// do we need to add the aff_id?
		if (aff_id != null) {
			url += join_char + aff_arg + '=' + aff_id;
			join_char = '&';
		}

		// do we need to add the asset_id?
		if (asset_id != null) {
			url += join_char + asset_arg + '=' + asset_id;
		}

		// do we need to add the tealeaf_id?
		if (tealeaf_id != null) {
			url += join_char + tealeaf_arg + '=' + tealeaf_id;
		}
	}

	return url;
}


function lobby_action(func, func_str, perm) {

	if (document.isLobby && typeof func.req === 'function') {
		func.req(perm);
		return false;
	} else {
		var listType = func_str.split('.')[0];

		if (listType == 'MySelns' && perm.split(',')[0] == 'my_selns') {
			if (!chkLogin('')) {
				return false;
			}
		}

		document.location.href = document.scgiURL + '?action=go_lobby&listType=' + listType + '&listParams=' + perm;
		return false;
	}
}


//
function is_firefox() {

	return (navigator.userAgent.toLowerCase().indexOf("firefox") != -1);
}


//
function is_windows() {

	return (navigator.userAgent.toLowerCase().indexOf("windows") != -1);
}


// arr.ttl - pop-up title
// arr.txt - pop-up text
// arr.ok  - 'ok' text
// arr.ccl - 'cancel' text
// arr.url - redirect url when cancel button pressed
function check_user_agent_func(arr) {

	if (!is_windows() && !is_mac) {
		sky.overlay.getChoice(
			arr.ttl,
			arr.txt,
			[	sky.overlay.button(arr.ok,  function() {}),
				sky.overlay.button(arr.ccl, function() {window.location = arr.url;})
			]
		);
	}
}


//
function num_open_windows() {

	var win, num = 0;
	for (var id in document.openWindows) {
		win = document.openWindows[id];
		try {
			if (win && win.location && !win.closed) {
				num++;
			}
		} catch(e) {}
	}

	return num;
}


//
function getOpenWindows() {

	return document.openWindows;
}

function openTnmtLobby(gameId) {

	gameId = parseInt(gameId);

	if (window.parentSandboxBridge) {
		window.parentSandboxBridge.popupTnmt(gameId);
	} else {
	
		var i, len;
		
		// Work out which lobby window to use:
		
		//  1. First, purge any closed windows from the list
		for(i = document.tnmtLobby.length; i--; ) {
			if(typeof document.tnmtLobby[i].ref === 'undefined' || document.tnmtLobby[i].ref.closed) {
				document.tnmtLobby.splice(i, 1);
			}
		}
		len = document.tnmtLobby.length;

		//  2. If the lobby already exists, focus it.
		for(i = len; i--; ) {
			if(document.tnmtLobby[i].id === gameId) {
				document.tnmtLobby[i].ref.focus();
				_moveToEnd(document.tnmtLobby, i);
				return;
			}
		}
		
		//  3. If have not used max num of lobbies, create a new one
		if(len < document.max_tnmt_lobbies) {
			document.tnmtLobby[len] = {
				id:  gameId,
				ref: pu(
					[document.scgiURL, '?action=go_tnmt_lobby&game_id=', gameId, '&guid=', document.guid].join(''),
					'pu_tnmt_lobby',
					['TnmtLobby', gameId].join('')
				)
			};
			return;
		}
		
		//  4. Re-use the least-recently-used window
		document.tnmtLobby[0].id = gameId;
		document.tnmtLobby[0].ref.TnmtLobby.req(gameId);
		document.tnmtLobby[0].ref.focus();
		_moveToEnd(document.tnmtLobby, 0);
	}
}


// Move arr[pos] to the end of the array
//
function _moveToEnd(arr, pos) {

	var v = arr.splice(pos, 1)[0];
	arr[arr.length] = v;
}


// !!!!!!!!!!!!!!!!!!!!! delete for live! ?????????????????????
function DEBUG(str, colour) {

	if (document.debug) {
		var ul = document.getElementById('debug');
		var li = document.createElement('li');
		if (colour) {
			li.style.color = colour;
		}
		str = new Date().getTime().toString() + " " + str;
		li.innerHTML = str;
		ul.appendChild(li);
		document.getElementById('debug_div').scrollTop = 100000;
	}
}

function DEBUG_CLICK() {

}

function DEBUG_TEXT() {

	var txt = document.getElementById('debug_text');
	if (txt.value.length > 0) {
		DEBUG("evaling: " + txt.value);
		eval(txt.value);
	}
}

