/*
 * $Id: global.js,v 1.23 2010-05-27 17:02:34 akoufopo Exp $
 * Copyright (c) 2004 Orbis Technology Ltd. All rights reserved.
 */



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



function get_cookie (name) {

	var dc = document.cookie.split (/;\s*/);
	var re = new RegExp ("^" + name + "=(.*)$");

	for (var i = 0; i < dc.length; i++) {
		if (dc[i].match (re)) {
			return unescape (RegExp.$1);
		}
	}

	return null;
}



// set a cookie
function set_cookie(name, value, expires, path, domain, secure) {

	if (COOKIE_DOMAIN && COOKIE_DOMAIN != "") {
                domain = COOKIE_DOMAIN;
        }

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

	document.cookie = curCookie;
}



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



// Add a form variable
function insertInputObj(form, type, id, name, value) {

	var doc = form.ownerDocument;

	if(at.ie){
		inputObj = doc.createElement("<input name='" + name + "'>");
	} else {
		inputObj      = doc.createElement("input");
		inputObj.name = name;
	}

	inputObj.type  = type;
	inputObj.id    = id;
	inputObj.value = value;

	form.appendChild(inputObj);
}



// Change the display characteristics of a document element
function alterElements(tag, id, visibility) {

	var elements     = document.getElementsByTagName(tag);
	var num_elements = elements.length;

	for(var i = 0; i < num_elements; i++) {
		if(elements.item(i).id == id) {
			elements.item(i).style.display = visibility;
		}
	}
}



// get a currency symbol
function get_ccy_symbol (code) {

	switch(code) {
		case "GBP": { return "\u00A3"; }
		case "EUR": { return "\u20AC"; }
		case "USD": { return "$"; }
		default:    { return code + " "; }
	}
}



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

	return (parseFloat(num) / parseFloat(den)) + 1.00;
}
function addEvent(obj, evType, fn){

  if (obj.addEventListener){
    obj.addEventListener(evType, fn, false);
    return true;
  } else if (obj.attachEvent){
	var r = obj.attachEvent("on"+evType, fn);
    return r;
  } else {
	return false;
  }
}

// update a 'span' value
function upd_span_value(span_id, value) {

	var elements = document.getElementsByTagName("span");

	for(var i = 0; i < elements.length; i++) {
		if(elements.item(i).id == span_id) {
			elements.item(i).style.display = value.length == 0 ? "none" : "";
			elements.item(i).innerHTML = value;
		}
	}
}

function showExtraMkts(e) {

	// Get event
	if(!e) e = window.event;

	// Find the tag which has been onmouseovered
	var theTarget = e.srcElement ? e.srcElement : e.target;

	// declare variables
	var div_id, live_coupon, lc_tag;

	// Handle Live Coupon markets
	if (theTarget.id.split("_")[0] == "lc") {
		live_coupon = true;
		div_id = theTarget.id.split("_")[2] + "_" + theTarget.id.split("_")[3];
		lc_tag = "lc_";
	} else {
		live_coupon = false;
		div_id = theTarget.id.split("_")[1] + "_" + theTarget.id.split("_")[2];
		lc_tag = "";
	}

	var info_holder = document.getElementById(lc_tag + "extra_mkts_info_" + div_id);
	var info_box = (info_holder.style) ? info_holder.style:info_holder;

	if(e){
		//odds_info_locked = false;
		//oinfo_box.width = "";

		if (e.pageX || e.pageY)
		{ // this doesn't work on IE6!! (works on FF,Moz,Opera7)
			//mousex = e.pageX - 160 + "px";
			mousey = e.pageY - 10 + "px";
		}
		else if (e.clientX || e.clientY)
		{ // works on IE6
			//mousex = e.clientX - e.offsetX + document.documentElement.scrollLeft - 160;
			mousey = e.clientY - e.offsetY + document.documentElement.scrollTop - 10;
		}

		//display box
		info_holder.style.display = "block";
		info_holder.style.top = mousey;
		//info_holder.style.left = mousex;

		// lock it
		document.getElementById(lc_tag + "lock_" + div_id).value = 2;
		hideExtraMkts(div_id, lc_tag);
	}
}

function hideExtraMkts(div_id, lc_tag) {
	hideExtraMktsAfter(div_id, lc_tag, 1);
}

function hideExtraMktsAfter(div_id, lc_tag, remainingTime) {
	if(document.getElementById(lc_tag + "lock_" + div_id).value == 0) {
		if(remainingTime == 0) {
			document.getElementById(lc_tag + "extra_mkts_info_" + div_id).style.display = "none";
		} else {
			setTimeout("hideExtraMktsAfter('" + div_id + "','" + lc_tag + "',0)",3000);
		}
	} else if (document.getElementById(lc_tag + "lock_" + div_id).value == 2) {
		setTimeout("hideExtraMktsAfter('" + div_id + "','" + lc_tag + "',0)",1000);
	} else {
		document.getElementById(lc_tag + "lock_" + div_id).value = 0;
		setTimeout("hideExtraMktsAfter('" + div_id + "','" + lc_tag + "',0)",1000);
	}
}

var month_days = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

// check number of days in month
function chk_days_in_month(day, month, year) {

	if(month == 2 && year % 4 == 0 && day > 29) {
			return 29;
	}
	else if(day > month_days[month - 1]) {
			return month_days[month - 1];
	}

	return day;
}

// change the display of odds
function odds_type(sel) {

	var f = sel.form;
	submit_form(f.name,'GoChangePrice');
}

// change language depending on drop down
function change_language (sel, module) {

	var lang = sel.options[sel.selectedIndex].value;
	var host = document.getElementById("host_"+lang).value;

	var exp =/.*\?.*$/;
	if (module == "CA" || module == "GA") {
		url = host + RELATIVE_CASINO_URL;
	} else {
		url = host + RELATIVE_CGI_URL;
	}

	if (SET_LANG_FROM_HOST == 0) {
		if(exp.test(url)) {
			self.location = url + "&lang_choice=" + lang;
		} else {
			self.location = url + "?lang_choice=" + lang;
		}
	} else {
		self.location = url;
	}
}

/****
EG:NEW PROVIDED BY EG
************************************************/

// show hint
function showHint(object_id) {
	show_object_id(object_id);
}

// hide hint
function hideHint(object_id) {
	hide_object_id(object_id);
}

/****
END
************************************************/

// show the account error div with the given message
function show_acct_error(err_msg) {

	if (err_msg != '') {

		var text_span = document.getElementById('acct_error_text');

		// remove existing childs
		if (text_span.hasChildNodes()) {
			while (text_span.childNodes.length >= 1) {
				text_span.removeChild(text_span.firstChild);
			}
		}

		// and add new ones.
		var msg_arr = err_msg.split('\n');
		text_span.appendChild(document.createTextNode(msg_arr[0]))
		for (var i=1; i < msg_arr.length; i++) {
			text_span.appendChild(document.createElement('br'));
			text_span.appendChild(document.createTextNode(msg_arr[i]));
		}

		// show error pane
		document.getElementById('acct_error_pane').style.display = 'block';

		// give error focus
		window.location.replace('#acct_error_focus');
	}
}



// find an object (NS4 only)
function get_obj_NN4(obj, name)
{
	var x = obj.layers;
	var foundLayer;

	for(var i=0; i < x.length; i++) {
		if(x[i].id == name) {
		 	foundLayer = x[i];
		}
		else if(x[i].layers.length) {
			var tmp = get_obj_NN4(x[i], name);
		}
		if(tmp) {
			foundLayer = tmp;
		}
	}

	return foundLayer;
}



// get the style object for the different types of browsers
function get_object_style(object_id) {

	if(object_id == null || typeof object_id == 'undefined') {
		return null;
	} else if(document.getElementById && document.getElementById(object_id)) {
		return document.getElementById(object_id).style;
	} else if(document.all && document.all(object_id)) {
		return document.all(object_id).style;
	} else if(document.layers && document.layers[object_id]) {
		return get_obj_NN4(document, object_id);
	}

	return false;
}



// hide object with supplied id
function hide_object_id(object_id) {

	var style_object = get_object_style(object_id);
	if(style_object != null) {

		style_object.display = 'none';
		return true;
	}

	return false;
}



// show object with supplied id
function show_object_id(object_id) {

	var style_object = get_object_style(object_id);
	if(style_object != null) {

		style_object.display = '';
		return true;
	}

	return false;
}



// function that calculates the modulus of two numbers.
function mod(X, Y) {
    return X - Math.floor(X / Y) * Y;
}



// function that substracts two dates and gives the difference
// The dates have to be in seconds.
function showCountdown(targetId,startId,time1,time2) {

	diff = Math.abs(time1 - time2);
	days = Math.floor(diff/86400);
	hours = Math.floor(mod(diff,86400)/3600);
	minutes = Math.floor(mod(mod(diff,86400),3600)/60);

	if(document.getElementById) {
		target = document.getElementById(targetId);
		target.style.display = "inline";
		startText = document.getElementById(startId);

		startText.innerHTML = ""+days+" d, "+hours+" h and "+minutes+" min";
	}
}



function hideCountdown(targetId) {
	target = document.getElementById(targetId);
	target.style.display = "none";
	//clearInterval(MyInterval);
}



// highlight cells on drilddown pages which have been added to the betslip
// cookie_name - name of bet legs cookie
// highlight - 1 for highlight, 0 to remove highlight
// leg_num - leg in cookie to highlight/de-highlight. Use 'ALL' to specify
//           for all legs
function highlight_dd_cells(cookie_name,highlight,leg) {

	var cookie = get_cookie(cookie_name);
	if (cookie == null) {
		return;
	}

	var selns = cookie.split("|");
	if (selns.length % 11 != 0) {
		return;
	}

	for (var i = 0; i < selns.length; i++) {

		if (i % 11 == 0) {

			var leg_num = selns[i];
			var ev_oc_id = selns[i + 8];

			if (leg == 'ALL' || leg == leg_num) {

				if (parent.document.getElementById('td_oc_' + ev_oc_id)) {

					var class_name = 'odds';
					if (highlight) {
						class_name = 'oddsOn';
					}

					parent.document.getElementById('td_oc_' + ev_oc_id).className = class_name;
				}
			}
		}
	}
}



//
// Set selection counter based on the number of legs in the cookie
//
function refresh_selection_counter(cookie_name) {

	var cookie = get_cookie(cookie_name);
	if (cookie == null || cookie == "") {
		set_selection_counter(0);
		return;
	}

	var selns = cookie.split("|");
	if (selns.length % 11 != 0) {
		return;
	}

	var num_legs = selns.length / 11;

	set_selection_counter(num_legs);
}



//
// Generic function for making AJAX requests. This takes a fully qualified url
// and callback function name as its arguments. The callback function should
// accept a single argument which will consist of the reponse from the server.
// An example of how its used:
//
//   item has following listener
//   onclick="javascript:make_ajax_request('##TP_CGI_URL##?action=AjaxBalance','do_update_balance',1,'GET', param_list);"
//
//   function then looks like this
//   function do_update_balance(balance) {
//       document.getElementById("acct_header_balance").innerHTML = balance;
//   }
//
// The param_list can be an object of parameters to be set as POST arguments, eg:
// param_list: {
//      param1: value1,
//      param2: value2
// }
// will be transformed to:
//   "param1=value1&param2=value2&"
//
// Due to IE's caching, we have to make the url unique each time, to ensure
// that every request made actually hits the server. We do this by appending an
// extra arg (n) onto the url with a uid and counter appended. The uid will be
// unique each time the complete page is refreshed, and the ajax_counter will
// be unique for each ajax request made without refreshing the page.
//
///////////////////////////////
// IMPORTANT INFO - Use the 'unescape()' function on the parameter value received
// by the callback function, if string_response = 1
// ////////////////////////////
var ajax_counter = 0;
function make_ajax_request(url,callback,string_response,method,args_list) {

	var http_request = false;

	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
			}
		}
	}

	if (!http_request) {
		alert('Your browser does not support this functionality.');
		return false;
	}

	url = url + "&n=" + UNIQUE_ID + ajax_counter++;

	http_request.open(method, url, true);

	if (method = 'POST') {
		var params = "";
		// making a string of the form: "param1=value1&param2=value2&..."
		for (var i=0 in args_list) {
			params = params + i + "=" + args_list[i] + "&";
		}
		http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		http_request.setRequestHeader("Content-length", params.length);
		http_request.setRequestHeader("Connection", "close");
	}
	
	http_request.onreadystatechange = function() {
		if (http_request.readyState == 4) {
			if (http_request.status == 200 || http_request.status == 0) {
				try {
					// the response can be a json, so no need to escape it. Checking here.
					if (string_response == 1) {
						var esc_response_text = escape(http_request.responseText);
						eval(callback+"('"+esc_response_text+"')");
					} else {
						eval(callback+"("+http_request.responseText+")");
					}
				} catch (e) {
					alert('Unable to process your request at this time. Error: ' + e.description);
				}
			} else {
				alert('Unable to process your request at this time (status code: ' + http_request.status + ').');
			}
		}
	}
	if (method = 'POST') {
		http_request.send(params);
	} else {
		http_request.send(null);
	}
}



//
// Update the balance shown in the account header.
//
function update_acct_balance(balance) {

	if (window.top.document.getElementById("balance")) {
		window.top.document.getElementById("balance").innerHTML = unescape(balance);
	}
}



//
// Make an ajax call to refresh balance
//
function refresh_balance() {

	var bal_request = PROTO_URL + '?action=GetAjaxBalance';
	make_ajax_request(bal_request,'update_acct_balance',1,'GET',null);
}

// Wrapper for window.open() that also places the popup to a specific
// location in the screen.
function popUp(URL) {

	if (screen) {
		y=0
		x=(screen.width-685)
	}

	if (typeof WindowObjectReference == 'object') WindowObjectReference.close();

	WindowObjectReference = window.open(URL,'xxx','scrollbars=yes,width=650,height=570,screenX='+x+',screenY='+y+',top='+y+',left='+x);
}


//
// Refresh the odds shown in the event page.
//
function update_odds(odds) {
	var oc_array = unescape(odds).split("!");

// The val_array will have the form (it's set in SB_dd::H_refresh_odds):
// ev_status | seln_id | lp_num | lp_den | displayed | hcap_value | price_str | ev_id | ev_result | ev_progress

	for (var i=0; i<oc_array.length; i++) {
		var val_array = oc_array[i].split("|");

		var ev_id = val_array[7];
		var ev_result = val_array[8];
		var ev_progress = val_array[9];

		// if the event gets suspended while refreshing the page (reached the end)
		// stop refreshing, and load the page again (we'll get an error page)
		if (i==0 && val_array[0] == 'S') {
			location.reload();
			break;
		}

		// update event result and progress
		if (document.getElementById("ev_result_"+ev_id)) {
			document.getElementById("ev_result_"+ev_id).innerHTML = ev_result;
		}
		if (document.getElementById("ev_progress_"+ev_id)) {
			document.getElementById("ev_progress_"+ev_id).innerHTML = ev_progress;
		}

		// update the appropriate value
		// if shouldn't be displayed, print ""

		if (val_array[4] == 'Y') {
			if (document.getElementById("price_"+val_array[1])) {
				document.getElementById("price_"+val_array[1]).innerHTML = (val_array[6]);
			}

			// Handicap update
			if (val_array[5]!="")
				if (document.getElementById("hc_oc_"+val_array[1])) {
					document.getElementById("hc_oc_"+val_array[1]).innerHTML = (val_array[5]);
				}
		}
		else {
			if (document.getElementById("price_"+val_array[1])) {
				document.getElementById("price_"+val_array[1]).innerHTML = "";
			}
		}
	}
}

//
// Make an ajax call to keep refreshing the bet odds
// for live events (Bet In Running)
//
function do_ajax_refresh(EventId) {

	var ajax_url = PROTO_URL + '?action=GoRefreshOdds&event_id=' + EventId;
	make_ajax_request(ajax_url,'update_odds',1,'GET',null);
}



//
// Make an ajax call to keep refreshing the bet odds
// for live events (Bet In Running)
//
function doAjaxLiveRefresh(EventId,ExistingMarkets,JSONHash) {

	var ajax_url = PROTO_URL + '?action=GoLiveRefresh&event_id=' + EventId;
	var args_list = {};
	args_list["ExistingMarkets"] = ExistingMarkets;
	args_list["JSONHash"]  = JSONHash;
	// successFunction exists in live_event.js
	make_ajax_request(ajax_url,'successFunction',0,'POST',args_list);
}

//
// Make an ajax call to keep refreshing the bet odds
// for live events (Bet In Running)
//
function doAjaxLiveBetsBoxRefresh() {

	var ajax_url = PROTO_URL + '?action=GoLiveBetsBoxRefresh';
	// updateLiveBetsBox exists in live_bets.html
	make_ajax_request(ajax_url,'updateLiveBetsBox',1,'GET',null);
}


function clear_login_form (form)
{
	form.username.value = "";
	form.pwd     .value = "";
}


//array that checks if the image src for a particular image has been attempted before. 
var attempts= new Array()

// handler error produced loading an imagen  

function change_img_src(b, url) 
{
	if(attempts[b.src] == undefined)
	{		
		attempts[b.src]=1;	
		b.src = url;
		return true;	
	}
	else 
	{
		return true;
	}
}

