/****************************************************************************************
*   Project  : beije.fi
*   Type     : javascript prototype
*   File     : socialplugin.prototype.js
*	Requires : rssparser.prototype.js
*
*	Usage	 :
*	// Create object
*	social = new Socialplugin();
*	// Specify an inline object with a name (identifier), url (url to feed), tagname 
*	// (what the tagname is for the items in the feed)
*	social.set( 'feed', { 'identifier':'MyRssFeed', 'url':'www.example.com/rss', 'tag':'item' } );
*	// If you want to remove a word from each item, set it here
*	social.set( 'removeword', 'SOMEWORD');
*	// Specify how long you want the title to be
*	social.set( 'linelength', 40);
*	// How many items it should publish, zero being all
*	social.set( 'publishamount', 0);
*	// Destination, where you want the table appended, set id of destination
*	social.set( 'destination', 'mydiv');
*	// Build the table
*	social.build();
*
****************************************************************************************/

function Socialplugin()
{
	this.feeder = new Array();
	this.feeds = new Array();
	this.feeddata = new Array();
	this.combined = new Array();
	this.timestamps = new Array();
	this.combined = new Array();
	this.removeword = '';
	this.linelength = 20;
	this.publishamount = 0;
	this.destination = document.body;
	this.randomizedid = Math.random()*100000000;
	this.useicons = false;
	this.usesource = false;
	this.showdate = true;
	this.sourceurls = new Array();
	this.done = false;
}

Socialplugin.prototype.set = function( type, value )
{
	switch( type )
	{
		case 'feed':
			this.feeds.push(value);
		break;
		
		case 'removeword':
			this.removeword = String(value);
		break;	
		
		case 'linelength':
			this.linelength = value;
		break;
		
		case 'publishamount':
			this.publishamount = value;
		break;
		
		case 'destination':
			this.destination = document.getElementById( value );
		break;
		
		case 'useicons':
			this.useicons = ( value ? true : false );
		break;	
		
		case 'usesource':
			this.usesource = ( value ? true : false );
		break;	
		
		case 'showdate':
			this.showdate = ( value ? true : false );
		break;		
		
		case 'publish':
			this.publishtable = ( value ? true : false );
		break;
	}

}

Socialplugin.prototype.checkfeeds = function()
{
	this.feedsparsed = 0;
	
	for( this.i = 0; this.i < this.feeds.length; this.i++ )
	{
		if( this.feeder[this.i].complete == true )
		{
			if( this.feedparsed[this.i] == false )
			{
				this.feeddata[this.i]['data'] = this.feeder[this.i].parse();

			}
		
			this.feedsparsed++;
			this.feedparsed[this.i] = true;
			
		}
	}
	
	if( this.feedsparsed == this.feeds.length )
	{
		clearInterval( this.feedtimer );
		this.combine();
		this.rebuilddata();
		this.sortdata();
		
		if( this.publishtable )
		{
			this.publish();
			this.cleanup();
		}
	}
}

Socialplugin.prototype.parse = function()
{
	this.feedloaded = new Array();
	this.feedparsed = new Array();
	this.feedtimer = 0;
	
	for( this.i = 0; this.i < this.feeds.length; this.i++ )
	{
		this.feedloaded[this.i] = false;
		this.feedparsed[this.i] = false;
		this.feeddata[this.i] = new Array();
		this.feeddata[this.i]['identifier'] = this.feeds[this.i]['identifier'];
		this.feeddata[this.i]['data'] = new Array();
		
		this.sourceurls[this.feeds[this.i]['identifier']] = this.feeds[this.i]['sourceurl'];
		
		this.feeder[this.i] = new Rssparser();
		this.feeder[this.i].set('url', this.feeds[this.i]['url']);
		this.feeder[this.i].set('identifier', this.feeds[this.i]['identifier']);
		this.feeder[this.i].set('usetag', this.feeds[this.i]['tag']);
		this.feeder[this.i].set('useproxy', false);
		this.feeder[this.i].fetch();
		
		this.set_status( 'Loading feed: '+this.feeds[this.i]['identifier'] );
		
	}
	
	this.feedtimer = setInterval( this.checkfeeds.bind( this ), 100 );
	
	this.set_status( 'Initialized.' );

}

Socialplugin.prototype.combine = function()
{
	this.set_status( 'Combining datasets.' );

	this.combined = new Array();
	
	for( this.i = 0; this.i < this.feeddata.length; this.i++ )
	{
		this.combined = this.combined.concat( this.feeddata[this.i]['data'] );
	}
	
	this.set_status( 'Done combining.' );
	
	return true;
}


Socialplugin.prototype.rebuilddata = function()
{

	this.set_status( 'Rebuilding data.' );
	this.timestamps = new Array();
	
	for( this.i = 0; this.i < this.combined.length; this.i++ )
	{

		this.timestamps[this.i] = new Array();

		if( this.combined[this.i]['pubdate'] ||this.combined[this.i]['RSSPARSER_ID'] == 'twitter' )
		{
			this.timestamp = new Date( this.combined[this.i]['pubdate'] )
			this.combined[this.i]['timestamp'] = (this.timestamp.getTime());
			this.combined[this.i]['date'] = this.timestamp.getUTCMonth()+' / '+this.timestamp.getUTCDate()+' - '+this.timestamp.getUTCHours()+':'+this.timestamp.getUTCMinutes();
			this.combined[this.i]['dateonly'] = ( this.timestamp.getUTCDate() < 10 ? '0'+this.timestamp.getUTCDate() : this.timestamp.getUTCDate() )+'.'+(this.timestamp.getUTCMonth()+1)+'.'+this.timestamp.getUTCFullYear();
			this.timestamps[this.i][0] = this.combined[this.i]['timestamp'];
			this.timestamps[this.i][1] = this.i;

		}
		else if( this.combined[this.i]['RSSPARSER_ID'] == 'flickr' )
		{
			this.timestamp = new Date( this.combined[this.i]['published'] )
			this.combined[this.i]['timestamp'] = (this.timestamp.getTime());
			this.combined[this.i]['pubdate'] = this.combined[this.i]['published'];
			this.combined[this.i]['date'] = this.timestamp.getUTCMonth()+' / '+this.timestamp.getUTCDate()+' - '+this.timestamp.getUTCHours()+':'+this.timestamp.getUTCMinutes();
			this.combined[this.i]['dateonly'] = ( this.timestamp.getUTCDate() < 10 ? '0'+this.timestamp.getUTCDate() : this.timestamp.getUTCDate() )+'.'+(this.timestamp.getUTCMonth()+1)+'.'+this.timestamp.getUTCFullYear();
			this.timestamps[this.i][0] = this.combined[this.i]['timestamp'];
			this.timestamps[this.i][1] = this.i;
			
			if( typeof(this.combined[this.i]['link']) != 'undefined' )
			{
				this.combined[this.i]['link'] = String( this.combined[this.i]['link'].attributes['href'].nodeValue );
			}
		}
		else if( this.combined[this.i]['RSSPARSER_ID'] == 'xbox live' )
		{
			this.timestamp = new Date( this.combined[this.i]['lastplayed']*1000 )
			this.combined[this.i]['timestamp'] = (this.timestamp.getTime());
			this.combined[this.i]['pubdate'] = this.combined[this.i]['lastplayed'];
			this.combined[this.i]['date'] = this.timestamp.getUTCMonth()+' / '+this.timestamp.getUTCDate()+' - '+this.timestamp.getUTCHours()+':'+this.timestamp.getUTCMinutes();
			this.combined[this.i]['dateonly'] = ( this.timestamp.getUTCDate() < 10 ? '0'+this.timestamp.getUTCDate() : this.timestamp.getUTCDate() )+'.'+(this.timestamp.getUTCMonth()+1)+'.'+this.timestamp.getUTCFullYear();
			this.timestamps[this.i][0] = this.combined[this.i]['timestamp'];
			this.timestamps[this.i][1] = this.i;
			this.combined[this.i]['title'] = 'Played '+this.combined[this.i]['title'];
			this.combined[this.i]['link'] = String( this.combined[this.i]['marketplaceurl'] );

		}
		else
		{
			this.timestamps[this.i][0] = 0;
			this.timestamps[this.i][1] = this.i;
		}
		
		if( this.removeword != '' )
		{
			if( typeof(this.combined[this.i]['title']) != 'undefined' )
			{
				this.combined[this.i]['title'] = this.combined[this.i]['title'].split( this.removeword ).join('');
			}
		}
		
		if( typeof(this.combined[this.i]['title']) != 'undefined' )
		{
			if( this.combined[this.i]['title'].split('').length > this.linelength )
			{
				this.combined[this.i]['short_title'] = this.combined[this.i]['title'].substring(0, this.linelength)+'..';
			}
			else
			{
				this.combined[this.i]['short_title'] = this.combined[this.i]['title'];
			}
		}
	
	}
	
	this.set_status( 'Done rebuilding.' );

}

Socialplugin.prototype.sortdata = function()
{

	this.set_status( 'Sorting data according to timestamp.' );

	this.timestamps.sort((function(index){
		return function(a, b){
			return (a[index] === b[index] ? 0 : (a[index] < b[index] ? -1 : 1));
		};
	})(0));

	this.tempfeeds = new Array();

	for( this.i = 0; this.i < this.timestamps.length; this.i++ )
	{
		this.tempfeeds[this.i] = this.combined[this.timestamps[this.i][1]];
	}

	this.tempfeeds = this.tempfeeds.reverse();
	this.combined = this.tempfeeds;
	
	if( !this.publishtable )
	{
		this.done = true;
	}
	this.set_status( 'Sort done.' );

}

Socialplugin.prototype.fetchdata = function()
{
	return this.combined;
}

Socialplugin.prototype.publish = function()
{

	this.set_status( 'Publishing. Amount of items '+this.combined.length );

	if( this.publishamount == 0 || this.publishamount > this.combined.length || this.publishamount < 0 )
	{
		this.publishamount = this.combined.length;
	}
	
	for( this.i = 0; this.i < this.publishamount; this.i++ )
	{
		this.set_status( 'Publshing item '+this.i );
		row = document.createElement( 'tr' );
		
		if( this.showdate )
		{
			datecell = document.createElement( 'td' );
			datecell.className = 'date';
			datecell.innerHTML = this.combined[this.i]['dateonly'];
			row.appendChild( datecell );
		}
		
		if( this.useicons && this.usesource != true )
		{
			logocell = document.createElement( 'td' );
			logocell.className = 'icon';
			logocell.innerHTML = '<img src="gfx/small_icons/'+this.combined[this.i]['RSSPARSER_ID']+'.jpg" title="'+this.combined[this.i]['RSSPARSER_ID']+'" style="margin-top:4px;" />';
		}
		
		cell = document.createElement( 'td' );
		cell.innerHTML = '<a href="'+this.htmlentities(this.combined[this.i]['link'])+'" title="'+this.htmlentities(this.combined[this.i]['title'])+'">'+this.htmlentities(this.combined[this.i]['short_title'])+'</a>';
		
		if( this.usesource && this.useicons )
		{
			cell.innerHTML += ' from '+'<img src="gfx/small_icons/'+this.combined[this.i]['RSSPARSER_ID']+'.jpg" title="'+this.combined[this.i]['RSSPARSER_ID']+'" style="display:inline-block; vertical-align:middle; margin-top:-4px;" />';
		}
		if( this.usesource && !this.useicons )
		{
			cell.innerHTML += ' from <a style="text-transform:capitalize" href="'+this.sourceurls[this.combined[this.i]['RSSPARSER_ID']]+'">'+this.combined[this.i]['RSSPARSER_ID']+'</a>';
		}
		
		
		if( this.useicons && this.usesource != true )
		{
			row.appendChild( logocell );
		}
		else
		{
			cell.setAttribute('colspan','2');
		}
		row.appendChild( cell );
		document.getElementById( 'feed_'+this.randomizedid ).appendChild( row );
		
	}
	
	this.done = true;
	
	this.set_status( 'Complete' );
}


Socialplugin.prototype.buildhtml = function()
{
	sptable = document.createElement('table');
	sptable.id = 'feed_'+this.randomizedid;
	sptable.className = 'socialplugintable';
	sptable.setAttribute('cellspacing', '0');
	sptable.setAttribute('cellpadding', '0');

	
	tablebody = document.createElement('tbody');
	
	firstrow = document.createElement('tr');
	
	statuscell = document.createElement('td');
	statuscell.setAttribute('colspan', '2');
	statuscell.id = 'current_status_'+this.randomizedid;
	statuscell.style.textAlign = 'center';
	statuscell.colspan = '2';

	firstrow.appendChild( statuscell );
	sptable.appendChild( firstrow );
	this.destination.appendChild( sptable );
}

Socialplugin.prototype.cleanup = function()
{
	document.getElementById('current_status_'+this.randomizedid).parentNode.parentNode.removeChild( document.getElementById('current_status_'+this.randomizedid).parentNode );
}

Socialplugin.prototype.build = function()
{
	if( this.publishtable )
	{
		this.buildhtml();
	}
	
	this.parse();
}

Socialplugin.prototype.htmlentities = function( txt ) 
{
	if( typeof(txt) == 'undefined' )
	{
		return '';
	}
	
	txt = txt.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
	return txt;
}

Socialplugin.prototype.set_status = function( msg )
{
	if( this.publishtable )
	{
		document.getElementById('current_status_'+this.randomizedid).innerHTML = msg;
	}
}

