/**
 * supplant() does variable substitution on the string. It scans
 * through the string looking for expressions enclosed in {} braces.
 * If an expression is found, use it as a key on the object,
 * and if the key has a string value or number value, it is
 * substituted for the bracket expression and it repeats. 
 */
String.prototype.supplant = function( o ) {
	return this.replace(/{([^{}]*)}/g,
		function(a, b) {
			var r = o[b];
			return typeof r === 'string' || typeof r === 'number' ? r : a;
		}
	);
};

Array.prototype.indexOf = Array.prototype.indexOf || function(elt /*, from*/) {
	var len = this.length >>> 0;
	var from = Number(arguments[1]) || 0;
	from = (from < 0) ? Math.ceil(from) : Math.floor(from);
	if (from < 0) { from += len; }
	for (; from < len; from++) {
		if (from in this && this[from] === elt) {
			return from;
		}
	}
	return -1;
};

function $defined(obj) {
	return (obj != undefined && obj != null);
};
function $id ( id ){
	var obj = document.getElementById(id);
	return $defined( obj ) ? obj : document.createElement('select');
};
function $chkObj (id) {
	return $defined( document.getElementById(id) );
};
function $clearField (id) {
	$id(id).value='';
};
function $clear(timer){
	clearTimeout(timer);
	clearInterval(timer);
	return null;
};

function $event( event ) {
	event.preventDefault = event.preventDefault || function(){this.returnValue = false;};
	event.stopPropagation = event.stopPropagaton || function(){this.cancelBubble = true;};
	// Fix target property, if necessary
	if ( !event.target ) {
		event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either
	}
	// check if target is a textnode (safari)
	if ( event.target.nodeType === 3 ) {
		event.target = event.target.parentNode;
	}
	// Add relatedTarget, if necessary
	if ( !event.relatedTarget && event.fromElement ) {
		event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
	}
	// Calculate pageX/Y if missing and clientX/Y available
	if ( event.pageX == null && event.clientX != null ) {
		var doc = document.documentElement, body = document.body;
		event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
		event.pageY = event.clientY + (doc && doc.scrollTop  || body && body.scrollTop  || 0) - (doc && doc.clientTop  || body && body.clientTop  || 0);
	}
	// Add which for key events
	if ( event.which == null && (event.charCode != null || event.keyCode != null) ) {
		event.which = event.charCode != null ? event.charCode : event.keyCode;
	}
	// Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
	if ( !event.metaKey && event.ctrlKey ) {
		event.metaKey = event.ctrlKey;
	}
	// Add which for click: 1 === left; 2 === middle; 3 === right
	// Note: button is not normalized, so don't use it
	if ( !event.which && event.button !== undefined ) {
		event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
	}
	return event;
};

function round(value, precision){
	precision = Math.pow(10, precision || 0);
	return Math.round(value * precision) / precision;
};

var Base64 = (function(){
	var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	function _utf8_encode (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
		for (var n = 0, len = string.length; n < len; n++) {
			var c = string.charCodeAt(n);
			if (c < 128) {
				utftext += String.fromCharCode(c);
			} else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			} else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
		}
		return utftext;
	};
	function _utf8_decode (utftext) {
		var string = "", i = 0, c = c1 = c2 = 0;
		while ( i < utftext.length ) {
			c = utftext.charCodeAt(i);
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			} else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			} else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}
		return string;
	};
	return {
		encode : function (input) {
			var output = "", chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;
			input = _utf8_encode(input);
			while (i < input.length) {
				chr1 = input.charCodeAt(i++);
				chr2 = input.charCodeAt(i++);
				chr3 = input.charCodeAt(i++);
				enc1 = chr1 >> 2;
				enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
				enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
				enc4 = chr3 & 63;
				if (isNaN(chr2)) {
					enc3 = enc4 = 64;
				} else if (isNaN(chr3)) {
					enc4 = 64;
				}
				output += _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
			}
			return output;
		},
		decode : function (input) {
			var output = "", chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;
			input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
			while (i < input.length) {
				enc1 = _keyStr.indexOf(input.charAt(i++));
				enc2 = _keyStr.indexOf(input.charAt(i++));
				enc3 = _keyStr.indexOf(input.charAt(i++));
				enc4 = _keyStr.indexOf(input.charAt(i++));
				chr1 = (enc1 << 2) | (enc2 >> 4);
				chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
				chr3 = ((enc3 & 3) << 6) | enc4;
				output += String.fromCharCode(chr1) + (enc3 != 64 ? String.fromCharCode(chr2) : '') + (enc4 != 64 ? String.fromCharCode(chr3) : '' );
			}
			return  _utf8_decode(output);
		}
	};
})();

var 
	ltime,
	ctime,
	interval = 10000,
	contenturl = "getdata.php?sec=100031&noscript=1",
	response = "",
	stime,
	HistoryAjaxArea = "",
//	HistoryAjaxArea = "content main_content subcontent",
	AjaxHistory = []
;

/* === change style of popup div === */
function changeAmt(id, odd, row, lay){
	var
		amtElem = $id(id+'amt'),
		profitElem = $id(id+'profit'),
		oddElem = $id(id+'odd'),
		amtValue = amtElem.value,
		oddValue = round(oddElem.value, 2)
	;

	if( (oddValue < 1.01) || (oddValue > 1000) ) {
		alert( js_messages["Odds value for this market should be between 1.01 and 1000"] );
		oddElem.value = oddValue = 1.01;
	}

	if (lay == 1) {
// 		document.getElementById(profitId).value = parseFloat(amt).toFixed(2);
		CalculateLiabltyProfit(id);
	} else {
		profitElem.value = round( amtValue*(oddValue - 1 ), 2);
	}
	
	ScriptDoLoad( "getdata.php?sec=100006&id="+id+"&amt="+amtValue+"&odd="+oddValue, "tmp", '', 1);
	ScriptDoLoad( contenturl, "content", '', 1);
}

function silentUpdateOdd(id, row, lay, diff) {
	var 
		oddElem = $id(id+'odd'),
		oddVal = Math.min(Math.max(parseFloat(oddElem.value) + diff, 1.01), 999)
	;
	oddElem.value = round(oddVal, 2);
	changeAmt(id, oddVal, row, lay);
}

function add(id, row, lay){
	silentUpdateOdd(id, row, lay, 0.01);
}

function subtract(id, row, lay){
	silentUpdateOdd(id, row, lay, -0.01);
}

function CalculateLiabltyProfit(id){
	$id( id + 'profit' ).value = round( $id(id + "amt").value * ($id("sel_"+id).value == 'liability' ? ( $id(id + "odd").value - 1) : 1), 2);
}

function getProfileType( etype ){
	ScriptDoLoad( "getdata.php?sec=000003&subsec=myinfo&etype="+etype, 'main_content');
}

function selectCurrencyReport(subsec, area){
	ScriptDoLoad("getdata.php?sec=reports&subsec=" + (subsec || $id('rep_type').value), ( area || 'subarea'));
}

function selectLeague() {
	ScriptDoLoad( "getdata.php?sec=100051&subsec=updt&sport="+$id('sport').value ,'main_content');
}

function selectEvent() {
	ScriptDoLoad( "getdata.php?sec=100051&subsec=updt&sport="+$id('sport').value+"&league="+$id('league').value, 'main_content');
}

function selectCatLeagues(area) {
	$j.get("getdata.php?sec=100762&sport=" + $id('sport').value, function(data) {
		$j('#' + area).children('select').html(data);
	});
}

function selectLeagueEvents(area){
	$j.get("getdata.php?sec=100772&league="+$id('league').value, function(data) {
		$j('#' + area).children('select').html(data);
	});
}

function showEvents(){
	ScriptDoLoad( "getdata.php?sec=100051&subsec=eve&sport="+$id('sport').value+"&league="+$id('league').value+"&event="+$id('event').value, 'sub_content');
}

function GetLeagues( area ){
	ScriptDoLoad( 'getdata.php?sec=100013&sportid=' + $id('sport').value, area );
}

function SubmitSearchForm( url, formname, area, val ) {
	$id('datesec').value = val;
	ScriptDoLoadPost( url, formname, area);
}

/* func to submit alarms *///
/* old function */
function SettleEvents( url, subpos, mid){
		var action= $id('action' + mid).value;
		if (action != ''){
			ScriptDoLoad( url + "&action=" + action ,subpos);
		} else {
			return false;
		}
		return true;
}

function ClearDateSec(url,formname,xsubpos){
	$clearField('datesec');
	ScriptDoLoadPost(url,formname,xsubpos);
}

// func to list leagues
function Listleagues(url,xpos,query){
	if( $chkObj('betcard') ) {
		$id(xpos).style.display = '';
		ScriptDoLoad(url,xpos);
		setTimeout(function(){ScriptDoLoad('getdata.php?sec=100003&subsec=bcdisp','betcard');},1000);
	} else {
		window.location.href='home.php?sid=' + xpos.split("larea")[1];
	}
}

// show events while selecting league
function ShoweEvents(url, xpos, league){
	$clear(ctime);
	ScriptDoLoad( url + '&lid=' + $id('league').value + (!league ? '&eventid=' +  $id('event').value : ''), xpos);
}

// func to add default match bets
function AddDefaultMatchBet(url, xpos, load_func){
	if( !$chkObj('bet') ) {
		ScriptDoLoad('getdata.php?sec=100003&subsec=bcdisp','betcard');
		setTimeout(function(){
			ScriptDoLoad(url, xpos);
		},200);
	}else{
		ScriptDoLoad(url, xpos);
	}
}

function CheckUserId(url, xpos){
	ScriptDoLoad(url + '&uid=' + $id('uid').value, xpos);
}

function ScriptDoLoadPostCustom(url, form, area, sec, subsec, cust) {
	if (sec) { document.forms[form].sec.value = sec; }
	if (subsec) { document.forms[form].subsec.value = subsec; }
	ScriptDoLoadPost(url, form, area);
}

function ScriptDoLoadPost(url, formName, area, NoLoading, callback){
	var form = document.forms[formName], 
		/* tempory fix for IE */
		POST = true || (form.method || 'post').toLowerCase() == 'post',
		data = FormSerialize( form )
	;
	if( POST ) {
		jQuery.ajax({
			type: "post",
			data: data,
			url: url,
			beforeSend: function(){
				jQuery(document).trigger( jQuery.extend(jQuery.Event('show__loading'), {NoLoading: !!NoLoading, area: area, formName: formName }) );
			},
			success: function(html, status){
				if( !(jQuery.isFunction(callback) && callback.apply(document.forms[formName], arguments) === false) ) {
					jQuery("#"+area).html(html);
				}
				jQuery(document).trigger( jQuery.extend(jQuery.Event('hide__loading'), {NoLoading: !!NoLoading, area: area, formName: formName }) );
			}
		});
	} else {
		ScriptDoLoad( url + (url.indexOf('?') < 0 ? '?' : '&') + data, area, '', NoLoading, false, true);
	}
}

function ScriptDoLoad(url, area, hashval, NoLoading, NoClearInterval, EmptyResponse){
	if( ScriptDoLoad["content"] && jQuery.isFunction( ScriptDoLoad["content"].abort ) ) { ScriptDoLoad["content"].abort(); }
	var 
		hisrtoryArea = HistoryAjaxArea.split(" "),
		index = hisrtoryArea.indexOf( area ),
		contentArea = " content main_content subcontent ".indexOf(" "+ area +" ") > -1
	;
	if ( index > -1 && !hashval ) {
		var copyUrl = url.slice(0);
		if( url.indexOf("?") > -1 ) {
			url = encodeURI( url.split("?")[1].split("&amp;").join("&").split("&").join("/").split("=").join("/") );
		}
		hashval = "u="+url+"&a="+index+"&nl="+1*(!!NoLoading)+"&nci="+1*(!!NoClearInterval)+"&er="+1*(!!EmptyResponse);
		url = copyUrl;
		AjaxHistory.push( url );
	}
	if ( index > -1 && typeof hashval == "string" && hasval ) {
		location.hash = hashval;
		ScriptDoLoad.hash = hashval;
	}
	if (area == 'content' && !$chkObj('content')) {
		area = 'main_content';
	}

	if ((area == 'content') || (area == 'eventsel')){
		contenturl = url;
		if(!NoClearInterval) { $clear(ctime); }
	}

	if (area == 'bet') { 
		if (!$chkObj('bet')) {
			ScriptDoLoad('getdata.php?sec=100003&subsec=bcdisp','betcard');
			setTimeout( function(){ ScriptDoLoad( url, area ); },200);
			return;
		} else {
			$id('betcard').style.display = '';
		}
	}
	
	var maxrequest = 5, target = $id( area ), tuid = 'timer'+ jQuery.now();
	
	var getdata = function(){
		ScriptDoLoad[ contentArea ? "content" : "other" ] = jQuery.ajax({
			url: url,
			beforeSend: function(){
				jQuery(document).trigger( jQuery.extend(jQuery.Event('show__loading'), {NoLoading: !!NoLoading, area: area}) );
			},
			success: function(html, status){
				if (!EmptyResponse && !html && (area == "main_content" || area == "content") && maxrequest--) {
					target[tuid] = setTimeout(getdata, 100);
					return;
				}
				$clear(target[tuid]);
				getdata = function(){};
				jQuery(target).html(html);
				jQuery(document).trigger( jQuery.extend(jQuery.Event('hide__loading'), {NoLoading: !!NoLoading, area: area}) );
				ScriptDoLoad[  contentArea ? "content" : "other" ]  = null;
			}
		});
	};
	
	target[ tuid ] = setTimeout( getdata, 0);
}

function PlaceBetReload(){
	ScriptDoLoad(contenturl, 'content');
	setTimeout( function(){
		ScriptDoLoad('getdata.php?sec=100021','logoutbox');
	},200);
}

function DefaultReload(ScriptUrl,ScriptPos,no_interval){
	$clear(ctime);
	if(no_interval) {
		ScriptDoLoad(ScriptUrl,ScriptPos, location.hash.replace("#",'') || 1,1);
	} else {
		ctime = setInterval(function() {
			ScriptDoLoad(ScriptUrl, ScriptPos, location.hash.replace("#",'') || 1, 1, true);
		}, interval);
	}
}

function toForm ( form ) {
	var _form = form;
	if( typeof form == 'string' ) {
		_form = document.forms[form];
		if( !$defined( _form ) ) {
			_form = $id(_form);
			if( /^select$/i.test(_form.tagName) ) {
				_form = jQuery( form );
				_form = _form.length ? form.get(0) : null;
			}
		}
	}
	return ( _form.nodeType == 1 && /^form$/i.test(_form.tagName) ) ? _form : null;
}

function FormSerialize( form ) {
	return jQuery( toForm(form) ).serialize();
}

function ClearBetCard(){
	ScriptDoLoad( 'getdata.php?sec=100005&subsec=clear', 'betcard');
}

function SearchEvents(url, xpos){
	$clear(ctime);
	ScriptDoLoad(url + "&keyword="+$id("searchbox").value, xpos, '', 1);
}

function ShowJavascriptConfirm(url,xpos){
	return confirm("Do you really want to proceed?") && ScriptDoLoad(url,xpos);
}

function confirmSubmitPost(url,xform,xpos){
	return confirm("Do you really want to proceed?") && ScriptDoLoadPost(url, xform, xpos);
}

function ShowPagination(pageno, url, formname, xpos){
	$id('pageno').value = pageno;
	ScriptDoLoadPost( url, formname, xpos);
}

function checkEnter(event, script, fname ) {
	event = $event(evetn || window.event);	
	if ( event.which == 13 || event.which == 10 ) {
		$clear(ctime);
		SearchEvents(script,fname);
		event.preventDefault();
		event.stopPropagation();
	}
}

function changeColor(id,url,pos){
	var rid = "place_bet,my_bet,event_info".split(",");
		
	for( var i = 0, n = rid.length; i < n; i++ ) {
		var elem = $id( rid[i] ),
			fontWeight = ( id == rid[i] ) ? "700" : "400",
			textDecoration = ( id == rid[i] ) ? "none" : "underline";
		elem.style.fontWeight = fontWeight;
		elem.style.textDecoration = textDecoration;
	}

	$id('betcard_bot').style.display = 'none';

	if (!url) { return; }
	
	ScriptDoLoad(url,pos,'', 1);
	
}

function hideArea(xpos){
	var elem = $id(xpos);
	elem.style.display = 'none';
	elem.innerHTML = '';
}

function showArea(xpos){
	$id(xpos).style.display = '';
}

function SettleEvent(url,xpos,no_status){
	if ( no_status || $id('status').value == 'settle' ){
		ShowJavascriptConfirm(url,xpos);
	}
}

function OpenNewWindow(url,win_width,win_height){
	window.open(url,'mywindow','width='+win_width+',height='+win_height+',left=160,top=115,screenX=160,screenY=110');
}

function confirmExclusion() {
	if ( $id('excluded').checked ) {
		if (!confirm("Self exclusion will prevent you from placing any bets, and from accessing your account for a minimum of 6 months. Any un-matched bets will be cancelled. Any matched bets will stand. Should you have any available funds in your account, please withdraw them before invoking self exclusion or contact the Helpdesk to ask for a withdrawal on your behalf. Your account will not be reactivated under any circumstances during the 6 months minimum exclusion period. If we become aware of any other accounts held by you, we will enforce self exclusion on those accounts additionally. For further information regarding our Responsible Gambling Policy, please contact our Helpdesk.")) {
			$id('excluded').checked  = false;
		}
	}
}

function euclid(n, m) {
	if (m == 0) return n;
	var p = n % m;
	while (p != 0) {
		n = m;
		m = p;
		p = n % m;
	}
	return m;
}

function ConvertToFractional(odds){
	var odd = parseFloat(odds);
	var trad = "";
	if (isNaN(odd) || odd == 0) {
		trad = "0/0";
	} else {
		odd = Math.round((odd - 1) * 100);
		var e = euclid(odd, 100);
		trad = (odd / e) + "/" + (100 / e);
	}
	Tip(trad);
}

function CheckProfitLoss() {
	if ( $id('check_prft_loss').checked ) {
		$id('check_settle_bet').disabled = $id('check_exp_comm').disabled = $id('check_exp').disabled = false;
	} else {
		$id('check_settle_bet').disabled = $id('check_exp_comm').disabled = $id('check_exp').disabled = true;
		$id('check_exp_comm').checked = $id('check_settle_bet').checked = $id('check_exp').checked = false;
	}
}

function showInterval(url,pos,count_int){
	if( count_int > 0 ) {
		$id(pos).innerHTML = 'Placing bet in '+ count_int + ' seconds';
		stime = setTimeout(function(){
			showInterval(url,pos, --count_int);
		},interval);
	} else {
		count_int = 0;
		$clear(stime);
		ScriptDoLoad(url,'betcard');
	}
}

function AddValueToOption(inputid,selectid){
	var inpElem = $id(inputid), value = inpElem.value;
	if( !value ) return;
	jQuery("#"+selectid).append('<option value="'+value+'">'+value+'</option>');
	inpElem.value = '';
}

function RemoveValueToOption(selectid){
	jQuery("#"+selectid).children(":selected").remove();
}

function SelectAllAndSubmit(selectid,xform,xarea){
	selectAllOptions(selectid);
	confirmSubmitPost('getdata.php',xform,xarea);
}

function selectAllOptions(selectid) {
	var obj=$id(selectid);
	for (var i=0, len = obj.options.length; i < len; i++) { obj.options[i].selected = true; }
}

function submitFormByName(act, form, cont, NoLoading, callback){
	if( "subsec" in document.forms[form] ) {
		document.forms[form].subsec.value = act;
	}
	ScriptDoLoadPost('getdata.php', form, cont, NoLoading, callback);	
}

function submitForm(act, NoLoading, callback) {
	submitFormByName(act, 'betFn', 'main_content', NoLoading, callback);
}

var Router = (function(){
	var hash, iframe, name = "iframe"+(new Date()).getTime(), hisrtoryArea = HistoryAjaxArea.split(" ");
	var setIframeLocation = function (h) {
		if (h) {
			var doc = iframe.contentWindow.document;
			doc.open().close();	
			doc.location.hash = h;
		}
	};
	var parseUrl = function ( url ){
		for( var i = 0,params = url.split("/"), n = params.length, url = "getdata.php"; i < n; url += ( i && i & 1 ?  "="  : ( i ? "&" : "?" ) ) + params[i++] );
		return url;
	};
	var reloadContent = function(h){
		if (hash !== h && ScriptDoLoad.hash == h){ hash = h; }
		if (hash !== h && ScriptDoLoad.hash != h) {
			if( h ) {
				var params = h.split("&"), len = params.length, args = [];
				if( len > 1 ) {
					args[0] = parseUrl( decodeURI(params[0]).replace(/^u=/, '') );
					args[1] = hisrtoryArea[params[1].replace(/^a=/, '')];
					args[2] = h;
					args[3] = len > 2 ? parseInt(params[2].replace(/^nl=/, '')) : 0;
					args[4] = len > 3 ? parseInt(params[3].replace(/^nci=/, '')) : 0;
				} else {
					throw new Error("incorrect hash url");
				}
				hash = h;
				ScriptDoLoad.apply(window, args);
			}
		}
	};
	if ( "\v" == "v" && !window.Storage ) {
		// create iframe that is constantly checked for hash changes
		if ( !iframe ) {
//			iframe = document.createElement('iframe');
//			iframe.scr = "javascript:false;";
//			iframe.style.display = "none";
//			iframe.name = iframe.id = name;
//			window.document.body.appendChild(iframe);
//			return function(){
//				setInterval(function() {
//					var idoc = iframe.contentWindow.document,
//						h = idoc.location.hash.replace("#", '');
//					reloadContent(h);
//				}, 100);
//			};
//			setIframeLocation(location.hash || '#');
		}
	} else { 
		return function(){
			setInterval(function() {
				var h = location.hash.replace("#", '');
				reloadContent(h);					
			}, 100);
		}
	}
})();

