/*
 * ChatMain.js
 * (c)2008 Bell Systems
 * 
 * License: http://bellspace.net/licenses/non-commercial.html (Non-Commercial) 
 * Licensing: http://bellspace.net/licensing/index.html 
 * 
 * Main Chat Program
 *
 */

var chatLoopInterval = false;
var titleUpdateInterval = false;
var originalTitle = document.title;

var whoButton = document.getElementById("who_button");
var whoInput = document.getElementById("who_are_you");

var myUserName = "";
var chatUsersArray = new Array();

var windowLostFocus = false;
window.onfocus = function()
{
    stopTitleLoop();
}

if(browserDetect.browser == "Explorer")
{
	var whoAreYouInput = document.getElementById("who_are_you");
	whoAreYouInput.onfocus = function()
	{
		setTimeout("windowLostFocus=false;", 500);
	}
	
	var messageStringInput = document.getElementById("message_string");
    messageStringInput.onblur = function()
    {
        windowLostFocus = true;
    }
    window.onblur = function()
    {
		messageStringInput.focus();
        windowLostFocus = false;
    }		
} 

window.onblur = function()
{
	if(browserDetect.browser == "Explorer")
	{
		//alert("here")
	}
	else
	{
		//DBUG.innerHTML += "lostfocus";
        windowLostFocus = true;
	}
}
//initForms(whoButton, whoInput)

function chatErrorFunction()
{
	if(!windowIsUnloading)
	{
        updateChat('<span style="color:red;">ChatMain.js ajaxCall() Error!</span><br><span style="color:red;">Please try again.</span><br><br>', false);
	}
}

var windowIsUnloading = false;
window.onbeforeunload = function()
{
	//tell any open private chats that we are leaving
	for(var i=0; i<chattingWithUserNames.length; i++)
	{
		closePrivChat(chattingWithUserNames[i]);
	}
	
    //logout of the chat
	windowIsUnloading = true;
    var param = "http://" + myHost + "/chat/lib/php/ajax/ChatIO.php?logout=true";
    ajaxCall(param, false, chatErrorFunction);    
}

//login function
function whoAreYou()
{
    var whoAreYouString = document.getElementById("who_are_you");
    
    //set who the person is
    var successFunction = function(response)
    {
        if(response.Login == "SUCCESS")
        {
            chatLoopInterval = setInterval("chatLoop();", 5000);            
            document.getElementById("who_are_you_container").style.display = "none";
            document.getElementById("message_string_container").style.display = "block";
            initForms(document.getElementById("post_button"), document.getElementById("message_string"));
            updateChat('<span style="color:red;">Hi ' + whoAreYouString.value + '! You have successfully logged in.</span><br><br>', false);          
        
	        //Update Chat Users: box
	        if(response.chatUsersHtml != "")
	        {
	            document.getElementById("chat_users_floatbox").style.display = "block";         
	            updateChatUsers(response.chatUsersHtml)
	        }   		
		}
		else if(response.Login == "FAIL USERNAME")
		{
            updateChat('<span style="color:red;">Sorry, the username "' +whoAreYouString.value+ '" has already been taken.</span><br><span style="color:red;">Please try again.</span><br><br>', false);			
		}
		else
		{
            updateChat('<span style="color:red;">You could not be logged into the chat.</span><br><span style="color:red;">Please try again.</span><br><br>', false);           			
		}	        
    };  
        
    var param = "http://" + myHost + "/chat/lib/php/ajax/ChatIO.php";
	var content = new Object();
	
	//set chat user name
	myUserName = whoAreYouString.value;
    content['who_are_you'] = whoAreYouString.value;
	ajaxPostCall(param, content, successFunction, chatErrorFunction, "json");    
}

function chatPost(messageString, destination, chatContents)
{
	//configure the function params
	var messageStringEl = false;
	if(!messageString)
	{
        messageStringEl = document.getElementById("message_string");
        messageString = messageStringEl.value;
	}
	
	if(!destination)
	{
		destination = "*"
	}
	
    //post a chat Message
    var successFunction = function(response)
    {
        if(response != "")
        {
            updateChat(response, true, chatContents);
			windowLostFocus = false;
        }
        else
        {
            //
        }        
    };  
     
    if(messageString.search(/\/msg /) != -1)
    {
		//these are special messages that do not get sent out to the server
        var users = messageString.split(" ");
        for(var i=0; i<users.length; i++)
        {
            if(users[i] != "/msg")
            {
				if(users[i] != myUserName)
				{
                    initPrivChat(users[i]);
				}
				else
				{
					//you cannot chat with yourself
					updateChat("<span class='system_says'>Sorry, you cannot chat with yourself.</span>", false);      
				}
            }
        }
    }
    else if(messageString.search(/\/unblock /) != -1)
    {
        //these are special messages that do not get sent out to the server
        var users = messageString.split(" ");
        for(var i=0; i<users.length; i++)
        {
            if(users[i] != "/unblock")
            {
                unblockPrivChat(users[i]);
            }
        }
    }	
	else
	{
		//these are normal chat messages that get sent to the server	    
	    var param = "http://" + myHost + "/chat/lib/php/ajax/ChatIO.php";
		var content = new Object();
		content['message_string'] = messageString;
		content['destination'] = destination;

	    ajaxPostCall(param, content, successFunction, chatErrorFunction); 
    }  
    
	if(messageStringEl)
	{
        messageStringEl.value = "";
	}
	
	//check if our chat contents has a vertical scrollbar
	//if it does we move the chat_users_floatbox over some
	/*var chatUsersFloatBox = document.getElementById("chat_users_floatbox");
	var chatContents = document.getElementById("chat_contents");
	if(chatContents.clientHeight <= chatContents.scrollHeight)
	{
		var posRight = getCss("div.chat_users_floatbox", "right");
		posRight = posRight.split("px")[0];
		chatUsersFloatBox.style.right = parseInt(posRight) + 17 + "px";
	}*/ 
}

function serverPost(messageString, destination)
{
	//same as chatPost() except the chat is not updated
	//therefore the successFunction() is empty
    var successFunction = function(response)
    {
        //        
    };  
	
    if(!destination)
    {
        destination = "*"
    }	
     
    //post a message directly to the server    
    var param = "http://" + myHost + "/chat/lib/php/ajax/ChatIO.php";
    var content = new Object();
    content['message_string'] = messageString;
	content['destination'] = destination;
    ajaxPostCall(param, content, successFunction, chatErrorFunction);  
}

function updateChat(message, localUpdate, chatContents)
{
	if(!chatContents)
	{
        var chatContents = document.getElementById("chat_contents");		
	}
	
    var messageDiv = document.createElement("div");
    if(localUpdate)
    {
        messageDiv.innerHTML = 'YOU SAY: ' + message + "<br>";
        messageDiv.className = "you_say";
    }
    else
    {
		messageDiv.innerHTML = message;
        messageDiv.className = "they_say";
    }
    chatContents.appendChild(messageDiv);
	if(chatContents.className == "private_chat_contents")
	{
		chatContents.parentNode.scrollTop = chatContents.parentNode.scrollHeight;
	}
	else
	{
        chatContents.scrollTop = chatContents.scrollHeight;
	}
	
	if(!localUpdate)
	{
	   titleLoop();
    }
}

function updateChatUsers(chatUsersHtml)
{
	var chatUsersContainer = document.getElementById("chat_users");
    chatUsersContainer.innerHTML = chatUsersHtml;
}

function chatLoop()
{   
    //check for new messages and return them
    var successFunction = function(response)
    {
		//the chat message
        if(response.messageString != "")
        {
            //alert(response);
            updateChat(response.messageString, false);
        }
		
		var privMessageStringCount = parseInt(response.privMessageStringCount);
		if(privMessageStringCount > 0)
		{			
			for(var i=0; i<privMessageStringCount; i++)
			{
				if(response.privMessageString[i] == "!initprivchat")
				{
					recvInitPrivChat(response.privMessageSender[i]);
				}
				else if(response.privMessageString[i] == "!SYN1")
				{
                    synPrivChat(response.privMessageSender[i])
				}
                else if(response.privMessageString[i] == "!SYN2")
                {
					//send the ack
                    ackPrivChat(response.privMessageSender[i]);
                }
				else if(response.privMessageString[i] == "!ACK")
				{
					//recieve the ack
                    ackPrivChat(response.privMessageSender[i], true);					
				}
				else if(response.privMessageString[i] == "!REJ")
				{
                    //our chat "!initprivchat" request was rejected					
                    var privChatFloater = dijit.byId(response.privMessageSender[i]);
                    if(privChatFloater)
					{
				        updateChat("<span class='system_says'>Your chat request with " + response.privMessageSender[i] + " was rejected.</span>", false, privChatFloater.contentDiv);
					}								
				}
                else if(response.privMessageString[i] == "!BLK")
				{
					//we have been blocked from making !initprivchat requests
					//to this user               
                    var privChatFloater = dijit.byId(response.privMessageSender[i]);
                    if(privChatFloater)
					{
						updateChat("<span class='system_says'>You have been blocked from making any further chat requests with " + response.privMessageSender[i] + "</span>", false, privChatFloater.contentDiv);
					}					
				}
                else if(response.privMessageString[i] == "!CLOSE")
                {
                    //the other user closed the chat
					
                    var privChatFloater = dijit.byId(response.privMessageSender[i]);					
					
					if(privChatFloater)
					{
						//first remove the postControlsDiv
						var postControlsDiv = getElementByClassName("post_controls", privChatFloater.domNode);
						if(postControlsDiv)
						{
	                        postControlsDiv.parentNode.removeChild(postControlsDiv);
						}
                        
						if(!privChatFloater.inactive)
						{                      
                            updateChat("<span class='system_says'>" + response.privMessageSender[i] + " left the chat.</span>", false, privChatFloater.contentDiv);	
							privChatFloater.inactive = true;
						}
								
					}                   
                }			
				else
				{
                    var privChatFloater = dijit.byId(response.privMessageSender[i]);
					if(privChatFloater)
					{
					   updateChat(response.privMessageString[i], false, privChatFloater.contentDiv);
					}   					
				}				
			}
		}
        
		//Chat Users: box
		if(response.chatUsersHtml != "")
		{
			updateChatUsers(response.chatUsersHtml)
		}
		
		//chatUsersArray
		chatUsersArray = response.chatUsersArray;	
		
		//check that our open private chats are with users that exist
		//if the user is not found..close the chat
		for(var i=0; i<chattingWithUserNames.length; i++)
		{
            var found = false;
            for(var j=0; j<chatUsersArray.length; j++)
            {
				if(chattingWithUserNames[i] == chatUsersArray[j])
				{
					//alert("1"+chattingWithUserNames[i]);
					//alert("2"+chatUsersArray[j])
					found = true;
					break;
				}
			}
			if(!found)
			{
                var privChatFloater = dijit.byId(chattingWithUserNames[i]);                    
                
                if(privChatFloater)
                {
                    //first remove the postControlsDiv
                    var postControlsDiv = getElementByClassName("post_controls", privChatFloater.domNode);
                    if(postControlsDiv)
                    {
                        postControlsDiv.parentNode.removeChild(postControlsDiv);
                    }
                    if(!privChatFloater.inactive)
                    {   
                        updateChat("<span class='system_says'>" + chattingWithUserNames[i] + " left the chat.</span>", false, privChatFloater.contentDiv);
						privChatFloater.inactive = true;
					} 
                }
				chattingWithUserNames.splice(i, 1);
			}
		}			       
    };  
        
    var param = "http://" + myHost + "/chat/lib/php/ajax/ChatIO.php?heartbeat=true";
    ajaxCall(param, successFunction, chatErrorFunction, "json");    
}

function stopTitleLoop()
{
	clearInterval(titleUpdateInterval);
	titleUpdateInterval = false;
	windowLostFocus = false;
	document.title = originalTitle;
}

function titleLoop()
{
	if(windowLostFocus)
	{		
		if(document.title == originalTitle)
		{
			document.title = "New Message!";
		}
		else if(document.title == "New Message!")
		{
			document.title = originalTitle;
		}
		
        if(!titleUpdateInterval)
        {
            titleUpdateInterval = setInterval("titleLoop();", 1000)
        }		
	}
}

/*private (im/dcc style) chatting*/
var chattingWithUserNames = new Array();
function initPrivChat(withUserName)
{	
	//first check if we already had an incoming request
	var privChatFloater = dijit.byId(withUserName);
	if(privChatFloater)
	{
		return;
	}
	
    //speed up the loop from 5 seconds to 1 second
    clearInterval(chatLoopInterval);
    chatLoopInterval = setInterval("chatLoop();", 1000);
		
	//1st called function on sending request side
	var titleBarContent = "Chatting with " + withUserName;
	var Content = '<span class="system_says">Initiating private chat with ' + withUserName + '...</span>';
	var privChatFloater = brandNewFloater(titleBarContent, Content, withUserName);
	serverPost("!initprivchat", withUserName);
	
    //if we close the window
    dojo.connect(privChatFloater, "close", function(){
        closePrivChat(withUserName);
    });
	
    //the scrollbar seems to jump up when we click on something 
    //we reset it here
    var chatContents = document.getElementById("chat_contents");
    chatContents.scrollTop = chatContents.scrollHeight;	 	
}

function recvInitPrivChat(withUserName)
{
    //speed up the loop from 5 seconds to 1 second
    clearInterval(chatLoopInterval);
    chatLoopInterval = setInterval("chatLoop();", 1000);	
	
	//1st called function on receiving request side
	var titleBarContent = "Chat request from " + withUserName;
    var Content = '<span class="system_says">Do you want to chat with ' + withUserName + '?</span><br>';
	
	var ieSpecialHover = "";
	if(browserDetect.browser == "Explorer")
	{
		ieSpecialHover = 'onmouseover="this.style.cursor=\'pointer\';"';
	}
	
	Content += '<span style="color:green;" class="js_link_bold" '+ieSpecialHover+' onclick="willPrivChat(\''+withUserName+'\');">Yes</span>&nbsp;|&nbsp;';
    Content += '<span style="color:red;" class="js_link_bold" '+ieSpecialHover+' onclick="wontPrivChat(\''+withUserName+'\');">No</span>&nbsp;|&nbsp;';
	Content += '<span style="color:blue;" class="js_link_bold" '+ieSpecialHover+' onclick="blockPrivChat(\''+withUserName+'\');">Block</span>&nbsp;';
	
	//handle the rare cases that we both requested chats at the same time,
	//or one person closed a window... came back real fast and requested the chat
	//again
    var privChatFloater = dijit.byId(withUserName);
	if(privChatFloater)
	{
		//since our floater is here that means we made a initPrivChat() call right
		//as we recieved the recvInitPrivChat() call
		//this means we automatically accept
		
		//first check if we have postControls already
		var postControls = getElementByClassName("post_controls", privChatFloater.domNode);
		if(postControls)
		{
			//first clear out any left over stuff that may be in the window content
			privChatFloater.contentDiv.innerHTML = "";
			
			//make sure we are active
			privChatFloater.inactive = false;
			
        	//we are ready to go... just send the ACK
			serverPost("!ACK", withUserName); 		
		}
		else
		{
            //make sure we are active
            privChatFloater.inactive = false;			
            willPrivChat(withUserName);
		}
	}
	else
	{
	   var privChatFloater = brandNewFloater(titleBarContent, Content, withUserName);
    }
	
	//if we close the window
    dojo.connect(privChatFloater, "close", function(){
	   closePrivChat(withUserName);
	});		
}

function willPrivChat(withUserName)
{		
    var privChatFloater = dijit.byId(withUserName);
	privChatFloater.contentDiv.innerHTML = "<span class='system_says'>Waiting for connection to " + withUserName + "...</span>";
	serverPost("!SYN1", withUserName); 	
}

function synPrivChat(withUserName)
{
    var privChatFloater = dijit.byId(withUserName);
    privChatFloater.contentDiv.innerHTML = "<span class='system_says'>Waiting for connection to " + withUserName + "...</span>";
    serverPost("!SYN2", withUserName);	
}

function ackPrivChat(withUserName, recvAck)
{
    var privChatFloater = dijit.byId(withUserName);
    if(!recvAck)
	{
        serverPost("!ACK", withUserName);
    }
	var input = document.createElement("input");
	input.className = "textbox";
	input.style.marginLeft = "4px";
	input.style.marginTop = "4px";
      
	var floatingPaneTitle = getElementByClassName("dojoxFloatingPaneTitle", privChatFloater.domNode)
	var floatingPaneContent = getElementByClassName("dojoxFloatingPaneContent", privChatFloater.domNode)
	
	
    var spacer = document.createElement("div");	
	if(browserDetect.browser == "Explorer")
	{
        var postButton = document.createElement('<input type="button" style="position:relative; left:2px;" class="button" type="button" value="Send">')
		postButton.onclick = function()
		{
		    chatPost(input.value, withUserName, privChatFloater.contentDiv);
		    input.value = "";
		}
		spacer.style.marginTop = "-11px";	
	}
	else
	{
		var postButton = document.createElement('input');
		postButton.style.position = "relative";
		postButton.style.left = "2px";
		postButton.className = "button";
		postButton.type = "button";
		postButton.value = "Send";
		postButton.onclick = function()
		{
			chatPost(input.value, withUserName, privChatFloater.contentDiv);
			input.value = "";
			input.focus();
		}
	    spacer.style.marginTop = "4px";		
	}
	
	spacer.style.marginBottom = "4px";
	spacer.style.width = "100%";
	spacer.style.borderBottom = "1px solid gray";
	//floatingPaneTitle.parentNode.insertBefore(postButton, floatingPaneTitle);
	
	var canvas = getElementByClassName("dojoxFloatingPaneCanvas", privChatFloater.domNode);
	
	var postControlsDiv = document.createElement("div");
	postControlsDiv.className = "post_controls";
	postControlsDiv.appendChild(input);
	input.focus();
	postControlsDiv.appendChild(postButton);
	postControlsDiv.appendChild(spacer);
	
	canvas.parentNode.insertBefore(postControlsDiv, canvas);
	var adjustedHeight = canvas.clientHeight - postControlsDiv.clientHeight - spacer.style.marginBottom.replace(/px/, "");
	   
	//add keyboard enter submit   
    initForms(postButton, input);	
	
	privChatFloater.contentDiv.innerHTML = "";
    var title = getElementByClassName("dijitInline dijitTitleNode", privChatFloater.domNode);
	title.innerHTML = "Chatting with " + withUserName;
	
	canvas.style.height = adjustedHeight + "px";
	floatingPaneContent.appendChild(privChatFloater.contentDiv);
	
	//we are chatting withUserName now
	chattingWithUserNames.push(withUserName);
	
    ///slow loop back down from 1 second to 5 seconds
    clearInterval(chatLoopInterval);
    chatLoopInterval = setInterval("chatLoop();", 5000);			
}

function wontPrivChat(withUserName)
{
	//we will not chat withUserName at this time
    var privChatFloater = dijit.byId(withUserName);
    privChatFloater.close();
	//send the rejection message
    serverPost("!REJ", withUserName);
	
    ///slow loop back down from 1 second to 5 seconds
    clearInterval(chatLoopInterval);
    chatLoopInterval = setInterval("chatLoop();", 5000);		
}

function blockPrivChat(withUserName)
{
    //we are blocking withUserName from making any further
	//chat requests with us
    var privChatFloater = dijit.byId(withUserName);
    privChatFloater.contentDiv.innerHTML = "<span class='system_says'>You have blocked " + withUserName + " from making any further chat requests.</span><br>";
	privChatFloater.contentDiv.innerHTML += "<span class='system_says'>You can unblock by typing the command /unblock username in any chat window.</span>";
	
    //send the block message
    serverPost("!BLK", withUserName);
	
    ///slow loop back down from 1 second to 5 seconds
    clearInterval(chatLoopInterval);
    chatLoopInterval = setInterval("chatLoop();", 5000);		
}

function unblockPrivChat(withUserName)
{
    //send the unblock message
    serverPost("!UNBLK", withUserName);
	updateChat("<span class='system_says'>" + withUserName + " is no longer blocked.</span>", false);   	
}

function closePrivChat(withUserName)
{
    //send the close message
    serverPost("!CLOSE", withUserName);	
}

function brandNewFloater(titleBarContent, Content, domNodeId, floaterDimensions)
{
    var node = document.createElement('div');
	if(domNodeId)
	{
		node.id = domNodeId;
	}
	
    var myPaneContainer = document.createElement("div");
    
    //if not "inline" scrollbars will build up when they should not
    myPaneContainer.style.display = "inline";
    myPaneContainer.style.margin = "0 auto";
         
    var div = document.createElement("div");
    div.className = "private_chat_contents";		
	div.innerHTML = Content;
    
    node.appendChild(div);
    document.body.appendChild(myPaneContainer);
    myPaneContainer.appendChild(node);
    
    var floater = new dojox.layout.FloatingPane(
    {
        title:titleBarContent,
        dockable: false,
        maxable: true,
        closable: true,
        resizable: false,
		contentDiv: div,
		inactive: false
    },node);
	 	
    //open where cursor is
    //floater.domNode.style.top = gClientY + "px";
    //floater.domNode.style.left = gClientX + "px";          
    
    //open in center of window
    if(browserDetect.browser == "Explorer")
    {
        floater.domNode.style.top = (document.documentElement.clientHeight/2)-(220/2) + "px";
        floater.domNode.style.left = (document.documentElement.clientWidth/2)-(380/2) + "px";
    }
    else
    {
        floater.domNode.style.top = (window.innerHeight/2)-(220/2) + "px";
        floater.domNode.style.left = (window.innerWidth/2)-(380/2) + "px";
    }               
    
    floater.startup();
    floater.resize({ w:380, h:220 });   
    floater.bringToTop();
     
	/*below are custom minimize/maximize functions*/
	
    var closeIcon = getElementByClassName("dojoxFloatingCloseIcon", floater.domNode);
    //digitInline is a <span> that contains the title
    var digitInline = getElementByClassName("dijitInline dijitTitleNode", floater.domNode)	
	
    floater.windowShadeMinimize = function()
    {
        var titlePane = getElementByClassName("dojoxFloatingPaneTitle", this.domNode);
		this.domNode.original_domNodeHeight = this.domNode.offsetHeight-1;
        this.domNode.original_domNodeWidth = this.domNode.offsetWidth-1;
        this.domNode.style.height = titlePane.offsetHeight-1 + "px";
        this.domNode.style.width = digitInline.offsetWidth + 110 + "px";
    }

    floater.windowShadeMaximize = function()
    {
        this.domNode.style.height = this.domNode.original_domNodeHeight + "px";
        this.domNode.style.width = this.domNode.original_domNodeWidth + "px";
    }
    
    //everything is backwards from dojo... we convert the maximize function
    //to a minimize function
    floater.maximize = function()
    {
        this.windowShadeMinimize();
        var theMinimizeIcon = getElementByClassName("dojoxFloatingMaximizeIcon", this.domNode);
		theMinimizeIcon.style.display = "none";
        var theMaximizeIcon = getElementByClassName("dojoxFloatingMinimizeIcon", this.domNode);
        theMaximizeIcon.style.display = "inline";
    }
    
    //convert the maximize function to a minimize function;
    floater.minimize = function()
    {
        this.windowShadeMaximize();
        var theMinimizeIcon = getElementByClassName("dojoxFloatingMaximizeIcon", this.domNode);
        theMinimizeIcon.style.display = "inline";
        var theMaximizeIcon = getElementByClassName("dojoxFloatingMinimizeIcon", this.domNode);
        theMaximizeIcon.style.display = "none";             
    }  	 
	 
    return floater;
}
