//	dino.js
// code for the site
var connectToSite = true; // true do ajax stats
var useRandomValueAjax = true; // true do add rnd=4534534 to each Ajax call
var dino_path = ""; // nothing for now
var slideshowOn = false; // if is activated
var myShow = ""; // slideshow object to be destroyed
var mySexyLightBox = "";
var gameEnded = 0; // if set not ask exit game room and not destroy game, also contains the number of the player that win
var chatLastID = 0;
var privateRoomID = 0;	// used to force enter on the private room if is set the room ID

// multi language text
document.write("<script type='text/javascript' src='languageJSCreate.php'></script>");

function mooAjaxLoadPage( page ) {
	if ( slideshowOn ) {
		if ( myShow ) {
			myShow.destroy();
			myShow = "";
		}	
	}
		
	//$('Contents').set('load', {method: 'get'});
	// add random ID to avoid cache!
	if ( useRandomValueAjax )
		page += "?rnd=" + makeRandomID();
	//alert ( page);
	$('Contents').load(page);

	//req = new Request.HTML( {url: page, method : 'get' , update: $('Contents'), evalScripts: true} );
	//req.send();

}

function dummyFunction() {
}

function makeRandomID() {
	var day = new Date();
	var rnd = day.getTime() + Math.floor ( Math.random() * 1000000 );
	return( rnd );
}

//ondomready...
window.addEvent('domready', function() {
	// alarm for quickmenu 'not working yet' message
    Sexy = new SexyAlertBox();


});

function mooAjaxLoadPlusExecuteJs( page ) {
	//alert( page );
	if ( slideshowOn ) {
		if ( myShow ) {
			myShow.destroy();
			myShow = "";
		}
	}

	// add random ID to avoid cache!
	page += "?rnd=" + makeRandomID();
	req = new Request.HTML( {url: page, method : 'get' , update: $('Contents'), evalScripts: true} );
	req.send();
	return false;
}


function drawBacktoMenuBar( title ) {
	mybackToMenuSlide = new Fx.Slide('backToMenu', {mode: 'horizontal'});
	mybackToMenuSlide.hide();
	mybackToMenuSlide.slideIn();

	var myFx = new Fx.Tween("linkBackToMenu");
	var myQuickMenu = $('linkBackToMenu');
	myQuickMenu.addEvents({
	'mouseenter': function() { myFx.start('color', '#ffffff', '#ffed00'); },
	'mouseleave': function() { myFx.start('color', '#ffed00', '#ffffff'); }
	});

	var myFx2 = new Fx.Tween("backToMenu");
	var myQuickMenu = $('backToMenu');
	myQuickMenu.addEvents({
	'mouseenter': function() { myFx2.start('background-color', '#1c3c61', '#395e89'); },
	'mouseleave': function() { myFx2.start('background-color', '#395e89', '#1c3c61'); }
	});
}


var multiplayerFlag = false;
function askEndGame() {
	//alert( multiplayerFlag);
	var textToDisplay = Quoridor.I18N.msg["WARNING_INTERRUPTGAME"]; 
	var textButtonYes = Quoridor.I18N.msg["ENDGAME"]; // "ENDGAME";
	var textButtonCancel = Quoridor.I18N.msg["CONTINUE_PLAY"]; // "CONTINUE PLAY";
	if ( gameEnded == 1 ) {
		textToDisplay = Quoridor.I18N.msg["CONFIRM_EXIT_ROOM"]; // "Confirm to exit from the game room?";
		textButtonYes = Quoridor.I18N.msg["YES"]; // "YES";
		textButtonCancel = Quoridor.I18N.msg["CONTINUE_CHAT"]; // "CONTINUE CHAT";
	}
	
	var value = Sexy.confirm(textToDisplay, {
	textBoxBtnOk: textButtonYes,
	textBoxBtnCancel: textButtonCancel,
	onComplete:
	function(returnvalue) {
	if (returnvalue) {
		if ( multiplayerFlag )
			document.location.href= "playmulti_quit.php";
		else
			document.location.href= "playsolo.php";
	} else
		return false;
	}
	});

}

// usage: 
// HTML: class="rolloverPlayButton"
// JS:   doRollovers($$('.rolloverPlayButton'));

doRollovers = function(elements) {
elements.each(function(thisel){
var src = thisel.getProperty('src');
src = src.replace('_over','');
var extension = src.substring(src.lastIndexOf('.'),src.length);
thisel.getParent().getParent().setStyle('background','url('+src.replace(extension,'_over' + extension)+') no-repeat');
thisel.addEvent('mouseenter', function() { this.fade(0.01); });
thisel.addEvent('mouseleave', function() {
this.fade(1);
});
});
};

function setMenuNormalColor( id ) {
	var element = $(id);
	element.setStyle('background-color', '#8dc4df');
}

function sendForgot() {
	if ( ! document.sample.email.value ) {
		var value = Sexy.alert(Quoridor.I18N.msg["WARNING_EMAILNOTSET"] ); // 'WARNING - email address is not set!'
		return false;
	} 
	temp = emailControl( document.sample.email );
	if ( temp == false )  {
		var value = Sexy.alert(Quoridor.I18N.msg["WARNING_EMAILNOTVALID"] ); //'WARNING - email address is not valid!'
        return false;
     }
	var mailPage = "forgot-server.php?email=" + document.sample.email.value + "&rand=" + makeRandomID();
	//alert( mailPage );
	req = new Request.HTML( {url: mailPage, method : 'get' , evalScripts: false, onComplete:updatePageForForgot} );
	req.send();
	return false;
}

// valori tornati da MootTools
// onComplete: function(tree, elements, html, js) { text.set('html', html); }

function updatePageForForgot( tree, elements, html, js ) {
	//alert( 'hi cd:' + html + ' ' + elements  );
	if ( html ) 
		$('formInvia').set('html', html );
}

function sendMail() {

	if ( ! document.sample.email.value ) {
		var value = Sexy.alert(Quoridor.I18N.msg["WARNING_EMAILNOTSET"]); //'WARNING - your email address is not set!'
		return false;
	} else if ( ! document.sample.message.value ) {
		var value = Sexy.alert(Quoridor.I18N.msg["WARNING_WRITEMESSAGE"]); //'WARNING - write the message please.'
		return false;
	} 

	temp = emailControl( document.sample.email );
	if ( temp == false )  {
		var value = Sexy.alert(Quoridor.I18N.msg["WARNING_EMAILNOTVALID"] ); //'WARNING - email address is not valid!'
        return false;
     }

	
	// update site statistics
//	if ( connectToSite == false )
	//	return;
	var mailPage = "contact-server.php?email=" + document.sample.email.value + "&lastname=" +  document.sample.lastname.value + "&name=" +  document.sample.name.value + "&message=" +  document.sample.message.value + "&rand=" + makeRandomID();
	//alert( mailPage );
	req = new Request.HTML( {url: mailPage, method : 'get' , evalScripts: false} );
	req.send();
	$('formInvia').set('html', '<span style="font-size: 26px">' + Quoridor.I18N.msg["MAIL_SENT"] + '</span>' ); // Your mail is successfull delivered!
}

function emailControl( email ) {
	var email_reg_exp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z0-9]{2,})+$/;
	if (! email_reg_exp.test( email.value ) || ( email.value == "") || (email.value == "undefined")) {
		//alert( "Nel campo e-mail inserire un indirizzo email corretto." );
		return false;
		}
	else
		return true;
	}

function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

var CPU_YES = 1;
var CPU_NO = 0;
var QUORIDOR_GAME = 1;
var QUORIDOR_GAME_RESTORE = 3;
var level=0;
var PLAY_MULTI = true;
var PLAY_SOLO = false;

function goPlay( solo , type , players, cpu2 , cpu3 , cpu4 , level , version ) {
	if ( solo == false )
		var URL = 'playsolo_start.php?type=' + type + '&players=' + players + '&cpu2=' + cpu2 + '&cpu3=' + cpu3 + '&cpu4=' + cpu4 + '&level=' + level + '&version=' + version;
	else
		var URL = 'playmulti_start.php?type=' + type + '&players=' + players + '&cpu2=' + cpu2 + '&cpu3=' + cpu3 + '&cpu4=' + cpu4 + '&level=' + level;
	document.location.href = URL;
}

function goPlayDebug( solo , type , players, cpu2 , cpu3 , cpu4 , level , version ) {
	if ( solo == false )
		var URL = 'playsolo_start2.php?type=' + type + '&players=' + players + '&cpu2=' + cpu2 + '&cpu3=' + cpu3 + '&cpu4=' + cpu4 + '&level=' + level + '&version=' + version;
	else
		var URL = 'playmulti_start2.php?type=' + type + '&players=' + players + '&cpu2=' + cpu2 + '&cpu3=' + cpu3 + '&cpu4=' + cpu4 + '&level=' + level;
	document.location.href = URL;
}

function goRestoreGame(  xml ) {
	var URL = 'playsolo_start.php?type=' + QUORIDOR_GAME_RESTORE + '&xml=' + xml;
	URL += '&level=' + document.options.levelCPU.value;
	document.location.href = URL;
}

function askSendDebug() {
 if ( thisMovie("Quoridor").returnGameTurnToJavascript() < 2 ) {
	var value = Sexy.alert(Quoridor.I18N.msg["DEBUG_AFTERFIST_TURN"] );
	return false; 
	}
Sexy.prompt('<h1>' + Quoridor.I18N.msg["DEBUG_HELPUS_WRITE"] ,'' ,
  	{ onComplete: 
    	function(returnvalue) {
      		if(returnvalue)    
      			sendToActionScript(returnvalue);
	     	else
	     		return false;
	     }   
	 });
  return false;
}

// update site statistics
function updateStatistics( pageName ) {
	var statsPage = "statistics.inc.php?pagename=" + pageName + "&rand=" + makeRandomID();
	//alert( statsPage );
	req = new Request.HTML( {url: statsPage, method : 'get' , evalScripts: false} );
	req.send();
}

function openSexyLightBox( goToURL , myWidth, myHeight ) {
	updateStatistics( goToURL );
	if ( useRandomValueAjax )
		goToURL += "?rnd=" + makeRandomID();

	var mySexyLightBox = new SexyLightBox({width: 650 , height: 450 ,find:'sexylightbox',color:'black', OverlayStyles:{'background-color':'#1c3c61'}});
	mySexyLightBox.options.width = myWidth;
	mySexyLightBox.options.height = myHeight;
	mySexyLightBox.show('', goToURL ,'sexylightbox');

}

function showRulebook( language ) {
	var URL = 'rulebook_showingame.php?id=' + language + "&rnd=" + makeRandomID();
	var IE = /*@cc_on!@*/false;
	if(IE){
		//IE specific code goes here
		window.open(URL,'Rulebook','width=740,height=530');
	}else{
		var mySexyLightBox = new SexyLightBox({width: 740 , height: 530 ,find:'sexylightbox',color:'black', OverlayStyles:{'background-color':'#1c3c61'}});
		mySexyLightBox.show('', URL ,'sexylightbox');
	}
}

function showKeys() {
	var URL = 'keys_showingame.php';
	var IE = /*@cc_on!@*/false;
	if(IE){
		//IE specific code goes here
		window.open(URL,'Rulebook','width=740,height=530');
	}else{
		var mySexyLightBox = new SexyLightBox({width: 715 , height: 500 ,find:'sexylightbox',color:'black', OverlayStyles:{'background-color':'#1c3c61'}});
		mySexyLightBox.show('', URL ,'sexylightbox');
	}
}

var countDown = 10;
var COUNTDOWN_STARTVALUE = 10;

/* **************************** PLAY MULTI CODE ***************************** */
var TwoPlayersAvailable = 0;
var FourPlayersAvailable = 0;

// Ajax function
function checkForAvailableGames() {
	var statsPage = "playmulti_ajax_availplayers.php?rand=" + makeRandomID();
	//alert( 'ajax' );
	req = new Request.HTML( {url: statsPage, method : 'get' , evalScripts: false, onComplete:updatePageForAvailableGamesUpdateCountdown } );
	req.send();
}

		
function startUpdatePageForAvailableGames() {
	setTimeout( "updatePageForAvailableGames();" , 1000 );
}

function updatePageForAvailableGames() {
	if ( countDown > 1 ) {
		countDown--;
		$('myCountdown').set('html', " "+ countDown + " " +Quoridor.I18N.msg["SECONDS"] );
		setTimeout( "updatePageForAvailableGames();" , 1000 );
	} else {
		countDown = COUNTDOWN_STARTVALUE;
		checkForAvailableGames();
		$('myCountdown').set('html', 'Updating...' );
	}
}

// valori tornati da MootTools
// onComplete: function(tree, elements, html, js) { text.set('html', html); }

var statusRooms2 = false;
var statusRooms4 = false;

function updatePageForAvailableGamesUpdateCountdown( tree, elements, html, js ) {
	//alert( 'hi cd:' + html + ' ' + elements  );
	if ( html ) {
		var arrayReply = html.split( "|" );
		$('onlineOpponents2').set('html', arrayReply[0] );
//		$('onlineOpponents4').set('html', arrayReply[1] );
		if ( arrayReply[0] > 0 ) {
			statusRooms2 = true;
			$('onlineTwoPlayersOption').set('html', '<a href="#" onClick="goMultiPlay( 2 )"> ' + Quoridor.I18N.msg["ENTER_TO_PLAY"] + ' </a>' );
		} else if ( privateRoomID == 0) {
			statusRooms2 = false;
			$('onlineTwoPlayersOption').set('html', '<a href="playmulti_enter.php?gameType=2">' + Quoridor.I18N.msg["CREATEROOM"] + '</a>' );		
		}
/*
		if ( arrayReply[1] > 0 ) {
			statusRooms4 = true;
			$('onlineFourPlayersOption').set('html', '<a href="#" onClick="goMultiPlay( 4 )"> ' + Quoridor.I18N.msg["ENTER_TO_PLAY"] + ' </a>' );
		} else if ( privateRoomID == 0) {
			statusRooms4 = false;
			$('onlineFourPlayersOption').set('html', '<a href="playmulti_enter.php?gameType=4">' + Quoridor.I18N.msg["CREATEROOM"] + '</a>' );		
		}
*/
setTimeout( "updatePageForAvailableGames();" , 1000 );
	}
}

function goMultiPlay( command ) {
	if ( command == 2 ) 
		document.location.href = "playmulti_enter.php?gameType=2";
	else 
		document.location.href = "playmulti_enter.php?gameType=4";
}

function goMultiPlayPrivate( command ) {
	if ( command == 2 ) 
		document.location.href = "playmulti_enter.php?gameType=2&game_privateroom=" + privateRoomID;
	else 
		document.location.href = "playmulti_enter.php?gameType=4&game_privateroom=" + privateRoomID;
}

function sendPlayForm() {

	if ( privacyNotCheck == false ) {
		if ( ! getCheckedValue( document.sample.user_privacypolicy ) ) {
			var value = Sexy.alert(Quoridor.I18N.msg["NOTACCEPT_PRIVACY"] ); 
			return false;
		} else if ( document.sample.user_age.value < 6 ) {
			var value = Sexy.alert(Quoridor.I18N.msg["INSERT_AGE"] );
			return false;
		} 
	}
	
	if ( getCheckedValue( document.sample.user_use_nickname ) ) {
		if ( ! document.sample.user_nickname.value ) {
			var value = Sexy.alert(Quoridor.I18N.msg["INSERT_NICK"] );
			return false;
		}
	} else {
		if ( ! document.sample.user_name.value ) {
			var value = Sexy.alert(Quoridor.I18N.msg["INSERT_NAME"] );
			return false;
		}
		if ( ! document.sample.user_lastname.value ) {
			var value = Sexy.alert(Quoridor.I18N.msg["INSERT_LASTNAME"] );
			return false;
		}
	}	

	if ( ! document.sample.user_country.value ) {
		var value = Sexy.alert(Quoridor.I18N.msg["INSERT_COUNTRY"] );
		return false;
	}
	if ( ! document.sample.user_city.value ) {
		var value = Sexy.alert(Quoridor.I18N.msg["INSERT_CITY"] );
		return false;
	}
	if ( document.sample.user_email ) {
		if ( ! document.sample.user_email.value ) {
			var value = Sexy.alert(Quoridor.I18N.msg["WARNING_EMAILNOTSET"] );
			return false;
		}
		temp = emailControl( document.sample.user_email );
		if ( temp == false )  {
			var value = Sexy.alert(Quoridor.I18N.msg["WARNING_EMAILNOTVALID"]);
			return false;
		 }
	}

	// here at the last one ever
	if ( document.sample.user_password ) {
		if ( ! document.sample.user_password.value ) {
			var value = Sexy.alert(Quoridor.I18N.msg["INSERT_PASSWORD"] );
			return false;
		}
		if ( document.sample.user_password.value != document.sample.user_password2.value ) {
			var value = Sexy.alert(Quoridor.I18N.msg["PASSWORD_NOTMATCH"] );
			return false;
		}
	}
	
	// store user localtime
	data = new Date();
	var mySqldate = data.getHours() + ":" + data.getMinutes() + ":" + data.getSeconds() ;
	document.sample.local_time.value = mySqldate; // userDate.toGMTString();
	//alert( document.sample.local_time.value );
	return true;
}


function checkPasswordMatch () {
	if ( document.sample.user_password.value != document.sample.user_password2.value ) {
			document.sample.user_password2.value = "";
			var value = Sexy.alert(Quoridor.I18N.msg["PASSWORD_NOTMATCH"]);
			return false;
	}
}

// game waiting

var currentRoomID = 0;
var currentPlayerID = 0;
var COUNTDOWN_STARTVALUE_WAIT = 9;
var currentPlayers = 0;
var maxPlayers = 0;
var gameType = 0;

function startCheckForJoinedPlayers() {
	setTimeout( "updatePageForAvailablePlayers();" , 1000 );
	countDown = COUNTDOWN_STARTVALUE_WAIT;
}

function updatePageForAvailablePlayers() {
	if ( countDown > 1 ) {
		countDown--;
		$('myCountdown').set('html', " " + countDown + " second(s)" );
		setTimeout( "updatePageForAvailablePlayers();" , 1000 );
	} else {
		countDown = COUNTDOWN_STARTVALUE_WAIT;
		checkForAvailablePlayers();
		$('myCountdown').set('html', Quoridor.I18N.msg["UPDATING"] );
	}
}

// Ajax function
function checkForAvailablePlayers() {

	var statsPage = "playmulti_waiting_ajax_availplayers_room.php?id=" + currentRoomID + "&rand=" + makeRandomID();
	//alert( 'hi' );
	req = new Request.HTML( {url: statsPage, method : 'get' , evalScripts: false, onComplete:updatePageForAvailablePlayersUpdateCountdown } );
	req.send();
}


// valori tornati da MootTools
// onComplete: function(tree, elements, html, js) { text.set('html', html); }

function updatePageForAvailablePlayersUpdateCountdown( tree, elements, html, js ) {
	//alert( 'hi cd:' + countDown + ' ' + elements  );
	if ( html ) {
		var arrayReply = html.split( "|" );
		currentPlayers = arrayReply[0];
		maxPlayers = arrayReply[1];
		gameType = arrayReply[2];
		$('waitingRoomContainer').set('html', arrayReply[3] );
		if ( currentPlayers == maxPlayers ) {
			$('waitingRoomLoadingMessage').set('html', Quoridor.I18N.msg["LOADING_GAME"] );
			setTimeout( "loadingMultiPlayerGame()" , 2500 );
		} else
			setTimeout( "updatePageForAvailablePlayers();" , 1000 );
	}
}

function loadingMultiPlayerGame() {
	var URL = 'playmulti_start.php';
	document.location.href = URL;
	//goPlay( PLAY_MULTI, QUORIDOR_GAME, 3, CPU_NO , CPU_NO, CPU_NO , 1); 	
}


function askReEnterGameRoom( ) {
    Sexy = new SexyAlertBox();

var value = Sexy.confirm(Quoridor.I18N.msg["REJOIN"] , {
textBoxBtnOk: Quoridor.I18N.msg["YES"],
textBoxBtnCancel: Quoridor.I18N.msg["NO"],
onComplete:
function(returnvalue) {
if (returnvalue) 
 	document.location.href= "playmulti_join_auto.php";
else {
	var statsPage = 'playmulti_clearResumeGame.php';
	//alert( 'hi' );
	req = new Request.HTML( {url: statsPage, method : 'get' , evalScripts: false} );
	req.send();
	return false;
	}
}
});

}

function getMessageFromActionscript( message ) {
	//alert( message );
	document.formDebug.longMessage.value += message;

}

function gameAborted() {
	$('flashGameContainer').innerHTML = '<div id="AbortContainer">' + Quoridor.I18N.msg["ABORTED_GAME"] + '<br /><br /><br /><a href="playmulti_quit.php"><span style="text-decoration:underline; color: yellow">' + Quoridor.I18N.msg["CLICK_QUITROOM"] + '</a></div>';

}

function gameAbortedWithRequestInfo() {
	var value = Sexy.confirm(Quoridor.I18N.msg["ABORTED_GAME_2PL"] , {
	textBoxBtnOk: Quoridor.I18N.msg["OK"],
	textBoxBtnCancel: Quoridor.I18N.msg["DAMN"],
	onComplete:
	function(returnvalue) {
		document.location.href= "playmulti_quit.php";
		}
	});
}

// TODO ask continue without him for 4 players
/*
function gameAborted( msg ) {
	if ( currentPlayers < 3 ) {
		var value = Sexy.confirm(Quoridor.I18N.msg["ABORTED_GAME"], {
		textBoxBtnOk: 'OK',
		textBoxBtnCancel: 'DAMN',
		onComplete:
		function(returnvalue) {
			document.location.href= "playmulti_quit.php";
		}
		});
	} else {
		var value = Sexy.confirm(Quoridor.I18N.msg["CONTINUE_WITHOUT_HIM"] , {
		textBoxBtnOk: Quoridor.I18N.msg["CONTINUE"],
		textBoxBtnCancel: Quoridor.I18N.msg["ABORT"],
		onComplete:
		function(returnvalue) {
			if (returnvalue) {
				var statsPage = 'multiplayerPutContinue.php';
				//alert( 'hi' );
				req = new Request.HTML( {url: statsPage, method : 'get' , evalScripts: false} );
				req.send();
				return false;
			} else
				document.location.href= "playmulti_quit.php";
		}
		});
	}
}
*/

function checkLoginExists() {
	if ( document.sample.email.value && document.sample.password.value) {
		var statsPage = "playmulti_ajax_login.php?login=" + document.sample.user_email.value + "&password=" + document.sample.user_password.value + "&rand=" + makeRandomID();
		//alert( 'hi' );
		req = new Request.HTML( {url: statsPage, method : 'get' , evalScripts: false, onComplete:checkLoginExistsAnswer } );
		req.send();
	}
	return false;
}

function checkLoginExistsAnswer( tree, elements, html, js ) {
	if ( html == "ok" ) 
		var value = Sexy.alert(Quoridor.I18N.msg["MAIL_PASS_USED"] );
	return false;	
}

function checkLogin() {
	temp = emailControl( document.sample.email );
	if ( temp == false )  {
		var value = Sexy.alert(Quoridor.I18N.msg["WARNING_EMAILNOTVALID"]);
        return false;
        }

	var statsPage = "playmulti_ajax_login.php?email=" + document.sample.user_email.value + "&password=" + document.sample.user_password.value + "&rand=" + makeRandomID();
	//alert( 'hi' );
	req = new Request.HTML( {url: statsPage, method : 'get' , evalScripts: false, onComplete:checkLoginAnswer } );
	req.send();
	return false;
}

function checkLoginAnswer( tree, elements, html, js ) {
	//alert ( html );
	if ( html == "ok" ) 
		document.location.href = "playmulti_login.php?email="+ document.sample.user_email.value + "&password=" + document.sample.user_password.value + "&rand=" + makeRandomID();
	else {
		var value = Sexy.alert(Quoridor.I18N.msg["MAIL_PASS_NOTFOUND"] );
		return false;	
	}
}	

// Ajax function
function inGameGetPlayerStatusBar() {
	var statsPage = "playmulti_play_ajax_player_status.php?id=" + currentRoomID + "&rand=" + makeRandomID();
	//alert( 'hi' );
	req = new Request.HTML( {url: statsPage, method : 'get' , evalScripts: false, onComplete:inGameGetPlayerStatusBarUpdateDiv } );
	req.send();
}


// valori tornati da MootTools
// onComplete: function(tree, elements, html, js) { text.set('html', html); }

function inGameGetPlayerStatusBarUpdateDiv( tree, elements, html, js ) {
	//alert( 'hi cd:' + countDown + ' ' + elements  );
	if ( html ) {
		var arrayReply = html.split( "|" );
		statusPlayersArray = arrayReply[0].split( "-" );
		$('divPlayer1').set('html', arrayReply[1] );
		$('divPlayer2').set('html', arrayReply[2] );
		$('divPlayer3').set('html', arrayReply[3] );
		$('divPlayer4').set('html', arrayReply[4] );
		if ( infoBarTimeoutID )
			clearTimeout( infoBarTimeoutID );
		if ( gameEnded == 0 )
			infoBarTimeoutID = setTimeout( "inGameGetPlayerStatusBar();" , 4000 );
	}
}



function askLogOut() {

var value = Sexy.confirm(Quoridor.I18N.msg["DISABLE_AUTOLOGIN"] , {
textBoxBtnOk: Quoridor.I18N.msg["YES"],
textBoxBtnCancel: Quoridor.I18N.msg["NO"],
onComplete:
function(returnvalue) {
if (returnvalue) {
 	document.location.href= "playmulti_logout.php";
} else
	return false;
}
});

}


// ---------------- CHAT -------------------

function chatCheckForMessages() {
	var statsPage = "chat_ajax_get_messages.php?id_last=" + chatLastID + "&myid=" + mySelfNumberInTheRoom + "&room=" + currentRoomID + "&rand=" + makeRandomID();
	//document.sample.message.value = 'last ID: ' + chatLastID + " myID:" + mySelfNumberInTheRoom;
	//alert( statsPage );
	//alert( 'post new msg: last msg ID is ' + chatLastID );
	req = new Request.HTML( {url: statsPage, method : 'get' , evalScripts: false ,  onComplete:chatUpdateList } ); 
	req.send();

	return false;
}

/* format:
	OK		|		lastMsgID	|	message number	|	message1 ---	|	message 2 ----
		message1 ---
			id	-	datetime	-	playerNumber	-	iconNumber	- 	message (base64encoded)
*/

var contatoreDummy = 1;
var chatTimeoutID = 0;
var infoBarTimeoutID = 0;

function chatUpdateList( tree, elements, html, js ) {
	if ( html ) {
		var arrayReply = "";
		arrayReply = html.split( "|" );
		//alert( html );
		//$('chatDebug').innerHTML = contatoreDummy + ' ' + 'last ID: ' + chatLastID + " myID:" + mySelfNumberInTheRoom + "<br>" + arrayReply[0] + " " + arrayReply[1] + " " + arrayReply[2];
		if ( arrayReply[0] == "OK" ) {
			contatoreDummy++;
			if ( arrayReply[1] > 0 )
				chatLastID = arrayReply[1];
			//document.sample.message.value = 'last ID: ' + chatLastID + " m#" + arrayReply[2];
			//alert( 'last id: ' + chatLastID );
			var messagesNumber = Math.floor(arrayReply[2]); // avoid try the loop later (IE fix specially)
			var htmlCode = "";
			var tmpArray = new Array();
			var elementCounter = 1;
			if ( messagesNumber ) {
				//alert( messagesNumber );
				while( messagesNumber-- ) {
					if ( arrayReply[elementCounter+2] ) {
						tmpArray = arrayReply[elementCounter+2].split("-");
						//alert( 'msg ' + elementCounter+2 + ': ' + tmpArray[0] + " " + decodeBase64(tmpArray[4]) );
						htmlCode += chatDrawSingleMessage(tmpArray , true );
						elementCounter++;
					}
				}
		
				$("chatTableDiv").innerHTML += htmlCode;
				// nel caso sposta scroll bar
				$("chatTableDiv").scrollTop = $("chatTableDiv").scrollHeight; 
			}
		}
	}
	if ( chatTimeoutID )
		clearTimeout( chatTimeoutID );
	chatTimeoutID = setTimeout( "chatCheckForMessages()" , 4000); // another attempt in 4 seconds
}

function chatDrawSingleMessage( tmpArray , flagDecode ) {
	var tmpHtmlCode = '<table class="chatElementTable"><tr>';
	tmpHtmlCode += '<td width="18"><image src="images/chat/pawn' + tmpArray[2]  + '.png"></td>';
	tmpHtmlCode += '<td>';
	if ( flagDecode ) {
		tmpHtmlCode += '<i>(' + tmpArray[5] + ')'; // decodeBase64( )
		if ( tmpArray[6] ) 
			tmpHtmlCode += ' ' + decodeBase64(tmpArray[6]);
		if ( tmpArray[7] ) 
			tmpHtmlCode += ' ' + Quoridor.I18N.msg["AGE"] +':' + decodeBase64(tmpArray[7]);
		tmpHtmlCode += '</i><br /><image src="images/chat/' + tmpArray[3]  + '.png">' +decodeBase64(tmpArray[4])  + '</td>';

	} else
		tmpHtmlCode += '<i>' + Quoridor.I18N.msg["ME"] + '</i><br /><image src="images/chat/' + tmpArray[3]  + '.png">' + ' '+ tmpArray[4] + '</td>';
	tmpHtmlCode += '</tr></table>';	
	return(tmpHtmlCode);
}


function chatSendMessage(){
     if( $("message").value == "" ){
		var value = Sexy.alert(Quoridor.I18N.msg["WARNING_WRITEMESSAGE"]);
        return false;
    }
	//alert ( $("message").value );
        
    params = "?message=" + encodeBase64( $("message").value ) ;
    params+= "&icon_id=" + chatSelectedIcon;
	params+= "&myid=" + mySelfNumberInTheRoom + "&room=" + currentRoomID;

 	var statsPage = "chat_message_store.php" + params + "&rand=" + makeRandomID();
	//alert( 'hi ' + statsPage );
	req = new Request.HTML( {url: statsPage, method : 'get' , evalScripts: false } );
	req.send();

	var tmpArray = new Array();
	tmpArray[2] = mySelfNumberInTheRoom;
	tmpArray[3] = chatSelectedIcon;
	tmpArray[4] = $("message").value;
	var htmlCode = chatDrawSingleMessage(tmpArray , false );
	$("chatTableDiv").innerHTML += htmlCode;
	//alert( 'hi ' + $("chatDiv").scrollTop + ' ' + $("chatDiv").scrollHeight );
	$("chatTableDiv").scrollTop = $("chatTableDiv").scrollHeight; 
	
    $("message").value = "";
	$("message").value.focus;
	if ( chatSelectedIcon ) {
		var iconName = "chatIcon" + chatSelectedIcon;
		$(iconName).setStyle( "border" ,"0px solid red" );
	}
	chatSelectedIcon = 0;

   	return false;

 }

function chatIconSet( icon ) {
	if ( chatSelectedIcon ) {
		iconName = "chatIcon" + chatSelectedIcon;
	//	$(iconName).bgColor = "#ffffff";
		$(iconName).setStyle( "border" ,"0px solid red" );
	}
	chatSelectedIcon = icon;
	iconName = "chatIcon" + chatSelectedIcon;
//	$(iconName).bgColor = "#000000";
	$(iconName).setStyle( "border" , "1px solid red" );
	return false;
}

function setEndGameMultiplayer( playerWinner ) {
	gameEnded = playerWinner;
}

// table row functions
/* usage:
<input type="button" onclick="insRow('myTable',0,'0,1,2')" value="Insert row"> 
<input type="button" onclick="delRow('myTable',0)" value="Delete row 0"> 

<input type="button" onclick="insRow('myTable',3,'r3c0,r3c1,r3c2')" value="Insert at row 3"> 
<input type="button" onclick="delRow('myTable',3)" value="Delete at row 3"> 

<input type="button" onclick="addRow('myTable','ARC1,ARC2')" value="Append row"> 
<input type="button" onclick="delLastRow('myTable')" value="Delete last row"> 

*/
function tblSize(TBL) {// number of rows in the table: 
return document.getElementById(TBL).rows.length; 
} 

function insRow(TBL,RowPosition,RowContents) { 
var numRows = tblSize(TBL); 
if (numRows < RowPosition) { RowPosition = numRows; }// check for valid insertion 

var x=document.getElementById(TBL).insertRow(RowPosition); 
var tmp = RowContents.split(','); 
for (var i=0; i<tmp.length; i++) { 
var y=x.insertCell(i); 
y.innerHTML = tmp[i]; 
} 
} 

function delRow(TBL,RowPosition) { 
var numRows = tblSize(TBL); 
if (RowPosition < numRows) { // check for valid deletion 
document.getElementById(TBL).deleteRow(RowPosition); 
} 
} 

function addRow(TBL,RowContents) { // append row to end of table 
var idxLastRow = tblSize(TBL); 
insRow(TBL,idxLastRow,RowContents); 
} 


function delLastRow(TBL) { 
var numRows = tblSize(TBL); 
delRow(TBL,numRows-1); 
} 

function delAllRows(TBL) { 
// delete all rows in the table (continuously delete first row until all rows gone): 
var objTable = document.getElementById(TBL); 
while (objTable.rows.length > 0) { objTable.deleteRow(0); } 
} 

// debug game from AS
function getMessageForDebug( myString ) {
	$('chatDebug').innerHTML = myString;
}
