

var RodocsContacts = function()
{
	var that = this,
		container,
		online,
		offline,
		contacts = null,
		enableBubbles = true,
		enableListing = true;
	
	function makeList( heading )
	{
		var caption = document.createElement( 'h4' );
		caption.appendChild( document.createTextNode( heading ) );
		var listing = document.createElement( 'ul' );
		
		container.appendChild( caption );
		container.appendChild( listing );
		
		return listing;
	}
	
	function create()
	{
		//console.log( 'creating RodocsContacts listing' );

		container = document.createElement( 'div' );
		container.className = 'contactlist scrollFixed';
		
		var t = document.createElement( 'h3' );
		t.appendChild( document.createTextNode( 'Meine Freunde' ) );
		container.appendChild( t );
		
		online = makeList( 'Online' );
		offline = makeList( 'Offline' );

		jQuery('#contactList').replaceWith( jQuery(container) );

		//console.log( 'creating RodocsContacts listing - DONE' );
	}
	
	function redraw( newContacts )
	{
		//console.log( 'redrawing RodocsContacts' );
		if( enableListing && (!container || !online || !offline) )
			create();

		var diff = { online:[], offline:[], initial:true }, 
			ustate = {};

		if( newContacts )
		{
			if( contacts && contacts.length )
			{
				diff.initial = false;
				
				for( var i=0, contact; contact = contacts[i]; i++ )
					ustate[ contact.name ] = contact.online;
			}
			
			contacts = newContacts;
			storage.set( 'contacts', contacts );
			storage.set( 'contactsUpdate', (new Date()).getTime() );
		}
		
		if( enableListing )
		{
			// remove previous items
			while( online.hasChildNodes() )
				online.removeChild( online.childNodes[0] );
		
			// remove previous items
			while( offline.hasChildNodes() )
				offline.removeChild( offline.childNodes[0] );	
		}
		
		for( var i=0, contact; contact = contacts[i]; i++ )
		{	
			if( contact.online && !ustate[ contact.name ] )
				diff.online.push( contact );
			else if( !contact.online && ustate[ contact.name ] )
				diff.offline.push( contact );
		
			if( enableListing )
			{
				var item = document.createElement( 'li' ),
					link = document.createElement( 'a' );

				link.appendChild( document.createTextNode( contact.name ) );
				link.href = contact.uri;
			
				item.appendChild( link );
				if( contact.online )
					online.appendChild( item );
				else
					offline.appendChild( item );
			}
		}
		
		if( !enableBubbles )
			return;
		
		if( !diff.initial && diff.online.length > 4 )
		{
			if( typeof(RodocsBubble) != 'undefined'  )
				new RodocsBubble( '<p><a href="'+ RS.user.uri +'/kontakte/freunde">Zu meinen Freunden</a></p>', diff.online.length + ' Freunde online', 'contact', '/styles/default/img/bubbles/contacts.png' );
		}
		else if( !diff.initial && diff.online.length > 0 )
		{
			for( var i=0, user; user = diff.online[i]; i++ )
			{
				if( typeof(RodocsBubble) != 'undefined'  )
					new RodocsBubble( '<p><a href="'+ user.uri + '">'+ user.name + '</a> kam gerade online</p>', user.name , 'contact', user.avatar.small );
			}
		}
	}
	
	this.refresh = function()
	{
		//console.log( 'refreshing RodocsContacts' );
		
		if( typeof( RS ) == 'undefined' || typeof( RS.user ) == 'undefined' || typeof( RS.user.name ) == 'undefined' )
		{
			//console.log( 'RodocsContacts aborted since handling guest here' );
			return;
		}
		
		if( typeof( RS ) == 'undefined' || typeof( RS.primary ) == 'undefined' || !RS.primary )
		{
			//console.log( 'RodocsContacts aborted since handling secondary window here' );
			return;
		}
		
		var xhr;
		xhr = jQuery.getJSON(
			RS.user.uri +'/kontakte/freunde?format=json&ident=' + storage.get('ident'),
			function( data )
			{
				// show error Bubble
				// terminate interval if session transparently died
				if( xhr.status != 200 )
				{
					if( typeof(RodocsBubble) != 'undefined'  )
						RodocsBubbles.ajaxError( xhr );
					
					return;
				}
				
				redraw( data );
				window.setTimeout( function(){ that.refresh(); }, 120000 );
			} 
		);
	};
	
	this.getAll = function()
	{
		return contacts;
	};
	
	this.fill = function( select, grouped )
	{
		// come back later if data has not been loaded yet
		if( contacts === null )
		{
			window.setTimeout( function(){ that.fill( select, grouped ); }, 500 );
			return;
		}
		
		var $select = jQuery( select );
		
		if( !grouped )
		{
			jQuery.each( contacts, function( o )
			{
				$select.append( jQuery( '<option value="'+ this.id +'">'+ this.name +'</option>' ) ); 
			} );
		}
		else
		{
			var groups = [
				{ group: jQuery( '<optgroup label="Online">' ).appendTo( $select ), list: online },
				{ group: jQuery( '<optgroup label="Offline">' ).appendTo( $select ), list: offline }
			];
			
			jQuery.each( groups, function( g )
			{
				var group = this.group;
				jQuery.each( this.list, function( o )
				{
					group.append( jQuery( '<option value="'+ this.id +'">'+ this.name +'</option>' ) ); 
				} );
			} );
		}
	};
	
	this.initialize = function( bubbles, listing )
	{
		//console.log( 'initializing RodocsContacts' );

		if( typeof( RS ) == 'undefined' || typeof( RS.primary ) == 'undefined' || !RS.primary )
		{
			//console.log( 'RodocsContacts aborted since handling secondary window here' );
			return;
		}
		
		if( typeof( RS ) == 'undefined' || typeof( RS.user ) == 'undefined' || typeof( RS.user.name ) == 'undefined' )
		{
			//console.log( 'RodocsContacts aborted since handling guest here' );
			return;
		}
		
		enableBubbles = !bubbles;
		enableListing = jQuery('#contactList').length && !listing;

		contacts = storage.get( 'contacts' );
		var lastUpdate = storage.get( 'contactsUpdate' ),
			nextUpdate;

		if( lastUpdate )
		{
			nextUpdate = lastUpdate - (new Date()).getTime() + 120000;
			
			if( nextUpdate > 0)
			{
				redraw();
				window.setTimeout( function(){ that.refresh(); }, nextUpdate );
				//console.log( 'RodocsContacts scheduled to run in ', nextUpdate / 1000, 'seconds' );
				//console.log( 'RodocsContacts aborted since timeout not reached yet' );
				return;
			}
		}
		
		that.refresh();
		//console.log( 'initializing RodocsContacts - DONE' );
	};
}

// load when DOM ready
jQuery( function(){ RodocsContacts = new RodocsContacts(); RodocsContacts.initialize( ) } );