
//debug globals
var _totaldelays = 0;  //temp testing
var _numberrequests = 0;    //temp testing

//globals
var _objHttp = null;
var _pendingRequests=new Array;
var _pendingRequestsCount=1;
var _pendingRequestsCurrent=0;
var _pendingRequestsCurrent = "";
var _overaddiv = false;
var _chatwindow = null;
var _fireFoxSavedHeight = 0;
var _playerActive = true;
var _timedOut = false;
var _playnexttext = "Play next available";
var _transparenttext = "transparent";
var _roundsremainingtext = " Rounds remaining: ";
var _firstView=true;
var _scrolling = false;
var _scrollingDown = false;
var _scrollingUp = false;
var _offsetChatHeight=null;  //iphone scroll bug
var _offsetChatWidth=null;  //iphone scroll bug
var	_disableclick=false;
var	_guessed = false;
var _gamechatfocused = false;
var _zoomscale = 1;

//timers
var chatTimerID = null;
var playerActiveTimerID = null;
var skipTimerID = null;

var agt=navigator.userAgent.toLowerCase();
var is_nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
        && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
        && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1));
var is_mac    = (agt.indexOf("mac")!=-1);
var is_linux = (agt.indexOf("inux")!=-1);
var is_safari = (agt.indexOf("safari")!=-1);
var is_iphone = ((agt.indexOf("webkit")!=-1) && (agt.indexOf("mobile")!=-1)) || (agt.indexOf("iphone simulator")!=-1);
var is_IE=!is_nav;



//------------------------------------- Global Events ---------------------------------------

if (is_nav) {
	document.captureEvents(Event.CLICK);
	document.captureEvents(Event.KEYDOWN);
};	

window.onbeforeunload=PageQuit;
window.document.focus();


	
//------------------------------------- Global Start/Stop ------------------------------------

function PageQuit()
{

	if (_timedOut) return;
	if (_objHttp) ClearPendingRequests();
		
	if  (_overaddiv) {} //alert('Hit backspace to return to Geosense')
	else {
		if (_chatwindow!=null && !_chatwindow.closed) _chatwindow.close();
		HttpSend("commandcomm.aspx?rev=1.20&command=ENDSESSION");  //ASYNC
		try {
			if (window.top.opener) window.top.opener.newwindow=null;
			//window.top.opener.location.href=window.top.opener.location.href; //refresh for ads
		}
		catch (er) {}	
	}
};
	
	
function AddIphoneEvents() {
	if (is_iphone) {
	  document.removeEventListener("touchstart", TouchStart, false);
	  document.removeEventListener("touchmove", TouchMove, false);
	  document.removeEventListener("touchend", StoreGuess, false);
	  ge("divPlayerTableWrap").removeEventListener("touchmove", TouchScroll, false);
	  document.addEventListener("touchstart", TouchStart, false);
	  document.addEventListener("touchmove", TouchMove, false);
	  document.addEventListener("touchend", StoreGuess, false);
	  ge("divPlayerTableWrap").addEventListener("touchmove", TouchScroll, false);
	  
	  ge("btnScrollUp").removeEventListener("touchstart", ScrollPlayersUpStart, false);
	  ge("btnScrollDown").removeEventListener("touchstart", ScrollPlayersDownStart, false);
	  ge("btnScrollUp").removeEventListener("touchend", ScrollPlayersUpStop, false);
	  ge("btnScrollDown").removeEventListener("touchend", ScrollPlayersDownStop, false);
	  ge("btnScrollUp").addEventListener("touchstart", ScrollPlayersUpStart, false);
	  ge("btnScrollDown").addEventListener("touchstart", ScrollPlayersDownStart, false);
	  ge("btnScrollUp").addEventListener("touchend", ScrollPlayersUpStop, false);
	  ge("btnScrollDown").addEventListener("touchend", ScrollPlayersDownStop, false);
	}
};


function StartAll() {

	AddIphoneEvents();
	playerActiveTimerID  = setTimeout("InactiveTimer()", 60000);
	
	if (is_iphone) SetIphoneDisplay();
	
	if (!is_safari) { 
		//if (ge("divEntryPage").offsetHeight > document.body.clientHeight) ge("divEntryPage").style.height=document.body.clientHeight;
		//ge("divGamePage").style.height=document.body.clientHeight;
	}
	
	if (is_IE) { 
		ge("divGamePage").style.cursor="default"; //TEMP 
		ge("tblStatus").style.cursor="default"; //TEMP 
		ge("divChatInGame").style.cursor="default"; //TEMP 
		ge("divMapImage").style.zIndex="-2000";  
	 	try {
	   document.body.focus();
		}
		catch (er) {}	
	}

	ge("divViewPort").style.left="0px";

 	EntryPageStart();
  ResetIphoneDisplay();
};



//------------------------------------- Entry Page Start/Stop------------------------------------

function SetEntryGlobals() {
	_dpwindow = null;
	_chatcheckwait = 2000; //3000 bandwidth
	_plyrstatus="unavailable";
	_islinked=false;
	_playingself=false;
	_hasopponent=false;
	_pagedisabled=false;
	_cleanstate=false;
	_entrychatfocused=false;
	
	_totaldelays = 0;		//temp testing
	_numberrequests = 0;	//temp testing
	
	_admin = ge("btnDp").style.visibility == "visible";  //sgeo
	
	chatTimerID = null;
	skipTimerID = null;
	
	ClearPendingRequests();
};
 

function StartEntryPageEvents() {
	document.onkeypress = keyPress; //go to chat
	document.onclick = onClick; 
	window.onbeforeunload=PageQuit;
};

function StopEntryPageEvents() {
	document.onkeypress = null; //go to chat
	document.onclick = null; 
	chatTimerID=null;	
};

function EntryPageStart()
{
	SetEntryGlobals();
	StartEntryPageEvents();
	SetEntryPersonalPrefs();
	
	ge("btnPlayNextAvailable").value=_playnexttext;
	ge("btnLocalReady").style.visibility = "hidden";
	ge("btnRemoteReady").style.visibility = "hidden";
	ge("btnAbortLink").style.visibility = "hidden";

	if (is_nav) { //Firefox rendering bug
		if (_fireFoxSavedHeight>0) ge('divDynamicContent').style.height=_fireFoxSavedHeight+"px";
		else _fireFoxSavedHeight = ge('divDynamicContent').offsetHeight;
	}

  if (is_iphone) {
    if (_firstView) {
      _firstView=false;
      SpinToEntryNext();
    }
    else {
      SpinToEntry();
    }
    
  }
  else {
	  ge("divViewPort").style.left="0px";
  }

	
	try {
		if (_chatwindow!=null && !_chatwindow.closed) {
			_chatwindow.ge("txtChatOut").disabled=false;
			_chatwindow.ge("divChatIn").disabled=false;
			_chatwindow.ge("btnCloseChat").disabled=false;
			_chatwindow.ge("btnClearChat").disabled=false;
		}
	}
	catch (er) {}

 	var s=""+window.top.name;
	if ((s.length<12 || s.substring(0,12)!="GeosensePlay") && !is_iphone) { 
		clearTimeout(chatTimerID);
		DisablePage();
		document.onkeydown="";
		document.onkeypress="";
		ge("bdyTag").onkeydown=null;
		ge("bdyTag").onkeypress=null;
		ge("divGeosenseTitle").innerHTML="Geosense: Preview";
	}
	else {
		HttpSend( "commandcomm.aspx?rev=1.20&command=CLEANSTATE");
		_cleanstate=true;
		chatTimerID  = setTimeout("ChatTimer()", 500);
	}
};		
		
function DisablePage() 
{
	_pagedisabled=true;
	ge("divChatIn").disabled=true;
	ge("txtChatOut").disabled=true;
	ge("btnLocalReady").disabled=true;
	ge("btnPlayNextAvailable").disabled=true;
	ge("chkScramble").disabled=true;
	ge("rdbWorld").disabled=true;
	ge("rdbAdvanced").disabled=true;
	ge("rdbUS").disabled=true;
	ge("rdbEurope").disabled=true;
	ge("btnAbortLink").disabled=true;
	ge("btnPlaySelf").disabled=true;
};	


function StartGame()
{
	clearTimeout(chatTimerID);
	ge("bdyTag").style.cursor = "wait";
	skipTimerID  = setTimeout("SkipStart()", 100);
};


function SkipStart()
{
	clearTimeout(skipTimerID);
			
	ge("btnPlaySelf").style.color = "black";
	ge("bdyTag").style.cursor = "default";
	
	StopEntryPageEvents();
	GamePageStart();
};	
	
function StartTwoPlayerGame() 
{
	HttpSend("commandcomm.aspx?rev=1.20&command=PLAYING");  //ASYNC
	StartGame();
};

function StartSelfPlay()
{
	if (_plyrstatus=="available" || _plyrstatus=="unavailable") {
		_playingself=true;
		_plyrstatus="playing";
		ge("btnPlaySelf").style.color = "green";
		StartGame();
	}
	else {
		HttpSend( "commandcomm.aspx?rev=1.20&command=CLEANSTATE");
		_cleanstate=true;
		ge("btnPlayNextAvailable").value=_playnexttext;
		ge("btnLocalReady").style.visibility = "hidden";
		ge("btnRemoteReady").style.visibility = "hidden";
		ge("btnAbortLink").style.visibility = "hidden";
		_plyrstatus="unavailable";
	}
};



//-------------------------------------------- Timers  -----------------------------------------------


function ChatTimer() 
{
  if (is_iphone && !_entrychatfocused && window.top.oneIsOpen==true) ResetIphoneDisplay();

	clearTimeout(chatTimerID);
		
	if (!_dpwindow) {	
		HttpSend("entrycomm.aspx?rev=1.20");
	}
	if (_chatcheckwait<6000) _chatcheckwait+=40;
//	if (_chatcheckwait<8000) _chatcheckwait+=80   //bandwidth
	if (ge("txtChatOut").value=="sleep") _chatcheckwait=10000; //debug
	chatTimerID  = setTimeout("ChatTimer()", _chatcheckwait);
};

function InactiveTimer() 
{
  return; //bandwidth
	if (_playerActive==false && !_admin) {
		if (_objHttp) ClearPendingRequests();
		try {
			if (_chatwindow!=null && !_chatwindow.closed) {  
				_chatwindow.close();
		    HttpSend("commandcomm.aspx?rev=1.20&command=ENDSESSION");  //ASYNC
		    alert("Your Geosense session ended due to inactivity.");
				if (is_iphone) window.top.location="iphone.htm";
        else window.top.close();
			}
		}
		catch (er) {}						
	}
	
	clearTimeout(playerActiveTimerID);	
	_playerActive=false;
	playerActiveTimerID  = setTimeout("InactiveTimer()", 600000); // 10 mins
};


//-------------------------------------- Misc Player Initiated Events -------------------------------------

function onClick() {
	_chatcheckwait = 2000;//3000  bandwidth
};		


function keyPress(e)  
{
	if (!_entrychatfocused && ge("divChatControls").style.display=="block") {
		ge("txtChatOut").focus();
		ge("txtChatOut").value=ge("txtChatOut").value;
	}

	_chatcheckwait = 2000;
	
//	  var keycode;
//  
//	if (is_iphone) {
//	  keycode=13;
//	}
//	else {
//	  if (is_IE) keycode = event.keyCode;
//	  else keycode = e.which;
//	}
//	
	if (is_IE) var keycode = event.keyCode;
	else var keycode = e.which;

	if (keycode==13) {
    SendChat();
	}
	
};

function SendChat() {
																	
		var chatstr=""+ge("txtChatOut").value.replace( /\n/g, "" ).replace( /\r/g, "" );
		if (chatstr=="") {
			ge("txtChatOut").value="";
			return;		
		}
		chatstr+="\n";
					
		if (_admin) {				
			chatstr=chatstr.replace(/</g,'lhlh');
			chatstr=chatstr.replace(/>/g,'ghgh');
		}
		else {
			chatstr=chatstr.replace(/</g,'ltlt');
			chatstr=chatstr.replace(/>/g,'gtgt');
  		chatstr=chatstr.replace(/(\S{50})/g, '$1 '); //short words please
		}		
		

		if (chatstr.length>400 && !_admin) chatstr="...buffer_overflow..."+chatstr.substring(chatstr.length-400,chatstr.length);
		if (!_admin) chatstr=chatstr.replace(/^\s*/, '').replace(/\s*$/, '') + "\n"; //trim
	
		ge("txtChatOut").value="";
		HttpSend("entrycomm.aspx?rev=1.20&msg="+chatstr+"&command=");
};

function LocalReadyClick()
{
	clearTimeout(chatTimerID);

	if (ge("btnLocalReady").style.color=="red") {
		ge("btnLocalReady").style.color="green";

		HttpSend("entrycomm.aspx?rev=1.20&msg=&command=SET_PLAYERREADYON");
	}	
	
	chatTimerID  = setTimeout("ChatTimer()", 1000);
};

function AbortLinkClicked()
{
	clearTimeout(chatTimerID);

	HttpSend("entrycomm.aspx?rev=1.20&msg=&command=SET_BREAKLINK");
	
	chatTimerID  = setTimeout("ChatTimer()", 1000);
};

function PlayNextAvailableClicked()
{
	clearTimeout(chatTimerID);
		
	if (ge("btnPlayNextAvailable").value==_playnexttext) {
		HttpSend("entrycomm.aspx?rev=1.20&msg=&command=SET_AVAILABLE");	 
		ge("btnPlayNextAvailable").value="Be unavailable";
		_plyrstatus="available";
 	}
	else {
		HttpSend("entrycomm.aspx?rev=1.20&msg=&command=SET_UNAVAILABLE");
		ge("btnPlayNextAvailable").value=_playnexttext;
		_plyrstatus="unavailable";
 	}
	chatTimerID  = setTimeout("ChatTimer()", 1000);
};
		
function ScrambleClicked()
{
	ChatTimer();  // clear old chatter
	clearTimeout(chatTimerID);
	var scrambleCommand="";

	if (ge("chkScramble").checked) {				
		scrambleCommand="SET_SCRAMBLEON";
		_scramble=true;
	}
	else {
		scrambleCommand="SET_SCRAMBLEOFF";
		_scramble=false;
	}

	HttpSend("entrycomm.aspx?rev=1.20&msg=&command="+scrambleCommand);
	
	chatTimerID  = setTimeout("ChatTimer()", 2500);
};

function WorldClicked()
{
	ChatTimer();
	clearTimeout(chatTimerID);
	HttpSend("entrycomm.aspx?rev=1.20&msg=&command=SET_WORLDON"); 
	chatTimerID  = setTimeout("ChatTimer()", 2500);
};

function AdvancedClicked()
{			
	ChatTimer();
	clearTimeout(chatTimerID);
	HttpSend("entrycomm.aspx?rev=1.20&msg=&command=SET_ADVANCEDON");
	chatTimerID  = setTimeout("ChatTimer()", 2500);
};

function EuropeClicked()
{			
	ChatTimer();
	clearTimeout(chatTimerID);
	HttpSend("entrycomm.aspx?rev=1.20&msg=&command=SET_EUROPEON"); 
	chatTimerID  = setTimeout("ChatTimer()", 2500);
};

function USClicked()
{
	ChatTimer(); 
	clearTimeout(chatTimerID);
	HttpSend("entrycomm.aspx?rev=1.20&msg=&command=SET_USON");	 
	chatTimerID  = setTimeout("ChatTimer()", 2500);
};

function OpponentCellClick(acell)
{
	if (_pagedisabled) return;
	if (_admin) {	
		ge("txtChatOut").value="terminate:"+this.firstChild.innerHTML+"-30";
		return;
	}
	clearTimeout(chatTimerID);
	var opponentLinkCommand="SET_OPPONENTLINK:";
	opponentLinkCommand+=this.firstChild.innerHTML;
	HttpSend("entrycomm.aspx?rev=1.20&msg=&command="+opponentLinkCommand);
	chatTimerID  = setTimeout("ChatTimer()", 2000);
};

function TeacherAdminHit()
{	
	if (screen.width<800 || screen.height<600) {
		l=5;
		t=20;
	}
	else {
		l=(screen.width-780)/2;
		t=(screen.height-536)/4+40;
	}
	var playwindow=window.open("teacheradmin.aspx?rev=1.20","GeosenseTeacherAdmin", "toolbar=0, directories=0, location=0, status=0, menubar=0, resizable=0, scrollbars=0, width=780, height=536, top="+t+", left="+l+",screenY="+t+",screenX="+l);
	ge("btnTeacherAdmin").style.color = "green";
	ge("bdyTag").style.cursor = "default";
	playwindow.focus();
};	


function MessageBoard()
{	
	
  if (is_iphone) {
    window.top.showTwoHideOne("messageboard.aspx");
  }
  else {
    if (screen.height<=1050) t=5;
    if (screen.height<=1050) t=5;
    else t=(screen.height-650)/4+15;

    if (screen.width<900){
    w=800;
    l=15;
    }
    else {
    w=825;
    l=(screen.width-825)/2+15; 
    }

    var day = new Date();
    var timeStamp = ""+day.getTime();

    var messagewindow=window.open("loader.htm?ver=5.50&contentUrl="+escape("messageboard.aspx"),"GeosenseMessageBoard"+timeStamp, "toolbar=0, directories=0, location=0, status=0, menubar=0, resizable=1, scrollbars=0, width="+w+", height="+(screen.height<650?530:620)+", top="+t+", left="+l+",screenY=0,screenX="+l);

    ge("bdyTag").style.cursor = "default";
    messagewindow.focus();
  }

};	


function PlayInstructions()
{	
  if (is_iphone) {
    window.top.showTwoHideOne("playInstructions.htm");
  }
  else {
    if (screen.height<=1050) t=5;
    if (screen.width<800 || screen.height<600) {
    l=5;
    t=20;
    }
    else {
    l=(screen.width-780)/2;
    t=(screen.height-536)/4+40;
    }

    var playwindow=window.open("playInstructions.htm?rev=1.20","GeoSensePlayingInstructions", "toolbar=0, directories=0, location=0, status=0, menubar=0, resizable=1, scrollbars=1, width=780, height=536, top="+t+", left="+l+",screenY="+t+",screenX="+l);
    ge("bdyTag").style.cursor = "default";
    playwindow.focus();
  }
};	



function HighScores()
{		
  if (is_iphone) {
    window.top.showTwoHideOne("highscores.aspx");
  }
  else {
	  if (screen.height<=1050) t=5;
	  else t=(screen.height-650)/4+15;

	  if (screen.width<900){
		  w=800;
		  l=15;
	  }
	  else {
		  w=825;
		  l=(screen.width-825)/2+15;
	  }
  	
	  //Sept4-removed full path
	  var highwindow=window.open("loader.htm?ver=5.50&scrolling=auto&contentUrl="+escape("highscores.aspx"),"GeosenseHighScoresWorldMap", "toolbar=0, directories=0, location=0, status=0, menubar=0, resizable=1, scrollbars=0, width="+w+", height="+(screen.height<650?530:620)+", top="+t+", left="+l+",screenY=0,screenX="+l);
  	
	  ge("bdyTag").style.cursor = "default";
	  highwindow.focus();
  }
};	




function CountryScores()
{		
  if (is_iphone) {
    window.top.showTwoHideOne("countryscores.aspx");
  }
  else {
/*	
	  if (screen.height<=1050) t=5;
	  else t=(screen.height-650)/4+15;

	  if (screen.width<900){
		  w=800;
		  l=15;
	  }
	  else {
		  w=825;
		  l=(screen.width-825)/2+15;
	  }
  	
	  //Sept4-removed full path
	  var highwindow=window.open("loader.htm?ver=5.50&scrolling=auto&contentUrl="+escape("highscores.aspx"),"GeosenseHighScoresWorldMap", "toolbar=0, directories=0, location=0, status=0, menubar=0, resizable=1, scrollbars=0, width="+w+", height="+(screen.height<650?530:620)+", top="+t+", left="+l+",screenY=0,screenX="+l);
  	
	  ge("bdyTag").style.cursor = "default";
	  highwindow.focus();
*/
  }
};	




function Relo()
{
	var l;
	if (screen.width<1000) l=5;
	else l=(screen.width-1000)/2;

	_dpwindow=window.open("relo.aspx?rev=1.20","DP", "toolbar=0, directories=0, location=0, status=0, menubar=1, resizable=1, scrollbars=2, width=1000, height=620, top=0, left="+l+",screenY=0,screenX="+l);
};




//------------------------------------- Process Server Response ------------------------------------

function ProcessChat(resp) 
{
	if (resp=="OK") return;
	
	if (resp=="Timed Out.") { 
		_timedOut=true;
		if (is_iphone) window.top.location="iphone.htm";
		if (window.top) window.top.close();		
		if (document) document.close();
		return;
	}

  var resplength=resp.length;
	resp=resp.replace(/lhlh/g,'<'); //admin only
	resp=resp.replace(/ghgh/g,'>'); //admin only
  if (resp.length<resplength) resp=resp.replace(/\[admin.\]/g,'');

	resp=resp.replace(/ltlt/g,'&lt;');
	resp=resp.replace(/gtgt/g,'&gt;');
	
	var stateresp=""+resp.substring(0,resp.indexOf("!"));
	resp=resp.substring(resp.indexOf("!")+1,resp.length);
	
	var tableresp=""+resp.substring(0,resp.indexOf("!"));
	resp=resp.substring(resp.indexOf("!")+1,resp.length);

	if (stateresp=="STATE_LINKED") { 
		_hasopponent=true;
		_plyrstatus="linked";
		ge("btnLocalReady").style.color = "red";
		ge("btnRemoteReady").style.color = "red";
		ge("btnLocalReady").style.visibility = "visible";
		ge("btnRemoteReady").style.visibility = "visible";
		ge("btnAbortLink").style.visibility = "visible";
		ge("btnAbortLink").disabled=true;
		setTimeout("ge('btnAbortLink').disabled=false;", 5000);
	}
	
	if (stateresp=="STATE_READYON") { 
		ge("btnLocalReady").style.color="green";
		_plyrstatus="ready";
	}
	
	if (stateresp=="STATE_READYOFF") { 
		ge("btnLocalReady").style.color="red";
		_plyrstatus="linked";
	}
				
	if (stateresp=="STATE_BOTHREADY") {
		
		// clean state				
		clearTimeout(chatTimerID);
		_plyrstatus="playing";
		_playingself=false;
		
		ClearPendingRequests();
				
		startTwoPlayerTimer = setTimeout("StartTwoPlayerGame()", 500);
		
		return;
	}
	
	if (stateresp=="STATE_LINKABORTED") {
		_plyrstatus="unavailable";
		ge("btnPlayNextAvailable").value=_playnexttext;
		ge("btnLocalReady").style.visibility = "hidden";
		ge("btnRemoteReady").style.visibility = "hidden";
		ge("btnAbortLink").style.visibility = "hidden";
	}	
	
	if (stateresp=="STATE_SESSIONABORTED") {
		alert("aborting session");
    if (is_iphone) window.top.location="iphone.htm";
		else window.top.close();
	}
		
	if (stateresp=="STATE_SCRAMBLEON") {  
		ge("chkScramble").checked=true;
		_scramble=true;
	}
	
	if (stateresp=="STATE_SCRAMBLEOFF") {  
		ge("chkScramble").checked=false;
		_scramble=false;
	}
	
	if (stateresp=="STATE_WORLDON") {  	
		ge("rdbWorld").checked=true;
	}
		
	if (stateresp=="STATE_ADVANCEDON") {  	
		ge("rdbAdvanced").checked=true;
	}
	
	if (stateresp=="STATE_EUROPEON") {  	
		ge("rdbEurope").checked=true;
	}
		
	if (stateresp=="STATE_USON") {  		
		ge("rdbUS").checked=true;
	}
	
	if (stateresp=="STATE_UNAVAILABLE") ge("btnPlayNextAvailable").value=_playnexttext;
	if (stateresp=="STATE_AVAILABLE") ge("btnPlayNextAvailable").value="Be unavailable";
	
	if (resp!="") {		
		UpdateChat(resp);
		try {
			if (_chatwindow!=null && !_chatwindow.closed) {  
				_chatwindow.UpdateChat(resp);
			}
		}
		catch (er) {}
	}	
	UpdateTable(tableresp);
};

function UpdateTable(newuserdata)
{	

	tableitems=newuserdata.split(":");

	var tbodyElem = ge("myTbody");
	
	if (_cleanstate) {
	
		try {
			if (_chatwindow!=null && !_chatwindow.closed) _chatwindow.CleanAvailablePlayers();
		}
		catch (er) {}

		while (tbodyElem.rows.length>0) {
			tbodyElem.deleteRow(0);
		}
		_cleanstate=false;
	}
	var trElem, tdElem;
	var oldRowCount = tbodyElem.rows.length;
	var i,j,statusText;
	
	for (w=0; w<1; w+=3) {	//test many players
	for (i=0; i<tableitems.length-1; i+=3) {	
		
		var statusSymbol=tableitems[i+2];
		var plyrName = tableitems[i].substring(1,tableitems[i].length);//+w//test many players
		var opponentName = tableitems[i+1];
		var plyrRow = ge("plyr_" + plyrName);
		var plyrTypeSymbol = tableitems[i].substring(0,1);
		
		if (statusSymbol=="S" || statusSymbol=="O" || plyrName=="S") continue;
				
		switch (statusSymbol) {
			case "S": statusText="signing on"; break;
			case "P": statusText="playing"; break;
			case "U": statusText="unavailable"; break;
			case "A": statusText="available"; break;
			case "B": statusText="breakinglink"; break;
			case "L": statusText="linked"; break;
			case "R": statusText="ready"; break;
			case "O": statusText="signed on"; break;
			case "E": {
				statusText="endsession";
				if (plyrRow!=null) {				
					try {
						if (_chatwindow!=null && !_chatwindow.closed) _chatwindow.RemoveAvailablePlayers(plyrRow.childNodes[0].firstChild.innerHTML);
					}
					catch (er) {}
					tbodyElem.removeChild(plyrRow);
					continue;
				}		
				break;
			}
			case "D": {
				if (plyrRow!=null) {
					try {
						if (_chatwindow!=null && !_chatwindow.closed) _chatwindow.RemoveAvailablePlayers(plyrRow.childNodes[0].firstChild.innerHTML);
					}
					catch (er) {}
					tbodyElem.removeChild(plyrRow);			
					continue;
				}		
			}
		}
				
		var newbgColor="";
		
		if (plyrTypeSymbol=="#") {	//opponent
			newbgColor="#ff6666";
			if (_hasopponent && !(statusSymbol=="L" || statusSymbol=="R" ||  statusSymbol=="P")) {
				HttpSend( "commandcomm.aspx?rev=1.20&command=CLEANSTATE");
				_cleanstate=true;
				_hasopponent=false;
			}
			if (statusSymbol=="R") ge("btnRemoteReady").style.color="green";
			else ge("btnRemoteReady").style.color="red";
		}
		if (plyrTypeSymbol=="*") {	//self			
			newbgColor="#6699ff";
			if (statusSymbol=="L") { //other player initiated
				_plyrstatus="linked";
				_hasopponent=true;
				ge("btnLocalReady").style.visibility = "visible";
				ge("btnRemoteReady").style.visibility = "visible";
				ge("btnAbortLink").style.visibility = "visible";
				ge("btnAbortLink").disabled=true;
				setTimeout("ge('btnAbortLink').disabled=false;", 5000);
				ge("btnLocalReady").style.color = "red";
				ge("btnRemoteReady").style.color = "red";
			}
		}
		if (plyrTypeSymbol=="$") {	//requests to
			newbgColor="#e0e000";
		}
		if (plyrTypeSymbol=="%") {  //requests from
			newbgColor="#66ff33";
		}
		if (plyrTypeSymbol=="@") {  //class show for _admin 
			newbgColor="#666666";
		}
				
		if (plyrRow==null) {	
			try {
				if (_chatwindow!=null && !_chatwindow.closed) _chatwindow.AddAvailablePlayers(plyrName,(statusText=="playing"));
			}
			catch (er) {}
			trElem = document.createElement('TR');
			trElem.id = "plyr_" + plyrName;
			tbodyElem.appendChild(trElem);

			tdElem = document.createElement('TD');
			tdElem.style.width="33%";
			trElem.appendChild(tdElem);
			tdElem.innerHTML = "<div style='border:1px solid transparent'>"+((plyrName=="S")?"signing on":plyrName)+"</div>";
			tdElem.plyrTypeSymbol = plyrTypeSymbol;
			tdElem.bgColor = newbgColor;
			tdElem.onclick=OpponentCellClick;
      tdElem.onmouseover=function() { 
        switch(this.plyrTypeSymbol)
        {
          case "*":
            this.title="This is you.";
            break;
          case "#":
            this.title="This is your opponent.";
            break;
          case "$":
            if (_plyrstatus!="unavailable") break;
            this.title="You have requested to play this player, click to remove.";
            this.firstChild.style.border = "1px solid red";
            break;
          case "%":
            if (_plyrstatus!="unavailable") break;
            this.title="This player has requested a game, click to accept.";
            this.firstChild.style.border = "1px solid red";
            break;
          default:
            if (_plyrstatus!="unavailable") break;
            var statusText=this.nextSibling.nextSibling.innerHTML;
            if (statusText=="available") {
              this.title="Click to play this player.";
              this.firstChild.style.border = "1px solid red";
            }
            if (statusText=="unavailable") {
              this.title="Click to request a game with this player.";
              this.firstChild.style.border = "1px solid red";
            }
        }
      };
      tdElem.onmouseout=function() {
        this.title="";
        this.firstChild.style.border = "1px solid transparent";
      };
					
			tdElem = document.createElement('TD');
			tdElem.style.width="33%";
			trElem.appendChild(tdElem);
			tdElem.innerHTML = ((opponentName=="N")?"none":opponentName);
				
			tdElem = document.createElement('TD');
			trElem.appendChild(tdElem);
			tdElem.innerHTML = statusText;
		}
		else {
			try {
				if (_chatwindow!=null && !_chatwindow.closed) _chatwindow.UpdateAvailablePlayers(plyrName,(statusText=="playing"));
			}
			catch (er) {}
			plyrRow.childNodes[0].plyrTypeSymbol = plyrTypeSymbol;
			plyrRow.childNodes[0].bgColor = newbgColor;
			plyrRow.childNodes[0].onclick=OpponentCellClick;
			plyrRow.childNodes[1].innerHTML = ((opponentName=="N")?"none":opponentName);
			plyrRow.childNodes[2].innerHTML = statusText;

		}
	}	
	}
	var newRowCount=tbodyElem.rows.length;
	if (oldRowCount!=newRowCount) ge("divPlayerHeader").innerHTML="<font color='#ffff00'>Players (" + newRowCount + ")<font>";
	
};


function ScrollPlayersDownStart() {
  _scrollingDown=true;
  ScrollPlayersDownTimer();
}

function ScrollPlayersDownTimer() {
  if (!_scrollingDown) return;
	ge("divPlayerTableWrap").scrollTop=ge("divPlayerTableWrap").scrollTop+10;
	setTimeout("ScrollPlayersDownTimer()",100);
}

function ScrollPlayersDownStop() {
  _scrollingDown=false;
}

function ScrollPlayersUpStart() {
  _scrollingUp=true;
  ScrollPlayersUpTimer();
}

function ScrollPlayersUpTimer() {
  if (!_scrollingUp) return;
	ge("divPlayerTableWrap").scrollTop=ge("divPlayerTableWrap").scrollTop-10;
	setTimeout("ScrollPlayersUpTimer()",100);
}

function ScrollPlayersUpStop() {
  _scrollingUp=false;
}



//-------------------------------------------  Chat ---------------------------------------------


	
function OpenChatWindow()  
{	
  if (is_iphone) {
    _chatwindow = window.top.showTwoHideOne("chat.aspx");
  }
  else {
	
	  try {
		  if (_chatwindow!=null && !_chatwindow.closed) {
			  _chatwindow.focus();
			  return;
		  }
	  }
	  catch (er) {}
  	
	  if (screen.height<=1050) t=5;
	  else t=(screen.height-650)/4+15;

	  if (screen.width<900){
		  w=800;
		  l=15;
	  }
	  else {
		  w=825;
		  l=(screen.width-825)/2+15 ;
	  }
  	
	  var day = new Date();
	  var timeStamp = ""+day.getTime();
  	
	  ge("bdyTag").style.cursor = "default";
  		
	  try {
		  _chatwindow=window.open("chat.aspx","GeosenseChat"+timeStamp, "toolbar=0, directories=0, location=0, status=0, menubar=0, resizable=1, scrollbars=0, width="+w+", height="+(screen.height<650?530:620)+", top="+t+", left="+l+",screenY=0,screenX="+l);		
		  _chatwindow.focus();
	  }
	  catch (er) {}
	}
};	


function CloseChatWindow()  
{	
	try {
		if (_chatwindow!=null && !_chatwindow.closed) _chatwindow.close();
	}
	catch (er) {}
};	

function ClearChat()  
{	
	ge("divChatIn").innerHTML="";
	ge("txtChatOut").value="" ;
	
	try {
		if (_chatwindow!=null && !_chatwindow.closed) {
			_chatwindow.ge("divChatIn").innerHTML="";
			_chatwindow.ge("txtChatOut").value="" ;
		}
	}
	catch (er) {}
};	


function UpdateChat(newMarkup)
{
	if (_admin) {				
		newMarkup=newMarkup.replace(/pic=\".*(http.+\..+\..+\.*)\"/g,"\n<img src='$1'>");
	} 
	newMarkup=newMarkup.replace(/\n/g, '<br>');
	
	var divElem = document.createElement('DIV');
	divElem.innerHTML = newMarkup;
	ge("divChatIn").appendChild(divElem);
	
	if (is_iphone) {
	    ge("divChatIn").style.height=_offsetChatHeight;
	    ge("divChatIn").style.width=_offsetChatWidth;
		  ge("divChatIn").scrollTop=ge("divChatIn").scrollHeight;
		  ge("divChatIn").scrollTop=ge("divChatIn").scrollHeight;
	}
	
	if (Math.abs(parseInt(ge("divChatIn").scrollTop) - parseInt(ge("divChatIn").scrollHeight))< 250)	{
		ge("divChatIn").scrollTop=ge("divChatIn").scrollHeight;
		ge("divChatIn").scrollTop=ge("divChatIn").scrollHeight;
	}
};


function SetChatWindowAvailablePlayers() 
{
	if (_chatwindow==null || _chatwindow.closed) return;
	
	var tbodyElem = ge("myTbody");
	var plyrRow;
	
	try {
		for (var i=0; i<tbodyElem.rows.length; i++) {	
			plyrRow=tbodyElem.rows[i];
			_chatwindow.AddAvailablePlayers(plyrRow.childNodes[0].firstChild.innerHTML,(plyrRow.childNodes[2].innerHTML=="playing"));
		}
	}
	catch (er) {}

};

var resetCell=null;

function ChangeColorChat(clickedCell, newcolor)
{
  if (is_iphone && clickedCell!=null) {
    clickedCell.className="colorpicked";
    if (resetCell!=null) resetCell.className="";
    resetCell=clickedCell; 
    setTimeout("resetCell.className=''",500);
  }
   
	if (_pagedisabled) return;
	ge("txtChatOut").style.color=newcolor;
	
	try {
		if (_chatwindow!=null && !_chatwindow.closed) {
			_chatwindow.ge("txtChatOut").style.color=newcolor;
		}
	}
	catch (er) {}

	ge("imgColorCircleChat").style.backgroundColor=newcolor;
	
	clearTimeout(chatTimerID);
	HttpSend("entrycomm.aspx?rev=1.20&msg=&command=SET_CHATCOLOR:"+newcolor.replace(/#/g,''));

	chatTimerID  = setTimeout("ChatTimer()", 2000);
};



//------------------------------------------ Preference Panel----------------------------------------

function FlipPreferencesPanel() {   

	var on = (ge('divPreferences').style.display=='block');
	ge('divPreferences').style.display=(on?'none':'block');
	ge('divDynamicContent').style.display=(on?'block':'none');
	
	if (on) {
		SetEntryPersonalPrefs(); 
		SavePersonalPrefs();
	}
};

function SetEntryPersonalPrefs()
{
	ge("divChatControls").style.display = ge("chkEntryChatPref").checked?"block":"none";
	ge("divChatOptionsBar").style.display = ge("chkEntryChatPref").checked?"block":"none";
	
	//ge("tblInsert").style.height = 50px;
	if (!is_iphone)  ge("tblInsert").style.height = ge("chkEntryChatPref").checked?"70%":"100%";
		
	if (ge("chkChatColorPref").checked && ge("txtChatOut").style.color!=ge("imgColorCircleChat").style.backgroundColor)	
	{
		ChangeColorChat(null,ge("imgColorCircleChat").style.backgroundColor);
	}
};

function SavePersonalPrefs()
{ 
	if (_pagedisabled) return;
	clearTimeout(chatTimerID);
	
	var prefstring=""	;
	prefstring+="!EntryChatPref!" + ge("chkEntryChatPref").checked;
	prefstring+="!GameChatPref!" + ge("chkGameChatPref").checked;
	prefstring+="!SignonUpdatesPref!" + ge("chkSignonUpdatesPref").checked;
	prefstring+="!ProgressBarPref!false"; // + ge("ProgressBarPref").checked;  'removed Aug1
	prefstring+="!ChatColorPref!" + ge("chkChatColorPref").checked;
	prefstring+="!MapBackgroundColorPref!" + ge("chkMapBackgroundColorPref").checked;
	prefstring+="!ColorCircleChat!" + ge("imgColorCircleChat").style.backgroundColor;
	prefstring+="!ColorCircleMap!" + ge("imgColorCircleMap").style.backgroundColor;
	HttpSend("commandcomm.aspx?rev=1.20&msg=&command=SET_PREFS:"+prefstring.replace(/#/g,'')+"!");

	chatTimerID  = setTimeout("ChatTimer()", 2000);
};


//------------------------------------- Http Request functions ------------------------------------ 

function HttpSend(_sendstr) 
{	
	if (_objHttp!=null) { 
		if (_sendstr.indexOf("command")>=0) _pendingRequests[_pendingRequestsCount++]=_sendstr;
		return;
	}
	
	_numberrequests++;    //temp testing
	if (_numberrequests==20) {
		_sendstr=_sendstr.replace(/rev...../, 'rev='+_totaldelays/_numberrequests);		
		_numberrequests=0;
		_totaldelays=0;
	}	
						
//CommentEntry(_sendstr) 

	m_starttime = new Date().getTime();
	
	if (window.ActiveXObject) {
		_objHttp = new ActiveXObject("Microsoft.XMLHTTP");
		_objHttp.Open('GET',encodeURI(_sendstr),true);
		SetHeaderHTTP(_objHttp);  //bandwidth
		_objHttp.Send();
	}
	else if (window.XMLHttpRequest) {		
		_objHttp = new XMLHttpRequest();
		_objHttp.open('GET',encodeURI(_sendstr),true);
		_objHttp.send(null);
	}
	
	if (ge("txtChatOut").value=="clear") ge("divChatIn").innerHTML=""; //debug
	if (ge("txtChatOut").value=="query") CommentEntry(_sendstr); //debug
	
	_objHttp.onreadystatechange = HttpAsyncCallback;
	
};
	
function HttpAsyncCallback() 
{
	if (!_objHttp) return;
	if (_objHttp.readyState!=4) return;
	
	var responseTime=new Date().getTime()-m_starttime;
	
	if (ge("txtChatOut").value=="refresh") CommentEntry(responseTime+" "); //debug

	_totaldelays+=responseTime;
	ProcessChat( _objHttp.responseText);
	_objHttp=null;
	
	if (_pendingRequests[_pendingRequestsCurrent+1]) {
		_pendingRequests[_pendingRequestsCurrent]=null;
		_pendingRequestsCurrent++;
		HttpSend(_pendingRequests[_pendingRequestsCurrent]);
	}
};

function ClearPendingRequests() 
{
	_pendingRequests=new Array;
	_pendingRequestsCount=1;
	_pendingRequestsCurrent=0;
};


function SetHeaderHTTP(anHTTPobj) {   //bandwidth
	//return;
	anHTTPobj.setRequestHeader("User-Agent", "x");
	anHTTPobj.setRequestHeader("Accept", "x");
	anHTTPobj.setRequestHeader("Referer", "x");
	anHTTPobj.setRequestHeader("Accept-Language", "x");
	//anHTTPobj.setRequestHeader("Accept-Encoding", "x");
};


//------------------------------------- Color Picker ------------------------------------

function FindPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
};

function FindPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
};


function Hex(nmbr) {
	var hexStr = "ABCDEF";
	var hexVal = Math.round(nmbr * 255 / 65535);
	dig1 = hexVal % 16;
	dig2 = (hexVal - dig1)/16;
	if (dig1 > 9) {dig1 = hexStr.charAt(dig1 - 10)}
	if (dig2 > 9) {dig2 = hexStr.charAt(dig2 - 10)}
	hexVal = dig2.toString() + dig1.toString();
	return hexVal;
};

function ColorVal(color, ang, vect, xPos, yPos) {
	with (Math) {
		var angCorr = 0;	
		if (color == "green") {angCorr = 2*PI/3};
		if (color == "blue") {angCorr = 4*PI/3};
		var angVal = ang - angCorr;	
		if (angVal < 0) {angVal += 2*Math.PI}	
		var xVal = xPos;
		var yVal = yPos;
		if (color != "red") {
			yVal = abs(vect * sin(angVal));
			xVal = abs(vect * cos(angVal));
			if (angVal > PI/2 && angVal < 3*PI/2) {
					xVal = -1 * xVal;
			}
		}
		var colval = 0;
		if (angVal <= 2*PI/6 || angVal >= 10*PI/6) {
			colVal = 65535;
		}
		else {
			var x1 = sqrt(100*100 - yVal*yVal) + xVal;
			var x2 = abs(yVal)/tan(PI/3) - xVal;
			colVal = 65535 * x1/(x1 + x2);
		}
		colVal = round(colVal);
		return colVal;
	}
};

function AdjustColor(e) {
	var mX,mY;
	if (is_IE){
		mX = event.clientX-FindPosX(event.srcElement);
		mY = event.clientY-FindPosY(event.srcElement);
	}
	else {
		return;
	}				
	
	mX = mX - 81-5;
	mY = -(mY - 81)+5;
	var r = Math.sqrt(mX*mX + mY*mY);
	if (r<81) {
		with (Math) {
			var theta = asin(abs(mY/r));
			if (mX < 0 && mY  > 0) {theta = PI - theta};
			if (mX < 0 && mY < 0) {theta += PI};
			if (mX >= 0 && mY < 0) {theta = 2*PI - theta};
			var theta_deg = theta*360/2/PI;
		}
		red = ColorVal("red", theta, r, mX, mY);
		green = ColorVal("green", theta, r, mX, mY);
		blue = ColorVal("blue", theta, r, mX, mY);
		if (event.srcElement.id=="imgColorCircleChat") ge("imgColorCircleChat").style.backgroundColor = (r<3?"#000000":("#" + Hex(red) + Hex(green) + Hex(blue)));
		if (event.srcElement.id=="imgColorCircleMap") {
			var newmapback = (r<3?"#000000":("#" + Hex(red) + Hex(green) + Hex(blue)));
			ge("divGamePage").style.backgroundColor = newmapback;
			ge("imgColorCircleMap").style.backgroundColor = newmapback;
		}
	}
};


//-------------------------------------------  Misc ---------------------------------------------


function CommentEntry(commentstr)
{
	ge("divChatIn").innerHTML=ge("divChatIn").innerHTML+"\n"+commentstr+"\n";
	ge("divChatIn").scrollTop=ge("divChatIn").scrollHeight;
};


function ge(anID) {
	return document.getElementById(anID);
};







var _pendingRequestsGame=new Array;
var _pendingRequestsGameCallBacks=new Array;
var _pendingRequestsGameCount=1;
var _pendingRequestsGameCurrent=0;

var _objHttpGame = null;
var _objHttpResponseData = "";

//------------------------------------- Game Page Start ------------------------------------

function SetGameGlobals() {

	//constants
	RACETIME=10;
	SCRAMBLETIME=20;
	FLAGWIDTH=57;
	FLAGHEIGHT=42;
	FLAGTOP="";
	FLAGLEFT="";

	//globals
	_currentcity="";
	_revealcity="";
	_guessed = false;
	_pauseLocal = false;
	_pauseRemote = false;
	_flagPercentRevealed=1.1;
	_displayTimeLeft = 0;
	_waitingForUpdates=false;
	_newQueryStr="";
	_disableclick=false;
	_roundsplayed=-1;
	_roundsplayedLocal=0;
	_roundsplayedRemote=0;
	_vroundswonLocal=0;
	_vroundswonRemote=0;
	_vroundsTOutLocal=0;
	_vroundsTOutRemote=0;
	_aPointsLocal = 0;
	_aErrorLocal = 0;
	_aTimeLocal = 0;
	_aPointsRemote = 0;
	_aErrorRemote = 0;
	_aTimeRemote = 0;
	_adjustrounds = 0;
	_pausedonce = false;
	_gamechatfocused = false;
	_map="world";
		
	//timers
	guessTimerID = 0;
	displayTimerID = 0;
	flickTimerID = 0;
	allflickTimerID = 0;
	pauseTimerID = 0;
	shrinkTimerID = 0;
	revealflagTimerID = 0;
	checkhighscoreID = 0;
	dataInOutTimerID = 0;	

	//debug	variables
	_roundcount=-1;
		
	//shared with EntryPage
	if (ge("rdbWorld").checked) _map="world";
	if (ge("rdbAdvanced").checked) _map="advanced";
	if (ge("rdbEurope").checked) _map="europe";
	if (ge("rdbUS").checked) _map="us";
	_scramble=(ge("chkScramble").checked);
	
	DEFAULTROUNDS=(_map=="advanced"?20:10);
	_roundsremaining=DEFAULTROUNDS;
};

	
function SetGamePageEvents() {	

	if (is_nav) document.onmousedown=StoreGuess;
	if (is_IE) bdyTag.onmousedown=StoreGuess;
	
	document.onkeydown=KeyDown;
	window.onbeforeunload=PageQuit;
};


function SetIphoneDisplay() {
  if (is_iphone) {
    _playnexttext="Play next avail";
    _transparenttext="";
    _roundsremainingtext="Rounds left: "; 
    _offsetChatHeight=ge("divChatIn").offsetHeight;
    _offsetChatWidth=ge("divChatIn").offsetWidth-2;
    ResetIphoneDisplay();
  }
};

function SpinToGame() {
   ge("divViewPort").style.left="-1400px";
   document.getElementById("divGamePage").className="showgame";
   document.getElementById("divEntryWrapper").className="hideentry";
};

function SpinToEntry() {
	 document.getElementById("divGamePage").className="hidegame";
   setTimeout("SpinToEntryNext()",1500);  
};

function SpinToEntryNext() {
   ge("divViewPort").style.left="0px";
   document.getElementById("divEntryWrapper").className="showentry";
};

function ResetIphoneDisplay() {
  if (is_iphone) {
      setTimeout("window.scrollTo(0,1);",10);
      setTimeout("window.top.scrollTo(0,1);",10);
  }
};


function ShutDownGamePageEvents() {	

	if (is_nav) document.onmousedown=null;
	if (is_IE) bdyTag.onmousedown=null;
	document.onkeydown=null;
};

function SetGamePersonalPrefs()
{
	ge("tblChatTables").style.display=ge("chkGameChatPref").checked?"block":"none";
	ge("btnChatOn").style.backgroundColor=ge("chkGameChatPref").checked?"green":"red";
	ge("btnUpdatesOnButton").style.backgroundColor=ge("chkSignonUpdatesPref").checked?"green":"red";
	
	if (ge("chkMapBackgroundColorPref").checked) {
	
		//ge("divGamePage").style.backgroundImage="";
		ge("divGamePage").style.backgroundColor=ge("imgColorCircleMap").style.backgroundColor;

	}
	else {
		ge("divGamePage").style.backgroundColor="transparent";
	}
	
};		
	
	
function GamePageStart() {

	ClearPendingRequestsGame();
	SetGameGlobals();
	SetGamePageEvents();
	SetGamePersonalPrefs();

	ge("divTime").style.visibility="visible";
	ge("tblStatus").style.visibility="visible";
	
	if (_chatwindow!=null && !_chatwindow.closed) {
		_chatwindow.ge("txtChatOut").disabled=true;
		_chatwindow.ge("divChatIn").disabled=true;
		_chatwindow.ge("btnCloseChat").disabled=true;
		_chatwindow.ge("btnClearChat").disabled=true;
	}
	
	SetFirstCity();
  ResetIphoneDisplay();
};

function SetFirstCity() {
	var cmd="";
	if (_playingself) cmd="NEWGAMEONE";
	else cmd="NEWGAMETWO";
	
	HttpSendGame("gamecomm.aspx?rev=1.20&newchattext="+cmd , "SetFirstCityCallBack" );
	
};	

function SetFirstCityCallBack() {

	_currentcity = Parse(_objHttpResponseData, "OC");
	_map = Parse(_objHttpResponseData,"OM");
	_scramble = (Parse(_objHttpResponseData,"OS")=="ON");
	ge("divRemotePlayer").innerHTML=Parse(_objHttpResponseData, "OO");

	_roundsremaining--;
	_roundsplayed++;
	_roundcount++;     //debug
	
	//get first city	
	LoadFlagPic();
	ge("divCity").innerHTML=_currentcity;
	SetMapImage();
	
	//setup fresh display
	ge("txtChatOutGame").value="";				
	ge("txtRounds").innerHTML=_roundsremainingtext+(_roundsremaining+1);
	ge("divCity").style.visibility="visible";
					
		
	//alter display for _scramble mode	
	if (_scramble) {  
		_revealcity="";
		for (i=0;i<_currentcity.length;i++) _revealcity+=" ";
		ge("divCity").innerHTML= _revealcity;
		ge("imgFlag").width=0;
		ge("imgFlag").height=0;
		_flagPercentRevealed=0;
		revealflagTimerID=setTimeout("RevealFlagTimer()", 500);
	}
	else {
		ge("imgFlag").width=FLAGWIDTH;
		ge("imgFlag").height=FLAGHEIGHT;
	}
	
	//dont display flags for us _map
	if (_map=="us") ge("imgFlag").style.visibility="hidden";
	else ge("imgFlag").style.visibility="visible";
			
	if (_scramble) ge("divTime").innerHTML=SCRAMBLETIME;
	else ge("divTime").innerHTML=RACETIME;

	guessTimerID = setTimeout("GuessTimer()", 1000);
	dataInOutTimerID=setTimeout("DataInOut()",500);
};


function SetMapImage() {

	var sw=screen.width;
	var sh=screen.height;
	
	var screensize=800;
	if (sw>=1000 && sh>=700) screensize=1024;
	if (sw>=1280 && sh>=860) screensize=1280;

	var mapstr=_map;
	if (mapstr=="advanced") mapstr="world";

	if (ge("divMapImage").style.backgroundImage.indexOf(mapstr)<0) {
	  var mapurl;
	  if (is_iphone) {
      mapurl="url(map/Map"+mapstr+screensize+(mapstr=="europe"?".jpg)":".png)");
    }
	  else {
      mapurl="url(map/Map"+mapstr+screensize+".png)";
	  }
    ge("divMapImage").style.backgroundImage=mapurl;
	}
	
	if (!is_iphone) {
	  try {
		  if (is_IE) ge("divMapImage").filters.item("Alpha").enabled = (_map=="europe");
	  }
	  catch(err) {
	  }
	}
  if (is_iphone) {
    SpinToGame();
  }
  else {
	  ge("divViewPort").style.left="-1400px";
  }
  
};


//------------------------------------- Game Page Stop ------------------------------------

	
function ExitGame()
{
	ClearPendingRequestsGame();
	
	_plyrstatus="unavailable";
	ShutDownGamePageEvents();
	StopAllTimersFinal();
		
  ge("divMapImage").className="";
	
	ge("btnLocalPause").style.backgroundColor=_transparenttext;
	ge("btnRemotePause").style.backgroundColor=_transparenttext;
	ge("cllKmsOffLocal").innerHTML="";
	ge("cllKmsOffRemote").innerHTML="";
	ge("cllLocalPointsOut").innerHTML="";
	ge("cllLocalScoreOut").innerHTML="";
	ge("cllRemotePointsOut").innerHTML="";
	ge("cllRemoteScoreOut").innerHTML="";
	ge("divGameStatus").innerHTML="";
	ge("cllHeaderBorder2").style.display="none";
	ge("tblRoundsResults").style.display="none";
	ge("txtContinue").style.display="none";
	ge("txtHighScore").style.display="none";
	ge("btnHighScore").style.display="none";
	ge("imgRedButton").style.visibility="hidden";
	ge("imgRedCircle").style.visibility="hidden";
	ge("imgBlueButton").style.visibility="hidden";
	ge("imgBlueCircle").style.visibility="hidden";	
	ge("imgYellowButton").style.visibility="hidden";
	ge("imgYellowCircle").style.visibility="hidden";
	ge("btnLocalPause").value="Pause";
	ge("btnRemotePause").value="Pause";
								
	if (_waitingForUpdates) _roundcount=-999;//debug

	var sendstr = "gamecomm.aspx";
	sendstr += "?rev=1.20";
	sendstr += "&roundover=false";
	sendstr += "&adjust=0";
	sendstr += "&pause=F";
	sendstr += "&newchattext=BREAKLINK";
	sendstr += "&roundcount=" + _roundcount;
	sendstr += "&gameChatOn=" + (ge("btnChatOn").style.backgroundColor=="green");
	sendstr += "&gameChatUpdatesOn=" + (ge("btnUpdatesOnButton").style.backgroundColor=="green");
	
	HttpSendGame( sendstr, "EntryPageStart");
	
  //if (is_iphone) ToggleSpinwrapOn(true);
};


//-------------------------------------------- Timers  -----------------------------------------------

function StopAllTimersFinal() {
	StopAllTimers();
	clearTimeout(dataInOutTimerID);
	dataInOutTimerID=0;

	//timers
	guessTimerID = 0;
	displayTimerID = 0;
	flickTimerID = 0;
	allflickTimerID = 0;
	pauseTimerID = 0;
	shrinkTimerID = 0;
	revealflagTimerID = 0;
	checkhighscoreID = 0;
	dataInOutTimerID = 0;	
};

function StopAllTimers() {
	clearTimeout(guessTimerID);
	guessTimerID=0;
	clearTimeout(displayTimerID);
	displayTimerID=0;
	clearTimeout(flickTimerID);
	flickTimerID=0;
	clearTimeout(allflickTimerID);
	allflickTimerID=0;
	clearTimeout(pauseTimerID);
	pauseTimerID=0;
	clearTimeout(shrinkTimerID);
	shrinkTimerID=0;
	clearTimeout(revealflagTimerID);
	revealflagTimerID=0;
	clearTimeout(checkhighscoreID);
	checkhighscoreID=0;
};



function GuessTimer() {
	clearTimeout(guessTimerID);
	if (_pauseLocal || _pauseRemote) {
		guessTimerID = setTimeout("GuessTimer()", 1000);
		return;
	}
	ge("divGameStatus").innerHTML="<span style='background-color:limegreen'>Playing...</span>";
	ge("divTime").innerHTML=ge("divTime").innerHTML*1-1;
	
	if (_scramble) ScrambleUpdate();
	if (ge("divTime").innerHTML*1>0) {
		guessTimerID = setTimeout("GuessTimer()", 1000);
	}
	else { //timed out
		_guessed=true;
		_waitingForUpdates=true;
		
		ge("imgFlag").width=FLAGWIDTH;
		ge("imgFlag").height=FLAGHEIGHT;
		ge("divCity").innerHTML=_currentcity;
		ge("divGameStatus").innerHTML="Waiting...";
	
		SendReceiveUpdates();
		
		clearTimeout(dataInOutTimerID);
		dataInOutTimerID=null;
		dataInOutTimerID=setTimeout("DataInOut()",500);
	}
};

function FlickerTimer()
{
	if (_plyrstatus!="playing") return;
	if (allflickTimerID || !flickTimerID) return;
	clearTimeout(flickTimerID);
	if (ge("imgBlueButton").style.visibility=="visible") {
		ge("imgBlueButton").style.visibility="hidden";
		flickTimerID  = setTimeout("FlickerTimer()",(is_iphone?1000:200)); 
	}
	else {
		ge("imgBlueButton").style.visibility="visible";
		flickTimerID  = setTimeout("FlickerTimer()",(is_iphone?1000:500));
	}
};

function AllFlickerTimer()
{
	if (_plyrstatus!="playing") return;
	if (flickTimerID) { 
		clearTimeout(flickTimerID);
		flickTimerID=0;
	}
	clearTimeout(allflickTimerID);
	
	if (ge("imgYellowButton").style.visibility=="visible") {
		ge("imgBlueButton").style.visibility="hidden";
		ge("imgRedButton").style.visibility="hidden";
		ge("imgYellowButton").style.visibility="hidden";
		allflickTimerID  = setTimeout("AllFlickerTimer()",(is_iphone?1000:200));
	}
	else {
					
		if (ge("cllLocalPointsOut").innerHTML!="timed out...") {
			ge("imgBlueButton").style.visibility="visible";
		}
					
		if (!_playingself && ge("cllRemotePointsOut").innerHTML!="timed out...") {
			ge("imgRedButton").style.visibility="visible";
		}
		
		ge("imgYellowButton").style.visibility="visible";
		allflickTimerID  = setTimeout("AllFlickerTimer()",(is_iphone?1000:500));
	}
};


//shrinking button effect
function ShrinkTimer() 
{
	if (_plyrstatus!="playing") return;
	clearTimeout(shrinkTimerID);
	shrinkTimerID=0;
			
	if (ge("imgBlueButton").height>8) {
	  ge("imgBlueButton").height-=2;
	  ge("imgBlueButton").width-=2;
	  ge("imgBlueButton").style.top = parseInt(ge("imgBlueButton").style.top)+1;
	  ge("imgBlueButton").style.left = parseInt(ge("imgBlueButton").style.left)+1;
			
	  if (!_playingself) {
		  ge("imgRedButton").height-=2;
		  ge("imgRedButton").width-=2;
		  ge("imgRedButton").style.top = parseInt(ge("imgRedButton").style.top)+1;
		  ge("imgRedButton").style.left = parseInt(ge("imgRedButton").style.left)+1;
	  }
	
	  ge("imgYellowButton").height-=2;
	  ge("imgYellowButton").width-=2;	
	  ge("imgYellowButton").style.top = parseInt(ge("imgYellowButton").style.top)+1;
	  ge("imgYellowButton").style.left = parseInt(ge("imgYellowButton").style.left)+1;
	
	  shrinkTimerID  = setTimeout("ShrinkTimer()",47);
	}			
	else {
		flickallTimerID  = setTimeout("AllFlickerTimer()",497);
	}				
};
	

function PauseFlashTimer()
{
	if (_plyrstatus!="playing") return;
	clearTimeout(pauseTimerID);
	
	if (_pauseLocal) {
		if (ge("btnLocalPause").style.backgroundColor==_transparenttext) ge("btnLocalPause").style.backgroundColor="blue";
		else ge("btnLocalPause").style.backgroundColor=_transparenttext;
	}
	if (!_playingself && _pauseRemote) {
		if (ge("btnRemotePause").style.backgroundColor==_transparenttext) ge("btnRemotePause").style.backgroundColor="red";
		else ge("btnRemotePause").style.backgroundColor=_transparenttext;	
	}
	
	ge("btnRemotePause").value=(_pauseRemote?"Play":"Pause");
		
	if (ge("divGameStatus").innerHTML!="Paused...") ge("divGameStatus").innerHTML="Paused...";
	pauseTimerID=setTimeout("PauseFlashTimer()", (is_iphone?1000:320));
};
	
function RevealFlagTimer()
{
	if (_plyrstatus!="playing") return;
	clearTimeout(revealflagTimerID);
	if (_map=="us") return;

	if (_pauseLocal || _pauseRemote) {
		revealflagTimerID=setTimeout("RevealFlagTimer()", 500);
		return;
	}
	
	_flagPercentRevealed=_flagPercentRevealed+1.0/(SCRAMBLETIME*2);
	ge("imgFlag").width=parseInt(FLAGWIDTH*_flagPercentRevealed);
	ge("imgFlag").height=parseInt(FLAGHEIGHT*_flagPercentRevealed);

	if (_flagPercentRevealed<1) revealflagTimerID=setTimeout("RevealFlagTimer()", 500);				
};

		
//display results of last city for 5 seconds
function DisplayResultsTimer()  //may be set by self on timer
{				
	if (_plyrstatus!="playing") return;
	clearTimeout(displayTimerID);
	
	if (_pauseLocal || _pauseRemote) {
		displayTimerID = setTimeout("DisplayResultsTimer()", (is_iphone?1000:200));
		return;
	}
	
	if (ge("divGameStatus").innerHTML!="Results...") ge("divGameStatus").innerHTML="Results...";
	
	_displayTimeLeft = _displayTimeLeft-1;

	if (ge("divTime").innerHTML==".") ge("divTime").innerHTML="";  //flicker
	else ge("divTime").innerHTML=".";
		
	if (_displayTimeLeft<0) {
		ContinueNextCity();
	}
	else {
		displayTimerID = setTimeout("DisplayResultsTimer()", (is_iphone?1000:200));
	}
};	


//-------------------------------------- Misc Player Initiated Events  -------------------------------------

function KeyDown(e)   //send chat message
{	
	
	if (is_IE) var keycode = event.keyCode;
	else var keycode = e.which;

	if (!_gamechatfocused && ge("tblChatTables").style.display=="block") {
		ge("txtChatOutGame").focus();
		ge("txtChatOutGame").value=ge("txtChatOutGame").value;
	}
	
	if (keycode==13) {//enter key
		SendChatGame();
	}	
};


function SendChatGame() {
									
		var chatstr=""+ge("txtChatOutGame").value;
		chatstr=chatstr.replace(/^\s*/, '').replace(/\s*$/, ''); //trim	
		if (chatstr=="") return;
		
		chatstr=chatstr.replace(/</g,'(');
		chatstr=chatstr.replace(/>/g,')');								
											
		if (chatstr.length>400) chatstr="...buffer_overflow... "+chatstr.substring(chatstr.length-400,chatstr.length);
		ge("txtChatOutGame").value="";
					
		if (!(chatstr.indexOf('[')==0 && chatstr.indexOf(']')!=-1)) {  //private messsage	
			ge("divChatInGame").innerHTML=ge("divChatInGame").innerHTML+ "<br>"+ "[" + ge("divLocalPlayer").innerHTML + "] " +chatstr;
			ge("divChatInGame").scrollTop=ge("divChatInGame").scrollHeight;
			ge("divChatInGame").scrollTop=ge("divChatInGame").scrollHeight;
		}
				 	
		//if (chatstr=="\n") chatstr="";
							
		if (_waitingForUpdates) {
			SendReceiveUpdates();
			_newQueryStr+= "|" + chatstr;
			return;
		}
			
		if (_newQueryStr=="") {
			_newQueryStr="gamecomm.aspx?rev=1.20&roundover=false&adjust="+_adjustrounds+"&pause="+(_pauseLocal?"T":"F")+"&newchattext="+"|"+chatstr;
		}
		else {
			_newQueryStr+= "|" + chatstr;
		}
};

function TouchScroll(e) {
  if (e.touches.length > 1) {
    if (e.touches[0].pageX>140 && e.touches[0].pageX<650 && e.touches[0].pageY>0 && e.touches[0].pageY<350 && e.touches[1].pageX>140 && e.touches[1].pageX<650 && e.touches[1].pageY>0 && e.touches[1].pageY<350) {
      _scrolling=true;
      return;
    }
  } 
  // _scrolling=true;
};

function TouchMove(e) {
  if (_scrolling && e.touches.length > 1) {
    _scrolling=false;
    return;
  }
  e.preventDefault();
	if (_pauseLocal) return;
	if (_plyrstatus!="playing" || _guessed) return;
  if (e.changedTouches.length == 1) { // Only deal with one finger
    var touch = e.changedTouches[0]; // Get the information for finger #1
    var node = touch.target; // Find the node the drag started from
    if ((node+"").indexOf("Input")>-1) return;
    mX = touch.pageX;
    mY = touch.pageY;
    if (_zoomscale==1) {
      startMX=mX;
      startMY=mY;
    }
    ge("imgBlueButton").width=8;
		ge("imgBlueButton").height=8;
		ge("imgBlueButton").style.left=(startMX+mX)/2-4-2-(50/_zoomscale);
		ge("imgBlueButton").style.top=(startMY+mY)/2-4-2-(50/_zoomscale);
		ge("imgBlueCircle").style.left=(startMX+mX)/2-20-2-(50/_zoomscale);
		ge("imgBlueCircle").style.top=(startMY+mY)/2-20-2-(50/_zoomscale);
		ge("imgBlueButton").style.visibility="visible";
		ge("imgBlueCircle").style.visibility="visible";
  }
};

function TouchStart(e) {
	if (_pauseLocal) return;
  if (e.touches.length > 1) return;
	if (_plyrstatus!="playing" || _guessed) return;

  if (e.touches.length == 1){ // Only deal with one finger
    var touch = e.touches[0]; // Get the information for finger #1
    var node = touch.target; // Find the node the drag started from
    if ((node+"").indexOf("Input")>-1) {
     _disableclick=true;
     return;
    }

    _disableclick=false;

    mX = touch.pageX;
    mY = touch.pageY;

    startMX=mX;
    startMY=mY;
 
    ge("divMapImage").style.webkitTransformOriginX=mX+"px";
    ge("divMapImage").style.webkitTransformOriginY=mY+"px";
    ge("divMapImage").className="zoommap"+_zoomscale;
    
    ge("imgBlueButton").width=8;
		ge("imgBlueButton").height=8;
		ge("imgBlueButton").style.left=mX-4-2-(50/_zoomscale);
		ge("imgBlueButton").style.top=mY-4-2-(50/_zoomscale);
		ge("imgBlueCircle").style.left=mX-20-2-(50/_zoomscale);
		ge("imgBlueCircle").style.top=mY-20-2-(50/_zoomscale);
		ge("imgBlueButton").style.visibility="visible";
		ge("imgBlueCircle").style.visibility="visible";
  }
};


function StoreGuess(e) { //button click 

	if (_pauseLocal || _pauseRemote) return;
  if (is_iphone && e.touches.length >1) return;
  if (_plyrstatus!="playing" || _disableclick || _gamechatfocused) return;

	if (!_guessed) {
	  if (is_iphone) {
      if(e.touches.length == 1) { // Only deal with one finger
        var touch = e.touches[0]; // Get the information for finger #1
        var node = touch.target; // Find the node the drag started from
        if ((node+"").indexOf("Input")>-1) return;
      }
	  }
	  else {
		  if (is_IE){
			  mX = event.clientX;
			  mY = event.clientY+1;
		  }
		  else {
			  mX = e.pageX+2;
			  mY = e.pageY+3;
		  }					
	  }
	  
	  var originX = 0;
	  var originY = 0;
	  if (is_iphone) {
	    originX = parseInt(ge("divMapImage").style.webkitTransformOriginX);
      originY = parseInt(ge("divMapImage").style.webkitTransformOriginY);
	  }

    if (_zoomscale==1) {
      startMX=mX;
      startMY=mY;
    }
    var locX=(is_iphone?(startMX+mX)/2:mX)-2-(is_iphone?(50/_zoomscale):0);
    var locY=(is_iphone?(startMY+mY)/2:mY)-2-(is_iphone?(50/_zoomscale):0);
		ge("imgBlueButton").width=8;
		ge("imgBlueButton").height=8;
		ge("imgBlueButton").style.left=locX-4;
		ge("imgBlueButton").style.top=locY-4;
		ge("imgBlueCircle").style.left=locX-20;
		ge("imgBlueCircle").style.top=locY-20;
		ge("imgBlueButton").style.visibility="visible";
		ge("imgBlueCircle").style.visibility="visible";
		
		clearTimeout(guessTimerID);
		flickTimerID  = setTimeout("FlickerTimer()", 200);
		
		_guessed=true;
		_waitingForUpdates=true;
		
		if (_scramble && _map!="us") {
			ge("imgFlag").width=FLAGWIDTH;
			ge("imgFlag").height=FLAGHEIGHT;
			clearTimeout(revealflagTimerID);
		}
		
    ge("divMapImage").className="";

		
		ge("divCity").innerHTML= _currentcity;
		ge("divGameStatus").innerHTML="Waiting...";

		SendReceiveUpdates();
		
		clearTimeout(dataInOutTimerID);
		dataInOutTimerID=null;
		dataInOutTimerID=setTimeout("DataInOut()",500);
	}	
};

function PauseHit()
{			

	if (!_pauseLocal) {	
		_pauseLocal=true;
		ge("btnLocalPause").value="Play";
		if (_roundsremaining>=0) _pausedonce = true;
		if (!_pauseRemote || _roundsremaining<0) PauseFlashTimer();  //local initiates pause
		if (!_playingself && _roundsremaining<0) _pauseRemote=true;
	}
	else {
		_pauseLocal=false;
		ge("btnLocalPause").value="Pause";
		ge("btnLocalPause").style.backgroundColor=_transparenttext;
		
		if (!_pauseRemote) clearTimeout(pauseTimerID);
		
		if (_roundsremaining<0 && !_pauseRemote) {
			_roundsremaining=DEFAULTROUNDS-1;
			_roundsplayed=0;
			_roundsplayedLocal=0;
			_roundsplayedRemote=0;
			ge("cllHeaderBorder2").style.display="none";
			ge("tblRoundsResults").style.display="none";
			ge("txtContinue").style.display="none";
			ge("txtHighScore").style.display="none";
			ge("btnHighScore").style.display="none";				
			ge("divCity").style.visibility="visible";
			if (_map!="us") ge("imgFlag").style.visibility="visible";		
			ge("divTime").style.visibility="visible";

			ge("cllKmsOffLocal").innerHTML="";
			ge("cllKmsOffRemote").innerHTML="";
			ge("cllLocalPointsOut").innerHTML="";
			ge("cllLocalScoreOut").innerHTML="";
			ge("cllRemotePointsOut").innerHTML="";
			ge("cllRemoteScoreOut").innerHTML="";
			ge("txtRounds").innerHTML=_roundsremainingtext+DEFAULTROUNDS;
			_aPointsLocal = 0;
			_aErrorLocal = 0;
			_aTimeLocal = 0;
			_vroundswonLocal=0;
			_vroundswonRemote=0;
			_vroundsTOutLocal=0;
			_vroundsTOutRemote=0;
		}

	}

	//if (is_iphone) ge("btnLocalPause").blur();

	//create or update querystring		
	if (_waitingForUpdates) {
		SendReceiveUpdates();
		return;
	}
		
	if (_newQueryStr=="") {
		_newQueryStr="gamecomm.aspx?rev=1.20&roundover=false&adjust="+_adjustrounds+"&pause="+(_pauseLocal?"T":"F")+"&newchattext=";
	}
	else {
		pos=_newQueryStr.indexOf("&pause=");
		_newQueryStr=_newQueryStr.substring(0,pos+7)+(_pauseLocal?"T":"F")+_newQueryStr.substring(pos+8,_newQueryStr.length);				
	}
};

function RoundDownClicked() 
{
	if (_roundsremaining<=(_playingself?1:2)) return;  //0:1 enough?
	_roundsremaining--;
	_adjustrounds--;
	ProcessRoundChange();		
	//if (is_iphone) SetGamePageEvents();
};

function RoundUpClicked() 
{
	if (_roundsremaining>=98 || _roundsremaining<(_playingself?0:1)) return;  //0:1 enough?
	_roundsremaining++;
	_adjustrounds++;
	ProcessRoundChange();
	//if (is_iphone) SetGamePageEvents();
};

function HighScoresClicked()
{	
	dataInOutTimerID=null;
	
  if (is_iphone) {
    window.top.showTwoHideOne("highscores.aspx");
  }
  else {
	  if (screen.height<=1050) t=5;	
	  else t=(screen.height-650)/4;

	  if (screen.width<900){
		  w=800;
		  l=0;
	  }
	  else {
		  w=825;
		  l=(screen.width-825)/2;	
	  }
  	
	  var highwindow=window.open("loader.htm?ver=5.50&scrolling=auto&contentUrl="+escape("highscores.aspx"),"GeosenseHighScoresWorldMap", "toolbar=0, directories=0, location=0, status=0, menubar=0, resizable=1, scrollbars=0, width="+w+", height="+(screen.height<650?530:620)+", top="+t+", left="+l+",screenY=0,screenX="+1);

	  ge("bdyTag").style.cursor = "crosshair";
	  highwindow.focus();
  }
  
	if (_playingself) dataInOutTimerID=setTimeout("DataInOut()",2500);
	else dataInOutTimerID=setTimeout("DataInOut()",500);	
	//if (is_iphone) SetGamePageEvents();
};	



function HideChatClicked() 
{
	if (ge("btnChatOn").style.backgroundColor=="green") {
		ge("btnChatOn").style.backgroundColor="red";
		if (is_iphone) ge("chkGameChatPref").checked=false;
		ge("tblChatTables").style.display="none";
	}
	else {
		ge("btnChatOn").style.backgroundColor="green";
		if (is_iphone) ge("chkGameChatPref").checked=true;
		ge("tblChatTables").style.display="block";
	}
	if (is_iphone) SetGamePageEvents();
};

function StopUpdatesClicked() 
{
	if (ge("btnUpdatesOnButton").style.backgroundColor=="green") {
		ge("btnUpdatesOnButton").style.backgroundColor="red";
		if (is_iphone) ge("chkSignonUpdatesPref").checked=false;
		CommentGame("\nSign on updates have been stopped.");
	}
	else {
		ge("btnUpdatesOnButton").style.backgroundColor="green";
		if (is_iphone) ge("chkSignonUpdatesPref").checked=true;
		CommentGame("\nSign on updates have been activated.");
	}
};


//------------------------------------- Send Client Updates ------------------------------------

function DataInOut() //send and receive any waiting data
{

	if (_plyrstatus!="playing") return;
	if (dataInOutTimerID==null) return;	//traps possible double timers
	clearTimeout(dataInOutTimerID);
	dataInOutTimerID=null;
	
	//send
	if (_newQueryStr!="") {				
		var pos=0;
		var posrest=0	;								
		if (_newQueryStr.length>1000) {
			pos=_newQueryStr.indexOf("&newchattext=");
			_newQueryStr=_newQueryStr.substring(0,pos)+"&newchattext=|errorbufferfull";
		}
		
		if (_waitingForUpdates) SendReceiveUpdates();
		//make sure updates are fresh
		pos=_newQueryStr.indexOf("&adjust=");
		posrest=_newQueryStr.indexOf("&pause=");   //assumes order
		_newQueryStr=_newQueryStr.substring(0,pos+8)+_adjustrounds+_newQueryStr.substring(posrest,_newQueryStr.length);
		_adjustrounds=0;

		_newQueryStr = _newQueryStr.replace(/&roundover=true/, "&roundover="+(_waitingForUpdates?"true":"false"));  //Jan 2 Fix //mr
		_newQueryStr = _newQueryStr.replace(/&roundover=false/, "&roundover="+(_waitingForUpdates?"true":"false"));
		
		_adjustrounds=0;

		var pausestr="F";
		if (_pauseLocal) pausestr="T";

		if (!_playingself && _roundsremaining==0 && ge("divGameStatus").innerHTML=="Results...") pausestr="T";

		pos=_newQueryStr.indexOf("&pause=");
		_newQueryStr=_newQueryStr.substring(0,pos+7)+pausestr+_newQueryStr.substring(pos+8,_newQueryStr.length);

		HttpSendGame(_newQueryStr, "DataInOutCallBack");
		_newQueryStr="";
		return;	
	}
	
	SetupNextUpdate();
};

function SetupNextUpdate()
{
	//create new query after each request
	if (_newQueryStr=="" && _objHttpGame==null) {
		_newQueryStr="gamecomm.aspx?rev=1.20&roundover=false&adjust="+_adjustrounds+"&pause="+(_pauseLocal?"T":"F")+"&newchattext=";
	}

	if (dataInOutTimerID==null) {
		if (_playingself) dataInOutTimerID=setTimeout("DataInOut()",3000);	//500	
		else {
			if (_waitingForUpdates) dataInOutTimerID=setTimeout("DataInOut()",1500);	//500	
			else dataInOutTimerID=setTimeout("DataInOut()",2500);	//500	
		}	
	}
};

function DataInOutCallBack() {

	ProcessResponse(_objHttpResponseData);
	SetupNextUpdate();
};



//send player click	and request response
function SendReceiveUpdates() 
{				
	if (!_waitingForUpdates) return;
	
	var tleft="0px";
	var ttop="0px";
	
	var ttime=ge("divTime").innerHTML;
	if (ttime!="0") {
		tleft=parseInt(ge("imgBlueButton").style.left)+5+"px";
		ttop=parseInt(ge("imgBlueButton").style.top)+5+"px";
	}
	
	if (_newQueryStr=="") {
		_newQueryStr="gamecomm.aspx?rev=1.20&roundover=true&xtime="+ttime+"&xleft="+tleft+"&xtop="+ttop+"&adjust="+_adjustrounds+"&pause="+(_pauseLocal?"T":"F")+"&newchattext=";
	}
	else { //strip off chat and add back to query
		pos=_newQueryStr.indexOf("&newchattext=");
		_newQueryStr="gamecomm.aspx?rev=1.20&roundover=true&xtime="+ttime+"&xleft="+tleft+"&xtop="+ttop+"&adjust="+_adjustrounds+"&pause="+(_pauseLocal?"T":"F")+_newQueryStr.substring(pos,_newQueryStr.length);
	}
};


//------------------------------------- Process Server Response ------------------------------------


function ProcessResponse(resp) {
	
	if (resp=="Timed Out.") { 
		_timedOut=true;
		if (is_iphone) window.top.location="iphone.htm";
		if (window.top) window.top.close();
		if (document) document.close();
		return;
	}
		
	if (resp=="BROKENLINK") {     //other player broke connection
		StopAllTimersFinal();
		if (is_nav) document.onmousedown=null;
		if (is_IE) ge("bdyTag").onmousedown=null;
		ge("bdyTag").onbeforeunload=null;
		document.onkeydown=null;
		alert("Opponent has quit.");
		ExitGame();
		return;
	}
	
	if (resp=="OFFENSE") {     //connection terminate due to offense
		StopAllTimersFinal();
		alert("Connection terminated due to offense.");
    if (is_iphone) window.top.location="iphone.htm";
    else {
		  if (window.top) window.top.close();
		  if (document) document.close();
    }
		return;
	}

	if (resp.length>12 && resp.substring(0,12)=="ADJUSTROUND:") {     //other player adjusted round
		_roundsremaining=_roundsremaining+(resp.substring(12,resp.length)*1);
		if (_roundsremaining<0) _roundsremaining=0;
		ge("txtRounds").innerHTML=_roundsremainingtext+(_roundsremaining*1+1);
		return;
	}

	var pauseresp=resp.substring(0,1);
		
	if (pauseresp=="T" || pauseresp=="F") { 
		ProcessRegularChat(resp);			
	}			
	else { //end of round results are in
		ProcessResults(resp);
	}
};


//process chat and pause state
function ProcessRegularChat(resp)
{
	var pauseresp=resp.substring(0,1);
	
	//strip off signon updates
	if (ge("btnUpdatesOnButton").style.backgroundColor=="red") resp=resp.replace(/GEOSENSE.*signed on./g,'');
	
	//display chat
	if (resp.length>3) {
		resp=resp.substring(2,resp.length);
		ge("divChatInGame").innerHTML=ge("divChatInGame").innerHTML + resp.replace(/\r/g,'<br>');
		ge("divChatInGame").scrollTop=ge("divChatInGame").scrollHeight;
		ge("divChatInGame").scrollTop=ge("divChatInGame").scrollHeight;		
	}
	
	//two player update pause state
	if (!_playingself) {	
		if (_roundsremaining!=0) { 
			var oldpauseRemote=_pauseRemote	;						
			if (pauseresp=="T") _pauseRemote=true;
			if (pauseresp=="F") _pauseRemote=false;
			if (!_pauseRemote) {
				ge("btnRemotePause").style.backgroundColor=_transparenttext;
				ge("btnRemotePause").value="Pause";
			}
			if (!_pauseLocal) {
				ge("btnLocalPause").style.backgroundColor=_transparenttext;
				ge("btnLocalPause").value="Pause";
			}
			if (!_pauseRemote && !_pauseLocal) clearTimeout(pauseTimerID);
			if (_pauseRemote && !oldpauseRemote && !_pauseLocal) PauseFlashTimer(); //remote initiates pause	
		}				 	
		 	
		//both players unpaused, a new set of rounds begins					 		
		if (_roundsremaining<0 && !_pauseRemote && !_pauseLocal) {
			_roundsremaining=DEFAULTROUNDS-1;
			_roundsplayed=0;
			_roundsplayedLocal=0;
			_roundsplayedRemote=0;
			ge("cllHeaderBorder2").style.display="none";
			ge("tblRoundsResults").style.display="none";
			ge("txtContinue").style.display="none";
			ge("txtHighScore").style.display="none";
			ge("btnHighScore").style.display="none";
			ge("divCity").style.visibility="visible";
			ge("divTime").style.visibility="visible";
			if (_map!="us") ge("imgFlag").style.visibility="visible";

			ge("cllKmsOffLocal").innerHTML="";
			ge("cllKmsOffRemote").innerHTML="";
			ge("cllLocalPointsOut").innerHTML="";
			ge("cllLocalScoreOut").innerHTML="";
			ge("cllRemotePointsOut").innerHTML="";
			ge("cllRemoteScoreOut").innerHTML="";
			ge("txtRounds").innerHTML=_roundsremainingtext+DEFAULTROUNDS;
			_aPointsLocal = 0;
			_aErrorLocal = 0;
			_aTimeLocal = 0;
			_vroundswonLocal=0;
			_vroundswonRemote=0;
			_vroundsTOutLocal=0;
			_vroundsTOutRemote=0;
		}		
	}			
};
	
//process end of round results
function ProcessResults(resp)
{		

	_playerActive=true;

	_roundcount++; //debug

	_waitingForUpdates=false;
	clearTimeout(flickTimerID);
	flickTimerID=0;
	
	//parse out and update variables				
	var OC=Parse(resp,"OC");
	_currentcity=OC.replace(/\n/,"").replace(/\r/,"");

	ge("cllLocalScoreOut").innerHTML=Parse(resp,"OLS");					
	ge("cllLocalPointsOut").innerHTML=Parse(resp,"OLP");
												
	var OCL = Parse(resp, "OCL");
	ge("imgYellowButton").style.left=OCL-20;
	ge("imgYellowCircle").style.left=OCL-20;
	
	var OCT = Parse(resp, "OCT");
	ge("imgYellowButton").style.top=OCT-20;
	ge("imgYellowCircle").style.top=OCT-20;
					
	ge("imgBlueButton").style.left=ge("imgBlueCircle").style.left;
	ge("imgBlueButton").style.top=ge("imgBlueCircle").style.top;
	ge("imgBlueButton").height=41;
	ge("imgBlueButton").width=41;
	
	var OLE = Parse(resp, "OLE");
	ge("cllKmsOffLocal").innerHTML=ge("cllLocalPointsOut").innerHTML=="timed out..."?"0":""+OLE;

	var OSU = Parse(resp, "OSU");

	if (OSU!="") {
		ge("divChatInGame").innerHTML=ge("divChatInGame").innerHTML + OSU.replace(/\r/g,'<br>');
		ge("divChatInGame").scrollTop=ge("divChatInGame").scrollHeight;
		ge("divChatInGame").scrollTop=ge("divChatInGame").scrollHeight;
	}					
	
	if (!_playingself) {
		ge("cllRemoteScoreOut").innerHTML=Parse(resp,"ORS");
		ge("cllRemotePointsOut").innerHTML=Parse(resp,"ORP");
		
		var ORL = Parse(resp, "ORL");
		ge("imgRedButton").style.left=ORL-20;
		ge("imgRedCircle").style.left=ORL-20;
				
		var ORT = Parse(resp, "ORT");
		ge("imgRedButton").style.top=ORT-20;
		ge("imgRedCircle").style.top=ORT-20;
		
		var ORE = Parse(resp, "ORE");
		ge("cllKmsOffRemote").innerHTML=ge("cllRemotePointsOut").innerHTML=="timed out..."?"0":""+ORE;
		
		_roundsremaining = Parse(resp, "OR")*1-1;
		if (_roundsremaining<0) _roundsremaining=0;		
		ge("txtRounds").innerHTML=_roundsremainingtext+_roundsremaining;
		_adjustrounds=0;
	}
	
	//update averages
	var newLocalPoints=0;
	var newLocalTime=0;

	if (ge("cllLocalPointsOut").innerHTML!="timed out...") {
		_roundsplayedLocal++;
		var lp=""+ge("cllLocalPointsOut").innerHTML;
		newLocalPoints=lp.substring(0,lp.indexOf(" "));
		newLocalTime=lp.substring(lp.indexOf("(")+1,lp.indexOf("s"));
		_aPointsLocal = (_aPointsLocal*(_roundsplayedLocal-1)+newLocalPoints*1)/_roundsplayedLocal;
		_aErrorLocal =(_aErrorLocal*(_roundsplayedLocal-1)+OLE*1)/_roundsplayedLocal;
		_aTimeLocal = (_aTimeLocal*(_roundsplayedLocal-1)+newLocalTime*1)/_roundsplayedLocal;
	}
	else _vroundsTOutLocal++;			
	
	if (!_playingself) {
		newRemotePoints=0;
		newRemoteTime=0;
		if (ge("cllRemotePointsOut").innerHTML!="timed out...") {
			_roundsplayedRemote++;
			lp=""+ge("cllRemotePointsOut").innerHTML;
			newRemotePoints=lp.substring(0,lp.indexOf(" "));
			newRemoteTime=lp.substring(lp.indexOf("(")+1,lp.indexOf("s"));
			_aPointsRemote = (_aPointsRemote*(_roundsplayedRemote-1)+newRemotePoints*1)/_roundsplayedRemote;
			_aErrorRemote =(_aErrorRemote*(_roundsplayedRemote-1)+ORE*1)/_roundsplayedRemote;
			_aTimeRemote = (_aTimeRemote*(_roundsplayedRemote-1)+newRemoteTime*1)/_roundsplayedRemote;
		}
		else _vroundsTOutRemote++;
			
		if (newLocalPoints>newRemotePoints) _vroundswonLocal++;
		if (newRemotePoints>newLocalPoints) _vroundswonRemote++;
	}

	SetupDisplayResults();
};	


//------------------------------------- Display End Round Results ------------------------------------

//clear display and setup DisplayResults timer
function SetupDisplayResults()
{			
  ge("divMapImage").className="";

	StopAllTimers();
	if (_pauseLocal || _pauseRemote) pauseTimerID=setTimeout("PauseFlashTimer()", 320);

	ge("imgBlueCircle").style.visibility="hidden";
	ge("imgBlueButton").style.visibility="hidden";
				
	ge("imgBlueButton").width=40;
	ge("imgBlueButton").height=40;
	ge("imgRedButton").width=40;
	ge("imgRedButton").height=40;
	ge("imgYellowButton").width=40;
	ge("imgYellowButton").height=40;
	
	if (!_playingself && ge("cllRemotePointsOut").innerHTML!="timed out...") {
		ge("imgRedButton").style.visibility="visible";
		ge("imgRedCircle").style.visibility="visible";
	}
	if (ge("cllLocalPointsOut").innerHTML!="timed out...") {
		ge("imgBlueButton").style.visibility="visible";
		ge("imgBlueCircle").style.visibility="visible";
	}
	
	ge("imgYellowButton").style.visibility="visible";
	ge("imgYellowCircle").style.visibility="visible";
	shrinkTimerID=setTimeout("ShrinkTimer()",500);

	_guessed=true;
	if (_scramble) {
		_revealcity="";
		for (i=0;i<_currentcity.length;i++) _revealcity=_revealcity+' ';
	}  
	_displayTimeLeft=(is_iphone?5:25); //display results for 5 seconds 
	displayTimerID  = setTimeout("DisplayResultsTimer()", 300);	
};	


//finished results, started next city
function ContinueNextCity()
{
	if (_scramble) ge("divCity").innerHTML= _revealcity;
	else ge("divCity").innerHTML= _currentcity; 
	LoadFlagPic();
										
	if (_scramble && _map!="us") {
		ge("imgFlag").width=0;
		ge("imgFlag").height=0;
	}

	clearTimeout(allflickTimerID);
	allflickTimerID=0;
	clearTimeout(flickTimerID);
	flickTimerID=0;
	
	ge("imgRedButton").style.visibility="hidden";
	ge("imgBlueButton").style.visibility="hidden";
	ge("imgYellowButton").style.visibility="hidden";
	ge("imgRedCircle").style.visibility="hidden";
	ge("imgBlueCircle").style.visibility="hidden";
	ge("imgYellowCircle").style.visibility="hidden";
	
	_roundsremaining--;
	ge("txtRounds").innerHTML=_roundsremainingtext+(_roundsremaining+1);
	_roundsplayed++;
					
	if (_roundsremaining<0) {
		EndRounds();
	}
	
	_guessed=false;
	if (_scramble) {
		ge("divTime").innerHTML=SCRAMBLETIME;
		_flagPercentRevealed=0;
		revealflagTimerID=setTimeout("RevealFlagTimer()", 500);
	}
	else ge("divTime").innerHTML=RACETIME;
	
	guessTimerID = setTimeout("GuessTimer()", 1000);
};
		
//final round complete
function EndRounds()
{
	ge("divCity").style.visibility="hidden";
	ge("imgFlag").style.visibility="hidden";
	ge("divTime").style.visibility="hidden";
		
	ge("cllRRnameLocal").innerHTML="  "+ge("divLocalPlayer").innerHTML;
	
	ge("cllAvgPointsLocal").innerHTML=_aPointsLocal.toFixed?_aPointsLocal.toFixed(1):_aPointsLocal;
	ge("cllAvgErrorLocal").innerHTML=_aErrorLocal.toFixed?_aErrorLocal.toFixed(1):_aErrorLocal;
	ge("cllAvgTimeLocal").innerHTML=_aTimeLocal.toFixed?_aTimeLocal.toFixed(1):_aTimeLocal;
	ge("cllRoundsTimedOutLocal").innerHTML=_vroundsTOutLocal;
	ge("cllRRScoreLocal").innerHTML=ge("cllLocalScoreOut").innerHTML;
	ge("cllRRoundsPlayedLocal").innerHTML=_roundsplayed;
	
	if (!_playingself) {
		ge("cllAvgPointsRemote").innerHTML=_aPointsRemote.toFixed?_aPointsRemote.toFixed(1):_aPointsRemote;
		ge("cllAvgErrorRemote").innerHTML=_aErrorRemote.toFixed?_aErrorRemote.toFixed(1):_aErrorRemote;
		ge("cllAvgTimeRemote").innerHTML=_aTimeRemote.toFixed?_aTimeRemote.toFixed(1):_aTimeRemote	;		
		ge("cllRoundsWonRemote").innerHTML=_vroundswonRemote;
		ge("cllRoundsTimedOutRemote").innerHTML=_vroundsTOutRemote;
		ge("cllRRScoreRemote").innerHTML=ge("cllRemoteScoreOut").innerHTML;
		ge("cllRRnameRemote").innerHTML="  "+ge("divRemotePlayer").innerHTML;
		ge("cllRoundsWonLocal").innerHTML=_vroundswonLocal;
		ge("cllRRoundsPlayedRemote").innerHTML=_roundsplayed;
		_pauseRemote=true;
	}
	else {
		ge("cllAvgPointsRemote").innerHTML="-";
		ge("cllAvgErrorRemote").innerHTML="-";
		ge("cllAvgTimeRemote").innerHTML="-";
		ge("cllRoundsWonRemote").innerHTML="-";
		ge("cllRoundsTimedOutRemote").innerHTML="-";
		ge("cllRRScoreRemote").innerHTML="-";
		ge("cllRRnameRemote").innerHTML="";
		ge("cllRoundsWonLocal").innerHTML="-";
		ge("cllRRoundsPlayedRemote").innerHTML="-";
	}

	ge("txtContinue").style.display="block";
	ge("tblRoundsResults").style.display="block";			
	ge("cllHeaderBorder2").style.display="block";			

	PauseHit();
	
	clearTimeout(dataInOutTimerID);
	dataInOutTimerID=null;
	
	if (_roundsplayed>=DEFAULTROUNDS && _vroundsTOutLocal==0  && !_pausedonce) {
		checkhighscoreID=setTimeout("CheckHighScore()",500);	 //resets dataInOutTimerID					
	}
	else {
		if (_playingself) dataInOutTimerID=setTimeout("DataInOut()",2500);	
		else dataInOutTimerID=setTimeout("DataInOut()",500);
	}
			
	_pausedonce=false;
	ge("btnHighScore").style.display="block";
};




//-------------------------------------------- Misc  ---------------------------------------


function CheckHighScore() {

	if (ge("divLocalPlayer").innerHTML.indexOf('guest')<0) {
	
		var sendstr = "highscorecomm.aspx";
		sendstr += "?rev=1.20";
		sendstr += "&command=CHECKHIGHSCORE" + _map;
		sendstr += "&avgpoints=" + (_aPointsLocal.toFixed? _aPointsLocal.toFixed(0) :_aPointsLocal);
		sendstr += "&avgerror=" + (_aErrorLocal.toFixed? _aErrorLocal.toFixed(0): _aErrorLocal);
		
		HttpSendGame( sendstr, "CheckHighScoreCallBack");
	}
	if (_playingself) dataInOutTimerID=setTimeout("DataInOut()",2500);	
	else dataInOutTimerID=setTimeout("DataInOut()",500);
	
};
		
function CheckHighScoreCallBack() {

  ge("txtHighScore").innerHTML="";
	
  if (_objHttpResponseData.charAt(0)=="*") {
    ge("txtHighScore").innerHTML="That was a personal best!";
		ge("txtHighScore").style.display="block";
		_objHttpResponseData=_objHttpResponseData.substring(1,_objHttpResponseData.length)
  }
  
	if (_objHttpResponseData!="NO" && _objHttpResponseData!="ALLTIME" && _objHttpResponseData!="MONTH" && _objHttpResponseData!="WEEK") alert("A database error occurred:"+_objHttpResponseData);
	if (_objHttpResponseData=="ALLTIME") {
		ge("txtHighScore").innerHTML+="<br>That was an alltime high score!";
		ge("txtHighScore").style.display="block";
	}
	if (_objHttpResponseData=="MONTH") {
		ge("txtHighScore").innerHTML+="<br>That was a high score for the month!";
		ge("txtHighScore").style.display="block";
	}
	if (_objHttpResponseData=="WEEK") {
		ge("txtHighScore").innerHTML+="<br>That was a high score for the week!";
		ge("txtHighScore").style.display="block";
	}
};
		
		
function LoadFlagPic() {

	if (_map=="us") return;
	var country=_currentcity.match(/\b[^,]*/)[0].replace(/ /g,"");											
	ge("imgFlag").src="flagfiles/flag_"+country.toLowerCase()+".gif";
};
		
function ScrambleUpdate()
{
	if (_revealcity==_currentcity) return;
	
	var r = Math.floor(Math.random()*_currentcity.length);
	while(_currentcity.charAt(r)==' ' || _revealcity.charAt(r)!=' ') r = Math.floor(Math.random()*_currentcity.length);			
	_revealcity=_revealcity.substring(0,r) + _currentcity.charAt(r) + _revealcity.substring(r+1,_revealcity.length);
	ge("divCity").innerHTML= _revealcity ;
};			


function ProcessRoundChange()
{

	ge("txtRounds").innerHTML=_roundsremainingtext+(_roundsremaining+1);
				
	//create or update querystring		
	if (_waitingForUpdates) {
		SendReceiveUpdates();
		return;
	}
		
	if (_newQueryStr=="") {
		_newQueryStr="gamecomm.aspx?rev=1.20&roundover=false&adjust="+_adjustrounds+"&pause="+(_pauseLocal?"T":"F")+"&newchattext=";
	}
	else {
		var pos=_newQueryStr.indexOf("&adjust=");
		var posrest=_newQueryStr.indexOf("&pause=");   //assumes order
		_newQueryStr=_newQueryStr.substring(0,pos+8)+_adjustrounds+_newQueryStr.substring(posrest,_newQueryStr.length);
	}
};




//------------------------------------- Http Request functions ------------------------------------ 


function HttpSendGame(sendstr, callBackFunctionName) 
{	
	
	if (sendstr=="" || callBackFunctionName==null || callBackFunctionName=="") return;

	if (_objHttpGame!=null) { 
		_pendingRequestsGame[_pendingRequestsGameCount]=sendstr;
		_pendingRequestsGameCallBacks[_pendingRequestsGameCount]=callBackFunctionName;
		_pendingRequestsGameCount++;
		return;
	}
	
	
	if (window.ActiveXObject) {
		_objHttpGame = new ActiveXObject("Microsoft.XMLHTTP");
		_objHttpGame.Open('GET',encodeURI(sendstr),true);
		SetHeaderHTTP(_objHttpGame);  //bandwidth
		_objHttpGame.Send();
	}
	else if (window.XMLHttpRequest) {		
		_objHttpGame = new XMLHttpRequest();
		_objHttpGame.open('GET',encodeURI(sendstr),true);
		_objHttpGame.send(null);
	}
	
	if (ge("txtChatOut").value=="clear") ge("divChatIn").innerHTML=""; //debug
	if (ge("txtChatOut").value=="query") CommentGame(sendstr); //debug
	
	_objHttpGame.onreadystatechange = function() { eval("HttpAsyncCallBackGame('"  + callBackFunctionName + "')") };
	
};

function HttpAsyncCallBackGame(callBackFunctionName) 
{
	
	if (_objHttpGame==null || _objHttpGame.readyState!=4) return;
		
	_objHttpResponseData = _objHttpGame.responseText;
	_objHttpGame=null;
	
	eval(callBackFunctionName+"()");

	if (_pendingRequestsGame[_pendingRequestsGameCurrent+1]) {
		_pendingRequestsGame[_pendingRequestsGameCurrent]=null;
		_pendingRequestsGameCurrent++;
		HttpSendGame( _pendingRequestsGame[_pendingRequestsGameCurrent], _pendingRequestsGameCallBacks[_pendingRequestsGameCurrent]);
	}

};		

function ClearPendingRequestsGame()
{
	_pendingRequestsGame=new Array;
	_pendingRequestsGameCallBacks=new Array;
	_pendingRequestsGameCount=1;
	_pendingRequestsGameCurrent=0;

	_objHttpGame = null;
	_objHttpResponseData = "";
};

//------------------------------------- Utility functions ------------------------------------ 
	
function Parse(fromstr,findstr)
{		
	var foundstr="notfound";
	var splitstr=fromstr.split("!");
	for (i=0;i<splitstr.length;i++) if (splitstr[i]==findstr) foundstr=splitstr[i+1];
	if (foundstr=="notfound"){
		StopAllTimers();
		//document.write(fromstr);//debug
		//alert("Geosense:parse error");
		if (is_iphone) window.top.location="iphone.htm";
		else {
		  if (window.top) window.top.close();		
		  if (document) document.close();		
		}
		return;
	}	
	return foundstr;
};


function CommentGame(commentstr)
{
	ge("divChatInGame").innerHTML=ge("divChatInGame").innerHTML + commentstr + "<br>";
	ge("divChatInGame").scrollTop=ge("divChatInGame").scrollHeight;
};



