/* @Copyright Holoscape Inc. 2010
   All rights reserved.
*/

// Utility functions

function onLoadEvent()
{
}

function onUnloadEvent() 
{
	disconnectFromServer();
}

var bSendTypingEvent = true;

function onTyping()
{
	// only send the first typing event
	// then, do not send until there is a new message being typed
	if ( bSendTypingEvent )
	{
		socket.send("t:");
		bSendTypingEvent = false;
	}
}

function disableChat(on1, on2, on3)
{
	//disable/enable buttons, text according to state
	document.getElementById('textinput').disabled = on1;
	document.getElementById('send').disabled = on2;
	document.getElementById('next').disabled = on3;
	
}

function onKeyPress(e){
	if ( (e.keyCode || e.which) == 13 )
	{
		sendMessage();
	}
	else
	{
		onTyping();
	}
}



// obj has 'from' and 'message' fields
function addMessage(obj){

    var el = document.createElement('p');
        
    el.innerHTML = '<b>' + esc(obj.from) + ':</b> ' + esc(obj.message);
    
    document.getElementById('chat').appendChild(el);
    
    document.getElementById('chat').scrollTop = 1000000;
    
}


function setStatus(message){
    
	// show the 'other user typing' message and other things

	//document.getElementById('status').innerHTML = '<em>' + message.substring(3) + '</em>';
	document.getElementById('status').innerHTML = message.substring(3);
	
	if ( message.length == 0 )
	{
		return;
	}
	
	//enable/disable the chat according to the status
	switch ( message.substring(0,2) )
	{
	case '01':   	//"Connecting to the":
	case '02':	//"Connected to the ":
	case '12':	//Looking for a user":
			disableChat(true, true, true);
			break;
			
	case '03':   	//"Disconnected from":	

			connectToServer();
		
	case '13:':	//Other user left..":
			disableChat(true, true, false);
			document.getElementById('next').focus();

			break;
			
	case '11': 	//"Now chatting with":
			disableChat(false, false, false);
			document.getElementById('textinput').focus();
		
			bSendTypingEvent = true;	

			break;
			
        case '14': 	//"User typing
		
			//document.getElementById('textinput').focus();
			
			//TODO  start a timer that clears this after 5 seconds...
			break;
	default:
			//error!
			break;

	}
	
    
}
      
function sendMessage(){

    var val = document.getElementById('textinput').value;
    
    if ( val.length == 0 ) return;
    
    //TODO
    //if ( val.trim().length() == 0 )
    
    socket.send('m:'+val);
	
    bSendTypingEvent = true;
    
    addMessage({ from: 'You', message: val });
    
    document.getElementById('textinput').value = '';
}
      
function esc(msg){

    return String(msg).replace(/</g, '&lt;').replace(/>/g, '&gt;');
    
};

function connectToServer(){

    // connect to the server, this will create an event on the server
    socket.connect();

}

function disconnectFromServer(){

    // clean the chat
    document.getElementById('chat').innerHTML = '';
    
    // connect to the server, this will create an event on the server
    socket.disconnect();
    
}

function nextUser() {
		
    // clean the 'chat' element
    document.getElementById('chat').innerHTML = '';	
	setStatus('01:Connecting to the server...');
	
	//send an event to the server, saying 'next user'
	socket.send("n:");
		
}

var socket = null;
var baseurl = location.href.substring(7,14);

if ( baseurl == '127.0.0' )
{
	//alert("Running from 127.0.0.1!");
	socket = new io.Socket('127.0.0.1'); //, {port:8010, rememberTransport:false});
}
else if  (( baseurl == 'localim' ) || (baseurl == 'www.loc') )
{
	socket = new io.Socket('localim.com', {port:8010, rememberTransport:false});
}
else
{
	socket = new io.Socket('nchat.org', {port:8010, rememberTransport:false});
}

connectToServer();

socket.on('connect', function()
{
    // connected to server
    setStatus("02:Connected to the server!");
    
})

function processMessage(obj)
{
    if ( 'event' in obj )
    {
    	setStatus(obj.event);
    }
    else
    {
	    // add the message
    	addMessage(obj);
    	setStatus('');
    }
    
}

socket.on('message', function(obj)
{
	if ('buffer' in obj)
	{
		for (var i in obj.buffer) 
		{
			processMessage(obj.buffer[i]);
		}
	} 
	else 
	{
		processMessage(obj);
	}
	
})
	

socket.on('disconnect', function()
{
    // disconnected event came from server
    setStatus("03:Disconnected from the server! Click Next Person to chat with someone");
    
    // clean the 'chat' element
    document.getElementById('chat').innerHTML = '';
    
    // connect to server, look for another user?
})

