//---------------------------------------------------------------------------
// Filename: TopAjax.js
// This functions call the Ajax Interface for top bet programms
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
// Global Varibales
//----------------------------------------------------------------------------
//

// The URL for the File Interface (test only)
// var topServiceURL='/cgi-bin/dynamictopprogram.pl';

// THE URL for the Online Interface
// var topServiceURL='dynamictopprogram.jsp';

//  the round we want data for
var j_top_round=roundNumber; // var roundNumber must be Set by the JSP in the main HTML File

// Timeout between Ajax Request
// var TOPSERVICE_TIMEOUT=5000; // 5000 ==  5 Sec

// Test only 
var j_top_cycle=0; // - only needed for the file interface has to be ignored by the ClassicAjaxService "dynamictopprogram.jsp"
var roundtrip=0; // If set to 1 cycling restarts with j_cycle=0 after last sequence (file interface only)
//-------------------------------------------------------------------------------

function initTopAjax() {	
	// var url = topServiceURL+"&j_round="+j_top_round+"&ms="+(new Date().getTime());
	var url = topServiceURL+"&j_round="+j_top_round+"&j_cycle="+j_top_cycle+"&ms="+(new Date().getTime());
	// window.status=url;
	// alert(url);
	initTopRequest(url);
	// set callback function    
	topRequest.onreadystatechange = processTopRequest;    
	topRequest.send(null);
}

function initTopRequest(url) {    
	if (window.XMLHttpRequest) {        
		topRequest = new XMLHttpRequest();    
	} 
	else if (window.ActiveXObject) {        
		isIE = true;        
		topRequest = new ActiveXObject("Microsoft.XMLHTTP");    
	}    
	topRequest.open("GET", url, true);
}

function processTopRequestWithTimeount() {
	setTimeout(processTopRequest,1); 	// FIREFOX BUG "Component returned failure code: 0x80040111 (NS_ERROR_NOT_AVAILABLE)"
}

function processTopRequest() {

	if (topRequest.readyState == 4) {     
		if (topRequest.status == 200) {
			j_top_cycle++;
			var warningMessage=""; 
			var topBetArray = topRequest.responseXML.getElementsByTagName('bet'); 	// getting an Array of <bet> nodes
			for(var i=0;i<topBetArray.length;i++) {  				// for each <bet> do ....
				var result='&nbsp;';
				var detailId='-1';
				var betId=topBetArray[i].getAttribute('id');		// get the id Attrinute of <bet id="xxx">
				var myTopBet=topBetList.getTopBetById(betId);		// try to get a Bet-Object (One line in the bet program)
										// the global variable topBetlist is defined in showTopTable.js
										// in function showRoundTable();
				if(myTopBet != null) {
					var aTopBetOnTicket=null;
					var myTopBetsOnTicket=null;
					if(topBetTicket.bets != null) {			// do we have a bet ticket already?
										// the global variable is defined in showTopTable.js
										// get the first Element of a list of bets on the ticket
						myTopBetsOnTicket=topBetTicket.bets; 
										// try to get the bet we are currently looking at from the ticket
						aTopBetOnTicket=myTopBetsOnTicket.getTopBetById(betId); 
						// alert("aTopBetOnTicket="+aTopBetOnTicket);
					}
					var nodes = topBetArray[i].firstChild;		// get the first child of <bet> (normaly <betableuntil_day>xxx</betableuntil_day>)
					while(nodes != null) {			// at the and of the while we switch nodes to nodes.nextSibling
										// so we walk through all cilds of <bet>
						if(nodes.nodeType!=3) { 		// skip text nodes at this point (chr(13) and tabs)
							switch (nodes.nodeName) {
								case "betableuntil_day":	myTopBet.setGameDate(nodes.firstChild.nodeValue);
											break;
								case "betableuntil_time":	myTopBet.setGameTime(nodes.firstChild.nodeValue);
											break;
								case "tip":		var tippId=nodes.getAttribute('id');
											var tipp_is_set = -1;
											if(aTopBetOnTicket != null ) {
												tipp_is_set=aTopBetOnTicket.getTippBoxById(tippId);
												if(tipp_is_set!=-1) {
												// 	alert('aTopBetOnTicket.getTippBoxById('+tippId+')=='+tipp_is_set);
												}
											}
											tipNodes=nodes.firstChild;
											while(tipNodes != null) {
												if(tipNodes.nodeType!=3) {
													switch(tipNodes.nodeName) {
														case "quote":	var newTopQuote=tipNodes.firstChild.nodeValue;
																// newTopQuote=newTopQuote.toFixed(2);
																var oldTopQuote=myTopBet.getQuoteById(tippId);
																myTopBet.setQuoteById(tippId,newTopQuote);
																if (tipp_is_set>0) {
																	aTopBetOnTicket.setQuoteById(tippId,newTopQuote);
																	if(oldTopQuote!=newTopQuote) {
																		warningMessage+="Die Quote des Tipps "+aTopBetOnTicket.getTippByTippId(tippId)+" der Wette "+myTopBet.betEvent+" hat sich von "+formatQuote(oldTopQuote)+" auf "+formatQuote(newTopQuote)+" geändert\n";
																	}
																}
																break;
														case "status":	myTopBet.setStatusById(tippId,tipNodes.firstChild.nodeValue);
																topBetList.updateTopBet(myTopBet);
																// alert("Setting Status of Tipp "+tippId+" to "+tipNodes.firstChild.nodeValue+"\n"+myTopBet.tipp_quotesArray);
																if ((tipp_is_set>0) && (tipNodes.firstChild.nodeValue>0)) {
																	// alert('myTopBet.getTippNumberByTippId('+tippId+')');
																	deleteBetFromTicket(myTopBet.gameNumber,myTopBet.getTippNumberByTippId(tippId));
																	warningMessage+="Der Tipp "+aTopBetOnTicket.getTippByTippId(tippId)+" der Wette "+myTopBet.betEvent+" ist nicht mehr spielbar\n";
																}
																break;
														case "isresult":	
																	var win=tipNodes.firstChild.nodeValue;
																	if(win==1) {
																		myTopBet.setWinningTipp(tippId);
																		// var winningTipNrElement=document.getElementById('TIPP'+tippId+'_NR');
																		// if (winningTipNrElement != null)  {
																			// alert('Got: TIPP'+tippId+'_NR as winning TIPP: '+winningTipNrElement.style.color);
																		//	winningTipNrElement.style.color='#FF0000';
																			// alert('Done!');
																			// winningTipNrElement.innerHTML='<font color=\"red\">Hallo</font>';
																		// } 
																		// var winningTipTippElement=document.getElementById('TIPP'+tippId+'_TIPP');
																		// if (winningTipTippElement != null)  {
																		// 	winningTipTippElement.style.color='#FF0000';
																		// } 
																	
																		// var winningTipQuoteElement=document.getElementById('TIPP'+tippId+'_QUOTE');
																		// if (winningTipQuoteElement != null)  {
																		// 	winningTipQuoteElement.style.color='#FF0000';
																		// } 
																	}
																break;
														default: 		break;
													}
												}
											tipNodes=tipNodes.nextSibling;
											}
											break;
								case "result":		var time=nodes.getAttribute('time');
											time==null ? time='' : time=time+' ';
											result= nodes.firstChild ? time+nodes.firstChild.nodeValue: '';
											myTopBet.setResult(result,detailId);
											break;
								case "detailid":	detailId=nodes.firstChild.nodeValue;
											myTopBet.setResult(result,detailId);
											break;
								case "status":		var myBetStatus=nodes.firstChild.nodeValue;
											myTopBet.setBetStatus(myBetStatus);
											// if(myBetStatus==1) {
												// myTopBet.setAllTippStati(myBetStatus);
											// }
											break;
								default:
									break;
							}
						}
						nodes = nodes.nextSibling;		// switch to the next sibling (== next child of <bet>)
						// alert(nodes.nodeName);
					} // end while

					topBetList.updateTopBet(myTopBet);			// update the list of bets in the program

					if(aTopBetOnTicket!=null) {			//if the bet is on the ticket....
						myTopBetsOnTicket.updateTopBet(myTopBet);	// update the ticket, too.
						
					}
				} // end if(myTopBet != null)
			} // end for
		// alert('OpenId:'+getOpenId());
		//-------------------------------------------------
		// to keep open the betdetails
		//-------------------------------------------------
		keepOpen=true;
		var myWhat='';
		switch(currentSort) {
			case 0: myWhat=GAMENUMBER;
				setButtonImage('SORTNUMBER');
				break;
			case 1: myWhat=EVENT;
				setButtonImage('SORTEVENT');	
				break;
			case 2: myWhat=GAMEDATE;
				setButtonImage('SORTDATE');
				break;
			case 3: myWhat=LEAGUE;
				setButtonImage('SORTLEAGUE');
				break;
			case 4:	myWhat=BET_EVENT;
				setButtonImage('SORTBETEVENT');
				break;
			case 5:	myWhat=BETTYPE;
				setButtonImage('SORTBETTYPE');
				break;
			deafult:myWhat=GAMENUMBER;
				setButtonImage('SORTNUMBER');
				break;
		}
		setSortFlag(currentSort);
		sort(myWhat);
		// drawRoundTable(getCode(getOpenId())) // MST
		// showRoundTable('',getOpenId());					// redraw the program (getOpenId and showRoundTable are defined in showTopTable.js
		// keepOpen=false;    // MST

		if(topBetTicket.bets!=null) {							// if we have a bet ticket...				
			topBetTicket.renewBetList();						// redraw the ticket
			topBetTicket.renewSummary();
		}
		if(warningMessage!="") {					// whenever there were warnings ... (quote or status changes)
			alert("Achtung!\n"+warningMessage);			// Alert the customer
		}
		setTimeout("initTopAjax()", TOPSERVICE_TIMEOUT);				// do the initial poll after TOPSERVICE_TIMEOUT again and agian and again....
		}
										// for test only!
		if ((topRequest.status == 404) && (roundtrip==1)) {	// if we did not find a XML file for the current cycle
									// and the variable roundtrip in this script was set to 1
			j_top_cycle=0;					// we reset cycle to 0
			initTopAjax();					// and start Ajax again.
			
		} else {
			setTimeout("initTopAjax()", TOPSERVICE_ERRORTIMEOUT);
		}
		keepOpen=false; // MST
	}
}
