/*
 * $Id: global.js,v 1.1.2.84 2010-08-11 14:11:22 cmontoya Exp $
 * Copyright (c) 2006 Orbis Technology Ltd. All rights reserved.
 */

/*
  This file contains statically loaded javascript, used throughout the site.
*/

// minified CVS tag version
var dummy = '$Id: global.js,v 1.1.2.84 2010-08-11 14:11:22 cmontoya Exp $';


// Decode any \uXXXX sequences in a string into characters represented
// by Unicode codepoints with hex XXXX.
function unicode_unescape (str) {

	if (str == null) {
		return;
	}
	var rslt = '';
	// Look for sequences of the form \uXXXX.
	var re = /\\u([0-9A-Fa-f]{4})/g;
	var mtch;
	var prev_mtch = 0;
	while ((mtch = re.exec(str)) != null) {
		rslt += str.substring(prev_mtch, mtch.index);
		var hex_codepoint = mtch[1];
		rslt += String.fromCharCode(parseInt(hex_codepoint,16));
		prev_mtch = re.lastIndex;
	}
	rslt += str.substring(prev_mtch);
	return rslt;
}

// trim a string
//
function str_trim(src, delim) {

	var r = "";
	var b = "";
	var skipsp = false;

	for(var i = 0; i < src.length; i++) {
		var c = src.charAt(i);
		if (delim.indexOf(c) >= 0) {
			b += c;
		}
		else {
			if (r.length > 0) {
				r += b;
			}
			b = "";
			r += c;
		}
	}

	return r;
}



// round a float to 2 decimal places
//
function round_float(n) {

	var s = "" + Math.round(n * 100) / 100
	var i = s.indexOf('.')

	if(i < 0) {
		return s + ".00"
	}

	var t = s.substring(0, i + 1) + s.substring(i + 1, i + 3)
	if(i + 2 == s.length) {
		t += "0"
	}

	return t;
}

// open a window
//
function open_window(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) {
		heigth = h / 2;
	}

	var new_window = window.open(url, name,
		"resizable=" + resizable +
		",scrollbars=" + scrollbars +
		",width=" + width +
		",height=" + height +
		",status=yes");
	new_window.focus();
	new_window.opener = window;
}



// get a cookie
//
function get_cookie(name) {
	var c = document.cookie;
	if (c.length == 0) return '';

	// Search for this cookie name
	// valid cookie syntax is defined here by the regexp
	var reg_exp = "(^|[\\s;])" + name + "=";
	var start = c.search(reg_exp);
	if (start == -1) return '';

	if (start == 0) {
		start += name.length + 1;
	} else {
		start += name.length + 2;
	}
	var end = c.indexOf(';',start);
	if (end == -1) end = c.length;
	return c.substring(start,end);
}

// set a cookie
//
function set_cookie(name, value, expires, path, domain, secure) {

	if (!domain) {
		domain = cookie_domain;
	}

	var curCookie = name + '=' + value +
		((expires) ? '; expires=' + expires.toGMTString() : '') +
		((path) ? '; path=' + path : '') +
		((domain) ? '; domain=' + domain : '') +
		((secure) ? '; secure' : '');

	document.cookie = curCookie;
}

// get a customer preference
function get_pref(name) {

	var c = get_cookie(prefs_cookie_name);
	// Is this a persistent cookie?
	for (var i = 0; i < prefs_persistent_cookie_params.length; i++) {
		if (prefs_persistent_cookie_params[i] == name) {
			c = get_cookie('P_' + prefs_cookie_name);
		}
	}

	var r = new RegExp('^(?:.*\|)?' + name + '=([^|]*)');
	var m = c.match(r);
	return (m ? m.pop() : null)
}

// set a customer preference
function set_pref(name, value) {

	var c_name = prefs_cookie_name;

	if (prefs_persistent_cookie_params.indexOf(name) != -1) {
		var c_name = 'P_' + prefs_cookie_name;
		var c_expiry = new Date();
		//expires in a year, that is 31536000 seconds
		c_expiry.setTime(c_expiry.getTime()+31536000);
	} else {
		var c_expiry = '';
	}

	var c_data = get_cookie(c_name);

	c_data = remove_key(c_data, name);
	if (value && value != '') {
		c_data = append_key(c_data, name, value);
	}

	if (name != 'update') {
		if (appears_logged_in()) {
			if (c_name == prefs_cookie_name) {
				c_data = set_key(c_data, 'update', 1);
			} else {
				//persistent cookie, set update field of the non persistent cookie to 1
				set_cookie(prefs_cookie_name,set_key(get_cookie(prefs_cookie_name),'update',1),c_expiry,'/');
			}
		}
	}

	set_cookie(c_name,c_data,c_expiry,'/');
}

// check if a user appears to have logged in
function appears_logged_in() {

	var session_id = get_cookie(login_cookie_name);

	if(session_id != null && session_id != "") {
		return true;
	}

	return false;
}

// Adds a key value pair to a string
// Replaces the old one if it already exists
// Not in-place
// returns the modified string
function set_key(str, name, value) {
	var new_str = remove_key(str, name);
	new_str = append_key(new_str, name, value);
	return new_str;
}

// appends a key value pair to a str
// does not check for duplicates keys
// returns the modified string
function append_key(str, name, value) {
	var pair = name + '=' + value;
	return (str.length == 0 ? pair : str + '|' + pair);
}

// removes a key value pair from a pipe separated string of pairs
// returns the modified string
function remove_key(str, name) {
	var r = new RegExp('^(.*\|)?' + name + '=[^|]*(.*)$');
	var new_str = str;

	var m = new_str.match(r);
	while (m) {
		var h = m[1];
		var t = m[2];
		if (h == null || h.length == 0) {
			new_str = t.substring(1);
		} else if (t.length == 0) {
			new_str = h.substring(0, h.length-1);
		} else {
			new_str = h + t.substring(1);
		}
		m = new_str.match(r);
	}

	return new_str;
}

// get user-agent
//
var at = new UserAgent();
function UserAgent() {

	var b = navigator.appName.toUpperCase();

	if(b == "NETSCAPE") {
		this.b = "ns";
	}
	else if(b == "MICROSOFT INTERNET EXPLORER") {
		this.b = "ie";
	}
	else if(b == "OPERA") {
		this.b = "op";
	}
	else {
		this.b = b;
	}

	this.version = navigator.appVersion;
	this.v = parseInt(this.version);

	this.ns = (this.b=="ns" && this.v>=4);
	this.ns4 = (this.b=="ns" && this.v==4);
	this.ns5 = (this.b=="ns" && this.v==5);

	this.ie = (this.b=="ie" && this.v>=4);
	this.ie4 = (this.version.indexOf('MSIE 4')>0);
	this.ie5 = (this.version.indexOf('MSIE 5')>0);
	this.ie55 = (this.version.indexOf('MSIE 5.5')>0);
	this.ie6 = (this.version.indexOf('MSIE 6')>0);

	this.op = (this.b=="op");
	this.op4 = (this.b=="op" && this.v==4);
	this.op5 = (this.b=="op" && this.v==5);
}



// fraction to decimal conversion
//
function frac_to_dec(num, den) {

	var p = num + "/" + den;

	if(p == "13/8") {
		return 2.62;
	}
	if(p == "15/8") {
		return 2.87;
	}
	if(p == "11/8") {
		return 2.37;
	}
	if(p == "8/13") {
		return 1.61;
	}
	if(p == "2/7") {
		return 1.28;
	}
	if(p == "1/8") {
		return 1.12;
	}

	// Support Fix 40830
	// Here the fraction decimal convertion synchronized with that
	// of shared_tcl's util.tcl (get_price_str) procedure.

	if (den > 100) {
		return ((parseFloat(num) / parseFloat(den)) + 1.00).toFixed(3);
	} else {
		return ((parseFloat(num) / parseFloat(den)) + 1.00).toFixed(2);
	}

}


// Format the price based on the customer price type preference
//
function format_price(lp_num,lp_den) {

	if (lp_num == lp_den) {
		return xl_evens
	}

	var price_type = get_pref('PRICE_TYPE');

	if (price_type == 'DECIMAL') {
		return frac_to_dec(lp_num,lp_den);
	}
	return lp_num + odds_sep + lp_den;
}



// Convert a form's content into a request parameter string which can be
// used with an XMLHttpRequest e.g. Given a form like:
//
// <form name="betSlipForm">
//   <input type="hidden" name="action" value="GoBetSlip">
//   <input type="text" name="username" value="misterx">
// </form>
//
// getFormContent("betSlipForm") should return:
//
//   'action=GoBetSlip&username=misterx'
//
// We treat checkboxes as a special case.  We only add the checkbox element's
// name/value if the checkbox is checked.
function getFormContent(form) {
	var f = document.forms[form];
	var n = f.elements.length;
	var content = '';
	var name, value, fi;

	for (var i=0; i<n; i++) {
		fi = f.elements[i];
		name = fi.name;
		value = fi.value;
		if (name == '') continue;
		if (fi.type == 'checkbox' && !fi.checked) continue;
		content = content + name + '=' + value + '&';
	}
	return content;
}



function ieDropDownFix () {
	var uls=document.getElementsByTagName("ul");
	var ul,li,lis,num;
	var i=uls.length-1

	if (i == -1) return;
	do {
		if(uls[i].className=="dd-mkt"||uls[i].className=="dd-tv"||uls[i].className=="i") {
			li=uls[i].getElementsByTagName("li");
			li[0].onmouseover = function() {
				this.className+=" sfhover";
				this.style.zIndex="99"
			}
			li[0].onmouseout=function() {
				this.className = this.className.replace(new RegExp(" sfhover\\b"),"");
			}
			ul=li[0].getElementsByTagName("ul");
			if (!ul.length) continue;
			lis=ul[0].getElementsByTagName("li");
			if(lis.length>10) ul[0].className+=" scroll";
		}
	} while(i--);
}

// Highlight
function hltRow(ref) {

	var tds = ref.parentNode.getElementsByTagName("td");
	var i = tds.length;

	do {
		if (tds[i-1].style.backgroundColor == "")
			tds[i-1].style.backgroundColor = "#efefef";
		else
			tds[i-1].style.backgroundColor = "";
	} while (--i)
}

function hltAttach() {

	var main = document.getElementById('main');
	var tables = main.getElementsByTagName('table');
	var highlight = function () {hltRow(this)}
	var i = tables.length;
	
	if (i > 0) {

		do {
			if (tables[i-1].className.indexOf('hvr') > -1) {
	
				var tds = tables[i-1].getElementsByTagName('td');
				j = tds.length;
	
				do {
					tds[j-1].onmouseover = highlight;
					tds[j-1].onmouseout  = highlight;
				} while (--j)
			}
		} while (--i)
	}
}


/*
 All js below has been removed from left_nav.html on the app
*/

function validateNavCriteria() {
	var criteria = document.navSearch.sCriteria.value
	if (criteria ==left_nav_dummy || criteria=='') {
		alert(left_nav_enter);
	} else {
		return true;
	}
	return false;
}

function validateNavCriteriaButton() {
	if (validateNavCriteria()) document.navSearch.submit();
}

function viewAllSettings() {

	var cookie_val=get_cookie(cookie_name);

	if (appears_logged_in()) {
		html = '<a href='+url+'>'+output+'</a>';
	} else {
		html = '<a class="tipper">'+output+'<span class="tip">'+ttip+'</span></a>';
	}

	document.getElementById('view_all_settings_span').innerHTML = html;
}


/*
 All js below has been removed from pp_html on the app
*/

		var isIE=document.all;
		var isMoz=document.getElementById;
		var isNS4=document.layers;
		var px=document.layers? "" : "px";

		function getCookie(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 deleteCookie(name, path, domain)
		{
			if (getCookie(name))
			{
				document.cookie = name + "=" +
					((path) ? "; path=" + path : "") +
					((domain) ? "; domain=" + domain : "") +
					"; expires=Thu, 01-Jan-70 00:00:01 GMT";
			}
		}

		function drop_poker_download(){
			if (!getCookie('PP_disp_pok')) return;
			deleteCookie('PP_disp_pok','/','');
			if (!isMoz&&!isIE&&!isNS4) return;
			div_handel=(isMoz)?document.getElementById("dropin").style : isIE? document.all.dropin : document.dropin;
			div_handel.top=get_page_offset()-250+px;
			div_handel.visibility=(isMoz||isIE)? "visible" : "show"
			dropstart=setInterval("increment_position()",50);
		}

		function increment_position(){
			if (parseInt(div_handel.top)<50+get_page_offset()) {
				div_handel.top=parseInt(div_handel.top)+40+px;
			} else {
				clearInterval(dropstart)
			}
		}

		function close_poker_box(){
			div_handel.visibility="hidden";
		}

		function get_page_offset(){
			if (isIE){

				return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement.scrollTop : document.body.scrollTop;
			} else {
				return window.pageYOffset;
			}
		}

		function poker_popup_fs() {
			if (document.getElementById("chk_pok_no_shw").checked) {
				window.frames['popup_blocker'].document.forms[0].submit();
			}
		}

/*
  The below js has been removed from pp_login.html
*/

    // Check if the user 'appears' to be logged in
		//
		function check_login_details(first_time) {

			var cust_login_body  = document.getElementById('cust_login_body');
			var guest_login_body = document.getElementById('guest_login_body');
			var cust_first_name  = document.getElementById('login_cust_firstname');
			var num_messages     = document.getElementById('num_messages_div');
			var my_bets_num_bets = document.getElementById('my_bets_num_bets_div');
			var loginUID         = document.getElementById('loginUID');
			var prev_req         = document.getElementById('prev_req');

			if (appears_logged_in()) {

				cust_login_body.style.display = '';
				guest_login_body.style.display = 'none';

				// Update the customer firstname

				cust_first_name.innerHTML = unicode_unescape(get_pref('USERNAME'));
				
				if (num_messages != null) {
					num_messages.innerHTML = unicode_unescape(get_pref('NUMMESSAGES'));
				}

				var my_bets_num = unicode_unescape(get_pref('MY_BETS_NUM_BETS'));
				// a value of '-' indicates that my bets counting is turned off
				if (my_bets_num_bets != null && my_bets_num != '-' ) {
					my_bets_num_bets.innerHTML = '(' + my_bets_num + ')';
				}

				// Update the customer balance
				displayBalance();
			} else {

				cust_login_body.style.display = 'none';
				guest_login_body.style.display = '';

				// Update the Login_Uid
				loginUID.value = get_cookie(loginuid_cookie_name);

				if (first_time) {
					// On first load, we need to copy the prev_req from the cookie to
					// form so that the user is brought back to the same page after
					// logging in. On subsequent calls (which happen every half a second or so)
					// we will not copy the prev_req anymore. This is necessary to avoid requests
					// made in popups putting their location in the cookie.
					prev_req.value = get_cookie(pre_req_cookie_name);
				}

			}
		}

		// log a customer out
		function do_customer_logout () {

			// is inline betslip visible or not?
			var bs = document.getElementById('bsScroller');
			if (bs) {
				if(bs.style.display != 'none') {
					// do nothing
				} else {
					var betslip_window = window.open('',betslipheader.popup_name,'width=300,scrollbars=1,resizable=1');
					betslip_window.close();
				}
			} else {
				// close the remote betslip if it's open
				var betslip_window = window.open('',betslipheader.popup_name,'width=300,scrollbars=1,resizable=1');
				betslip_window.close();
			}
			window.parent.location = parent.tld + "?action=logout&page_mode=" + parent.logout_pagemode;
		}

		// open up the betslip if it's detached
		function go_betslip () {
			BS_pop_out();
		}

function displayBalance() {

	if(document.getElementById('login_cust_bal')) {
		// Balance display is switched off - to retrieve their balance
		// customers will do an AJAX call
		return
	}

	var ccy_code = '';
	if (get_pref('ccy_code') == 'EUR') {
		ccy_code = '&euro;';
	}
	if (get_pref('ccy_code') == 'GBP') {
		ccy_code = '&pound;';
	}

	// display customer balance if HIDE_BALANCE pref is ON
	if (get_pref('HIDE_BALANCE') == '1') {
		document.getElementById('cust_bal').innerHTML     = '';
		document.getElementById('show_bal').style.display = 'none';
		document.getElementById('hide_bal').style.display = 'block';
	} else {
		document.getElementById('cust_bal').innerHTML = ccy_code + get_pref('balance');
		document.getElementById('show_bal').style.display = 'block';
		document.getElementById('hide_bal').style.display = 'none';
	}
	// always display freebet balance if positive
	var fb_bal = get_pref('fb_balance');
	if (fb_bal > 0) {

		var fb_bal_el = document.getElementById('fb_bal');
		if (fb_bal_el) {
			fb_bal_el.innerHTML = ccy_code + fb_bal;
		}

		var show_fb_bal = document.getElementById('show_fb_bal');
		if (show_fb_bal) {
			show_fb_bal.style.display = 'block';
		}

	} else {

		var show_fb_bal = document.getElementById('show_fb_bal');
		if (show_fb_bal) {
			show_fb_bal.style.display = 'none';;
		}

	}

	var fb_bal_sport = get_pref('fb_balance_sports');
	var fb_bal_gp = get_pref('fb_balance_gp');

	if (fb_bal_sport > 0) {

		var freebet_sport = document.getElementById('freebet_sport');
		if (freebet_sport) {
			freebet_sport.style.display = 'block';
		}

		var fb_bal_sport_el = document.getElementById('fb_bal_sport');
		if (fb_bal_sport_el) {
			fb_bal_sport_el.innerHTML = fb_bal_sport;
			fb_bal_sport_el.style.display = 'block';
		}
	}

	if (fb_bal_gp > 0) {
		
		var freebet_game = document.getElementById('freebet_game');
		if (freebet_game) {
			freebet_game.style.display = 'block';
		}

		var fb_bal_gp_el = document.getElementById('fb_bal_gp');
		if (fb_bal_gp_el) {
			fb_bal_gp_el.innerHTML = fb_bal_gp;
			fb_bal_gp_el.style.display = 'block';
		}
	}
}

// toogle between show/hide customer balance
function toggleBalanceDisplay(){

	if (get_pref('HIDE_BALANCE') == '1'){
		set_pref('HIDE_BALANCE', '0');
	} else {
		set_pref('HIDE_BALANCE', '1');
	}
	//display balance
	displayBalance();
}

function toggleDisplayAllBal(state){
	document.getElementById("all_bal").style.display = (state == true) ? "block" : "none";
}

// Function to open a winner circle iRace virtual event
function open_wc_window () {

	var pp_wc_win = {};

	if (appears_logged_in()) {
		pp_wc_win = window.open(wc_video_url + "?ticket=" + get_cookie("PP_Login"),"PPWCWin","resizable=yes,scrollbars=no,status=yes,width=835,height=670");
	} else {
		pp_wc_win = window.open(wc_guest_video_url,"PPWCWin","resizable=yes,scrollbars=no,status=yes,width=580,height=670");
	}

	pp_wc_win.focus();
}


// Used by lottery pages
function genLink(link, type) {
	var url = '';
	var actionUrl = parent.tld;
	var staticUrl = document.domain;

	if (type == "action") {
		url = actionUrl + "?" + link;
	} else {
		url = staticUrl + '/' + actionUrl + '?' + link;
	}

	parent.location.href = url;

}

//Moved these here from racing.js as we will be using them all over the site now

function open_atr_window (ev_id) {
	var atr_url = video_cgi_url + "?action=go_atr_video_feed&ev_id="+ev_id;
	var pp_atr_win = window.open(atr_url,"PPATRWin","resizable=no,scrollbars=no,status=yes,width=580,height=480");
	pp_atr_win.focus();
}


function open_rp_window (ev_id) {
	var rp_url = video_cgi_url + "?action=go_racing_video_player&ev_id="+ev_id+"&hrplayer=1";
	var pp_rp_win = window.open(rp_url,"PPRPWin","resizable=no,scrollbars=no,status=yes,width=810,height=620");
	pp_rp_win.focus();
}

function open_etote_window () {
	var etote_url = video_cgi_url + "?action=etote_watch_live_racing";
	var pp_etote_win = window.open(etote_url,"PPETOTEWin","resizable=no,scrollbars=no,status=yes,width=600,height=500");
	pp_etote_win.focus();
}

// Scripts relating to the leftnav
function toggle_othersports() {
	
	if (document.getElementById("othersports_submenu").style.display == "none") {
		// Expand the Other Sports menu.
		document.getElementById("othersports_header").className = "expand";
		document.getElementById("othersports_submenu").style.display = "";
 	}
	else {
		// Collapse the Other Sports menu.
		document.getElementById("othersports_submenu").style.display = "none";
		document.getElementById("othersports_header").className = "last";
	}
	
}

function collapse_leftnav_item(url) {

	if (document.getElementById("selected_submenu").style.display != "none") {
		// Collapse submenu
		document.getElementById("selected_submenu").style.display = "none";
		elements = document.getElementsByClassName("on");
		for(var i=2; i<elements.length; i++){
			elements[i].style.backgroundPosition = '0px 0px';
		}
		
	}
	else {
		window.document.location = url;
	}

}


/* ---- Push Server Functionality (BEGIN) ---- */

/* ---- PUBLIC ---- */

/*
 * The push client API object.
 * Can only be used AFTER the onready handlers have fired.
 * See push/webclient/src/ps_client.js for API details.
*/
var ps_connect_push  = null;

/*
 * Register a callback function to be called once the page & push API are ready.
 * This CAN be called after they are ready (in which case the callback will be
 * invoked immediately).
 * The callback function will typically register a listener and subscribe
 * to channels.
*/
function ps_connect_add_onready(fn) {
	_ps_connect_required();
	if (!_ps_connect_started) {
		_ps_connect_onready_fns.push(fn);
	} else {
		fn();
	}
}

/*
 * Wrapper for ps_client_register.
 * Can be called before or after page & push are ready.
 */
function ps_connect_register(key, handler, channels, last_msg_id) {
	var fn = function () {
		ps_connect_push.ps_client_register
		  (key, handler, channels, last_msg_id);
	}
	ps_connect_add_onready(fn);
}

/*
 * Wrapper for ps_client_deregister.
 * Can be called before or after page & push are ready.
 */
function ps_connect_deregister(key) {
	var fn = function () {
		ps_connect_push.ps_client_deregister(key);
	}
	ps_connect_add_onready(fn);
}

/*
 * Left pad id with zeroes to a width of n (or 10 if not supplied).
 * Sufficiently commonly needed when preparing channel lists that
 * it's worth having here.
*/
function ps_connect_lpad_id(id, n) {
	var id = "" + id;
	if (!n) {
		n = 10;
	}
	while (id.length < n) id = "0" + id;
	return id;
}

/* ---- PRIVATE ---- */

// Element Id of the iframe holding the push iframe (typically in pp_bot.html)
var _ps_connect_iframe_id = "push_iframe";

// Array of onready functions.
var _ps_connect_onready_fns = [];

// Has anyone asked for push functionality yet?
var _ps_connect_is_required = false;

// Is the page loaded, the push API ready and the client started?
var _ps_connect_loaded   = false;
var _ps_connect_ready    = false;
var _ps_connect_started  = false;

// Someone needs a push.
function _ps_connect_required() {
	if (_ps_connect_is_required) {
		return;
	} else {
		_ps_connect_source_iframe();
		_ps_connect_is_required = true;
	}
}

// We don't source the iframe until push is needed.
function _ps_connect_source_iframe() {
	var d = document;
	var f = d.frames ? d.frames[_ps_connect_iframe_id] : d.getElementById(_ps_connect_iframe_id);
	if (!f) {
		window.setTimeout("_ps_connect_source_iframe()", 250);
	} else {
		var src = push_www_url + "/push_api.html" + "?v=" + push_version;
		if (f.location) {
			f.location.href = src;
		} else {
			f.src = src;
		}
	}
}

// Called once the page has loaded and the push API is ready.
function _ps_connect_start() {

	if (_ps_connect_started) return;

	// Set the authentication token if found.
	if (window.push_auth_token && push_auth_token.length) {
		ps_connect_push.ps_client_set_auth_token (push_auth_token);
	}

	// Add the servers defined by js_global.html
	for (var i = 0; i < push_servers.length; i += 3) {
		ps_connect_push.ps_client_add_server(
			push_servers[i + 0],
			push_servers[i + 1],
			push_servers[i + 2]
		);
	}

	// Call the onready handlers.
	for (var i = 0; i < _ps_connect_onready_fns.length; i++) {
		_ps_connect_onready_fns[i]();
	}

	ps_connect_push.ps_client_start();
	_ps_connect_started = true;

	return;
}

// Called when the page loads.
function _ps_connect_onload() {
	_ps_connect_loaded = true;
	if (_ps_connect_loaded && _ps_connect_ready) {
		_ps_connect_start();
	}
}

// Register the page load function.
function _ps_connect_reg_onload() {
	var f = _ps_connect_onload;
	if(typeof window.addEventListener != 'undefined') {
		window.addEventListener('load', f, false);
	} else if(typeof document.addEventListener != 'undefined') {
		document.addEventListener('load', f, false);
	} else if(typeof window.attachEvent != 'undefined') {
		window.attachEvent('onload', f);
	} else {
		throw("browser does not support adding onload function.");
	}
}
_ps_connect_reg_onload();

// Called by the push iframe once it's ready.
function push_ready() {

	// Record where the push iframe is.
	var d = document;
	var f = d.frames ? d.frames[_ps_connect_iframe_id] : d.getElementById(_ps_connect_iframe_id);
	ps_connect_push = f.contentWindow || f;

	/* Provided the page is also ready, start now. */
	_ps_connect_ready = true;
	if (_ps_connect_loaded && _ps_connect_ready) {
		_ps_connect_start();
	}

	return;
}

/*
 * Called on push iframe unload in an attempt to clean up anything
 * that might leak (in IE) or throw spurious errors (in FF).
*/
function push_shutdown() {
}

/* ---- Push Server Functionality (END) ---- */


function lcasino_keepalive() {
	if (appears_logged_in()) {
		if (document.location.protocol == 'http:') {
			var url = tld + "?action=do_evolution_session_check";
		}
		else {
			var url = tldsecure + "?action=do_evolution_session_check";
		}

		new Ajax.Request(url, {
			method: 'get',
			onSuccess: function(transport) {}
		});
	}
}

function showTab(tab){
	// Switch Tab
	var lis = document.getElementsByTagName("li");
	for(var i=0;i<lis.length;i++){
		if(lis[i].className == "on"){
			lis[i].className = "off";
		}
	}
	document.getElementById(tab + "-li").className= "on";
	
	//hide all divs
	document.getElementById("skills").style.display = "none";
	document.getElementById("yourRaces").style.display = "none";
	document.getElementById("faqs").style.display = "none";
	
	//display the new div
	document.getElementById(tab).style.display = "block";
	
}

// Checks if there has been a change in the perform cookie.
// Or if the customer has just logged in.
// If this is the case AND video was not being played
// it means that we should reload the player because the
// customer may have placed a qualifying bet or simply logged in
function checkVideoCookie () {

	var logged_in = appears_logged_in();
	var time ='';
	// Try to get the cookie and if it does not exist/ is empty abort
	try {
		time = get_cookie('Perform');
	} catch(err) {
		return;
	}

	// Check if there has been a change
	if ((time == null || time == '' || parseInt(video_curr_time) == parseInt(time))
	    && (!logged_in || logged_in == video_was_logged_in)) {
		video_was_logged_in = logged_in;
		return;
	}

	// Update login status
	video_was_logged_in = logged_in;

	// Update video cookie
	if (time != null) {
		video_curr_time = time;
	}

	// Do these inside try blocks since some of the variables may not exist
	var condition = 0;
	// Should we reload the media center/ horse racing player?
	try {
		if ( lb_playing_video != undefined
		     && lb_playing_video != 1 && logged_in ) {
			condition = 1;
		}
	} catch(err) {}

	if ( condition == 0 ) {
		try {
			if ( hr_player_playing_video != undefined
				 && hr_player_playing_video != 1 && logged_in ) {
				condition = 2;
			}
		} catch(err) {}
	}
	
	if ( condition == 0 ) {
		try {
			if ( lb_vp_playing_video != undefined
				 && lb_vp_playing_video != 1 && logged_in ) {
				condition = 3;
			}
		} catch(err) {}
	}

	var ev_id = -1;

	// Reload media center
	if ( condition == 1 ) {
		// Some new BIR pages use _lb_evt_ev_id
		if ( typeof _lb_evt_ev_id  == 'undefined' || _lb_evt_ev_id == null || _lb_evt_ev_id == "") {	

			ev_id = lb_evt_ev_id;

		} else {
			// Are we in a horse racing BIR page?

			ev_id = _lb_evt_ev_id;

		}
		_media_center_schedule_reload(ev_id);

	} else if ( condition == 2 ) {

		// Refresh the media player
		_hr_player_schedule_reload(hr_player_ev_id);

	} else if (condition == 3) {
		// Refresh the video player
		lb_vp_reload_flash(lb_vp_ev_id);
	}

}

var _hr_player_scheduled_reload = false;
function _hr_player_schedule_reload (ev_id) {

	var delay = 2500;

	// If we have already scheduled a call, bail out
	if (_hr_player_scheduled_reload) {
		return;
	} else {
		_hr_player_scheduled_reload = true;
	}

	window.setTimeout("_hr_player_reload("+ev_id+")", delay);

}

function _hr_player_reload (ev_id) {

	var url = '';

	// Refresh the media player
	if (document.location.protocol == 'http:') {
		url = video_cgi_url + '?action=go_racing_video_player&ev_id=' + ev_id + '&refresh=1&hrplayer=1';
	} else {
		url = video_scgi_url + '?action=go_racing_video_player&ev_id=' + ev_id + '&refresh=1&hrplayer=1';
	}

	var clientdata = {
		id : 'hr_player'
	};

	make_ajax_get_request(url, clientdata, got_ajax_content_updater);

	_hr_player_scheduled_reload = false;

}

var _media_center_scheduled_reload = false;
function _media_center_schedule_reload(ev_id) {

	// If we have already scheduled a call, bail out
	if (_media_center_scheduled_reload) {
		return;
	} else {
		_media_center_scheduled_reload = true;
	}

	var delay = 2500;
	window.setTimeout("_media_center_reload("+ev_id+")", delay);


}

function _media_center_reload (ev_id) {

	var url = '';
	var hr = 0;
	if (typeof _lb_evt_ev_id  != 'undefined' && _lb_evt_ev_id != null && _lb_evt_ev_id != "" && _lb_evt_cfg["bir_sort"] == "HR") hr = 1;

	// Refresh the media center
	if (document.location.protocol == 'http:') {
		url = video_cgi_url + '?action=go_betlive_media_center&ev_id=' + ev_id + '&popout=0&hr=' + hr;
	} else {
		url = video_scgi_url + '?action=go_betlive_media_center&ev_id=' + ev_id + '&popout=0&hr=' + hr;
	}

	var clientdata = {
		id : 'MP'
	};

	make_ajax_get_request(url, clientdata, got_ajax_content_updater);

	_media_center_scheduled_reload = false;

}

function auto_check_video_cookie () {

	var check_interval = 1000;
	setInterval('checkVideoCookie()',check_interval);

}

/*
 ** Given an Informix datetime string, return the number of milliseconds
 */
function time_in_milliseconds(date_str) {

	return Date.parse(
		new Date (
			parseInt(date_str.substring(0, 4), 10),
			(parseInt(date_str.substring(5, 7), 10) - 1),
			parseInt(date_str.substring(8, 10), 10),
			parseInt(date_str.substring(11, 13), 10),
			parseInt(date_str.substring(14, 16), 10),
			parseInt(date_str.substring(17), 10)
		)
	);
}

function vsize(id,value){
	//alert("resizing #"+id+" to "+value+"px");
	if(typeof document.getElementById(id) != "undefined"){
		document.getElementById(id).style.height = value + "px";
	}
}

function bh_level(){
	var bharr = $$('div.bh');
	var str = "";
	for(var b=0;b<bharr.length;b++){
		var n = bharr[b];
		var npp = bharr[b+1];
		if(n.className.indexOf("left") > 0){ // if there is a left, it will have a corresponding right to be matched
			//alert(n.id + "=" + n.getHeight() + " <> " + npp.id + "=" + npp.getHeight());
			var diff = n.getHeight() - npp.getHeight();
			//alert(diff);
			if(diff > 0){ // lengthen the box on the right
				//alert("lengthening the right");
				expander = $$("#"+npp.id+" .exp")[0];
			}else if(diff < 0){ //lengthen the box on the left
				//alert("lengthening the left");
				expander = $$("#"+n.id+" .exp")[0];
			}
			//alert(String(expander.getHeight() + Math.abs(diff)) + "px");
			if(diff != 0){
				var mp = 0;
				expander.style.height = String(expander.getHeight() + Math.abs(diff) - mp) + "px";
				expander.style.paddingTop = "0";
				expander.style.paddingBottom = "0";
			}
		}
	}
}


function parse_qstr(tmpURL,name) {
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( tmpURL );

	if( results == null ) {
		return "";
	}

	return results[1];
} 


function bookmarkpaddy(){
	title = "Paddy Power"; 
	url = "http://www.paddypower.com/bet?area=bookmark";

	if ( window.sidebar ) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title,url,"");
	} else if ( window.external ) { // IE Favorite
		window.external.AddFavorite(url,title); 
	} else if ( window.opera && window.print ) { // Opera Hotlist
		return true; 
	}

	if(typeof(netinsight) != "undefined"){
		if(netinsight){
			//add event here!!
			ntptEventTag("ev=bookmark");
		}
	}
}


var global_eval = function (src) {
	if (window.execScript) {
		window.execScript(src);
		return;
	}
	var fn = function() {
		window.eval.call(window,src);
	};
	fn();
};

function make_ajax_get_request(url, clientdata, callback) {

	if (typeof betlive_busy_sem != "undefined" && betlive_busy_sem == 1) {
		// Attempt this again in 300ms.
		setTimeout(function(){make_ajax_get_request(url, clientdata, callback)}, 300);
		return;
	}

	betlive_busy_sem = 1;
	var req = null;
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		req = new ActiveXObject('Microsoft.XMLHTTP');
	}
	if (req) {
		req.onreadystatechange = function() {
			if (req.readyState != 4) return;
			var reqStatus;
			try {
				reqStatus = req.status;
			} catch (e) {
				reqStatus = '';
			}
			if (reqStatus != 200) {
				betlive_busy_sem = 0;
				callback(url,clientdata,false,'HTTP');
			} else {
				betlive_busy_sem = 0;
				callback(url,clientdata,true,req.responseText);
			}
		}
		try {
			req.open('GET', url, true);
			req.send(null);
		} catch (e) {
			betlive_busy_sem = 0;
			callback(url,clientdata,false,'UNSUPPORTED');
		}
	} else {
		betlive_busy_sem = 0;
		callback(url,clientdata,false,'UNSUPPORTED');
	}
}

function got_ajax_content_updater (url,clientdata, ok, response) {
	var holder_el = document.getElementById(clientdata.id);
	if (ok) {
		
		// blank response means no new data
		if (response == "") {
			return;
		}
		
		var parts = parse_script_tags(response);
		if (holder_el) {
			holder_el.innerHTML = parts[0];
		}
		if (parts[1].length) {
			try {
				global_eval(parts[1]);
			} catch (e) {
				ok = false;
			}
		}
	}
}

function parse_script_tags(str) {
	var html = '';
	var js   = '';
	var i = 0;
	var state = 'HTML';
	var script_re =
	  new RegExp('<(/?)' + 'scr'+'ipt' + '([^>]*)>', 'gi');
	while ((mtch = script_re.exec(str)) != null) {
		mS = mtch.index;
		if (state == 'HTML') {
			html += str.substring(i, mS);
		} else {
			js += str.substring(i, mS) + ';\n';
		}
		var closer = mtch[1];
		var attrs  = mtch[2];
		if (closer == '/') {
			state = 'HTML';
		} else {
			if ( attrs.charAt(attrs.length - 1) != '/' &&
			     attrs.indexOf('src=') == -1 ) {
				state = 'JS';
			}
		}
		i = script_re.lastIndex;
	}
	if (state == 'HTML') {
		html += str.substring(i);
	} else {
		js += str.substring(i);
	}
	return [ html, js ];
}

// poll_betslip_display_check and _determine_betslip_display are here because
// they cannot be called from the betslip code (because the purpose is that they
// run for the inline betslip, but not the pop out betslip).
//
// Periodically called _determine_betslip_display to ensure the Attached betslip
// isn't displayed when the pop out betslip is open.
function poll_betslip_display_check () {

	setInterval(_determine_betslip_display, 1000);
}

// Function periodically called to ensure the correct betslip is displayed.
// If the pop out betslip is active, the in page betslip should be hidden.
function _determine_betslip_display () {

	// Try to get the cookie.
	var betslip_style = get_pref("BETSLIP_STYLE");

	// If the betslip is detacted, ensure the attached betslip is hidden.
	if (betslip_style == "Detached") {

		var bs   = document.getElementById('bsScroller');
		var bshl = document.getElementById('bsHeaderLeft');
		var bsOA = document.getElementById('bsOpenAnchor');

		if (bs != null) {
			bs.style.display = 'none';

			if (bshl) bshl.style.display = 'none';
		}

		if (bshl) bshl.style.display = 'block';
		if (bsOA) bsOA.style.display = 'inline';
	}
}
