/*
	$Id: script.js,v 1.3 2008-04-02 04:09:59 pspillma Exp $
	Copyright (c) 2005 Orbis Technology Ltd. All rights reserved.
*/

var cgiURL           = null;
var cgiSSLURL        = null;
var cgiCustSSLURL    = null;
var cgiCustPmtSSLURL = null;
var gifURL           = null;
var staticURL        = null;
var tocMinus         = null;
var tocPlus          = null;
var invalidStr       = null;
var loginUid         = null;
var betSlipName      = null;
var tooShort         = null;
var tooLong          = null;
var strDigits        = null;
var strCharacters    = null;

var isBetSlip        = false;
var isLoggedIn       = false;

var extraBetTimeout  = "";
var selectTimeout    = "";
var extraBetHilite   = new Array(false,0,0);



/**********************************************************************
 * DOM Utilities
 *********************************************************************/

// sniff out problem browsers
function SniffBrowser() {

	this.ns4 = document.layers;
	this.op5 = navigator.userAgent.indexOf("Opera 5") != -1 ||
	           navigator.userAgent.indexOf("Opera/5") != -1;
	this.op6 = navigator.userAgent.indexOf("Opera 6") != -1 ||
	           navigator.userAgent.indexOf("Opera/6") != -1;
	this.op8 = navigator.userAgent.indexOf("Opera 8") != -1;
	this.op  = this.op5 || this.op6 || this.op8;
	this.agt = navigator.userAgent.toLowerCase();
	this.mac = this.agt.indexOf("mac") != -1;
	this.ie  = this.agt.indexOf("msie") != -1;
	this.mac_ie = this.mac && this.ie;
	this.ffox = this.agt.indexOf("firefox") != -1;
}
var browser = new SniffBrowser();



// ie specific APIs...
/*
if(!browser.ie) {

	// swap node
	Node.prototype.swapNode = function(node) {

		var nextSibling = this.nextSibling;
		var parentNode = this.parentNode;

		node.parentNode.replaceChild(this, node);
		parentNode.insertBefore(node, this);
	}


	// remove node
	Node.prototype.removeNode = function() {

		this.parentNode.removeChild(this);
	}
}
*/


// get window inner height
function getWindowInnerHeight() {
	return browser.ie ? document.body.clientHeight : window.innerHeight;
}



// get window inner width
function getWindowInnerWidth() {
	return browser.ie ? document.body.clientWidth : window.innerWidth;
}



// get object for the different types of browsers
function getObject(objectId) {

	if(objectId == null || typeof objectId == 'undefined') {
		return null;
	}
	if(document.getElementById && document.getElementById(objectId)) {
		return document.getElementById(objectId);
	}
	if(document.all && document.all(objectId)) {
		return document.all(objectId);
	}
	if(document.layers && document.layers[objectId]) {
		return getObjNN4(document, objectId);
	}

	return null;
}



// get the style object for the different types of browsers
function getStyleObject(objectId) {

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

	return false;
}



// find an object (NS4 only)
function getObjNN4(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 = getObjNN4(x[i], name);
		}
		if(tmp) {
			foundLayer = tmp;
		}
	}

	return foundLayer;
}



// change style class of an element
function changeClass(Elem, Class) {

	var elem;

	if(Elem == null || typeof Elem == 'undefined') {
		return;
	}
	if(document.getElementById) {
		elem = document.getElementById(Elem);
	}
	else if(document.all){
		elem = document.all[Elem];
	}
	if(browser.op5 || browser.op6) {
		elem.style.className = Class;
	}
	else {
		elem.className = Class;
	}
}



// hide or show a page element
function changeObjectDisplay(objectId, newDisplay) {

	var styleObject = getStyleObject(objectId, document);
	if(styleObject != null) {
		styleObject.display = newDisplay;
		return true;
	}

	return false;
}



// hide or show a page element
function changeObjectVisibility(objectId, newVisibility) {

	var styleObject = getStyleObject(objectId, document);
	if(styleObject != null) {
		styleObject.visibility = newVisibility;
		return true;
	}

	return false;
}



// get the Y co-ordinate of an element
function getElementTop(Elem, offsetParent) {

	var elem, yPos, tempEl;

	if(Elem == null || typeof Elem == 'undefined') {
		return 0;
	}

	if(browser.ns4) {
		elem = getObjNN4(document, Elem);
		return elem.pageY;
	}

	if(document.getElementById) {
		elem = document.getElementById(Elem);
	} else if (document.all) {
		elem = document.all[Elem];
	}
	yPos = elem.offsetTop;
	tempEl = elem.offsetParent;
	while((typeof offsetParent == 'undefined' || offsetParent) &&
	        tempEl != null) {
		yPos += tempEl.offsetTop;
		tempEl = tempEl.offsetParent;
	}
	return yPos;
}



// get the X co-ordinate of an element
function getElementLeft(Elem, offsetParent) {

	var elem, xPos, tempEl;

	if(Elem == null || typeof Elem == 'undefined') {
		return;
	}

	if(browser.ns4) {
		elem = getObjNN4(document, Elem);
		return elem.pageX;
	}

	if(document.getElementById) {
		elem = document.getElementById(Elem);
	} else if (document.all){
		elem = document.all[Elem];
	}
	xPos = elem.offsetLeft;
	tempEl = elem.offsetParent;
	while((typeof offsetParent == 'undefined' || offsetParent) &&
	        tempEl != null) {
		xPos += tempEl.offsetLeft;
		tempEl = tempEl.offsetParent;
	}

	return xPos;
}



// get an element's width
function getElementWidth(Elem) {

	var elem, xPos;

	if(Elem == null || typeof Elem == 'undefined') {
		return;
	}

	if(browser.ns4) {
		elem = getObjNN4(document, Elem);
		return elem.clip.width;
	}

	if(document.getElementById) {
		elem = document.getElementById(Elem);
	} else if(document.all) {
		elem = document.all[Elem];
	}

	if(browser.op5) {
		xPos = elem.style.pixelWidth;
	}
	else {
		xPos = elem.offsetWidth;
	}

	return xPos;
}



// get an element's height
function getElementHeight(Elem) {

	var elem, xPos;

	if(Elem == null || typeof Elem == 'undefined') {
		return;
	}

	if(browser.ns4) {
		elem = getObjNN4(document, Elem);
		return elem.clip.height;
	}

	if(document.getElementById) {
		elem = document.getElementById(Elem);
	} else if (document.all) {
		elem = document.all[Elem];
	}

	if(browser.op5) {
		xPos = elem.style.pixelHeight;
	} else {
		xPos = elem.offsetHeight;
	}

	return xPos;
}



// change the background of an element
function changeBGColour(Object, colour) {

	if(browser.ns4) {
		var obj = getObjNN4(document, Object);
		obj.bgColor=colour;
	} else {
		var obj = getStyleObject(Object);
		if(obj != null && browser.op5) {
			obj.background = colour;
		}
		else if(obj != null) {
			obj.backgroundColor = colour;
		}
	}
}



// change an image source
function changeImage(target, source) {

	var imageObj;

	if(browser.ns4) {
		imageObj = getImage(target);
		if(imageObj != null) {
			imageObj.src = eval(source).src;
		}
	} else {
		imageObj = eval('document.images.' + target);
		if(imageObj != null) {
			imageObj.src = eval(source).src;
		}
	}
}



// get an image (NS4 only)
function getImage(name) {

	if(document.layers) {
		return findImage(name, document);
	}
	return null;
}



// find an image (NS4 only)
function findImage(name, doc) {

	var i, img;

	for(i = 0; i < doc.images.length; i++) {
		if(doc.images[i].name == name) {
			return doc.images[i];
		}
	}
	for(i = 0; i < doc.layers.length; i++) {
		if((img = findImage(name, doc.layers[i].document)) != null) {
			img.container = doc.layers[i];
			return img;
		}
	}

	return null;
}



// move an element to a new set of X + Y co-ordinates
function moveXY(Obj, x, y) {

	var obj = getStyleObject(Obj)

	if(obj == null) {
		return;
	}

	if(browser.ns4) {
		obj.top = y;
		obj.left = x;
	}
	else if(browser.op5) {
		obj.pixelTop = y;
		obj.pixelLeft = x;
	}
	else {
		obj.top = y;
		obj.left = x;
	}
}



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

	var doc = form.ownerDocument;

	if(browser.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);
}



// get the X co-ordinate of an image
function getImageLeft(img) {

	if(document.layers) {
		var m = getImage(img);
		if(m.container != null) {
			return m.container.pageX + m.x;
		}
		return m.x;
	}

	return getElementLeft(img);
}



// get the Y co-ordinate of an image
function getImageTop(img) {

	if(document.layers) {
		var m = getImage(img);
		if(m.container != img) {
			return m.container.pageY + m.y;
		}
		return m.y;
	}

	return getElementTop(img);
}



// get image width
function getImageWidth(img) {

	if(document.layers) {
		var m = getImage(img);
		return m.width;
	}

	return getElementWidth(img);
}



// get image height
function getImageHeight(img) {

	if(document.layers) {
		var m = getImage(img);
		return m.height;
	}

	return getElementHeight(img);
}



/**********************************************************************
 * Table Utilties
 *********************************************************************/

// expand a menu table
function expandTable(name) {

	changeObjectDisplay('expanded_' + name, '');
	changeObjectDisplay('collapsed_' + name, 'none');

	// set cookie so that the expanded table will be displayed
	setCookie("expanded_" +name, "Y");
}


// collapse a menu table
function collapseTable(name) {

	changeObjectDisplay("expanded_" + name, 'none');
	changeObjectDisplay("collapsed_" + name, '');

	// set cookie so that the collapsed table will be displayed
	setCookie("expanded_" + name, "N");
}



/**********************************************************************
 * Cookie Utilities
 *********************************************************************/

// get a cookie
function getCookie(name) {

	var dc     = document.cookie.split(';');
	var prefix = name + "=";
	for(var i = 0; i < dc.length; i++) {
		if(dc[i].indexOf(prefix) != -1) {
			return unescape(dc[i].substring(dc[i].indexOf(prefix) + prefix.length));
		}
	}

	return null;
}



// set a cookie
function setCookie(name, value, expire, path, domain, secure) {

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

	document.cookie = curCookie;
}

/**********************************************************************
 * Form Utilities
 *********************************************************************/

// form-validation error list
function Error() {

	var errorList = "";
	var total = 0


	// any errors
	this.isErr = function() {
		return this.total;
	}


	// reset the error-list
	this.reset = function() {

		this.errorList = "";
		this.total = 0;
	}


	// add an error
	this.add = function(str) {

		if (this.errorList.length > 0) {
			this.errorList += "\n";
		}
		this.errorList += str;
		this.total++;

		return this.total;
	}

	// display the error list within an alert
	this.alert = function() {
		alert(this.errorList);
	}
}
var err = new Error();



// check a mandatory string
function ckMandatory(str, desc, min_len, max_len, val_chars) {

	if(str == null || str.length <= 0 || (min_len != 0 && str.length < min_len) ||
			(max_len != 0 && str.length > max_len)) {
		return err.add(invalidStr + desc + ".");
	}

	if(val_chars) {
		var re = "^[A-Za-z0-9\.\_\-]*$";
		if(!str.match(new RegExp(re))) {
			return err.add(invalidStr + desc + ":\n\t" + containChar +
							' \'A-Z\', \'a-z\', \'0-9\', \'.\', \'_\', \'-\'.');
		}
	}
	return 0;
}

function ckPhone(str, desc, min_len, max_len) {
	if (str == null || str.length == 0) {
		return 0;
	}
	if (str.length > max_len) {
		return err.add(desc + " " + tooLong + " " + max_len + " " + strDigits + ".");
	} else if (str.length < min_len) {
		return err.add(desc + " " + tooShort + " " + min_len + " " + strDigits + ".");
	}

	var re = "^[0-9\x28\x29\x20\+\-]*$";
	if (!str.match(new RegExp(re))) {
		return err.add(invalidStr + desc + ":\n\t" + containChar +
							' \'0-9\', \'\(\', \'\)\', \' \'.');
	}
	return 0;
}

function ckMobile(str, desc, min_len, max_len) {
	if (str == null || str.length == 0) {
		return 0;
	}

	if (str.length > max_len) {
		return err.add(desc + " " + tooLong + " " + max_len + " " + strDigits + ".");
	} else if (str.length < min_len) {
		return err.add(desc + " " + tooShort + " " + min_len + " " + strDigits + ".");
	}

	var re = "^[0-9\x20]*$";
	if (!str.match(new RegExp(re))) {
		return err.add(invalidStr + desc + ":\n\t" + containChar + ' \'0-9\', \' \'.');
	}
	return 0;
}


// check for no numbers 
function ckAlphaOnly(str, desc) {

	var re = "[0-9_]";
	if (str.match(new RegExp(re))) {
		return err.add(invalidStr + desc + ":\n\t" + containChar + '\'A-Z\', \'a-z\', \' \',  \'-\'');
	}
	return 0;
}


// check an integer
function ckInteger(str, desc, pm, min_len, max_len) {

	var inStr = strTrim(str, " ");
	var exp = pm ? /^[+-]?[0-9]+$/ : /^[0-9]+$/;

	if(!exp.test(inStr)) {
		return err.add(invalidStr + desc + ".");
	}

	if((min_len != 0 && inStr.length < min_len) || (max_len != 0 && inStr.length > max_len)) {
		return err.add(invalidStr + desc + ".");
	}

	return 0;
}



// check a float
function ckFloat(str, desc) {

	var inStr = strTrim(str, " ");
	var exp = /^([0-9]*(\.[0-9]+))$|^([0-9]+(\.)?)$/;

	if((!inStr.length) || !exp.test(inStr)) {
		return err.add(invalidStr + desc + ".");
	}

	return 0;
}



// check a amount field
function ckAmount(str, desc, pm) {

	var inStr = strTrim(str, " ");
	var exp = pm ? /(^[+-]?\d+$)|(^[+-]?\d*\.\d{1,2}$)/ : /(^\d+$)|(^\d*\.\d{1,2}$)/;

	if((!inStr.length) || !inStr.match(new RegExp(exp))) {
		return err.add(invalidStr + desc + ".");
	}

	return 0;
}



// Check if a update action requires an update by comparing the old with
// the new input values
function ckReqUpd(name, vals) {

	var f = document.forms[name];

	var details_not_change = 1;

	for (var i = 0; details_not_change ==1 && i < vals.length; i++) {
		if (eval("f.old_"+vals[i]+".value") != eval("f."+vals[i]+".value")) {
	    	details_not_change = 0;
		}
	}

	return details_not_change;
}


// Strip leading 0's from a string
function stripZeros(str) {

	while (str.charAt(0) == 0 && str.length > 0)
	{
		str = str.substring(1);
	}
	return str;
}


// submit a form
function submitOBForm() {

	var name = arguments[0];
	var action = arguments[1];
	var method = 'get';

	if (arguments.length == 3) {
		method = arguments[2];
	}

	var f = document.forms[name];

	insertInputObj(f, 'hidden', '', 'action', action);

	f.method = method;
	f.submit();
}



// submit a form over SSL
function submitSSLForm(name, action, not_cust, method, is_pmt) {

	var f = document.forms[name];

	// Remove the input element named 'action' if there is one.
	// Sadly, we appear to need to do this since we can't get to the
	// property of the form called action otherwise.
	var elems = f.elements;
	if (elems['action'] && elems['action'].value) {
		f.removeChild(elems['action']);
	}

	// Set the form property called 'action'.
	if (typeof(not_cust) != "undefined" && not_cust == 1) {
		f.action = cgiSSLURL;
	} else if (typeof(is_pmt) != "undefined" && is_pmt == 1) {
		// req is secure and involves movement of funds
		f.action = cgiCustPmtSSLURL;
	} else {
		f.action = cgiCustSSLURL;
	}

	if (typeof(method) != "undefined") {
		var form_method = method;
	} else {
		var form_method = "post";
	}

	// Now submit the form, putting the action input element back in
	// with the value given.
	submitOBForm(name, action, form_method);
}



/**********************************************************************
 * Misc Utilties
 *********************************************************************/

/*
 * Loads up the customer menu preferences; determining whether or
 * not particular menu tables specified by parameter 'name' should
 * should be expanded/collapsed
 */
function loadCustMenuPrefs(name, default_value) {

	var displayExpandedTable = getCookie("expanded_"+name);

	if (displayExpandedTable == null) {
		displayExpandedTable= default_value;
	}

	if (displayExpandedTable == "Y") {
		expandTable(name);
	} else {
		collapseTable(name);
	}
}



// Clear login fields
function clearLoginFields(name) {

	var form = document.forms[name];

	form.username.value = "";
	form.pwd.value = "";
}



// open a window
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) {
		heigth = h / 2;
	}

	var top = (h/2)-(height/2);
	var left = (w/2)-(width/2);

	var w = window.open(url, name,
		"resizable=" + resizable +
		",scrollbars=" + scrollbars +
		",width=" + width +
		",height=" + height +
		",top=" + top +
		",left=" + left +
		",status=yes");
	if (w) {
		w.focus();
		w.opener = window;
	}
}



// get a currency symbol
function getCcySymbol (code, code_dflt) {

	switch(code) {
		case "AUD": { return "$"; }
		case "CAD": { return "$"; }
		case "EUR": { return "\u20AC"; }
		case "GBP": { return "\u00A3"; }
		case "NZD": { return "$"; }
		case "USD": { return "$"; }
		default:    {
			if (code_dflt) {
				return code + " ";
			} else {
				return "";
			}
		}
	}
}



// fraction to decimal conversion
function fracToDec(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;
}



// trim a string
function strTrim(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 the given number to 2 decimal places, returning the result as a
// string containing exactly 2 decimal places.
//
// Numbers are (almost) always rounded towards zero (perhaps trucateFloat
// would be a better name).
//
// e.g.
//       -1.009  ->      "-1.00"
//       -1.001  ->      "-1.00"
//            0  ->       "0.00"
//            1  ->       "1.00"
//        1.001  ->       "1.00"
//        1.005  ->       "1.00"
//        1.009  ->       "1.00"
//           10  ->      "10.00"
//    1.234e+50  ->  "1.234e+50"
//         "foo" ->           ""
//          NaN  ->           ""
//     Infinity  ->   "Infinity"
//           ""  ->            0
//
// We make an exception for numbers whose absolute value is only a very
// small quantity less than a multiple of 0.01 - these are rounded towards
// that multiple. For example, 1.009 -> 1.00, but 1.00999999999999 -> 1.01.
//
// If n is not a number in Javascript's eyes, the empty string will be
// returned.
//
function roundFloat(n) {

	// Check n is indeed a number.
	if (isNaN(n)) {
		return "";
	}

	// Ensure we treat n as a number now.
	n = 1.0 * n;

	// Record if n was negative and then make it non-negative.
	// We do this to:
	//   a) ensure we round towards zero, not negative infinity.
	//   b) simplify the rest of the algorithm.
	var was_negative = false;
	if (n < 0) {
		was_negative = true;
		n = Math.abs(n);
	}

	// If n is small, consider it to be zero (in which case whether
	// it was negative or not is unimportant).
	if (n < 0.0001) {
		return "0.00";
	}

	// Add on a small quantity to ensure that a number like, say,
	// 1.00999999999999999999 which has presumably arisen due to some binary
	// floating point inaccuracy is rounded to 1.01, not 1.00.
	n = n + 1e-8;

	// Convert n to a string.
	var s = "" + n;

	if (s.indexOf("e") != -1 || s == "Infinity") {

		// If n is big enough to need to be expressed in scientific notation,
		// we don't need to round it. (We can assume the exponent is positive
		// due to the smallness check above).

	} else {

		// If the string contains no decimal point, add one.
		var dp_pos = s.indexOf(".");
		if (dp_pos == -1) {
			dp_pos = s.length;
			s = s + ".";
		}

		// Pad the string with zeroes (it doesn't matter if we add too many).
		s = s + "000";

		// Drop anything after the 1st two characters after the decimal point.
		s = s.substring(0, dp_pos + 3);

	}

	// If n was negative to begin with, make it negative again (unless our
	// string representation is non-positive).
	if (was_negative && s != "0.00" && s.charAt(0) != "-") {
		s = "-" + s;
	}

	return s;
}


// write a select input box
function writeSelect() {

	var sel = arguments[0];
	var i;
	var n;
	var v;
	var sel_tag;

	for(i = 1; i < arguments.length; i += 2) {
		v = arguments[i];
		n = arguments[i + 1];
		sel_tag = (sel == v) ? " selected" : "";
		document.writeln('<option value="' + v + '"' +
		                  sel_tag + '>' + n + '</option>');
	}
}

// open the betslip
document.open_betslip = 0;
function viewBetslip(url, name) {

	document.open_betslip = 1;
	parent.getObject('fr_Betslip').src = url;
}



/**********************************************************************
 * Images
 *********************************************************************/

// Swaps images
function MM_swapImgRestore() {

	var i,x,a=document.MM_sr;

	for(i=0; a && i<a.length && (x=a[i]) && x.oSrc; i++) {
		x.src=x.oSrc;
	}
}



// Preloads images
function MM_preloadImages() {

	var d=document;

	if (d.images) {
		if (!d.MM_p) {
			d.MM_p=new Array();
		}
		var i,j=d.MM_p.length,a=MM_preloadImages.arguments;
		for(i=0; i<a.length; i++) {
			if (a[i].indexOf("#") !=0) {
				d.MM_p[j]=new Image;
				d.MM_p[j++].src=a[i];
			}
		}
	}
}



// finds an image element
function MM_findObj(n, d) {

	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=MM_findObj(n,d.layers[i].document);
	}
	if(!x && d.getElementById) {
		x=d.getElementById(n);
	}
	return x;
}



// Swaps images
function MM_swapImage() {
	var i,j=0,x,a=MM_swapImage.arguments;

	document.MM_sr=new Array;

	for(i=0; i<(a.length-2); i+=3) {
		if ((x=MM_findObj(a[i])) !=null) {
			document.MM_sr[j++]=x;
			if(!x.oSrc) {
				x.oSrc=x.src;
			}
			x.src=a[i+2];
		}
	}
}


/*
 *	Returns a browser independant XMLHttpRequest object, or false on error.
 */
function getHttpRequestObject () {

	var xmlHttp = false;
	var e;

	try {
		xmlHttp = new XMLHttpRequest();
	} catch (e) {
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				// Browser does not support AJAX
			}
		}
	}

	return xmlHttp;
}

var currentTab;

function setTab(sel_tab_id) {

	var doc = top.frames['fr_Top'].document;

	var links = doc.getElementsByTagName("a");
	currentTab = sel_tab_id;

	for (var i = 0; i < links.length; i++) {
		if (links[i].id.indexOf("tab_") >= 0) {
			var tab_id = (links[i].id).substring(4, (links[i].id).length);

			if (tab_id == sel_tab_id) {
				set_tab_style(true, tab_id);

				// set current tab for event finder/news scroller since changing
				// tab in the header won't have triggered a reload in the header
				// to change the TAB variable
				doc.forms['typenav'].current_tab.value      = tab_id;
				doc.forms['newsscroller'].current_tab.value = tab_id;
				if (doc.forms['login']) {
					doc.forms['login'].tab.value = tab_id;
				}
			} else {
				set_tab_style(false, tab_id);
			}
		}
	}

	if (sel_tab_id == 'sports' || sel_tab_id == 'racing') {
		top.frames['fr_Top'].document.getElementById("HeaderDrilldownSelect").style.display = '';
	} else {
		top.frames['fr_Top'].document.getElementById("HeaderDrilldownSelect").style.display = 'none';
	}
}

function set_tab_style(selected, id) {

	var objTab = top.frames['fr_Top'].document.getElementById("tab_" + id);
	var doc = top.frames['fr_Top'].document;

	if (selected) {
		objTab.className = "tab_on";

		if (id != "nav") {
			doc.getElementById(id).style.display = "";
		}
	} else {
		objTab.className = "tab_off";

		if (id != "nav") {
			doc.getElementById(id).style.display = "none";
		}
	}
}

// Wrapper function to getLocalTimeWrite that provides the original
// default behaviour of using document.write instead of returning the
// datetime value for use in things like innerHTML
function getLocalTime(gmtDate, format) {

	return getLocalTimeWrite(gmtDate, format, true);
}

// get time in browser local time
// gmtDate - YYYY/MM/DD hh:mm:ss
function getLocalTimeWrite(gmtDate, format, write) {

	var year = parseInt(gmtDate.substring(0,4),10);
	var month = parseInt(gmtDate.substring(5,7),10) - 1;
	var day = parseInt(gmtDate.substring(8,10),10);
	var hh = parseInt(gmtDate.substring(11,13),10);
	var mm = parseInt(gmtDate.substring(14,16),10);
	var ss = parseInt(gmtDate.substring(17,19),10);

	var jsDate = new Date(year,month,day,hh,mm,ss);
	var localTime = jsDate.getTime() - jsDate.getTimezoneOffset() * 60000;
	var localDate = new Date(localTime)
	var hour = localDate.getHours();
	var mins = localDate.getMinutes();
	var secs = localDate.getSeconds();

	day   = localDate.getDate();
	// getMonth is zero based
	month = localDate.getMonth() + 1;

	if (day.toString().length < 2) {
		day = "0" + day;
	}
	if (month.toString().length < 2) {
		month = "0" + month;
	}
	if (hour.toString().length < 2) {
		hour = "0" + hour;
	}
	if (mins.toString().length < 2) {
		mins = "0" + mins;
	}
	if (secs.toString().length < 2) {
		secs = "0" + secs;
	}

	if (format == 'time') {
		if (write) {
			document.write(hour + ":" + mins);
		} else {
			return hour + ":" + mins;
		}
	} else if (format == 'jstime') {
		// we want yymmdd hhmiss
		shortYear = gmtDate.substring(2,4);

		return shortYear + month + day + " " + hour + mins + secs;
	} else if (format == 'js_datetime') {

		shortYear = gmtDate.substring(2,4);

		// we want yymmdd hhmmss
		return shortYear + month + day + " " + hour + mins + secs;
	} else if (format == 'short') {
		// we want dd/mm hh:mm

		if (write) {
			document.write(day + "/" + month + " " + hour + ":" + mins);
		} else {
			return day + "/" + month + " " + hour + ":" + mins;
		}
	} else if (format == 'long') {
		if (write) {
			document.write(localDate.toLocaleString());
		} else {
			return localDate.toLocaleString();
		}
	} else {
		var res = localDate.toLocaleString();
		// this gives (FIREFOX/IE) 'Tue 21 Nov 2006 14:53:21 GMT+0800 (WST)
		//            (SAFARI)     '21 November 2006 14:53:21 GMT+08:00'
		//            (OPERA)      'Tuesday November 21, 14:53:21 GMT+0800 2006'
		// we want to strip it down to '21 Nov 2006 14:53'

		year = localDate.getFullYear();
		var parts = res.split(' ');
		var l = parts.length;
		var x;
		for (var i=0; i < l; i++) {
			x = strTrim(parts[i],",");
			if (x == day) {
				break;
			}
		}
		var output = day;
		if (i == 0) {
			output += " " + parts[1] + " ";
		} else if (i == 1) {
			output += " " + parts[2] + " ";
		} else if (i == 2) {
			output += " " + parts[1] + " ";
		} else {
			output += "/"+ month + "/";
		}
		if (format == 'date') {
			output += year;
		} else {
			output += year+ " " + hour + ":" + mins;
		}

		if (write) {
			document.write(output);
		} else {
			return output;
		}
	}
}

// Centrebet supplied javascript utils

// Mouse over tool-tip help
function showBubble(text,evnt,bWidth,bPos) {
	if (document.all) {
		evntY = event.clientY + document.body.scrollTop;
		evntX = event.clientX;
	} else {
		evntY = evnt.pageY;
		evntX = evnt.pageX;
	}
	var el = document.getElementById("bubble");
	el.style.width = (bWidth?bWidth:"150") + "px";
	el.innerHTML = text;
	el.style.visibility = "visible";
	var bW = el.offsetWidth;
	var bH = el.offsetHeight;
	var dX;
	var dY;
	switch (bPos) {
		case "top":
			dX = 0 - (bW/2);
			dY = -10 - bH;
			break;
		case "topright":
			dX = 20;
			dY = -10 - bH;
			break;
		case "right":
			dX = 20;
			dY = 0 - (bH/2);
			break;
		case "bottomright":
			dX = 20;
			dY = 25;
			break;
		case "bottom":
			dX = 0 - (bW/2);
			dY = 25;
			break;
		case "bottomleft":
			dX = -15 - bW;
			dY = 25;
			break;
		case "left":
			dX = -15 - bW;
			dY = 0 - (bH/2);
			break;
		case "topleft":
			dX = -15 - bW;
			dY = -10 - bH;
			break;
		default:
			dX = 20;
			dY = 25;  // default delta values; equal to "bottomright"
	}
	el.style.left = ((evntX + dX) > 0 ? ((evntX + dX + bW) < document.body.clientWidth ? (evntX + dX) : (document.body.clientWidth-bW)) : 0) + "px";
	el.style.top = ((evntY + dY - document.body.scrollTop) > 0 ? ((evntY + dY + bH - document.body.scrollTop) < document.body.clientHeight ? (evntY + dY) : (document.body.clientHeight - bH + document.body.scrollTop)) : document.body.scrollTop) + "px";
}

function showTimerBubble(text, divID, bTime, evnt, bWidth, bPos) {
	showBubble(text, evnt, bWidth, bPos);
	getObject(divID).innerHTML = getTimeTo(bTime);
	timerOn(divID, bTime);
}

function clearTimerBubble() {
	timerOff();
	clearBubble();
}

function clearBubble() {
	if (getObject("bubble")) {
		getObject("bubble").style.visibility = "hidden";
		if (extraBetHilite[0]) {
			extraBetHilite[0] = false;
			if (getObject("td" + extraBetHilite[1] + "1_" + extraBetHilite[2])) {
					getObject("td" + extraBetHilite[1] + "1_" + extraBetHilite[2]).className = "nb";
			}
			if (getObject("td" + extraBetHilite[1] + "2_" + extraBetHilite[2])) {
				getObject("td" + extraBetHilite[1] + "2_" + extraBetHilite[2]).className = "desc";
			}
		}
	}
}

function openURLInParent(url, tab) {

	if (tab != null) {
		setTab(tab);
	}
	window.parent.location = url;
}

var bubbleTimer = null;
function timerOn(divID, bTime) {

	var tickTimer = function() {
		getObject(divID).innerHTML = getTimeTo(bTime)
	};

	bubbleTimer = setInterval(tickTimer,1000);
}

function timerOff() {
	if (bubbleTimer) {
		clearInterval(bubbleTimer);
		bubbleTimer = null;
	}
}

function toLocaleDate(dbTime) {

	matchDateObj = new Date("20" + dbTime.substr(0,2),
													eval(dbTime.substr(2,2) - 1),
													dbTime.substr(4,2),
													dbTime.substr(7,2),
													dbTime.substr(9,2),
													dbTime.substr(11));

	localeDateObj = new Array(matchDateObj.toLocaleString(), matchDateObj.valueOf());

	return localeDateObj;
}

function getTimeTo(timeA) {

	var xtemp = new Date();

	dayTo = hrTo = mnTo = scTo = 0;

	diff  = toLocaleDate(timeA)[1] - xtemp.valueOf();
	dayTo = Math.floor(diff/86400000);
	diff -= dayTo*86400000;
	hrTo  = Math.floor(diff/3600000);
	diff -= hrTo*3600000;
	mnTo  = Math.floor(diff/60000);
	diff -= mnTo*60000;
	scTo  = Math.floor(diff/1000);

	if (dayTo < 0) {
		return ""
	} else {
	 return ((dayTo>0)?("<strong>" + dayTo + "</strong> day" + (dayTo>1?"s ":" ")):"") +
					((hrTo>0)?("<strong>" + hrTo + "</strong> hr" + (hrTo>1?"s ":" ")):"") +
					((mnTo>0)?("<strong>" + mnTo + "</strong> min" + (mnTo>1?"s ":" ")):"") +
					((scTo>0)?("<strong>" + scTo + "</strong> sec" + (scTo>1?"s":"")):"");
	}
}

function showExtraBets() {
	/* arguments:
		[0][1]... link/text pair(s)
		[last]... button ID
	*/
	if (extraBetHilite[0]) clearBubble();
	htm = "";
	for (i = 0; i < arguments.length-1; i+=2) {

		if (arguments[i] == '') {
			htm += '<span onmouseover="clearTimeout(extraBetTimeout);" onmouseout="extraBetTimeout=setTimeout(clearBubble,2000);" class="popup"' + (i < arguments.length-3?' style="border-bottom:1px solid #aaa"':'') + '>' + arguments[i+1] + '</span>';
		} else {
			htm += '<a href="#" onClick="' + arguments[i] + ';return false" onmouseover="clearTimeout(extraBetTimeout);" onmouseout="extraBetTimeout=setTimeout(clearBubble,2000);" class="popup"' + (i < arguments.length-3?' style="border-bottom:1px solid #aaa"':'') + '>' + arguments[i+1] + '</a>';
		}
	}
	tId = arguments[arguments.length-1];
	showPriceBubble(htm,110,'left','ddown_' + tId);
	tIdPiece = tId.substr(tId.indexOf("_")+1);
	if (isNaN(tIdPiece)) {
		tdCode = tIdPiece.substr(0,1);
		tdNumber = tIdPiece.substr(1);
	} else {
		tdCode = "w";
		tdNumber = tIdPiece;
	}
	if (getObject("td" + tdCode + "1_" + tdNumber)) {
		clName = getObject("td" + tdCode + "1_" + tdNumber).className;
		if (clName == "nb") {
			getObject("td" + tdCode + "1_" + tdNumber).className = "nbHilite";
			getObject("td" + tdCode + "2_" + tdNumber).className = "descHilite";
		}
	}
	extraBetHilite = new Array(true,tdCode,tdNumber);
	clearTimeout(extraBetTimeout);
	extraBetTimeout = setTimeout(clearBubble,5000);
}


function showPriceBubble(text,bWidth,dPos,refImgId) {
	var el = getObject("bubble");
	el.className = "pricebubble";
	el.style.width = (bWidth?bWidth:"120") + "px";
	el.innerHTML = text;
	el.style.visibility = "visible";

	var bW = el.offsetWidth;
	var bH = el.offsetHeight;	

	var baseX = getObject(refImgId).offsetLeft;
	var baseY = getObject(refImgId).offsetTop;
	var dX;
	var dY;
	switch (dPos) {
		case "right":
			dX = baseX + getObject(refImgId).style.width;
			dY = baseY;
			break;
		case "left":
			dX = baseX - 8 - bWidth;
			dY = baseY;
			break;
		default:
			dX = baseX + getObject(refImgId).style.width;
			dY = baseY;
	}
	el.style.left = ((dX)>0?((dX + bW)<document.body.clientWidth?(dX):(document.body.clientWidth-bW)):0) + "px";
	el.style.top = ((dY - document.body.scrollTop)>0?((dY + bH - document.body.scrollTop)<document.body.clientHeight?(dY):(document.body.clientHeight-bH+document.body.scrollTop)):document.body.scrollTop) + "px";
}

function addFlashObj(fName,fWidth,fHeight,fId,fVars) {
	if (navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length) {
		document.write("<embed type=\"application/x-shockwave-flash\" src=\"" + fName + "\" width=\"" + fWidth + "\" height=\"" + fHeight + "\"  id=\"" + fId + "\" name=\"" + fId + "\" ");
		if (fVars != "") {
			document.write("flashvars=\"" + fVars + "\"");
		}
		document.write("/>");
	} else {
		document.write("<object id=\"" + fId + "\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\"" + fWidth + "\" height=\"" + fHeight + "\">");
		document.write("<param name=\"MMplayerType\" value=\"ActiveX\" />");
		document.write("<param name=\"movie\" value=\"" + fName + "\" />");
		if (fVars != "") {
			document.write("<param name=\"flashvars\" value=\"" + fVars + "\" />");
		}
		document.write("</object>");
	}
}

