var windowFocus = true;
var windowTitle;

$(document).ready(function(){
	
	windowTitle = document.title;
	
	$([window, document]).blur(function(){
		windowFocus = false;
	}).focus(function(){
		windowFocus = true;
		document.title = windowTitle;
	});
	
	$("#open_chat").click(function(){
		$("#chat_room").fadeIn("slow");
	});
	
	$("#minimize").click(function(){
		$("#chat_room").fadeOut("slow");
		
		if( $("#chat_window").css("display", "none") )
		{
			
		}
		else
		{
			$("#chat_window").fadeOut("slow");
		}
	});
	
	$(".contact").click(function(){
		load_wmsg($("#me").val(), this.id);
		$("#to").val(this.id);
	});
	
	$("input#message").keypress(function(event){
		if( event.keyCode == 13 )
		{
			send_message($("#me").val(), $("#to").val(), $("#message").val());
			$("#message").val("");
		}
	});
	
});

function update_msgs(me, to)
{
	if( windowFocus == false )
	{
		document.title = 'ups';
	}
	
	var path_to_apps = "";
	
	if( jQuery.url.segment(1) == null )
	{
		var path_to_apps = "apps/chatApp_reader.php";
	}
	else if( jQuery.url.segment(2) == null )
	{
		var path_to_apps = "../../apps/chatApp_reader.php";
	}
	else if( jQuery.url.segment(3) == null )
	{
		var path_to_apps = "../../apps/chatApp_reader.php";
	}
	else {
		var path_to_apps = "apps/chatApp_reader.php";
	}
	
	$.ajax({
		type: "POST",
		url: path_to_apps,
		cache: false,
		data: "me=" + me + "&to=" + to,
		success: function(msg){
			$("#chat_content").html(msg);
		}
	});
	
	setTimeout('update_msgs($("#me").val(), $("#to").val());', 1000);
}

function load_wmsg(me, to){
	$("#chat_window").fadeIn("slow");
	$("#message").focus();
	
	update_msgs(me, to);
	
	//setTimeout('update_msgs($("#me").val(), $("#to").val());', 1000);
}

function send_message(me, to, message){
	
	var path_to_apps = "";
	
	if( jQuery.url.segment(1) == null )
	{
		var path_to_apps = "apps/chatApp_writter.php";
	}
	else if( jQuery.url.segment(2) == null )
	{
		var path_to_apps = "../../apps/chatApp_writter.php";
	}
	else if( jQuery.url.segment(3) == null )
	{
		var path_to_apps = "../../apps/chatApp_writter.php";
	}
	else {
		var path_to_apps = "apps/chatApp_writter.php";
	}
	
	$.ajax({		
		type: "POST",
		url: path_to_apps,
		data: "me=" + me + "&to=" + to + "&message=" + message,
		success: function(msg){
			load_wmsg(me, to);
		}
	});	
}