// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

var last_call = new Date().setFullYear(2020).valueOf();
var delay = 1000;

function typing_check() {

	crt_time = new Date().valueOf();
	if ((crt_time - last_call > delay) && !stop_polling) {
		notify_typing('stop_type');
	}
	
};

function notify_typing(type_update) {

	crt_time = new Date().valueOf();
	if (crt_time - last_call < delay) {
		// don't notify unless some specified time has passed since the last notification
		return;
	}

	last_call = crt_time;

	$.ajax({type: "GET", url: "/talk/" + type_update, async: true})

};

function scrollConversation() {

	if (document.getElementById("conversation").innerHTML != "") {
		document.getElementById("transcript").style.display = "block";
		if (!stop_polling) {
			document.getElementById("notification").innerHTML = "";
		}
	}
	
	var convDiv = document.getElementById("content"); 
	convDiv.scrollTop = convDiv.scrollHeight;
	
};

function absTop(elementId){	
    var obj = document.getElementById(elementId);
	var offset = 0;
	while(obj.offsetParent) {
		offset += obj.offsetTop;
		obj = obj.offsetParent;
	}
	return(offset);
}

var ignore_clear_session  = false;

function clearSession() {
	clearInterval(check);
	stop_polling = true;
	if (!ignore_clear_session) {
		$.ajax({type: "GET", url: "/main/logout", async: true});
	}
}

function logout() {

	clearInterval(check);
	stop_polling = true;
	document.getElementById("conversation").innerHTML = "";
	document.getElementById("login").style.display = "block";
	$("#login").html("<a href=\"/main/login\" class=\"start\" onclick=\"ignore_clear_session=true;\">Porneste o conversatie</a>");

}

function updateChat(request) {
	
	if (request.status == 200) {

        var data = request.responseXML;
		var isTyping = false;
		users = $(data).find("users").text();
		//update user count div
		$("#useri-online").html("<span class='useri'>" + users + "</span> useri online");

		//update notifications and/or typing div
		$(data).find("notification").each(function() {		
			
		    var html_code = $(this).text();
			
			if (html_code.indexOf("tasteaza") != -1) {
				$("#typing").html(html_code);
				isTyping = true;
			} else {
				$("#notification").html(html_code);
			}
			
			if (html_code.indexOf("deconectat") != -1) {
				// partner disconnected
				stop_polling = true;
				document.getElementById("action").innerHTML = 
        			"<a href=\"/main/login\"><img border=\"0\" src=\"/images/reconectare.gif\" /></a>";
			}			
		});
		
		if (!isTyping) {
			$("#typing").html("");
		}
		
		//append new messages to message div
		$(data).find("message").each(function() {
		    message = $(this).text();
			$("#conversation").append(message);
			scrollConversation();
		});

		if (stop_polling) {
			//insert login button centered
			logout();
		}

		
    }
	
}
