var lastseen_poll = null;
var title_anim;

$(function() {
	checkedIds = new Array();
	id_counter = 0;	
	
	function checkNewMsg()
	{
	  $.ajax({
	    type: 'POST',
	    url : '/home/xml/lastseen_poll.php?rnd=' + Math.random(),
			dataType : 'json',
	    success: function (text) {
	
			lastseen_poll = text;
			
			// update online messages for each user
	    for( x=0; x<text.length; x++ )
	    {
	    	do_update_msg = true;
	    	user_id = text[x]['user_id'];
	    	
	    	if ( text[x]['fresh'] == 1 )
	    	{
	    		$( '#message' ) . html( text[x]['name'] + ':<br/>Nu online!' );
			  	$( '#message' ).fadeIn("slow");
			  	
			  	fader = setTimeout( function()
			  	{
			  		$( '#message' ).fadeOut("slow");
			  	}, 3000 );
			  	return;
	    	}
	    	
	    	// see if we already checked state
	    	/*
	    	for( y=0; y<checkedIds.length; y++ )
	    	{
	    		if ( checkedIds[y] == user_id )
	    		{
	    			//do_update_msg = false;
	    		}
	    	}
	    	*/
	    	
		    	if ( text[x]['unread_count'] > 0 && text[x]['newmsg'] )
		    	{
		    		if ( do_update_msg )
		    		{
			    		var bericht_str = text[x]['unread_count'] == 1 ? ' nieuw bericht' : ' nieuwe berichten';
			    		$( '#message' ) . html( '<b>' + text[x]['name'] + ':</b><br />' + text[x]['unread_count'] + bericht_str );
					  	$( '#message' ).fadeIn("slow");
					  	
              clearInterval( title_anim );
					  	titleAnim( 'klikthet - ' + text[x]['name'] + ': ' + text[x]['unread_count'] + bericht_str );
					  	
					  	checkedIds[id_counter] = text[x]['user_id'];					// mark as checked
					  	id_counter++;
					  	
					  	fader = setTimeout( function()
					  	{
					  		$( '#message' ).fadeOut("slow");
					  	}, 3000 );
					  	
			    		break;
			    	}
		    	}
		    	else 
		    	{
		    		$( '#message' ) . html( '' );
		    		$( '#message' ) . hide();
		    	}
		    	
		    	// server messages? layover (TODO)
		    	if( text[x]['server_msg'] == 'blaat' )
		    	{

							
		    	}
		    	
	
	    	}
	  	}
		});
	}
	checkNewMsg();
	
	$( '#message' ).mouseover( function(){$( '#message' ).fadeOut()} );
	
	
	new_msg = setInterval(function()
	{
		checkNewMsg();
	}, 5000 );

  function titleAnim( t )
  {
    var x = 0;

    function doAnim( t )
    {
      x++;
      document.title = (x % 2 == 0 ) ? 'klikthet - Nieuwe berichten!' : t;
    }

   	title_anim = setInterval(function()
  	{
  		doAnim( t );
  	}, 1000 );

  }

});
