/* Nikkto Talk 
** Author: Thomas Steinmetz
**
** License: MIT (http://www.opensource.org/licenses/mit-license.php) & GPL (http://www.gnu.org/copyleft/gpl.html)
**
** The purpose of Nikkto Talk is to create a _very_ easy to use chat that can easily
** plug into just about any existing website running PHP/MySQL. It features a real-time 
** buddy list and chat. 
**
** nikkto.tlk.js
**
** This file is responsible for driving what the user sees. It calls out to nikkto.tlk.php 
** for the buddy list, to send and recieve messages, and to log on to the chat.
**
*/

var count = 1;
var counter = 1; 
var chats = new Array(); // chats['username'] = <chat number>;
var username = '';
var maxChats = 10; //The max number of open chats is maxChats. Any more and my system lags

$(document).ready(function()
{
	// Prompt the user for a username
	getUserName();

	// Check for incoming messages
	var checkMessages = setInterval(function()
	{
		if(username != '')
		{
	  	var postData = 
	  	{
	      action: "chk_msg",
	      l_username: username
	    };
	
		  $.post('xhr/nikkto.tlk.php',postData,function(xml){ 
		  	
		  	$('message',xml).each(function(i)
		  	{
		  		var from = $(this).find('from').text();
		  		var msg	 = $(this).find('msgText').text();
		  		
		  		// First we check to see if the window is already open, if it just append to that
		  		if(chats[from])
		  		{
		  			$("#" + chats[from] + "_text").append("<br />" + from + " said: " + msg);
				    $("#" + chats[from] + "_text").attr({ scrollTop: $("#" + chats[from]+ "_text").attr("scrollHeight") });
		  		}
		  		// Otherwise we make a new one
		  		else
		  		{
		  			makeChat(from, msg);
		  		}
		  	});
		  });	
		}
  }, 1000); 
  
  // Load the buddy list
  var getBuddyList = setInterval(function()
  {
  	
  	if(username != '')
  	{
  		// Get all the people currently logged on and update the buddy_list div
  		var postData =
  		{
  			action: "buddy_list",
  			l_username: username
  		};
			 $.post('xhr/nikkto.tlk.php',postData,function(xml){ 
	      var status = $(xml).find('response').find('status').text();
	      
	      if (status == 'Success')
	      {
	      	var buddies = '';
					$('buddy',xml).each(function()
					{
						buddies += "<div class='buddy' id='msg_" + $(this).find('username').text() + "' onclick=\"newChat('" + $(this).find('username').text() + "')\">" + $(this).find('username').text() + "</div>";
					}
					);
					
					$("#buddy_list").html(buddies);
	      }
	      else
	      {
	        alert("message ERROR");
	      }
	    });

  		$("#buddy_list").dialog("open");
  	}
  }, 1000);
  
	$("#buddy_list").dialog(
  {
  	autoOpen: false,
  	modal: false,
  	title: "Buddy List",
  	width: 200,
  	height: 300,
  	position: ['left', 'bottom'],
  	beforeclose: function(event, ui) {  return false; }  
  });

});


makeChat = function(from, msg)
{
	var r_username = from;
	// Get the username and add to array of active chats
	chats[r_username] = "tlk_" + from;

	// Append the new chat box to the body of the page
	$("#body").append("<div id='tlk_" + from + "' style='display:none'><div style='width:100%; height:65%; border: solid 2px #c2c2c2;'><div style='width:100%; height:100%; overflow-y: scroll; scrollbar-arrow-color:blue; scrollbar-face-color: #e7e7e7; scrollbar-3dlight-color: #a0a0a0; scrollbar-darkshadow-color:#888888'id='tlk_" + from + "_text'></div></div><div style='width:100%; height:30%; margin-top: 3px;'><textarea id='tlk_" + from +"_msg' style='width:100%; height:100%;'></textarea></div></div>");
	
	// Listen for 'enter' ('return') key pressed
	$('#tlk_' + from + '_msg').keyup(function(e) {
		if(e.keyCode == 13) {
			sendMessage('tlk_' + from, r_username);
		}
	});
	
	// Add a dialog box for the chat box
	$("#tlk_" + from).dialog(
	{
    autoOpen: false,
    modal: false,
    title: "Chat with " + from,
    width: 350,
    height: 255,
    buttons: {
      "Send": function()
      {
				sendMessage(this.id, r_username);
      },
      "Close": function()
      {
      	// Close the chat
        $(this).dialog("close");
        // Find the username in the array with the current ID and delete it
				var delIndex = chats.indexOf(this.id);
        delete(chats[delIndex]);
        counter--; // Decrement counter of open chats
      }
    },
    beforeclose: function(event, ui) {
        // Close the chat
        $(this).dialog("close");
        // Find the username in the array with the current ID and delete it
				var delIndex = chats.indexOf(this.id);
        delete(chats[delIndex]);
        counter--; // Decrement counter of open chats
    }
    });
    
		// Open the new chat box
		$("#tlk_" + from).dialog("open");
    addMinimize();
	  $("#" + chats[from] + "_text").append("<br />" + from + " said: " + msg);
}

getUserName = function()
{
	$("#tlk_username").dialog(
	{
    autoOpen: true,
    modal: true,
    title: "Choose username",
    width: 400,
    height: 50,
    overlay: {
      opacity: 0.5,
      background: "#000000"
    },
    buttons: {
      "Submit": function()
      {
      	// Only send if there is something in the box
      	
      	if($("#username").val() != "")
      	{
					var postData = 
	      	{
			      action: "log_on",
			      l_username: $("#username").val()
			    };
					
			    $.post('xhr/nikkto.tlk.php',postData,function(xml){ 
			      var status = $(xml).find('response').find('status').text();

			      if (status == 'Success')
			      {
			      	//alert($(xml).find('username').text());
							username = $(xml).find('username').text();
							$("#tlk_username").dialog("close");
			      }
			      else
			      {
			      	// We will want to tell the user why the error happened (username already in use?)
			        alert("login error: " + $(xml).find('logonError').text());
			      }
			    });
      	}
      	else
      		$("#username").focus();
      }
    },
    beforeclose: function(event, ui) { if(username == '') return false; }
   });
   
   $("#tlk_username").dialog("open");

}

newChat = function(buddy)
{
	// Check to see if the user has a chat open with this username already
	
	// Limit the amount to ten chats -- any beyond can make even fast machines very slow
	if(counter < maxChats)
	{
		var r_username = buddy;
		// Get the username and add to array of active chats
		chats[r_username] = "tlk_" + buddy;
	
		// Append the new chat box to the body of the page
		$("#body").append("<div id='tlk_" + buddy + "' style='display:none'><div style='width:100%; height:65%; border: solid 2px #c2c2c2;'><div style='width:100%; height:100%; overflow-y: scroll; scrollbar-arrow-color:blue; scrollbar-face-color: #e7e7e7; scrollbar-3dlight-color: #a0a0a0; scrollbar-darkshadow-color:#888888'id='tlk_" + buddy + "_text'></div></div><div style='width:100%; height:30%; margin-top: 3px;'><textarea id='tlk_" + buddy +"_msg' style='width:100%; height:100%;'></textarea></div></div>");
		
	  // Listen for 'enter' ('return') key pressed		
		$('#tlk_' + buddy + '_msg').keyup(function(e) {
			if(e.keyCode == 13) {
				sendMessage('tlk_' + buddy, r_username);
			}
		});
		
		// Add a dialog box for the chat box
		$("#tlk_" + buddy).dialog(
		{
	    autoOpen: false,
	    modal: false,
	    title: "Chat with " + buddy,
	    width: 350,
	    height: 255,
	    buttons: {
	      "Send": function()
	      {
	      	sendMessage(this.id, r_username);
	      },
	      "Close": function()
	      {
	      	// Close the chat
	        $(this).dialog("close");
	        // Find the username in the array with the current ID and delete it
					var delIndex = chats.indexOf(this.id);
	        delete(chats[delIndex]);
	        counter--; // Decrement counter of open chats
	      }
	    }
	  }		
	  );
		
		// Open the new chat box
		$("#tlk_" + buddy).dialog("open");
	  
	  
	  addMinimize();
		
		
		// Increase the count for the next chat box
		count++;
		counter++;
	}
	else
		alert("You currently have " + maxChats + " chats open, please close one before opening another");
}

// Take the id of the message box and the username of the recipient and send the message
sendMessage = function(id, r_username)
{
	// Only send if there is something in the box
	if($("#" + id + "_msg").val() != "")
	{
  	// In here we need to send the message and also append it to the msg_text_<count> div for the user to see
  	var postData = 
  	{
      action: "send_msg",
      msgSender: username,
      msgRecipient: r_username,
      msgTxt: $("#" + id + "_msg").val(),
      l_username: username
    };

    $.post('xhr/nikkto.tlk.php',postData,function(xml){ 
      var status = $(xml).find('response').find('status').text();
      //alert(status);
      if (status != 'Success')
      {
        alert("message ERROR");
      }
    });
    $("#" + id + "_text").append("<br />You said: " + $("#" + id + "_msg").val());
	
  	// Scroll to the last message
  	$("#" + id + "_text").attr({ scrollTop: $("#" + id + "_text").attr("scrollHeight") });
  	
  	// Clear out message box and then focus on it
  	$("#" + id + "_msg").val("");
  	$("#" + id + "_msg").focus();

	}
	else
		$("#" + id + "_msg").focus();
}

addMinimize = function()
{
  // Need to make sure not to add another one if a minimize is already on it
  $("div.ui-dialog").each(function(){ 
    if($(this).children('a').hasClass("minimize"))
    {
      return;
    }
    else
    {
      $("a.ui-dialog-titlebar-close").before("<a href='#' class='minimize' style='float:right; margin-right: 25px;'>_</a>");
      $("a.minimize").click(function(){
        $(this).parent("div").siblings().toggle();
        var dlg = $(this).parent('div').parent('div').attr("aria-labelledby");
        
        // This is messy... But I'm not sure of a better way to get the dialog object off the top of my head
        dlg = "#" + dlg.replace("ui-dialog-title-", "");
        
        if($(this).parent("div").siblings().is(":visible"))
        {
          $(dlg).dialog('option', 'position', 'middle');
          $(this).css('border','none');
        }
        else
        {
          $(dlg).dialog('option', 'position', 'bottom');
          $(this).css('border','solid 2px grey');
        }
      });  
    }
  });
}
