/*
* $Header: /cvsroot/sig/www/js/ob/global.js,v 1.24 2010-02-13 15:28:02 pcotton Exp $
* Copyright (c) 2008 Orbis Technology Ltd. All rights reserved.
*/

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

// Global variables
var agt=navigator.userAgent.toLowerCase();
var is_ie  = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
var is_ie6 = (is_ie && (agt.indexOf("msie 6.") != -1) );
var is_ie7 = (is_ie && (agt.indexOf("msie 7.") != -1) );
var is_aol = (agt.indexOf("aol") != -1);
var is_nav = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1) && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1) && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1) && (agt.indexOf('firefox')==-1));
var is_ffx = (agt.indexOf("firefox") != -1);
var is_saf = (agt.indexOf("safari") != -1)
var is_opera = (agt.indexOf("opera") != -1);
var is_mac = (agt.indexOf("mac")!=-1);
var is_win = ( (agt.indexOf("win")!=-1) || (agt.indexOf("16bit")!=-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);}}}
}

// Debug functions
var debug = typeof window.debug !== "undefined" ? window.debug : {
	DEBUG : function (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;
		}
	},
	DEBUG_CLICK : function () {
	},
	DEBUG_TXT : function () {
		var txt = document.getElementById('debug_text');
		if (txt.value.length > 0) {
			debug.DEBUG("evaling: " + txt.value);
			eval(txt.value);
		}
	}
}

// Login object
var login = typeof window.login !== "undefined" ? window.login : {
	cookie          : '',
	logged_in       : false,
	message         : '',
	temp_auth       : false,
	status          : '',
	display_status  : '',
	ovs_status      : '',
	ovs_failed      : false,
	ovs_failed_all  : false,
	ovs_failed_xfer : false,
	acct_locked     : false,
	cust_id         : null,
	acct_id         : null,
	username        : '',
	ccy_code        : '',
	balance         : '',
	prefs           : '',
	init            : function() {
		this.cookie = get_cookie(document.login_cookie);
	},
	getToken        : function() {

		this.parseLogin(false);

		if (login.logged_in) {

			// double check with server
			check_login_status('false');

			if (login.logged_in)
				return get_cookie(cust_login_cookie_name);
			else
				return false;
		} else {
			return false;
		}
	},
	hasWhitelistedReferURL : function() {
		return (get_cookie(cust_has_referal) === '1');
	},
	isLoggedIn      : function() {

		this.parseLogin(false);
		if (typeof onload_wait == "undefined") {
			onload_wait = false;
		}

		if (this.logged_in && !onload_wait) {
			// double check with server
			check_login_status('false');
			return login.logged_in;

		} else {
			return login.logged_in;
		}
	},
	parseLogin      : function(gameCheck) {
		this.init();

		if (login.cookie == null) {
			login.logged_in = false;
			return;
		}

		var cookieVals = new Array();
		cookieVals = login.cookie.split("|");

		if (cookieVals.length != 8) {
			login.status         = 'BAD_COOKIE';
			login.display_status = '';
		} else if (cookieVals[1] != 'OB_OK') {
			login.status = cookieVals[1];
			if (login.status == 'OB_WARN_CUST_TEMP_PIN') {
				login.logged_in = true;
				login.temp_auth = true;
			} else {
				login.logged_in = false;
			}
		} else {
			login.logged_in = true;

			login.cust_id = cookieVals[0];
			login.status  = cookieVals[1];

			switch(document.login_status) {
				case 'OB_OK' :
					if (document.ovs_status == "OVS_FAIL_RETRY_ALLOWED") {
						login.ovs_failed = true;
					} else {
						login.ovs_failed = false;
					}

					if (document.ovs_status == "OVS_FAIL_ALL") {
						login.ovs_failed_all = true;
					} else {
						login.ovs_failed_all = false;
					}
					break;
				case 'OB_ERR_CUST_OVS_FAIL_ALL':
					login.ovs_failed_all = true;
					break;
				case 'OB_ERR_CUST_ACCT_LOCKED':
					login.acct_locked = true;
					break;
				case 'OB_ERR_CUST_OVS_FAIL_XFER' :
					login.ovs_failed_xfer = true;
					break;
			}

			login.ccy_code          = cookieVals[2];
			login.balance           = cookieVals[3];
			login.username          = cookieVals[4];
			login.prefs             = cookieVals[5];
			login.acct_id           = cookieVals[6];
			document.ccy_sym        = login.ccy_code;

			if (gameCheck && document.is_minigame != "1") {

				// make asynchronous and override success function
				check_login_status("true",function(A) {
					//Get Status did the ajax call go ok
					try {
						// capture login status
						login.logged_in = (A.getElementsByTagName("loggedin")[0].childNodes[0].nodeValue === 'true');

						// action depending on logged in/not
						if(login.logged_in) {
							set_cookie(cust_login_cookie_name,A.getElementsByTagName("token")[0].childNodes[0].nodeValue,"", cust_login_cookie_path);
						} else {
							login.message = A.getElementsByTagName("login_msg")[0].childNodes[0].nodeValue;
							game.loginOverlay(login.message);
						}
					}
					catch(err) {
					}
				});
			}
		}

	}
}

// Global object
var ob = typeof window.ob !== "undefined" ? window.ob : {
	id : function(id){return document.getElementById(id);},

	/* Setup the clock functions */
	clock : {
		clockID : 0,
		date : new Date(),
		getTime : function() {
			var secs = Number(ob.clock.date.getSeconds());
			var mins = Number(ob.clock.date.getMinutes());
			var hours = Number(ob.clock.date.getHours());

			if(secs < 10)   {secs  = "0" + secs;}
			if(mins < 10)   {mins  = "0" + mins;}
			if(hours == 24) {hours = 0;}
			if(hours < 10)  {hours = "0" + hours;}
			return hours + ":" + mins + ":" + secs
		},
		setClock : function() {

			if(this.clockID) {
				clearTimeout(this.clockID);
				this.clockID  = 0;
			}
			this.clockID = setTimeout("ob.clock.setClock()", 1000);

			var time = this.getTime();
			var clockDisp = ob.id('clockDisp');
			if (!clockDisp) {
				clearTimeout(this.clockID);
				return false;
			}
			clockDisp.innerHTML = time;
			this.date.setTime(this.date.getTime() + 1000);
		}
	},

	/* Setup the navigations functions (previously go_****)*/
	nav : {
		home : function () { document.location = cgi_url + '?action=GoEvHome'; },
		last_event : function () { document.location = scgi_url + '?action=GoLastEvent'; },
		betslip : function (extra) {
			if (typeof(extra) != 'undefined') {
				document.location = scgi_url + '?action=GoBetslip&z=' + random_arg() + extra;
			} else {
				document.location = scgi_url + '?action=GoBetslip&z=' + random_arg();
			}
		},
		poker : function () { document.location = scgi_url + '?action=export_user&target=SKYPOKER'; },
		acct_home : function () { document.location = account_secure_url + '?action=GoAcctHome'; },
		acct_manage : function () { document.location = pmt_secure_url + '?action=GoManageCPM'; },
		games : function () { document.location = games_secure_url;},
		bingo : function () { document.location = bingo_secure_url;},
		parent : {
			get : function () {
				if (window.opener) {
					return window.opener;
				} else {
					return window;
				}
			},
			register : function () {
				this.get().location.href = scgi_url + '?action=GoAcctReg1';
			},
			forgotten_pin : function() {
				this.get().location.href = account_secure_url + '?action=GoAcctForgottenPIN1';
			}
		}
	},
	js_args : function () {
		var inputVar=arguments; // create an array of the arguments
		switch (inputVar[0]) {
			// GENERAL
			case "s_custpghlp": ob.sh('custpghlp','','show','go_custpghlp','','hide'); break; // show custom page help
			case "h_custpghlp": ob.sh('custpghlp','','hide','go_custpghlp','','show'); break; // hide custom page help
			case "s_blnc": ob.sh('bal','','tab','nobal','','hide');
				var lnk = document.getElementById('swapbalance');
				lnk.innerHTML = "Hide Balance" ;
				break; // show #accntbar balance
			case "h_blnc": ob.sh('bal','','hide','nobal','','tab');
				var lnk = document.getElementById('swapbalance');
				lnk.innerHTML = "Show Balance" ;
				break; // hide #accntbar balance
			case "s_issue": ob.sh('issue','','show','issue2','','show'); break; // registration: show issue number row
			case "h_issue": ob.sh('issue','','hide','issue2','','hide'); break; // registration: hide issue number row
			case "yes_accnt": ob.sh('myuid','','tab'); break; // contact: show user id input
			case "no_accnt": ob.sh('myuid','','hide'); break; // contact: hide user id input
			case "h_askaccnt": ob.sh('askaccnt','','hide'); break; // contact: hide ask for account
			case "s_askaccnt": ob.sh('askaccnt','','show'); break; // contact: show ask for account
			// SKY SPORTS HOMEPAGE PROMO
			case "sksp_a": ob.sh('ss_a','','show','ss_b','','hide','ss_c','','hide'); break; // show stories (1)
			case "sksp_b": ob.sh('ss_a','','hide','ss_b','','show','ss_c','','hide'); break; // show stories (2)
			case "sksp_c": ob.sh('ss_a','','hide','ss_b','','hide','ss_c','','show'); break; // show stories (3)
			case "h_usrmkts": ob.sh('availmkts','','hide'); break; // hide US Racing available markets
			case "s_usrmkts": ob.sh('availmkts','','show','showmkts','','hide'); break; // show US Racing available markets
			// BET SLIP
			case "b_def": ob.sh(
				'sgh','','hide', // singles help
				's_sgh','','tab', // 'show singles help' tab
				'h_sgh','','hide', // 'hide singles help' tab
				'psh','','hide', // pools help
				's_psh','','tab', // 'show poolshelp' tab
				'h_psh','','hide', // 'hide pools help' tab
				'mlth','','hide', // 'multiples help'
				's_mlth','','tab', // 'show multiples help' tab
				'h_mlth','','hide', // 'show multiples help' tab
				'castsh','','hide', // '*casts help'
				'casts','','hide', // auto combined *casts
				'sum','','hide', // account summary contents
				'sumh','','hide', // account symmary help
				's_sumh','','tab', // 'show account summary' tab
				'h_sumh','','hide', // 'hide account summary help' tab
				'fbh','','hide', // 'free bets help'
				'fbs_sgh','','tab', // free bets help
				'fbh_sgh','','hide', // free bets help
				'mlt','','hide' //
			); break; // default onload
			case "s_casts": ob.sh('casts','','show','ncasts','','hide'); break; // show combined casts
			case "h_casts": ob.sh('casts','','hide','ncasts','','show'); break; // hide combined casts
			case "s_mlt": ob.sh('mlt','','show','nmlt','','hide'); break; // show advanced multiples
			case "h_mlt": ob.sh('mlt','','hide','nmlt','','show'); break; // hide advanced multiples
			case "s_fb": ob.sh('fb','','show','ifb','','hide','fb1','','hide','fb2','','tab'); break; // show free Bets
			case "h_fb": ob.sh('fb','','hide','ifb','','show','fb1','','tab','fb2','','hide'); break; // hide free Bets
			case "s_fbh": ob.sh('fbh','','show','fbs_sgh','','hide','fbh_sgh','','tab'); break; // show free Bets help
			case "h_fbh": ob.sh('fbh','','hide','fbs_sgh','','tab','fbh_sgh','','hide'); break; // hide free Bets help
			case "s_sgh": ob.sh('sgh','','show','s_sgh','','hide','h_sgh','','tab'); break; // show singles help
			case "h_sgh": ob.sh('sgh','','hide','s_sgh','','tab','h_sgh','','hide'); break; // hide singles help
			case "s_psh": ob.sh('psh','','show','s_psh','','hide','h_psh','','tab'); break; // show pools help
			case "h_psh": ob.sh('psh','','hide','s_psh','','tab','h_psh','','hide'); break; // hide pools help
			case "s_mlth": ob.sh('mlth','','show','s_mlth','','hide','h_mlth','','tab'); break; // show multiples help
			case "h_mlth": ob.sh('mlth','','hide','s_mlth','','tab','h_mlth','','hide'); break; // hide multiples help
			case "s_sum": ob.sh('sum','','show','s_sum','','hide','h_sum','','tab'); break; // show top-up
			case "h_sum": ob.sh('sum','','hide','s_sum','','tab','h_sum','','hide'); break; // hide top-up
			case "s_sumh": ob.sh('sumh','','show','s_sumh','','hide','h_sumh','','tab'); break; // show account summary help
			case "h_sumh": ob.sh('sumh','','hide','s_sumh','','tab','h_sumh','','hide'); break; // hide account summary help
		}
	},
	sh : function () {
		var i,p,v,obj,args=ob.sh.arguments;

		for (i=0; i<(args.length-2); i+=3) {
			if (typeof(tab_hist) != "undefined") {
				tab_hist.push(args[i]);
				tab_hist.push(args[i+1]);
				tab_hist.push(args[i+2]);
			}
			if ((obj=findObj(args[i]))!=null) {
				v=args[i+2];
				if (obj.style) {
					obj=obj.style; v=(v=='show')?'block':(v=='hide')?'none':(v=='tab')?'inline':v;
				}
				obj.display=v;
			}
		}
	},
	ajax : function (_req) {

		argsMand = ["type", "url", "global", "dataType", "success", "error"];
		for (var i in argsMand) {
			if (typeof(_req[argsMand[i]]) == "undefined") {
				return 0;
			}
		}

		new Ajax(_req);
		return 1;
	}
}

function init_onloads () {

	if (typeof(www) != "undefined") {
		www.init();
	}
	if (typeof(betslip) != "undefined") {
		betslip.init();
	}
	if (typeof(login) != "undefined") {
		login.init();
	}
	ob.clock.setClock();

	if (typeof(function_array) == "object") {
		for (i=0; i < function_array.length; i++) {
			function_array[i]();
		}
	}
}

function set_vegas_cookie () {

	var cookie_vegas_played;
	if (cookie_vegas_played != "") {
		set_cookie(cookie_vegas_played,"Y","","/");
	}
}

// OnDOMLoaded behaviours
// TODO: Execute init_onloads directly if browser is IE7, for some reason
//       DOMLoaded event is giving problems. Jamie M is looking into this.
//       (2008-04-15)
if (typeof(is_skybingo) == "undefined") {
	is_skybingo = false;
}
if (is_ie && is_skybingo) {
	init_onloads();
} else if(typeof(sky) != "undefined") {
	// Adding an onload event
	sky.grabEvent.addBehaviour(init_onloads,'DOMLoaded',true,false,false,'init_onloads');
}

if (typeof(sky) != "undefined") {
	// Adding behaviour for games
	sky.grabEvent.addBehaviour(set_vegas_cookie,'click',function(el) {if (!el.href) {return false;} if (el.href.match(/\?.*action.*GoGame(&*).*$/)) {return true;} else {return false;}},false,false,'set_vegas_cookie');
}

function findObj(n, d) { // find objects by id
	var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
	d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
	if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
	for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=findObj(n,d.layers[i].document);
	if(!x && d.getElementById) x=d.getElementById(n); return x;
}

// IE 5.0 and below redefinition (no jokes)
function Array_push() {
	var A_p = 0;
	for (A_p = 0; A_p < arguments.length; A_p++) {
		this[this.length] = arguments[A_p];
	}
	return this.length;
}
function Array_shift() {
	var A_s = 0;
	var response = this[0];
	for (A_s = 0; A_s < this.length-1; A_s++) {
		this[A_s] = this[A_s + 1];
	}
	this.length--;
	return response;
}
function Array_splice(index, delTotal) {
	var temp = new Array();
	var response = new Array();
	var A_s = 0;
	for (A_s = 0; A_s < index; A_s++) {
		temp[temp.length] = this[A_s];
	}
	for (A_s = 2; A_s < arguments.length; A_s++) {
		temp[temp.length] = arguments[A_s];
	}
	for (A_s = index + delTotal; A_s < this.length; A_s++) {
		temp[temp.length] = this[A_s];
	}
	for (A_s = 0; A_s < delTotal; A_s++) {
		response[A_s] = this[index + A_s];
	}
	this.length = 0;
	for (A_s = 0; A_s < temp.length; A_s++) {
		this[this.length] = temp[A_s];
	}
	return response;
}
function Array_unshift() {
	var A_u = 0;
	for (A_u = this.length-1; A_u >= 0; A_u--) {
		this[A_u + arguments.length] = this[A_u];
	}
	for (A_u = 0; A_u < arguments.length; A_u++) {
		this[A_u] = arguments[A_u];
	}
	return this.length;
}
if (typeof Array.prototype.push == "undefined") {
	Array.prototype.push = Array_push;
}
if (typeof Array.prototype.shift == "undefined") {
	Array.prototype.shift = Array_shift;
}
if (typeof Array.prototype.splice == "undefined") {
	Array.prototype.splice = Array_splice;
}
if (typeof Array.prototype.unshift == "undefined") {
	Array.prototype.unshift = Array_unshift;
}

// Scroll functions (replace the cust where he was on the page)
function frwrd(inputVar) { // User takes action which would exit process funnel
	var answer = confirm ("Are you sure you want to leave this page?.\n\nYou may lose all your changes.")
	if (answer) {
		document.location.href = inputVar;
		return true;
	}
	else {
		return false
	}
}

function init_scroll_hdlr() {
	// setup timeout to set cookie
	if (document.documentElement && document.documentElement.scrollTop) {
		sT = document.documentElement.scrollTop;
	} else if (document.body) {
		sT = document.body.scrollTop;
	} else {
		return false;
	}
	set_scroll_cookie = function() {
		if (scroll_cookie_timer != null) {
			clearTimeout(scroll_cookie_timer);

		}
		if (document.documentElement && document.documentElement.scrollTop) {
			sT = document.documentElement.scrollTop;
		} else if (document.body) {
			sT = document.body.scrollTop;
		}
		set_cookie(scrolltop_cookie_name, window.location.href + "|" + sT, "", "/", "", "");

		scroll_cookie_timer = setTimeout('set_scroll_cookie()',500);

	}
	set_scroll_cookie() ;
}

function read_scroll() {
	var st_cookie = get_cookie(scrolltop_cookie_name);
	if (st_cookie != null && st_cookie != "") {
		var st_conts = st_cookie.split('|');
		// need to check timestamp on the cookie, see if it's more than a few seconds old (say 5?)
		// if it is, ignore it :)
		if (st_conts[0] == window.location.href) {
			// we're still on the same page
			if (document.documentElement && document.documentElement.scrollTop != null) {
				document.documentElement.scrollTop = st_conts[1];
			} else if (document.body) {
				document.body.scrollTop = st_conts[1];
			}
		}
	}
}

// Util functions
function get_cookie(name) {

	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);

	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) {
			return null;
		}
	}
	else {
		begin += 2;
	}

	var end = document.cookie.indexOf(";", begin);
	if (end == -1) {
		end = dc.length;
	}

	return unescape(dc.substring(begin + prefix.length, end));
}

function set_cookie(name, value, expires, path, domain, secure) {

	var curCookie = name + "=" + value +
		((expires) ? "; expires=" + expires.toGMTString() : "") +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "");

	document.cookie = curCookie;
}

// *************************************************
// *** check_login_status **************************
//**************************************************
function check_login_status(asynchronous,successFunc) {

	// default success function
	if ( typeof successFunc != 'function' ) {
		var successFunc = function(A){
				//Get Status did the ajax call go ok
				try {
					// capture login status
					login.logged_in = (A.getElementsByTagName("loggedin")[0].childNodes[0].nodeValue === 'true');

					// action depending on logged in/not
					if(login.logged_in) {
						set_cookie(cust_login_cookie_name,A.getElementsByTagName("token")[0].childNodes[0].nodeValue,"", cust_login_cookie_path);
					} else {
						login.message = A.getElementsByTagName("login_msg")[0].childNodes[0].nodeValue;
					}
				}
				catch(err) {
				}
			};
	}

	if (scgi_url != "" && scgi_url != "undefined") {
		ob.ajax({
			global:"false",
			type:"GET",
			url:scgi_url+'?action=GoCheckLogin',
			dataType:"xml",
			asynchronous:asynchronous,
			success:successFunc,
			error:function(){
			}
		});
	}
}

// *************************************************
// *** Games function called by flash minigames
// *************************************************
function callUpdateBalanceJS(new_balance) {
	if(new_balance != null) {
		var balance ="";
		var currency="";
		login.parseLogin(true);
		var regexp = /USD/;
		var test = regexp.test(document.ccy_sym);
		if(test) {
			document.ccy_sym='$';
		}
		var regexp = /EUR/;
		var test = regexp.test(document.ccy_sym);
		if(test) {
			document.ccy_sym="&euro;";
		}

		var regexp = /GBP/;
		var test = regexp.test(document.ccy_sym);
		if(test) {
			document.ccy_sym="&pound;";
		}
		currency_sym=document.ccy_sym;
		balance=currency_sym + new_balance;
		sky.balance.set(balance);
	}
}

function updateBalance(new_balance) {
	if(new_balance != null) {
		var balance ="";
		currency_sym=document.ccy_sym;
		balance=currency_sym + new_balance;
		sky.balance.set(balance);
	}
}

// Sportsbook functions (Shouldn't be there)
function blank_bet_layout() {
	set_cookie(bet_tab_cookie_name, "", "", bet_cookie_path, "", "");

	var layout = get_cookie(bet_layout_cookie_name);
	if (layout != null && layout != "") {
		var new_layouts;
		var layouts = layout.split('|');
		if (layouts.length == 2) {
			new_layouts = new Array('', layouts[1]);
		} else {
			new_layouts = new Array('', '');
		}
		var new_layout_str = new_layouts.join('|');

		set_cookie(bet_layout_cookie_name, new_layout_str, "", bet_cookie_path, "", "");
	}
}

function dd_set_checked(checked, obj) {

	var i;
	var chks = obj.parentNode.parentNode.getElementsByTagName("INPUT");

	for (i = 0; i < chks.length; i++) {
		chks[i].checked = checked;
	}
}

function dd_class_check_submit() {

	var i, chks;

	chks = document.getElementsByName("tenglgs");
	for (i = 0; i < chks.length; i++) {
		if (chks[i].checked) {
			return true;
		}
	}

	chks = document.getElementsByName("englgs");
	for (i = 0; i < chks.length; i++) {
		if (chks[i].checked) {
			return true;
		}
	}

	alert("Please choose some competitions");
	return false;
}


function random_arg() {

	return Math.floor(Math.random() * 10000);
}

// moved in from hr.js, as it's being used in places other than horse racing
function upperFirstChar(desc) {
	var result = "";
	for (var i = 0; i < desc.length; i++) {
		if(i==0) {
			result += desc.charAt(i).toUpperCase();
		} else {
			result += desc.charAt(i).toLowerCase();
		}
	}
	return result;
}

// vf client functions
var vf_organisation     = "Client Organisation";
var vf_game_type        = "Bingo";
var vf_win_name         = "GameWindow";

if (is_ffx) {
	var vf_interim_win_name = "GameWindow2";
} else {
	var vf_interim_win_name = "GameWindow";
}

var vf_width  = "800";
var vf_height = "600"

var vf_use_interim = 1;

var vf_interim_window = false;
var vf_game_window = false;

try {
	vf_width = window.screen.availWidth;
	vf_height = window.screen.availHeight;
} catch (e) {
	vf_width = window.screen.width;
	vf_height = window.screen.height;
}

// launch vf account history (orbis_api.js needs to be linked beforehand)
function go_bingo_acct_hist(remote_acct) {
	openGamePlayDetailWindow(vf_organisation, remote_acct);
}

function reload_parent(url) {
	window.opener.location.href = url;
}

// launch vf bingo client (orbis_api.js needs to be linked beforehand)
function redirect_bingo_client(url) {

	reload_parent(url);

	vf_game_window = load_bingo_client();

	if (is_ffx && vf_game_window != false) {
		self.close();
	}
}

function openInParent(link) {
	// if there is no parent window, just follow the link's normal behaviour
	if (!window.opener) {
		return true;
	}
	// otherwise open it in the parent window and stop the link from
	// following the href itself
	var opener = window.opener;
	opener.location = link.href;
	window.close();
	return false;
}

function getWindowByName(wname) {
	return open('',wname);
}

function openWindow(url, name, width, height, resizable, scrollbars) {
	var w = window.screen.width;
	var h = window.screen.height;

	if(width > w) {
		width = w / 2;
	}

	if(height > h) {
		height = h / 2;
	}
	var w = window.open(url, name, "resizable,scrollbars,width=" + width + ",height=" + height );
	w.focus();
	w.opener = window;
}

function add_login_clk() {

	var leg;

	// Check casts - will return legs, names and prices arrays
	var legs = new Array();
	var names = new Array();
	var prices = new Array();
	var err_ovr = false;

	if (has_casts) {
		var selected_casts = addCasts(legs,names,prices);
		legs = selected_casts[0];
		names = selected_casts[1];
		prices = selected_casts[2];
		err_ovr = selected_casts[3];
	}
	if (has_pools) {
		var selected_pools = addPools(legs,names,prices);
		legs = selected_pools[0];
		names = selected_pools[1];
		prices = selected_pools[2];
		err_ovr = selected_pools[3];
	}
	if (has_tote_multi_race_pools) {
		var selected_multi_pools = addMultiRaceTotePools(legs,names,prices);
		legs = selected_multi_pools[0];
		names = selected_multi_pools[1];
		prices = selected_multi_pools[2];
		err_ovr = selected_multi_pools[3];
	}
	if (has_trni_multi_race_pools) {
		var selected_multi_pools = addMultiRacePools(legs,names,prices);
		legs = selected_multi_pools[0];
		names = selected_multi_pools[1];
		prices = selected_multi_pools[2];
		err_ovr = selected_multi_pools[3];
	}

	var checkboxes = new Array();

	var fm = document.forms["dd_selns"];

	if (fm == null) {
		return new Array(true, -1, err_ovr);
	}

	var form_elements = fm.elements;
	// Loop over form elements, if checked add to basket
	for(var form_idx = 0; form_idx < form_elements.length; form_idx++) {
		var element = form_elements[form_idx];
		var reg_exp = new RegExp("^each_way_");
		if (element.name != null && element.name.match(reg_exp)) {
			element.checked = false;
			element.disabled = true;
		}

		reg_exp = new RegExp("^(([0-9]+)|(bskt_leg_([0-9]+|sc)))$");

		if (element.name != null && element.name.match(reg_exp) && element.checked) {

			checkboxes.push(element);
			var value;

			if (element.value2 != null && element.value2 != ""){
				value = element.value2;
			} else {
				value = element.value;
			}

			leg = value.split("|");

			// Special case for scorecasts, can't be added to oc_array as
			// dynamically created complex leg
			if (element.name == "bskt_leg_sc") {
				legs.push(value);
				names.push(document.getElementById("sc_desc").value);
				prices.push(document.getElementById("sc_price").innerHTML);
				document.dd_selns.sc_cs.selectedIndex = 0;
				document.dd_selns.sc_fs.selectedIndex = 0;
				document.getElementById("sc_price").innerHTML = '';
			} else if (element.name == "bskt_leg_sl") {
				legs.push(value);
				names.push(document.getElementById("sl_desc").value);
				prices.push(document.getElementById("sl_price").innerHTML);
				document.dd_selns.sl_cs.selectedIndex = 0;
				document.dd_selns.sl_ls.selectedIndex = 0;
				document.getElementById("sl_price").innerHTML = '';
			} else {
				var oc_temp = ob.events.oc_array[ob.events.oc_idx[leg[9]]];
				var price;
				if (leg[3] == "S") {
					price = "SP";
				} else if (leg[4] == "WIN") {
					price = "US Racing Win Pool";
				} else if (leg[4] == "PLC") {
					price = "US Racing Place Pool";
				} else if (leg[4] == "SHW") {
					price = "US Racing Show Pool";
				} else if (leg[4] == "UWIN") {
					price = "Tote Pools Win pool";
				} else if (leg[4] == "UPLC") {
					price = "Tote Pools Place pool";
				} else {
					price = oc_temp.price;
				}
				var already_there = false;
				for (i=0; i < legs.length; i++) {
					if (legs[i] == value && names[i] == oc_temp.desc && prices[i] == price) {
						already_there = true;
					}
				}
				if (!already_there) {
					legs.push(value);
					names.push(oc_temp.desc);
					prices.push(price);
				}
			}
		}
	}
	if (legs.length == 0) {
		return new Array(true, -1, err_ovr);
	}

	var bskt_ret = add_select_leg_array(legs,names,prices);
	bskt_ret[2] = err_ovr;
	if (!bskt_ret[0]) {
		return bskt_ret;
	}

	for (i = 0; i < checkboxes.length; i++) {
		checkboxes[i].checked = false;
	}

	// reset scorecast checkbox
	var bskt_leg_sc = document.dd_selns.bskt_leg_sc;
	if (bskt_leg_sc != null) {
		bskt_leg_sc.value = "";
		bskt_leg_sc.disabled = true;
	}

	// reset scorelast checkbox
	var bskt_leg_sl = document.dd_selns.bskt_leg_sl;
	if (bskt_leg_sl != null) {
		bskt_leg_sl.value = "";
		bskt_leg_sl.disabled = true;
	}
	return true;
}

// go to one of the other product sites
function changeDomain(url) {

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

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

		// are there already params on the query string?
		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;
			join_char = '&';
		}

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

	return url;
}
