var tchat_sUserName 		= "";			//ID[String] 	Utilisateur de la session
var tchat_nCurId  			= 0;			//ID[Integer] 	Utilisateur en cours de tchat
var tchat_sAdded    		= "";			//STR[String] 	Indique que cette utilisateur a été ajouté à la liste des utilisateurs
var tchat_sCurUser  		= "";			//ID[String] 	Utilisateur en cours de tchat
var tchat_nVisTem   		= 0;			//IND[Integer] 	Indique la visibilité du Témoin Nouveau message
var tchat_bIsOutChat		= 0;			//IND[Integer] 	Indique si le messenger et ouvert (=1) ou pas (=0)
var tchat_tUsers    		= new Array();	//TAB[Array]	Tableau local contenant les utilisateurs
var tchat_nDateServ 		= 0;			//Num[Integer]	Date du serveur
var tchat_sDefaultTitle 	= document.title;//STR[String] 	Titre par défaut
var tchat_nTimerNewMsg	= null;

//URL Img
var baseurl = "img/tchat/";

function tchat_startChat(user){
	tchat_sUserName = user;
	tchat_getMessages();//init
	var timer = setInterval("tchat_getMessages()", 1500);
/*	$.get(PATH_AJAX+'jserver_xml_tchat.php?action=get&user='+tchat_sUserName,
			function(jsonObj) {
				alert(jQuery.parseJSON('{"messages": [{"user":"Riders974", "message":"", "me":"0", "lu":"0"}]}')+" -"+jQuery.parseJSON(jsonObj)+"- "+'{"messages":[]}');
			});*/
}

function tchat_getMessages() {
			//	alert(PATH_AJAX+'jserver_xml_tchat.php?action=get&user='+tchat_sUserName);
	$.getJSON(PATH_AJAX+'jserver_xml_tchat.php?action=get&user='+tchat_sUserName,
			function(jsonObj) {
				//alert(jsonObj.messages);
				tchat_nDateServ = parseInt(jsonObj.curdate);
				tchat_handleResponse(jsonObj.messages);
			});
}

function tchat_handleResponse(messages){
	var news   = new Array();
	tchat_tUsers = [];
	
	for(i=0;i<messages.length;i++){
		var matches  = 0;
		var matchesb = 0;
		if(messages[i].lu!=0){
			for(j=0;j<news.length;j++){
				if(news[j]==messages[i].user) matches++;
			}
			if(matches==0) news.push(messages[i].user);
		}
		
		for(l=0;l<tchat_tUsers.length;l++){
			if(tchat_tUsers[l]==messages[i].user) matchesb++;
		}
		if(matchesb==0) tchat_tUsers.push(messages[i].user);
	}
	
	//alert(messages,tchat_tUsers.length);
	tchat_showUsers(tchat_tUsers,messages,news);

	tchat_showMessages(tchat_tUsers[tchat_nCurId],messages);
}

function tchat_showUsers(tchat_tUsers,messages,news){
	
	//affiche les utilisateurs
	var userz = $('#userzTchat');
	if(document.getElementById('userzTchat')) document.getElementById('userzTchat').innerHTML = '';		
	
	var nbuz = tchat_tUsers.length;
	if(nbuz==0)return;
	tchat_sCurUser = nbuz - 1;
	
	var userz_ul = document.createElement('ul');
	
	for (var j=0; j < tchat_tUsers.length; j++) {		//affiche les utilisateur
	
		var new_li       = document.createElement('li');
		new_li.id        = "liTchat"+j; 
		var da_span      = document.createElement('span');
		var img          = document.createElement('img');
		img.src          = baseurl + "close_usr.png";
		img.className    = "imgclose";
		img.width		 = '14';
		img.heigth		 = '14';
		img.style.cursor = 'pointer';
		
		da_span.innerHTML = tchat_tUsers[j]+"&nbsp;&nbsp;&nbsp;";
		da_span.style.cursor = 'pointer';
		var da_span_content = da_span.innerHTML;
		
		if(da_span_content == da_span.innerHTML && tchat_sAdded!=""){
			tchat_nCurId = tchat_tUsers.length-1;
			tchat_sAdded   ="";
		}
			
		da_span.id       = j;
		img.id           = j;	
		
		//Flash + Alert des nouveaux messages
		for(var k = 0; k<news.length; k++){
			if(news[k] == tchat_tUsers[j] && news[k] != tchat_tUsers[tchat_nCurId])  {
				da_span.className = "flash";
				new_li.className = "flash";
			}
			if(news[k]!=""){
				if(tchat_bIsOutChat==0){
					$('#temoinTchat').css('bottom','0');
					$('#temoinTchat').css('visibility','visible');
					if(temoinchat = document.getElementById("temoinTchat")){
						temoinchat.innerHTML = "<em>Nouveau"+(news.length>1?"x":"")+" message"+(news.length>1?"s":"")+":</em> ";
						for(i=0;i<news.length;i++){
							if(i>1)temoinchat.innerHTML += ", ";
							temoinchat.innerHTML += news[i];
						}
						if(tchat_nVisTem==0){
							$('#temoinTchat').css('bottom','-60px');
							$('#temoinTchat').animate({"bottom":"+=60px"},"slow");
							tchat_nVisTem++;
						}
					}
				}
				if(tchat_nTimerNewMsg==null) tchat_nTimerNewMsg = setInterval("tchat_flashDoc()",1000);
			}
		}
			
		da_span.onclick	 = function() {//evt clic sur la span
			this.className	           = "focus";	
			tchat_nCurId        	   = this.id;	
			tchat_sCurUser             = this.innerHTML;
			document.getElementById("liTchat"+this.id).className = "focus";
			document.getElementById("temoinTchat").className = "temz";
			
			tchat_showMessages(this.innerHTML,messages);
			tchat_setRead(this.innerHTML);
		}
		img.onclick     = function() {	//evt clic sur l'image: on supprime l'utilisateur
			if(tchat_nCurId == this.id){
				if(this.id!=0){
					tchat_nCurId = this.id-1;
				}else{
					tchat_nCurId = 0;
				}
			}
			if(tchat_nCurId>this.id){
				tchat_nCurId--;
			}
			tchat_removeUser(tchat_tUsers[this.id], this.id, nbuz);
		} 
		
		if(j==tchat_nCurId) {//gestion d focus
			da_span.className = "focus";
			new_li.className = "focus";
		} else {
			//if(da_span.className!="flash" )da_span.className = "basic";
		}
		userz_ul.appendChild(new_li);
		new_li.appendChild(da_span);
		if(tchat_tUsers.length>1){//si il y a + d1 util on ajoute une image style boutton supprimer
			new_li.appendChild(img);
		}
	}
	for(i=0;i<news.length;i++){
		if(news[i]==tchat_tUsers[tchat_nCurId] && tchat_bIsOutChat==1) tchat_setRead(tchat_tUsers[tchat_nCurId]);//alert("news "+news[i]+ " tchat_tUsers " +tchat_tUsers[tchat_nCurId])
	}
	
	userz.append(userz_ul);
	
}

function tchat_selectUser(user){
	for(var k=1;k<tchat_tUsers.length;k++){
		if(tchat_tUsers[k]==user){
			document.getElementById(k).className = "focus";
			document.getElementById("liTchat"+k).className = "focus";
			document.getElementById("temoinTchat").className = "temz";
			tchat_nCurId = k;
			tchat_sCurUser = user;
			
			tchat_getMessages();
			tchat_setRead(user);
			
			return;
		}
	}
}

function tchat_showMessages(user,messages){//affiche les messages suivant l'utilisateur
	var mychat = document.getElementById('mychatTchat');
	if(mychat){
		var str = "<ul>";	
		var dateOffset = parseInt(((new Date()).getTime())/1000)-tchat_nDateServ;		//Offset du serveur et client en seconde
	//	alert(parseInt(((new Date()).getTime())/1000)+" -"+tchat_nDateServ+"- "+dateOffset);
		for (var i=0; i < messages.length; i++) {
			var mymess    = messages[i].message;	
			var myuser    = messages[i].user;
			var me        = messages[i].me;
			var adddate	  = parseInt(messages[i].adddate);
			if(myuser == user){
			  if(mymess!=""){
			   if(mymess!=undefined){
					if(me==1){
					str += "<li><b> moi </b><i>"+tchat_dateToString(new Date((adddate+dateOffset)*1000))+"</i>: " + mymess +"</li>";
					}else{
					str += "<li class='usr'><b class='usr'>"+ user + " </b><i class='usr'>"+tchat_dateToString(new Date((adddate+dateOffset)*1000))+"</i>: " + mymess +"</li>";
					}
				}
			  }
			}
		}
		str += "</ul>";
		mychat.innerHTML=str;
		mychat.scrollTop = mychat.scrollHeight;
	}
}

function tchat_dateToString(dateObj){
	var dateAbs = Math.abs(dateObj.getTime()-(new Date()).getTime());
	if(dateAbs<86400000) return dateObj.getHours()+":"+dateObj.getMinutes();
	else if(dateAbs<172800000) return "Hier "+dateObj.getHours()+":"+dateObj.getMinutes();
	else {
		var day, month;
		switch(dateObj.getDay()){
			case 0: day = "Dim "; break;
			case 1: day = "Lun "; break;
			case 2: day = "Mar "; break;
			case 3: day = "Mer "; break;
			case 4: day = "Jeu "; break;
			case 5: day = "Ven "; break;
			case 6: day = "Sam "; break;
		}
		switch(dateObj.getMonth()){
			case 0: month = " Jan"; break;
			case 1: month = " Fev"; break;
			case 2: month = " Mar"; break;
			case 3: month = " Avr"; break;
			case 4: month = " Mai"; break;
			case 5: month = " Jun"; break;
			case 6: month = " Jul"; break;
			case 7: month = " Aou"; break;
			case 8: month = " Sep"; break;
			case 9: month = " Oct"; break;
			case 10: month = " Nov"; break;
			case 11: month = " Dec"; break;
		}
		
		return 	day+dateObj.getDate()+month+","+dateObj.getHours()+":"+dateObj.getMinutes()
	}
}

function tchat_flashDoc(){
	if(document.title==tchat_sDefaultTitle) document.title = "Nouveau(x) message(s) - "+tchat_sDefaultTitle;
		else document.title = tchat_sDefaultTitle;
}


function tchat_sendMessage(){	
	var dest = tchat_tUsers[tchat_nCurId];
	if(dest==undefined) return;
	
	var message = document.getElementById('messageTchat').value;
	if (message == '') {
		alert('Essaye d ecrire un message...');
		return false;
	}
	
	// envoie le message
	$.getJSON(PATH_AJAX+'jserver_xml_tchat.php?action=add&user='+ tchat_sUserName + '&dest=' + dest + '&message=' + message,
			function(jsonObj) {
				tchat_nDateServ = parseInt(jsonObj.curdate);
				tchat_handleResponse(jsonObj.messages);
			});
	
	document.getElementById('messageTchat').value = '';
	document.getElementById('messageTchat').focus();
}


function tchat_setRead(myuser) {
	$.getJSON(PATH_AJAX+'jserver_xml_tchat.php?action=set_read&user='+ tchat_sUserName +'&cible='+ myuser,
			function(jsonObj) {
				tchat_nDateServ = parseInt(jsonObj.curdate);
				tchat_handleResponse(jsonObj.messages);
			});
}

function tchat_addUser(client, openChat) {
	
	tchat_sCurUser = client;
	
	if(client==tchat_sUserName){
		alert("tu veux chatter tout seul?");
		return;
	}
	
	var matches = 0;
	if(tchat_bIsOutChat==0){
		for(var i=0;i<tchat_tUsers.length;i++){
			if(tchat_tUsers[i]==client){
				tchat_openChat();
				tchat_selectUser(client);
	  			return;
			}
		}
	}
	//alert(tchat_tUsers.length);
	
	tchat_sAdded = client;
//	tchat_tUsers.push(client);
	
	$.getJSON(PATH_AJAX+'jserver_xml_tchat.php?action=add_user&user='+ tchat_sUserName +'&client='+ client,
			function(jsonObj) {
				tchat_nDateServ = parseInt(jsonObj.curdate);
				tchat_handleResponse(jsonObj.messages);
			});
	
	if(openChat==true) tchat_openChat();
}

function tchat_removeUser(myuser, id, nb){
	if(tchat_nCurId==id){
		if(tchat_nCurId>0){
		tchat_nCurId -=1;
		}else{
		tchat_nCurId=0;
		}
	} 
	if(nb==2)tchat_nCurId=0;
	$.getJSON(PATH_AJAX+'jserver_xml_tchat.php?action=rmv_user&user='+ tchat_sUserName +'&cible='+ myuser,
			function(jsonObj) {
				tchat_nDateServ = parseInt(jsonObj.curdate);
				tchat_handleResponse(jsonObj.messages);
			});
}

function tchat_addValue(value){
	document.getElementById('messageTchat').value += value;
	document.getElementById('messageTchat').focus();
}



function tchat_standByChat(){		//fin de session
	$('message').blur();
	var userz       = document.getElementById('userzTchat');
	var mychat      = document.getElementById('mychatTchat');
	var container   = $('#containerTchat');
	tchat_nCurId    = -1;
	container.fadeOut();
	userz.innerHTML = mychat.innerHTML = '';
	tchat_bIsOutChat = 0;
	tchat_nVisTem    = 0;
}

function tchat_closeChat(){		//fin de session : on vide la table messages + cache la fenetre!
	tchat_removeUser("all",0);
	tchat_standByChat();
}

function tchat_openChat(){
	tchat_nCurId = 0;
	var container = $("#containerTchat");
	container.fadeIn();							//[jQuery]
	container.draggable();						//[jQuery]
	$('#temoinTchat').css('visibility','hidden');
	tchat_bIsOutChat = 1;
}

//controlleurs <a> rel chat et enter
$(document).ready(function(){
			   
	createChat();
	$('#containerTchat').css('display','none');		//cache le container
	$('#temoinTchat').css('visibility','hidden');	//cache le temoin
	$('#messageTchat').keypress(function(e){
		if(e.which == '13'){
			tchat_sendMessage();
		}
	});	
	$('a').click(function(el){
		if(this.getAttribute('rel') == "chat"){
			tchat_addUser(this.getAttribute('name'),true);	
		};
	});
	
	$('#containerTchat').mouseover(function(el){
		$('#messageTchat').focus();
		if(tchat_nTimerNewMsg!=null) { clearInterval(tchat_nTimerNewMsg); tchat_nTimerNewMsg=null; document.title = tchat_sDefaultTitle; }
	});
	$(document).unload(function(){
		tchat_standByChat();
	})
});
