/* 
http://www.captain.at/howto-ajax-form-post-request.php
http://www.json.org/js.html
*/

var req;
var oXmlHttp = null;
var iInterval = 5000;
var iLastUpdateId = -1;
var divNotification = null;
var tab_id="";

var last_update="";
var last_id="";
var dorf='T';

var sort_col=0;
var sort_type=0;

var SORT_COLUMN_INDEX;
var daveCNT=0;
var refreshCNT=300;

var ccu_timeout = null;

arr_ajax_cells = new Array();
arr_ajax_names = new Array();

function checkCellUpdate() {
	var url="";

	last_update='20060718090000';
	if(iLastUpdateId === '') iLastUpdateId=-1;

	tab_id = document.getElementById('table_id').firstChild.nodeValue;

	/* Add if POST fails
	  var myvariables = "firstname=patrick&lastname=otten";
	  var mytime= "&ms="+new Date().getTime();
	  var url = "ajax/page.php?"+myvariables+mytime;
	*/
	//url="http://deven.oddschecker.com/loadJSON.php?ti="+tab_id+"&li="+iLastUpdateId+"&cnt="+daveCNT++;

	//url="loadJSON.php?ti="+tab_id+"&li="+iLastUpdateId+"&cnt="+daveCNT++;
	var params="ti="+tab_id+"&li="+iLastUpdateId+"&cnt="+daveCNT++;
	url = "loadJSON.php";

	dorf=getCookie("odds_type");
	if(dorf === '' || dorf == null) dorf='T';
	if(dorf.match(/traditional/)) dorf='T';
	if(dorf.match(/decimal/)) dorf='D';
	if(dorf.match(/us/)) dorf='A';

	/*
	if(daveCNT>refreshCNT) {
		window.location.reload();
		daveCNT=0;
	}*/
	
	sort_type=getCookie("sort_type");
	//alert('Sort Type '+sort_type);
	//alert('URL '+url+' Table '+tab_id+' dorf '+dorf+' params '+params);
	loadJSON(url,pollServerJSON,params);
}

function loadJSON(url,func,params) {
	if(!oXmlHttp) {
		oXmlHttp = zXmlHttp.createRequest();
		if (oXmlHttp.overrideMimeType) {
            oXmlHttp.overrideMimeType('text/html');
        }
	} else if (oXmlHttp.readyState != 0) {
		oXmlHttp.abort();
	}

  	oXmlHttp.onreadystatechange = func;

	//oXmlHttp.open("GET",url,true);
	oXmlHttp.open("POST",url,true);
	
    oXmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    oXmlHttp.setRequestHeader("Content-length", params.length);
    oXmlHttp.setRequestHeader("Connection", "close");

	//oXmlHttp.send(null);
	oXmlHttp.send(params);
}

function pollServerJSON() {
	if(oXmlHttp.readyState == 4) {
		try {
			if(oXmlHttp.status == 200) {
			
			   	if(oXmlHttp.responseText.match(/\[\{.+?\}\]/)) {
					
 					//var updates = eval('(' + oXmlHttp.responseText + ')');
 					var updates = json_parse(oXmlHttp.responseText);
 					//var updates = oXmlHttp.responseText;
					len = updates.length;

					for(i=0;i<len;i++) {
						id= updates[i].id;

						if(id != iLastUpdateId) {
							//alert('cell '+updates[i].cellId+' odds '+updates[i].odds+' inout '+updates[i].inout);
							if(id>0) showOdds(updates[i].cellId,updates[i].odds,updates[i].tdodds,updates[i].inout,updates[i].fdodds,updates[i].is_best);
							//iLastUpdateId = id;
						}
						iLastUpdateId = id;
					}
				}
				ccu_timeout = setTimeout(checkCellUpdate,iInterval);
			}
		} catch (e) {
	    	/*
	    	alert("Error. HTTP Status: "+oXmlHttp.status);
			txt="There was an error on this page.\n\n";
			txt+="Error description: " + e + "\n\n";
			txt+="Click OK to continue.\n\n";
			alert(txt);
			*/
			if(ccu_timeout) clearTimeout(ccu_timeout);
			ccu_timeout = setTimeout(checkCellUpdate,iInterval);
		}
	}
}

function returnClass(inout,best) {
	var str='';
	best=false;

	if(best==true) {
		if(inout=='IN') {
			str = "oib";
		} else if(inout=='OUT') {
			str= "oob";
		} else {
			str= "ob";
		}
	} else {
		if(inout=='IN') {
			str = "oi";
		} else if(inout=='OUT') {
			str= "oo";
		} else {
			str= "o";
		}
	}

	// alert('Returning '+str+' Best '+best);
	return str;
}


function showOdds(cellId,odds,dOdds,inout,pdOdds,is_best) {
	
	var ele='';
	var best;
	var rowcol='';
	var bs_str='';
	var resort=false;
	var bestclass=false;
	var was_best=false;
	var hmwb=0;
	var cnt_best=0;

	// Non racing
	if(cellId.match(/SI|EX|PN|GG|IG|PY/)) return;

	// Betexs
	//if(cellId.match(/BF|BD|IB|WB/)) return;

	//alert(' Cell ID '+cellId);
	//odds cells stored in the js table so no need to do getElementById for the same cell twice
    if(arr_ajax_cells[cellId] == undefined) {
    	cell = document.getElementById(cellId);
    	arr_ajax_cells[cellId] = cell;
    } else {
    	cell = arr_ajax_cells[cellId];
    }

	rowcol = cellId.split(/[_]/);
	name_cell_id = rowcol[0] + '_name';
	
	//participant names stored in the js table so no need to do getElementById for the name twice
	if(arr_ajax_names[name_cell_id] == undefined) {
    	name = document.getElementById(name_cell_id).innerHTML;
    	arr_ajax_names[name_cell_id] = name;
    } else {
    	name = arr_ajax_names[name_cell_id];
    }
	
	var num = cell.innerHTML;

	// Don't bother if the same
	oarr=odds.split(/[\/]1/);
	if(oarr[0]==num) return;
    

	// Remove trailing /1 and zeros for cell space
	//odds.replace(/[\/]1$/,'');
	//dOdds.replace(/[.]00?$/,'');

	// Don't bother if the same
	curr_dodds = cell.getAttribute("dodds_bslip");
	if(parseFloat(dOdds)==parseFloat(curr_dodds)) return;
    //else eval('timer_'+ cellId + " = setTimeout(\"blinkCell('" + cellId + "',0)\",400);");
    
	//alert(' Name '+name+' Cell ID '+cellId+' content '+num+' Odds '+oarr[0]);
	if(cell.innerHTML.match(/nbsp/) || name.match(/N\/R/)) {
	// if(cell.innerHTML.match(/nbsp/)) {
		// Do nothing
	} else {
		// Get old decimal odds to check against best
		old_dodds=cell.getAttribute("dodds_bslip");

		// Always set betslip value to trad odds
		cell.setAttribute("odds_bslip",odds);

		// Now lets set the decimal odds
		cell.setAttribute("dodds_bslip",dOdds);

		// Now set the cell value to be viewed in tge table based on cookie settings
		bs_str=(dorf=="T")?odds:dOdds;

		// cell.innerHTML = odds;
		cell.innerHTML = bs_str;

		// Lets exit now we have updated the odds as no best odds processing reqd
		if(cellId.match(/BF|BD|IB|WB/)) return;
		if(cell.getAttribute("submarket_bslip")=="N") return;

		// Get the value of best odds
		bestid=rowcol[0]+"_best";
		best=document.getElementById(bestid).innerHTML;

		// If old odds greater than best, then reset best
		if(parseFloat(old_dodds)>parseFloat(best)) {
			document.getElementById(bestid).innerHTML=old_dodds;
			resort=true;
		}
		//alert("Curr best for "+name+" is "+best);

		// If best then set the sorting column
		//if(is_best) document.getElementById(bestid).innerHTML = dOdds;

		if(parseFloat(dOdds)>parseFloat(best)) {
			var cssString = 'font-weight: bold;';
			cell.style.cssText = cssString;
			cell.setAttribute('style',cssString);

			// If best has changed reset and flag for re-sort
			if(parseFloat(dOdds)>parseFloat(best)) {
				//alert("UP Reseting best for "+name+" from "+document.getElementById(bestid).innerHTML+" to "+dOdds);
				document.getElementById(bestid).innerHTML=dOdds;
				best=dOdds;
				resort=true;
			}
		} else if(parseFloat(dOdds)==parseFloat(best)) {
			var cssString = 'font-weight: bold;';
			cell.style.cssText = cssString;
			cell.setAttribute('style',cssString);

		} else if(parseFloat(dOdds)<parseFloat(best)) {
			var cssString = 'font-weight: normal;';
			cell.style.cssText = cssString;
			cell.setAttribute('style',cssString);

			// Check if value was best but has dipped
			if(parseFloat(old_dodds)==parseFloat(best)) {
				was_best=true;
				resort=true;
			}
		}

		// If best odds has changed reset the styles
		if(resort) {
			/* Now lets do other bookies
			  var bks=new Array("B3","BX","BY","FR","SO","VC","BS","PP","BT","SK","SJ","LD","CE","WH","EE");
			  bks table is now created in html_head.xsl dynamically for current bookies
			*/
			for(x=0;x<bks.length;x++) {
				cid = rowcol[0]+"_"+bks[x];

				//alert("BK "+cid);
				// Lets check the other bookies in the table
				if(cid != cellId) {
				    //bookie has no odds for this market
					if(bk_cell = document.getElementById(cid)) {
					
						//alert(bk_cell);
						
						bk_odds=bk_cell.getAttribute("dodds_bslip");
	
						if(bk_cell.getAttribute("submarket_bslip") != "N") {
							if(parseFloat(bk_odds)<parseFloat(best)) {
								var cssString = 'font-weight: normal;';
								bk_cell.style.cssText = cssString;
								bk_cell.setAttribute('style',cssString);
							} else if(parseFloat(bk_odds)==parseFloat(best)) {
								var cssString = 'font-weight: bold;';
								bk_cell.style.cssText = cssString;
								bk_cell.setAttribute('style',cssString);
	
								// Other bookies have best so no need to resort
								resort=false;
	
								// Increment count of number of bookies with best odds
								cnt_best++;
							} else if(parseFloat(bk_odds)>parseFloat(best)) {
								var cssString = 'font-weight: bold;';
								bk_cell.style.cssText = cssString;
								bk_cell.setAttribute('style',cssString);

								// If greater than best then reset best and resort
								document.getElementById(bestid).innerHTML = bk_odds;
								resort=true;
	
								// Set number of bookies with best to 1
								cnt_best=1;
							}
						}
					}
				}
			}
		}

		// If the odds that have changed were best and are now not
		// AND no other bookies have best odds then re-set the best odds field
		if(was_best && !cnt_best) {
			//alert("DOWN Reseting best for "+name+" from "+document.getElementById(bestid).innerHTML+" to "+dOdds);

			// Try and find new best odds
			best="0.00";
			for(x=0;x<bks.length;x++) {
				cid=rowcol[0]+"_"+bks[x];
				bk_cell = document.getElementById(cid);
				bk_odds=bk_cell.getAttribute("dodds_bslip");

				if(parseFloat(bk_odds)>parseFloat(best)) best=bk_odds;
			}

			// Now re-check in terms of styles
			for(x=0;x<bks.length;x++) {
				cid=rowcol[0]+"_"+bks[x];
				bk_cell = document.getElementById(cid);
				bk_odds=bk_cell.getAttribute("dodds_bslip");

				if(parseFloat(bk_odds)==parseFloat(best)) {
					var cssString = 'font-weight: bold;';
					bk_cell.style.cssText = cssString;
					bk_cell.setAttribute('style',cssString);
				}
			}
			//document.getElementById(bestid).innerHTML = dOdds;
			document.getElementById(bestid).innerHTML = best;
			resort=true;
		}

		// Check for N/R etc. with no best odds these should appear at the bottom of the table
		best=document.getElementById(bestid).innerHTML;
		if(best=='0.00') {
			best=1000000;
			document.getElementById(bestid).innerHTML = best;
		}

		// Don't want SP showing as bold
		/*
		if(cell.getAttribute("submarket_bslip")=="N") {
			var cssString = 'font-weight: normal;';
			cell.style.cssText = cssString;
			cell.setAttribute('style',cssString);
		}
		*/

		// Don't want BEXS in bold
		/*
		if(cellId.match(/BF|BD|IB|WB/)) {
			var cssString = 'font-weight: normal;';
			cell.style.cssText = cssString;
			cell.setAttribute('style',cssString);
		}
		*/

		cell.className=returnClass(inout,resort);

		resort=false;
		if(sort_type<1 && resort) ts_resortTab(0);
	}
	
	//alert(timeDiff.getDiff());
}

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 startUp() {
	if(zXmlHttp.isSupported()) {
		checkCellUpdate();
	}
}
