// $Id: global.js,v 1.137 2010-04-13 15:03:25 jbesson 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);}}}
}

var applyOverrideJS = 'if (document.jsOverrides && document.jsOverrides[name]) {for (var i = 0; i < document.jsOverrides[name].length; i++) {try {eval (document.jsOverrides[name][i]);} catch (e) {}}}';

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;
var reqObjs = {};
var centralReqObjs = [];

function setup_global() {

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

	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');

	// 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 (!document.tnmtLobby) {
		document.tnmtLobby = {};
	}

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

	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);
}

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_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';
			}
		}

		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) {

		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 (!proceedCode || proceedCode == '') {
		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;
		}
	}

	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_els = document.getElementById('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 = '';

		site_tabs_in.style.display  = '';
		site_tabs_out.style.display  = 'none';

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

		// show welcome text
		var welcome_span = document.getElementById('top_nav_welcome');
		if (welcome_span) {
			if (State.login.nickname != '') {
				welcome_span.innerHTML = 'Welcome ' + State.login.first_name + ' (' + State.login.nickname + ')';
			} else {
				welcome_span.innerHTML = 'Welcome ' + State.login.first_name;
			}
		}

		// 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';
			}
		}

		// 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', 'window.location="' + profile_url + '"', null, promptText);
					return false;
				};
				if (document.check_nickname) {
					Nickname.showForm('nickname', null, '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 = '';

		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;

	if (aff_id != null || asset_id != null || tealeaf_id != null) {

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

		if (aff_id != null) {
			url += join_char + aff_arg + '=' + aff_id;
			join_char = '&';
		}

		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_str, perm) {

	if (document.isLobby) {
		return eval(func_str + '("' + perm + '")');
	} 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);
}


//
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) {

	try {
		if (typeof document.tnmtLobby.lobby === 'undefined' || document.tnmtLobby.lobby.ref.closed) {
			pu(document.scgiURL + '?action=go_tnmt_lobby&game_id=' + gameId, 'pu_tnmt_lobby', 'TnmtLobby');
		} else if (document.tnmtLobby.lobby.id == gameId) {
			document.tnmtLobby.lobby.ref.focus();
		} else {
			document.tnmtLobby.lobby.ref.focus();
			document.tnmtLobby.lobby.ref.TnmtLobby.req(parseInt(gameId));
		}
	} catch(e) {
		delete document.tnmtLobby.lobby;
		pu(document.scgiURL + '?action=go_tnmt_lobby&game_id=' + gameId, 'pu_tnmt_lobby', 'TnmtLobby');
	}
}

// !!!!!!!!!!!!!!!!!!!!! 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);
	}
}
