/* 
   FrenchTuesdays.com - im.js
   written by FXB Consulting 6/11/09 
*/

/* define global variables */
var lastMsg = 0;
var msgRequest;
var imgPath = '/themes/french_tuesdays/gfx/';
var thePhoto = '/photos/awaiting_small.gif';
var messageTimer;
var statusTimer;
var OGTitle = document.title;

/* Start lazy initialization for myContacts data binding object 
   see for reference: http://en.wikipedia.org/wiki/Lazy_initialization 
   Note: jQuery.data() was not used for this application due to the legacy implementation this was built on top of 
   DO NOT try to replace the data binding with jQuery.data().
*/

var myContacts = new Object();
myContacts.contact = new Object();
//myContacts = localContacts;

/* buddy list variables */
var maxContacts = 20;

/* end global variables */


/* document is ready and jQuery is ready */
$(document).ready( function(){

//$(window).unload( function () { WS.disconnect(); } );


//$("#jpId").jPlayer( {
//    ready: function () {
//      $(this).setFile("http://www.frenchtuesdays.com/jscript/im/IM00.mp3"); 
//    },
//    swfPath: "http://www.frenchtuesdays.com/jscript/im"
//  });




/* this hack will fix css hover menus in IE */
if(/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) 
{
	$('.subMenu').hover(function(){$(this).find('ul').show();}, function(){$(this).find('ul').hide();});
}

	/*bind all live events to the DOM before any elements are rendered */


		//$('.chatbox_footer_popinchat').draggable();

		/* BUDDY LIST EVENTS */
			/* user clicks on hide buddy list */
			$('.chatbox_maxon_op .minChat').live("click", function(){
				IM.changeStatus('Minimized');
			});


			/* user clicks on show buddy list */
			$('.chatbox_maxon_op .maxChat').live("click", function(){
				IM.stateData['buddyList'] = "Online";
          			  IM.saveState();
			$('.chatbox_maxon_op .maxChat').hide();
			$('#chatbox_footer_maxon').animate({
				height: "300",
				marginTop: "0"
			}, 350, function(){
				$('.chatbox_maxon_friends').fadeIn(350);
			});
	
			$('.chatbox_maxon_graphic img').attr('src', '/themes/french_tuesdays/gfx/chatbox_status_online.png');
			$('.chatbox_maxon_op .minChat').show();
			$('.chatbox_maxon_online').hide();
			$('.chatbox_maxon_offline').show();
			});


			/* user clicks "offline" */
			$('.chatbox_maxon_offline').live("click", function(){
				IM.changeStatus('Offline');
			});
	

			/* user clicks "online" */
			$('.chatbox_maxon_online').live("click", function(){
				IM.changeStatus('Online');
			});
			
			
			/* user clicks "show only online friends" */
			$('.chatbox_maxon_friendsitem_name span').live("click", function(){
				//console.log('show online friends');
			});


			/* user clicks on buddy name in buddy list*/
			$('.chatbox_maxon_friendsitem_name a').live("click", function(){
				/* Marak says: using parent().parent().attr() and contactID.replace(/imember_/,'') here is a hack, we should have used jQuery.data(this)*/																							
				var contactID = $(this).parent().parent().attr('id');
				contactID = contactID.replace(/imember_/,'');
				//IM.renderMessages(myContacts[contactID].messages);
				IM.openChatWindow(contactID);
			});
			
		
			/* user clicks on buddy image in buddy list*/
			$('.chatbox_maxon_friendsitem_pic img').live("click", function(){
				/* Marak says: using parent().parent().attr() and contactID.replace(/imember_/,'') here is a hack, we should have used jQuery.data(this)*/																							
				var contactID = $(this).parent().parent().attr('id');
				contactID = contactID.replace(/imember_/,'');
				//IM.renderMessages(myContacts[contactID].messages);
				IM.openChatWindow(contactID);
			});
		

			/* user mouse overs a buddy name */
			$('.chatbox_popinchat_friendsitem_name').live("mouseover", function(){
				$(this).css('background-color', 'black');
			});
 

			/* user is searching their buddy list */			
			$('#buddySearch').live("keyup", function(e){
				var key = e.charCode || e.keyCode || 0;
				switch (key) {
					case 13: /* 13 is the ASCII value of "enter" */
					 	}
				//console.log($('#buddySearch').val());
				/* perform search*/
			
			});

			
			/* user clicks on buddy list search */
			$('#buddySearch').live("click", function(e){
				$(this).val('');				
			});

			/* this hack will fix "fixed positioning" for IE6 */
			if(/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) 
			{
				$("#bottomBar").fixedPosition({vpos:"bottom", hpos:"right"});			
			}
			else
			{
				$('#bottomBar').css('bottom', 0);
				$('#bottomBar').css('right', 0);
				$('#bottomBar').css('position', 'fixed');
			}
			
		/* END BUDDY LIST EVENTS */
		
		/* CHAT WINDOW EVENTS */
			/* user clicks on hide chat window */
			$('.chatbox_popinchat_op .min').live("click", function(){
				/* Marak says: parent.parent.parent.etc is terrible usage of jQuery, again we should have used jQuery.data() */
				var myChat = $(this).parent().parent().parent().parent().attr('id');
				IM.hideChatWindow(myChat);
			});


			/* user maximizes chatWindow */
			$('.chatbox_popinchat_op .max').live("click", function(){
				/* Marak says: parent.parent.parent.etc is terrible usage of jQuery, again we should have used jQuery.data() */
				var myChat = $(this).parent().parent().parent().parent().attr('id');
				//alert(myChat);
				IM.showChatWindow(myChat);
			});


			/* user clicks on exit chat window */
			$('.chatbox_popinchat_op .exit').live("click", function(){
																	
																	
				/* Marak says: parent.parent.parent.etc is terrible usage of jQuery, again we should have used jQuery.data() */
				var myChat = $(this).parent().parent().parent().parent();
				$(myChat).hide();
				//$(myChat).fadeOut(600, function(){		});
				if(IM.chatWindowsOpen>0)
				{
                	IM.chatWindowsOpen = IM.chatWindowsOpen - 1;
					$('#activeChats').html(IM.chatWindowsOpen);
				}

                //alert(IM.chatWindowsOpen);
				/* remove this chat window from saveState */
				var myContactID = $(this).parent().parent().parent().parent().attr('id');
				myContactID = myContactID.replace(/ichat_/,'');
               		delete IM.stateData[myContactID];
				IM.saveState();

				/* this calculation represents a pixel percise layout adjustment for chat windows
				   I've chosen to not use "float" for certain features (such as chat windows) to ensure
				   a uniform user experiece cross browser and to have more control over chat window
				   positioning in the future */

				var magicRightOffset = parseInt($(myChat).css('right'));
				var magicWidth = 205; //replace with dynamic reference to width of window + current margin
				jQuery.each($('.chatbox_footer_popinchat'), function(i, val) {
				if($(val).css('display')!='none')
				    {
				     if(parseInt($(val).css('right'))>magicRightOffset)
				      {
				          $(val).css('right', (parseInt($(val).css('right')) - magicWidth ));
				      }
				    }
				});

			});


			/* user sends a message to a contact*/
			$('.messageText').live("keyup", function(e){
				var key = e.charCode || e.keyCode || 0;
				if (key == 13) {
					
					var myVal = $(this).val().replace(new RegExp( "\\n", "g" ),''); 
					$(this).val('');
					//console.log(myVal);
					if(myVal=='') {
						$(this).val('');
						//alert('Please enter your message.');
						return;
					}																						
					var contactID = $(this).parent().parent().parent().attr('id');
					contactID = contactID.replace(/ichat_/,'');
					IM.sendMessage(contactID,myVal);
					
				}
			});


			/* TODO: implement a better draggable window solution */
			/* disable draggable property of chat window when user is interacting with inner components of chat window*/

	/*
			$('.chatbox_popinchat_chatcontainer').live("mouseout", function(){
				//console.log('mouseover');
				$('.chatbox_footer_popinchat').draggable();
			 });
			


			$('.chatbox_popinchat_chatcontainer').live("mouseover", function(){
				$('.chatbox_footer_popinchat').draggable("disable");
				//console.log('mouseout');
			});
				
	*/

			/*
			$('.chatbox_maxon_op .maxChat').live("click", function(){
           			 
			//WS.connect();




			});
			*/
		/* END CHAT WINDOW EVENTS */


	/* After we have declared all of our "live" events, load the instant messanger */
	IM.init();
        //IM.changeStatus('Offline');

});


/* IM OBJECT */
	
var IM = {};
//IM.stateData = {};
IM.chatWindowsOpen = 0;
IM.lastMsg = '';
IM.rendering=false;

/* we are going to dynamically extend IM as we add new methods / properties */
IM.init = function(){




/* update server side smiles */
jQuery.each($('.chatbox_popinchat_chatitemto'), function(i, val) {
                  var emoteText = $().emoticon($(val).html());
                $(val).html(emoteText);
               });


jQuery.each($('.chatbox_popinchat_chatitemfrom'), function(i, val) {
                  var emoteText = $().emoticon($(val).html());
                $(val).html(emoteText);
               });





	/* myMemberID is defined outside of this file in im.tpl, if its defined you can assume it is a global JS variable containing the current users mem_id */
	if (typeof myMemberID != 'undefined') {
		IM.populateBuddyList(localContacts);
        //IM.loadState();
		//IM.renderBuddyList();
		//WS.getContacts();

		WS.getMessages(true);
	}
};


/* saves current UI state of IM */
IM.saveState = function(){
		try{		
		var myJSON = $.toJSON(IM.stateData); 
              var date = new Date();
              date.setTime(date.getTime() + (3 * 24 * 60 * 60 * 1000));
              $.cookie('FRENCHTUESDAYSIM', myJSON, { path: '/', expires: date });
		}
		catch(err)
		{
		}
};

/* retrieves previous UI state of IM */
IM.loadState = function(){
	//console.log('loadState');
	/* retrieve last state from cookie */
	var stateCookie = $.evalJSON($.cookie('FRENCHTUESDAYSIM'));
	if(stateCookie != null)
	{
		IM.stateData =  $.evalJSON($.cookie('FRENCHTUESDAYSIM'));
	}
	

	/* loop through previous state and open IMChatWindows  */
    var tArray = new Array();
	for(myContact in IM.stateData)
		{
                   if(myContact != 'buddyList')
                   {
                   tArray.push(myContact);
                   }
		}



        for(k=0;k<tArray.length;k++)
        {
           //console.log(tArray[k],IM.stateData[tArray[k]]);
           switch(IM.stateData[tArray[k]])
                   {
           case 'Open':
                   IM.openChatWindow(tArray[k]);
           break;
           case  'Min':
                   IM.openChatWindow(tArray[k],'Min');
                   //alert('hide ' + tArray[k])
                   //IM.hideChatWindow('ichat_' +tArray[k]);
           break;

           }

       //
        }

    	//console.log(tArray);
};


IM.renderBuddyList = function(){
	$('#im_container').append(IM.buddyList);

$('#chatbox_footer_maxon').slideDown(600, function(){	
		$('.chatbox_maxon_friendsitem').show();
		$('.chatbox_base').show();
	});	
};


/* This is another terrible example of jQuery usage. Due to the DOM from the previous build, 
   we are stuck with these long blocks  of show(), hide() */
IM.changeStatus = function(state){
	switch (state) {
		case 'Online':
            IM.stateData['buddyList'] = "Online";
	     //IM.chatWindowsOpen = 0;
            IM.saveState();
			$('.chatbox_maxon_op .maxChat').hide();
			$('#chatbox_footer_maxon').animate({
				height: "300",
				marginTop: "0"
			}, 350, function(){
				$('.chatbox_maxon_friends').fadeIn(350);
			});
	
			$('.chatbox_maxon_graphic img').attr('src', '/themes/french_tuesdays/gfx/chatbox_status_online.png');
			$('.chatbox_maxon_op .minChat').show();
			$('.chatbox_maxon_online').hide();
			$('.chatbox_maxon_offline').show();
			WS.connect();
	

		break;
		case 'Minimized':
            IM.stateData['buddyList'] = "Min";
            IM.saveState();
    		$('.chatbox_maxon_op .minChat').hide();
			$('.chatbox_maxon_friends').hide();
			$('.chatbox_maxon_online').hide();
			$('.chatbox_maxon_offline').show();
			$('.chatbox_maxon_op .maxChat').show();
			$('.chatbox_maxon_graphic img').attr('src', '/themes/french_tuesdays/gfx/chatbox_status_online.png');
			
			$('#chatbox_footer_maxon').animate({
				height: "70",
				marginTop: "230"
			}, 350, function(){
				$('.chatbox_maxon_friends').fadeOut(350);
			});
			//WS.disconnect();
		break;
		case 'Offline':
			IM.chatWindowsOpen = 0;
			$('#activeChats').html(IM.chatWindowsOpen);
			IM.lastMsg = '';
			$('.chatbox_maxon_op .minChat').hide();
			$('.chatbox_maxon_friends').hide();
			$('.chatbox_maxon_online').show();
			$('.chatbox_maxon_offline').hide();
			$('.chatbox_maxon_graphic img').attr('src', '/themes/french_tuesdays/gfx/chatbox_status_offline.png');
			$('.chatbox_maxon_op .maxChat').show();
			
			$('#chatbox_footer_maxon').animate({
				height: "70",
				marginTop: "230"
			}, 350, function(){
				$('.chatbox_maxon_friends').fadeOut(350);
			});

			/* close all chat windows */
			$('.chatbox_footer_popinchat').hide();
			WS.disconnect();
		break;
	}	
}


IM.sendMessage = function(recipientID, msgText) {

	/**/
	var TmsgText = msgText.replace(/</,'&lt;');
	var emoteText = $().emoticon(TmsgText);
	$('#ichat_' + recipientID + ' .chatbox_popinchat_chatcontainer').append('<div class="chatbox_popinchat_chattext"><div class="chatbox_popinchat_chatitemto">'+ '<strong>You</strong>' + ": " + emoteText+'</div></div>');
	


	//$('#ichat_' + recipientID + ' .chatbox_popinchat_chatcontainer').scrollTop($('#ichat_' + recipientID + ' .chatbox_popinchat_chatcontainer')[0].scrollHeight);

     jQuery.each($('.chatbox_popinchat_chatcontainer'), function(i, val) {
                    $(val).scrollTop($(val)[0].scrollHeight);
               });


	WS.sendMessage(recipientID, msgText);
};


IM.showChatWindow = function(myChat) {


    var myContactID = myChat;
	myContactID = myContactID.replace(/ichat_/,'');
	IM.stateData[myContactID] = 'Open';
    IM.saveState();

	/* previous maximize code 

	$('#' + myChat).animate({ top: "0"}, 350, function(){
	});
	*/
	$('#' + myChat + ' .max').hide();
	$('#' + myChat + ' .min').show();	
	$('#' + myChat + ' .chatbox_bottom').show();
	$('#' + myChat).css('height',298);
	$('#' + myChat).css('top',0);
	$('#' + myChat + ' .chatbox_popinchat_target_status').show();
	$('#' + myChat + ' .chatbox_popinchat_target_pic').css('height',45);

}

		
IM.hideChatWindow = function(myChat) {
	
	/* remove this chat window from saveState */
	var myContactID = myChat;
    //alert(myChat);
	myContactID = myContactID.replace(/ichat_/,'');
	IM.stateData[myContactID] = 'Min';
    IM.saveState();
	
	
	
	/* previous minimize code

	$('#' + myChat).animate({ top: "272"}, 350, function(){

	});
	*/
	$('#' + myChat + ' .min').hide(); 	
	$('#' + myChat + ' .max').show(); 
	$('#' + myChat + ' .chatbox_bottom').hide();
	$('#' + myChat + ' .chatbox_bottom').css('height',0);
	$('#' + myChat).css('height',28);
	$('#' + myChat).css('top',270);
	$('#' + myChat + ' .chatbox_popinchat_target_status').hide();
	
	$('#' + myChat + ' .chatbox_popinchat_target_pic').css('height',23);

}


	
IM.populateBuddyList = function(contacts,mode) {
	if(typeof mode == 'undefined'){var mode = "Online";}
	/* now that we have our contacts as json data we are going to parse through them and render each one */

		var contactCount = 0;
		var insertContact = false;
		/* empty contacts container */
		contacts.reverse();
		for(contact in contacts)
		{
			if(contactCount >= maxContacts){return;}
			insertContact = false;
			/* Marak says:  using myContacts[contacts[contact].mem_id]=contacts[contact] and "imember_" is a data binding hack
					  we should have used jQuery.data(element,contacts[contact]).
					  This custom data binding is due to previous implementation */

	
			if(typeof myContacts[contacts[contact].mem_id] == 'undefined')
				{
					myContacts[contacts[contact].mem_id] = new Object();
				}
			
			myContacts[contacts[contact].mem_id]=contacts[contact];

			if(contacts[contact].online=='true') 
			{
				 if(mode=='Online'){
					insertContact = true;
					contactCount++;
					IM.renderBuddy(contacts[contact].mem_id);

				 }
			}
			else
			{
				 if(mode=='Offline'){
					insertContact = true;
					contactCount++;	
					IM.renderBuddy(contacts[contact].mem_id);

				 }
				 
			}

		}	
	
		$('#contacts_container div').show();
		
		if((contactCount<=20) && mode == 'Online')
		{
			//no one is online, switch to offline view
			IM.populateBuddyList(contacts, 'Offline');
		}
		$('#buddySearch').show();
}
	
		
IM.openChatWindow = function(contactID,windowState) {

	/* 	Marak says: using contactID and "ichat_" is a data binding hack, we should have used jQuery.data()
		This custom data binding is due to previous implementation */

		//	IM.renderMessages(myContacts[contactID].messages);
		//	console.log(contactID);
		//    console.log(myContacts[contactID]);


		/* this calculation represents a pixel percise layout adjustment for chat windows
				   I've chosen to not use "float" for certain features (such as chat windows) to ensure
				   a uniform user experiece cross browser and to have more control over chat window
				   positioning in the future */

           var checkDuplicate = $('#ichat_'+contactID).length; // can anyone suggest a more elegant duplicate check here?
           if((checkDuplicate) && $('#ichat_'+contactID).css('display')!='none'){
             return;
           }
            else
           {
             IM.chatWindowsOpen++;
			 $('#activeChats').html(IM.chatWindowsOpen);
           }

		var k = 1; $('.chatbox_footer_popinchat').each(function(i,val){ if($(val).css('display')!='none'){k++;} }); 
		IM.chatWindowsOpen = k;
		$('#activeChats').html(IM.chatWindowsOpen);


        var magicPadding = 5;
        //alert(IM.chatWindowsOpen);
		var stackLeftMagicNumber = (($('#chatbox_footer_maxon').width() * (IM.chatWindowsOpen)) + (magicPadding * IM.chatWindowsOpen));
		//console.log(stackLeftMagicNumber);
		//console.log($(document).width());
		if(1==1)
		//if((stackLeftMagicNumber + 290) < $(document).width())
		{



	    var checkDuplicate = $('#ichat_'+contactID).length; // can anyone suggest a more elegant duplicate check here?
	    if(checkDuplicate){
            /* chatWindow already exists and the user is trying top open it again */
            //IM.showChatWindow('ichat_' + contactID);
            //$('#ichat_'+contactID).fadeIn(1500);
            jQuery.each($('.chatbox_popinchat_chatcontainer'), function(i, val) {
                        $(val).scrollTop($(val)[0].scrollHeight);
                   });


        }
            else
        {


		if(typeof myContacts[contactID] == 'undefined')
		{
		WS.getContacts(contactID);
		//IM.openChatWindow(contactID);
		return;
		}
		 
            //IM.chatWindowsOpen++;
                        /* having long string concat statements like this is very problematic and should not be done, this is a remant from the previous implementation */
	/* old code remants */
		var chatWindow = '<div class="chatbox_footer_popinchat" id ="'+'ichat_'+contactID+'">\
								<!-- start chatbox content -->\
	\
							<div class="chatbox_top">\
	\
	\
								<div class="chatbox_popinchat_links">\
									<div class="chatbox_popinchat_op">\
										<div class = "max">\
											<img src="' + imgPath + '/chatbox_max_white.gif">\
										</div>\
										<div class = "min">\
											<img src="' + imgPath + '/chatbox_min_white.gif">\
										</div>\
										<div class = "exit">\
											<img src="' + imgPath + '/chatbox_exit_white.gif">\
										</div>\
									<div class="chatbox_popinchat_links1"><a href="#">'+myContacts[contactID].mem_name+'</a></div>\
								</div>\
	\
								<div class="chatbox_popinchat_target">\
									<div class="chatbox_popinchat_target_pic"><a href = "/index.php?page=my_homepage&mem_id='+contactID+'"><img src="/photos/' + myContacts[contactID].photo_small + '" width="45" height="45"></a></div>\
									<div class="chatbox_popinchat_target_status">'+myContacts[contactID].my_status+'</div>\
								</div>\
							</div>\
	\						<div class="chatbox_bottom">\
								<div class="chatbox_popinchat_chatcontainer">\
									\
									\
								</div>\
	\
								<!--<div class="chatbox_popinchat_chattype">\
									How are yo|                    </div>-->\
								\
									<textarea class="chatbox_popinchat_chattype messageText" style="height:50px;"></textarea>\
								\
	\
								<!-- start chatbox content -->\
							</div>\
						</div>\
							';
		/* end old code remants */
              $('#im_container').append(chatWindow);
		 
				/* IM.renderMessages(myContacts[contactID].messages); */
		
            }

			$('#ichat_'+contactID).css('right',stackLeftMagicNumber);
            /* check if state was sent upon creation of window */
            if(typeof windowState !='undefined')
            {
                if(windowState=='Min')
                {

                    $('#' + 'ichat_' + contactID + ' .min').hide();
                    $('#' + 'ichat_' + contactID).css('top',272);
                    $('#' + 'ichat_' + contactID + ' .max').show();
                    //console.log('showmin: ', contactID);
                }

            }
            else
            {
                /* update GUI state */
                try{
                    IM.stateData[contactID] = 'Open';
                    }
                catch(err){
                    //alert(err);
                    }

                IM.saveState();
                
            }

			$('#ichat_'+contactID).show();

			//$('#ichat_'+contactID).draggable();
			$('#ichat_'+contactID +' .chatbox_popinchat_chatcontainer').scrollTop($('.chatbox_popinchat_chatcontainer')[0].scrollHeight);
		       IM.renderMessages(myContacts[contactID].messages);

			if($('#ichat_'+contactID +' .chatbox_popinchat_chatcontainer .chatbox_popinchat_chattext div').length <=1)
			  {
			
			  }
			/* if there is only one message try to re-render the messages */
			

            if(checkDuplicate==0){
				
				
				
		  /* since we are opening a new window we must retrieve previous conversation history */
      		  //console.log('opening new window');
		  //console.log('getting history');
		  //IM.lastMsg = 0;
		  //WS.longPoll.abort();
		  //WS.getMessages(false,contactID,'ignoreLast');
		  //return false;
		 

                
            } 
                        

		}
		else
		{
		    var myLimit = IM.chatWindowsOpen-1;
			//	'Based on your screen size I have determined that ' + myLimit + ' is the maximum amount of chat windows I can open. If you increase your screen size or resolution you may open more windows.');
		}
		
		
}

IM.titleBarNotify = function(titleText){
	/* document.title message notifier */
	document.title = titleText + ' ' + OGTitle; 

}

IM.renderMessages = function(messages) {
	
	
	var v = {}
	for(x in messages)
	{
		v[messages[x].mes_id] = messages[x];
	}
	
	/* try a sort */
	var b = new Array();
	for(x in messages)
	{
	 	b.push(messages[x].mes_id);
	}
	b.sort();
	var newM = {}
	for(y in b)
	{
	 	newM[y] = v[b[y]];
	}
	//console.log(newM);
	//console.log(messages);
	messages = newM;
    //if(IM.rendering==true){return IM.renderMessages(messages);}else{IM.rendering=true;}
	/* loop through each message */
	for(x in messages)
	{
		/* handle all data binding */
	    if (typeof myContacts[messages[x].sender_id]  == 'undefined')
	      {
		    myContacts[messages[x].sender_id] = new Object();
		  }
	    if (typeof myContacts[messages[x].sender_id].messages  == 'undefined')
		  {
		    myContacts[messages[x].sender_id].messages = new Object();
		  }
		if (typeof myContacts[messages[x].recipient_id] == 'undefined')
	      {
		    myContacts[messages[x].recipient_id] = new Object();
		  }
        if (typeof myContacts[messages[x].recipient_id].messages == 'undefined')
		  {
  		    myContacts[messages[x].recipient_id].messages = new Object();
		  }
		/* end data binding */

		/* if this message is a notification message I sent, this case shouldn't fire if webservice is configured correctly */
		if(messages[x].type=="a" && messages[x].sender_id == myMemberID){continue;}

		/* a notification message has been recieved */
	    if (messages[x].type == 'a' && messages[x].sender_id != myMemberID) 
	      {
		    if(messages[x].message=="Online")
			  {
			    //this indicates a user has signed online
			    /* check if user is not bound locally first */
			    if(typeof myContacts[messages[x].sender_id].mem_id == 'undefined')
			  	  {
				   									 //WS.getContacts(messages[x].sender_id);
				    //continue;
				  }
			    myContacts[messages[x].sender_id].online = "true";
			    $('#onlineFriends').html(IM.getContactCount());
			    //delete buddy from list
			    $('#imember_' + messages[x].sender_id).remove();
			    //re-render on top
			    IM.renderBuddy(messages[x].sender_id);
			    $('#imember_' + messages[x].sender_id + ' .chatbox_maxon_friendsitem_status img').attr('src',imgPath + 'chatbox_status_online.png')
		 	 }
		   else if(messages[x].message=="Offline")
			{
			  $('#imember_' + messages[x].sender_id + ' .chatbox_maxon_friendsitem_status img').attr('src',imgPath + 'chatbox_status_offline.png')
			  myContacts[messages[x].sender_id].online = "false";
			  $('#onlineFriends').html(IM.getContactCount());
			}
		  }
		/* END: a notification message has been recieved */


		if (messages[x].type == 'u') 
		  {
			var dupCheck = $('#imsg_'+messages[x].mes_id).length;
			if (dupCheck >= 1){continue;}  

			//console.log(messages[x]);
			/* replace with emoticon text */			  
  		    messages[x].message = $().emoticon(messages[x].message);

	  		/* i sent someone a message */
		    if(messages[x].sender_id == myMemberID)
			  {
				  
				   if (typeof myContacts[messages[x].recipient_id].messages == 'undefined')
				  {
	  		    myContacts[messages[x].recipient_id].messages = new Object();
				  }
				  
			    if (typeof myContacts[messages[x].recipient_id].messages[messages[x].mes_id] ==   'undefined')
			      { 
			        myContacts[messages[x].recipient_id].messages[messages[x].mes_id]  =  messages[x];
					
			      }


				 var checkDuplicate = $('#ichat_'+messages[x].recipient_id).length; // can anyone suggest a more elegant duplicate check here?
	             if(!checkDuplicate){
						if(IM.lastMsg != '')
						  {
						    $("#jpId").play();
						    IM.openChatWindow(messages[x].recipient_id);
						    continue;
							
						  }
					  
					 }


				jQuery.each($('#ichat_' + messages[x].recipient_id + '   .chatbox_popinchat_chatcontainer .chatbox_popinchat_chattext'), function(i, val) {
					if($(val).attr('id')=='')  {$(val).remove();}
	            });
			
				var theTime = messages[x].posted;
				theTime = theTime.replace(/ /,':');
				theTime = '<i>' + theTime + '</i>: ';
				theTime = '';
				$('#ichat_' + messages[x].recipient_id + '   .chatbox_popinchat_chatcontainer').append('<div class="chatbox_popinchat_chattext" id =  "imsg_'+messages[x].mes_id+'"><div  class="chatbox_popinchat_chatitemto">'+ '<strong>You</strong>: ' + theTime + '' + messages[x].message+'</div></div>');
				  
			  }
			  
			/* someone has sent me a message */
			if(messages[x].sender_id != myMemberID)
			  {
				  	   if (typeof myContacts[messages[x].sender_id].messages == 'undefined')
				  {
	  		    myContacts[messages[x].sender_id].messages = new Object();
				  }
				  
  			    if(typeof myContacts[messages[x].sender_id].messages[messages[x].mes_id] ==   'undefined')
				  {
				    myContacts[messages[x].sender_id].messages[messages[x].mes_id] = messages[x];
				  }
				 	    var checkDuplicate = $('#ichat_'+messages[x].sender_id).length; // can anyone suggest a more elegant duplicate check here?
				    	if(!checkDuplicate){
						if(IM.lastMsg != '')
						  {
						    $("#jpId").play();

						    IM.openChatWindow(messages[x].sender_id);
							
							continue;
							
						  }
					 }


				
				  if(typeof messages[x].posted == 'undefined'){continue;}
				  if(typeof myContacts[messages[x].sender_id].mem_name == 'undefined'){continue;}

				  var myName = myContacts[messages[x].sender_id].mem_name;
				  myName = myName.substring(0,myName.search(' '));
				  
				  var theTime = messages[x].posted;
			      theTime = theTime.replace(/ /,':');
				  theTime = '<i>' + theTime + '</i>: ';
				  theTime = '';
				  $('#ichat_' + messages[x].sender_id + '  .chatbox_popinchat_chatcontainer').append('<div class="chatbox_popinchat_chattext" id =  "imsg_'+messages[x].mes_id+'"><div   class="chatbox_popinchat_chatitemfrom">'+ '<strong>' + myName + '</strong>: ' + theTime+ '' + messages[x].message+'</div></div>');
				  
			  }
			
			  
			
			  
			  
			  
		  }
			  
		  }

		  /* Marak says: this is a scrollTop hack, use jQuery.scrollTo() plugin instead */
		  //$('.chatbox_popinchat_chatcontainer').scrollTop($('.chatbox_popinchat_chatcontainer')[0].scrollHeight);
		  jQuery.each($('.chatbox_popinchat_chatcontainer'), function(i, val) {
		    $(val).scrollTop($(val)[0].scrollHeight);
		  });
		  IM.rendering=false;

}

IM.getContactCount = function()
{
	var i=0;
	for(var c in myContacts)
	{
	 if(myContacts[c].online=='true')
		{
			i++;
			//console.log(myContacts[c]);
		}
	}	
	return i;
}
IM.renderBuddy = function(contactID)
{

	var myContact = myContacts[contactID];
	//console.log(myContact);
			var contactStatus = new Object();
			contactStatus.icon = 'chatbox_status_offline.gif';
			contactStatus.online = false;

			if(myContact.online=='true') 
			{
				   contactStatus.icon = 'chatbox_status_online.png';
				   contactStatus.online = true;
				   contactStatus.append = "top";
				   //try{WS.longPoll.abort();}catch(err){}
				   //WS.getMessages(false,contactID ,'ignoreLast');


			}
			else
			{
				 contactStatus.icon = 'chatbox_status_offline.png';
				 contactStatus.online = false;
				 contactStatus.append = "bottom";

				 
			}


			/* check if contact is already rendered in list */
			var dupCheck = $('#imember_'+myContact.mem_id).length;
			//console.log('status: ' + status.online + 'dupCheck: ' + dupCheck);
			if (dupCheck == 0) 
				{
				 /* old code remants */   
					res = '<div class="chatbox_maxon_friendsitem" id = "' + 'imember_' + myContact.mem_id + '">\
<div class="chatbox_maxon_friendsitem_pic"><img src="' + '/photos/' +	myContact.photo_small + '" alt="" width="25" height="25"></div>\
<div class="chatbox_maxon_friendsitem_name"><a href="#">' + myContact.mem_name + '</a></div>\
<div class="chatbox_maxon_friendsitem_status"><img src="' + imgPath + contactStatus.icon+ '" width="10" height="10"></div>\
</div>';
				  /* end old code remants */   
				  if( contactStatus.append == "top")
					{
					  $('#contacts_container').prepend(res);

					}
				  else
					{
					  $('#contacts_container').append(res);

					}
				 }
 	
}


/* END IM OBJECT */

	
/* having long string concat statements like this is very problematic and should not be done, this is a remant from the previous implementation */	

/* old code remnants*/
	var strRes = '';
	var res = '';
	
	strRes = '\
			<div id="chatbox_footer_maxon">\
				<div class="chatbox_base">\
					<div class="chatbox_maxon_pic">\
						<img src="' + thePhoto + '" alt="" width="30" height="30">\
					</div>\
					<div class="chatbox_maxon_status">\
						<a class = "chatbox_maxon_offline" href="#">Go Offline</a>\
						<a class = "chatbox_maxon_online" href="#">Go Online</a>\
					</div>\
					<div class="chatbox_maxon_graphic">\
						<img src="' + imgPath + '/chatbox_status_online.png">\
					</div>\
				</div>\
				<div class="chatbox_maxon_links">\
					<div class="chatbox_maxon_op">\
						<div class = "chatbox_title">Instant Tuesday</div>\
						<div class = "minChat"><img src="' + imgPath + '/chatbox_min_white.gif"></div>\
						<div class = "maxChat"><img src="' + imgPath + '/chatbox_max_white.gif"></div>\
						<div class = "exitChat"><img src="' + imgPath + '/chatbox_exit_white.gif"></div>\
						<div class="chatbox_maxon_links1" align = "left"></div>\
					</div>\
				</div>\
				<div class="chatbox_maxon_friends">\
					<div class="chatbox_maxon_friendson">\
						<input id = "buddySearch" name = "buddySearch" type = "text" size = "20" value = "Search your friends..."/> \
						<div class="chatbox_maxon_friendsitem_name" id="more_less_friends">\
						</div>\
					</div>\
				 	<div class="chatbox_maxon_friendslinks">\
						<div id="contacts_container" style="height:180px;overflow-y:auto;overflow-x:hidden">\
						</div>\
					</div>\
				</div>\
			</div>';
		IM.buddyList = strRes;
/* end old code remnants */
		
function Left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}


