// Manage user identification on website

function Ident()
{
	this.userName = "";
	this.token = "";
	this.anonymous = true;
	this.activeGames = new Array();
	this.showingRoom = new Array();
	
	this.tournaments = new Array();
}

var user = null;
var listeningGames = new Array();

function OpenIdentDiv(e)
{
	var evt = (e) ? e : window.event;
	
	openedDivs["IdentDiv"] = new Object();
	openedDivs["IdentDiv"].doNotClose = true;
	CreateAndOpenDiv("IdentDiv", evt, (document.body.clientHeight / 2) - 150, (document.body.clientWidth / 2) - 250, 500, 300, OnIdentDivOpened);
	
	CancelBubble(evt);
}

function OnIdentDivOpened()
{
	var html = new Array();
	html.push("<table width=500px height=280px><tr><td width=308px>");
		html.push("<table width=100% height=100%><tr><td class=Title1 valign=top>Vous n'&ecirc;tes pas encore membre ? Inscrivez-vous ici</td></tr>");
		html.push("<tr><td class=Title2>Vous voulez seulement jouer sans vous inscrire.</td></tr><tr><td><input type=text class=TxtAnonymous id=\"TxtAnonymous\">&nbsp;&nbsp;<button onclick=\"AnonymousConnect()\">Connexion anonyme</button></td></tr>");
		html.push("<tr><td class=Title2>Inscrivez-vous pour pouvoir b&eacute;n&eacute;ficier des diff&eacute;rents avantages r&eacute;serv&eacute;s aux membres :<ul><b>Cumuler</b> des points</ul><ul><b>Participer</b> au tournois</ul><ul><b>Miser</b> de l'argent sur les parties</ul></td></tr>");
		html.push("<tr><td><button onclick=\"GoToDiv('MAIN_INSCRIPTION_DIV', OpenAccountCreationDiv);\">S'inscrire</button></td></tr>");
	html.push("</table></TD><td valign=top>");
		html.push("<table width=100%><tr><td class=Title1 height=45px valign=top>Acc&egrave;s &agrave; la zone membre</td></tr>");
		html.push("<tr><td class=Title2>Pseudo</td></tr><tr><td><input type=text class=TxtIdent></td></tr>");
		html.push("<tr><td class=Title2>Mot de passe</td></tr><tr><td><input type=password class=TxtIdent></td></tr>");
		html.push("<tr><td height=40px><button onclick=\"AuthentConnect();\">Connexion</button></td></tr>");
	html.push("</td></tr></table>");
	
	var div = document.getElementById("IdentDiv");
	div.style.border = "";
	div.style.paddingTop = 15;
	div.style.background = "url('img/fond_ident.png') no-repeat";
	div.onclick = function(event) { CancelBubble(event)};
	div.innerHTML = html.join("");
	div.style.padding = 10;
	
	openedDivs["IdentDiv"].doNotClose = false;
}



function OnGameChoose(e, gameId)
{	
	//Look if user is already on this game
	var isLooking = false;
	for (var i = 0; i < listeningGames.length; i++)
	{
		if (listeningGames[i].gameId == gameId)
		{
			try {
				if ((listeningGames[i].popup != null) && (!listeningGames[i].popup.closed))
				{
					listeningGames[i].popup.focus();
					isLooking = true;
				}
				else
				{
					RemoveRoomsFromArray(gameId);
				}
			}
			catch(e) { //popup has been closed : reopen it
				RemoveRoomsFromArray(gameId);
			}
			break;
		}
	}
	
	if (!isLooking)
	{
		var uid = Math.random() * 1000000000000;
		uid = parseInt(uid, 10);
		
		//Open the game popup
		var popname = (gameId == 4) ? "jeuxdetables.php" : "room.php";
		var pop = window.open(popname + "?PopupName=" + traductions["Game" + gameId].trads[culture] + "&RoomId=" + gameId + "&Culture=" + culture + "&Beta=" + beta, "popupgame_" + uid,"menubar=no, status=no, scrollbars=no, menubar=no,resizable=no, width=1024, height=589");
		
		var roomObj = new RoomObject(gameId, pop);
		listeningGames.push(roomObj);
	}
}

function OpenAccountCreationDiv()
{
	var parent = document.getElementById("MAIN_INSCRIPTION_DIV");
	
	CreateAndOpenDiv("AccountCreationDiv3", null, (document.body.clientHeight / 2) - 20, (document.body.clientWidth / 2) - 250, 510, 356, OnAccountCreation3Opened, parent);
	CreateAndOpenDiv("AccountCreationDiv2", null, (document.body.clientHeight / 2) - 145 - 160, (document.body.clientWidth / 2) - 250, 250, 290, OnAccountCreation2Opened, parent);
	CreateAndOpenDiv("AccountCreationDiv", null, (document.body.clientHeight / 2) - 140 - 160, (document.body.clientWidth / 2), 250, 270, OnAccountCreationOpened, parent);
	
	if (document.getElementById("IdentDiv"))
	{
		document.body.removeChild(document.getElementById("IdentDiv"));
		delete openedDivs["IdentDiv"];
	}
	
}

function OnAccountCreationOpened()
{
	var html = new Array();
	html.push("<table width=100% cellpadding=0 cellspacing=0><tr><td class=Title1 valign=top height=30px>Pseudo et mot de passe</td></tr>");
		html.push("<tr><td class=Title2 valign=bottom height=20px>Créer votre pseudo</td></tr>");
		html.push("<tr><td ><input type=text class=TxtIdent style=\"width:180px\"><span class=RedArrow>&nbsp;*</span></td></tr>");
		html.push("<tr><td class=Title2 valign=bottom height=20px>Choisir votre mot de passe</td></tr>");
		html.push("<tr><td ><input type=password class=TxtIdent style=\"width:180px\"><span class=RedArrow>&nbsp;*</span></td></tr>");
		html.push("<tr><td valign=top><span class=InfoGrey>6 caractères minimum</span></td></tr>");
		html.push("<tr><td class=Title2 valign=bottom height=20px>Saisir de nouveau le mot de passe</td></tr>");
		html.push("<tr><td ><input type=password class=TxtIdent style=\"width:180px\"><span class=RedArrow>&nbsp;*</span></td></tr>");
		html.push("<tr><td valign=top><span class=InfoGrey>6 caractères minimum</span></td></tr>");
		html.push("<tr><td class=Title2 valign=bottom height=20px>Adresse e-mail</td></tr>");
		html.push("<tr><td ><input type=text class=TxtIdent style=\"width:180px\"><span class=RedArrow>&nbsp;*</span></td></tr>");
		html.push("<tr><td valign=top><span class=InfoGrey>Un e-mail de vérification vous sera</span><br><span class=InfoGrey>envoyé</span></td></tr>");
		
	html.push("</table>");
	
	var div = document.getElementById("AccountCreationDiv");
	div.style.border = "";
	div.style.padding = 18;
	div.style.background = "url('img/Fond_AccountCreation.png') no-repeat";
	div.onclick = function(event) { CancelBubble(event)};
	div.innerHTML = html.join("");
}

function OnAccountCreation2Opened()
{
	var html = new Array();
	html.push("<table width=100% cellpadding=0 cellspacing=0><tr><td colspan=2 class=Title1 valign=top height=30px>Vos coordonn&eacute;es</td></tr>");
		html.push("<tr><td class=Title2 valign=bottom height=20px colspan=2>Nom</td></tr>");
		html.push("<tr><td colspan=2><input type=text class=TxtIdent style=\"width:180px\"><span class=RedArrow>&nbsp;*</span></td></tr>");
		html.push("<tr><td class=Title2 valign=bottom height=20px colspan=2>Pr&eacute;nom</td></tr>");
		html.push("<tr><td colspan=2><input type=text class=TxtIdent style=\"width:180px\"><span class=RedArrow>&nbsp;*</span></td></tr>");
		html.push("<tr><td class=Title2 valign=bottom height=20px colspan=2>Adresse</td></tr>");
		html.push("<tr><td colspan=2><input type=text class=TxtIdent style=\"width:180px\"></td></tr>");
		html.push("<tr><td colspan=2><input type=text class=TxtIdent style=\"width:180px\"></td></tr>");
		html.push("<tr><td class=Title2 valign=bottom height=20px>Code postal</td><td class=Title2 valign=bottom height=20px>Ville</td></tr>");
		html.push("<tr><td><input type=text class=TxtIdent style=\"width:57px\"></td><td><input type=text class=TxtIdent style=\"width:120px\"></td></tr>");
		html.push("<tr><td class=Title2 valign=bottom height=20px colspan=2>Pays</td></tr>");
		html.push("<tr><td class=Title2 valign=bottom height=23px colspan=2><select class=TxtIdent style=\"width:180px\"><option value=France>France</option></select></td></tr>");
		
	html.push("</table>");
	
	var div = document.getElementById("AccountCreationDiv2");
	div.style.border = "";
	div.style.padding = 18;
	div.style.background = "url('img/Fond_AccountCreation2.png') no-repeat";
	div.onclick = function(event) { CancelBubble(event)};
	div.innerHTML = html.join("");
}

function OnAccountCreation3Opened()
{
	var html = new Array();
		html.push("<table width=100% cellpadding=0 cellspacing=0 border=0 style=\"table-layout:fixed;width:480px\">");
		html.push("<colgroup><col style=\"width:20px\" /> <col style=\"width:90px\" /> <col style=\"width:110px\" /> <col style=\"width:55px\"/> <col />");
				  html.push("<tr><td colspan=5 class=Title1 valign=top height=30px>Condition d'utilisation et rËglement</td></tr>");
		html.push("<tr><td class=Title2 valign=bottom height=20px colspan=5>Conditions d'utilisations</td></tr>");
		html.push("<tr><td colspan=5><textarea class=TxtIdent style=\"width:460px;height:50px\">Conditions G&eacute;n&eacute;rales d'utilisation\nLes pr&eacute;sentes Conditions G&eacute;n&eacute;rales d'utilisation (ci-apr&egrave;s les \"Conditions G&eacute;n&eacute;rales\") d&eacute;crivent les conditions selon lesquelles la soci&eacute;t&eacute; Ethnoludie propose l'acc&egrave;s ‡ ses services.\n\n...</textarea></td></tr>");
		html.push("<tr><td class=Title2 valign=bottom height=20px colspan=5>R&egrave;glement sur le respect de la vie priv&eacute;e</td></tr>");
		html.push("<tr><td colspan=5><textarea class=TxtIdent style=\"width:460px;height:50px\" cols=5>Nous attachons une grande importance au respect de la vie privÈe de nos utilisateurs. Dans le cadre du dÈroulement normal de nos activitÈs, nous recueillons, traitons et hÈbergeons les informations vous concernant aux Etats-Unis, et dans certains cas, pouvons Ítre amenÈs ‡ divulguer des informations vous concernant.\n...</textarea></td></tr>");
		html.push("<tr><td class=Title2 valign=bottom height=20px colspan=5>Donnez votre accord en cochant la case :</td></tr>");
		html.push("<tr><td class=Title2 valign=bottom height=20px><input type=\"Checkbox\" ></td><td colspan=4 class=Title2>J'accepte les conditions ci-dessous:</td></tr>");
		html.push("<tr><td class=Title2 valign=bottom height=20px>&nbsp;</td><td colspan=4 class=Title2>J'accepte les conditions d'utilisations et le r&egrave;glement sur le respect de la vie priv&eacute;e ci-dessus</td></tr>");
		html.push("<tr><td class=Title2 valign=bottom height=20px colspan=5>Date de naissance</td></tr>");
		html.push("<tr><td class=Title2 valign=bottom height=23px colspan=2><select class=TxtIdent style=\"width:100px\">");
			for (var i = 1; i <= 31; i++)
			{
				html.push("<option value=" + i + ">" + i + "</option>");
			}
			
		html.push("</select></td><td class=Title2 valign=bottom height=23px><select class=TxtIdent style=\"width:100px\">");
			for (var i = 1; i <= 12; i++)
			{
				html.push("<option value=" + i + ">" + i + "</option>");
			}
		html.push("</select></td><td class=Title2 align=right>Ann&eacute;e</td>");
		html.push("<td ><input type=text class=TxtIdent style=\"width:50px\"></td></tr>");
		html.push("<tr><td valign=top colspan=5><span class=InfoGrey>Seules personnes majeurs sont autoris&eacute;es &agrave; parier sur les parties</td></tr>");
		html.push("<tr><td valign=bottom colspan=5 align=center height=30px><button onclick=\"AccountValidate()\">valider</button><button onclick=\"AccountCancel()\">Annuler</button></td></tr>");
	html.push("</table>");
		
		
	
	var div = document.getElementById("AccountCreationDiv3");
	div.style.border = "";
	div.style.padding = 18;
	div.style.background = "url('img/Fond_AccountCreation3.png') no-repeat";
	div.onclick = function(event) { CancelBubble(event)};
	div.innerHTML = html.join("");
}

function AccountValidate()
{
	var allIsOk = true;
	var emailOk = true;
	
	//Verify all field
	var div = document.getElementById("AccountCreationDiv");
	var table = div.firstChild;
	
	var pseudo = table.rows[2].firstChild.firstChild;
	var passwd = table.rows[4].firstChild.firstChild;
	var passwd2 = table.rows[7].firstChild.firstChild;
	var email = table.rows[10].firstChild.firstChild;
	
	var div = document.getElementById("AccountCreationDiv2");
	var table = div.firstChild;
	
	var name = table.rows[2].firstChild.firstChild;
	var prenom = table.rows[4].firstChild.firstChild;
	var adress1 = table.rows[6].firstChild.firstChild;
	var adress2 = table.rows[7].firstChild.firstChild;
	var cp = table.rows[9].firstChild.firstChild;
	var town = table.rows[9].childNodes[1].firstChild;
	var country = table.rows[11].firstChild.firstChild;
	
	var div = document.getElementById("AccountCreationDiv3");
	var table = div.firstChild;
	
	var accept = table.rows[6].firstChild.firstChild;
	var birthDay = table.rows[9].firstChild.firstChild;
	var monthDay = table.rows[9].childNodes[1].firstChild;
	var yearDay = table.rows[9].childNodes[3].firstChild;
	
	if (pseudo.value == "")
	{
		pseudo.style.backgroundColor = "red";
		allIsOk = false;
	}
	if (passwd.value.length < 6)
	{
		passwd.style.backgroundColor = "red";
		allIsOk = false;
	}
	if (passwd.value != passwd2.value)
	{
		passwd.style.backgroundColor = "red";
		passwd2.style.backgroundColor = "red";
		passwd2.value = "";
		allIsOk = false;
	}
	
	var mail_pattern = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (email.value == "")
	{
		email.style.backgroundColor = "red";
		allIsOk = false;
	}
	else if (!email.value.match(mail_pattern))
	{
		email.style.backgroundColor = "red";
		emailOk = false;
	}
	if (name.value == "")
	{
		name.style.backgroundColor = "red";
		allIsOk = false;
	}
	if (prenom.value == "")
	{
		prenom.style.backgroundColor = "red";
		allIsOk = false;
	}
	
	var birthDate = "";
	if ((yearDay.value != "") && ((isNaN(Number(yearDay.value))) || (yearDay.value.length != 4))  )
	{
		yearDay.style.backgroundColor = "red";
		allIsOk = false;
	}
	else
	{
		if (yearDay.value != "")
		birthDate = yearDay.value + "-" + VerifDigits(monthDay.value, 2) + "-" + VerifDigits(birthDay.value, 2);
	}
						  
	
	if (!emailOk)
	{
		alert("Le format de l'email entré est incorrect");
		return;
	}
	if (!allIsOk)
	{
		alert("Veuillez corriger les erreurs et remplir les champs obligatoires manquants");
		return;
	}
	if (!accept.checked)
	{
		alert("Merci de lire les conditions d'utilisations !");
		return;
	}
	
	var params = new Array();
    params.push(new WSParams("login", pseudo.value));
	params.push(new WSParams("passwd", passwd.value));
	params.push(new WSParams("email", email.value));
	params.push(new WSParams("name", name.value));
	params.push(new WSParams("prenom", prenom.value));
	params.push(new WSParams("adr1", adress1.value));
	params.push(new WSParams("adr2", adress2.value));
	params.push(new WSParams("cp", cp.value));
	params.push(new WSParams("town", town.value));
	params.push(new WSParams("country", country.value));
	params.push(new WSParams("birthDate", birthDate));
	
	
    AjaxRequest("sawale_ws.php", OnAccountCreationResult, "CreateAccount", params, "robatmac/Awale");
}

function OnAccountCreationResult(res)
{
	res = parseInt(res, 10);
	if (res == 0)
	{
		alert("Vous allez recevoir un email dans quelques instands.\nClickez sur le lien dans le mail afin de confirmer votre inscription");
		
		AccountCancel();
	}
	else if (res == -1)
	{
		alert("Un autre utilisateur dispose déjà de ce nom d'utilisateur ou de cet email. Veuillez en choisir un autre");	
	}
	else
	{
		alert("Erreur... La création de compte est momentanément indisponible.\nVeuillez nous excuser pour la gène occasionnée");	
	}
}

function AccountCancel()
{
	if (document.getElementById("AccountCreationDiv"))
	{	
		document.getElementById("MAIN_INSCRIPTION_DIV").removeChild(document.getElementById("AccountCreationDiv"));
	}
	if (document.getElementById("AccountCreationDiv2"))
	{	
		document.getElementById("MAIN_INSCRIPTION_DIV").removeChild(document.getElementById("AccountCreationDiv2"));
	}
	if (document.getElementById("AccountCreationDiv3"))
	{	
		document.getElementById("MAIN_INSCRIPTION_DIV").removeChild(document.getElementById("AccountCreationDiv3"));
	}
	
	GoToDiv("MAIN_ACCEUIL_DIV");
}

function AnonymousConnect()
{	
	var pseudo = document.getElementById("TxtAnonymous").value;
	if (pseudo == "")
	{
		alert("Veuillez choisir un pseudonyme avant de vous connecter");
	}
	else
	{
		pseudo = pseudo.replace(/"/gi, "&quot;");
		getFlash().anonymousConnect(pseudo);	
	}
}

function AuthentConnect()
{
	var div = document.getElementById("IdentDiv");
	if (!div) return;
	
	var login = div.firstChild.rows[0].childNodes[1].firstChild.rows[2].childNodes[0].firstChild;
	var passwd = div.firstChild.rows[0].childNodes[1].firstChild.rows[4].childNodes[0].firstChild;
	
	var isOk = true;
	if (login.value == "")
	{
		login.style.backgroundColor = "red";
		isOk = false;
	}
	if (passwd.value == "")
	{
		passwd.style.backgroundColor = "red";
		isOk = false;
	}
	
	if (!isOk)
	{
		alert("Veuillez renseigner les champs obligatoires");
		return;
	}
	
	try
	{
		getFlash().login(login.value.replace(/"/gi, "&quot;"), passwd.value.replace(/"/gi, "&quot;"));
	}
	catch(e)
	{
		alert("error : " + e.message);
	}
}

function ConnectionFailed(serverAdress, serverPort)
{
	//Close all popups
	for (var i = 0; i < listeningGames.length; i++)
	{	
		try {
			listeningGames[i].popup.close();
		}
		catch(e) { }
	}
	
	alert(traductions["ErrorCx1"].trads[culture] + ".\n" + serverAdress + ":" + serverPort + "\n" + traductions["ErrorCx2"].trads[culture] + ".");
	
	if (document.getElementById("IdentDiv"))
	{
		document.body.removeChild(document.getElementById("IdentDiv"));
		delete openedDivs["IdentDiv"];
	}
	
}

function IdentResult(res, userName, isGuest, token)
{	
	if (((res == true) || (res == "true")) && (userName != "") && (userName != "null"))
	{
		user = new Ident();
		user.userName = userName;
		user.anonymous = ((isGuest == true) || (isGuest == "true")) ? true : false;
		user.token = token;
		
		var td = document.getElementById("AccueilTxtConnection");
		if (td)
		{
			td.innerHTML = "<b id=\"TxtUserName\">" + user.userName + "</b>&nbsp;<img src=\"img/bt_close.png\" border=0 style=\"margin-top:3px\" onclick=\"Disconnect(event)\">";
			td.onclick = null;
		}
		
		if (document.getElementById("IdentDiv"))
		{
			document.body.removeChild(document.getElementById("IdentDiv"));
			delete openedDivs["IdentDiv"];
		}
		
		//Notify all games popup opened of connection
		for (var i = 0; i < listeningGames.length; i++)
		{
			try {
				listeningGames[i].popup.AfterUserLog();
			}
			catch(e) { }
		}
		
		//Load user tournaments
		var params = new Array();
 	   	params.push(new WSParams("login", userName));
    	AjaxRequest("sawale_ws.php", OnLoadUserTournaments, "GetRegisteredTournaments", params, "robatmac/Awale");
	}
	else if ((userName == "") || (userName == "null"))
	{
		if ((!isGuest) || (isGuest == "false")) AlertError(traductions["ErrorCx3"].trads[culture]);
		else AlertError(traductions["ErrorCx4"].trads[culture], true);
		getFlash().logoff();
	}
	else
	{
		AlertError(traductions["ErrorCx5"].trads[culture], true);
		getFlash().logoff();
	}
}

function Disconnect(e)
{
	var evt = (e) ? e : window.event;
	if (evt) CancelBubble(evt);
	
	if (user != null)
	{		
		for (var i = 0; i < listeningGames.length; i++)
		{	
			try {
				listeningGames[i].popup.close();
			}
			catch(e) { }
		}
	
		CloseUserAccountPopup();
	
		getFlash().logoff();
		user = null;
	}
	
	LoadNextTournament();
	
	var td = document.getElementById("AccueilTxtConnection");
	if (td != null) 
	{
		td.innerHTML = "Se connecter";
		td.onclick = OpenIdentDiv;
	}
}

function OnDisconnect()
{
	if (user != null)
	{		
		var isPopup = false;
		for (var i = 0; i < listeningGames.length; i++)
		{	
			isPopup = true;
			try {
				listeningGames[i].popup.close();
			}
			catch(e) { }
		}
	
		CloseUserAccountPopup();
		user = null;
		
		if (isPopup)
		{
			AlertError(traductions["ErrorDisconnect"].trads[culture], true);
		}
	}
}