/**
 * BLVDSTATUS Widget - http://www.blvdstatus.com
 * Copyright (C) 2010 BLVDSTATUS Status
 * Author: Aaron Pace
 * 
 * v 0.3 BLVDSTATUS hot topics scrolling w/share widget
 */

//no conflict with other libraries
var blvdwidgetjq = jQuery.noConflict();

BLVDSTATUS=window.BLVD||{};
// BLVD Widget
(function() {
	if( BLVDSTATUS.Widget ) { return; }
	BLVDSTATUS.WidgetCount = 0;
	BLVDSTATUS.Widget = function(options) {
		this.id = BLVDSTATUS.WidgetCount++;
		if( typeof options != 'object' ) {
			options = {};
		}
		this.options = blvdwidgetjq.extend( {}, this.defaultOptions, options );
		
		this.maxTitleLength = 38;
		this.intervalId = -1;
		this.start = 0;
		this.end = 0;
		this.content = new Array();
		this.initialized = false;
		this.pauseCount = 0;
		this.complete = false;

		var widget = this;
		blvdwidgetjq(document).ready( function() {
			widget.head = document.getElementsByTagName('head').item(0);
			widget.addCss();
			widget.init();
		} );
	};
	
	BLVDSTATUS.Widget.prototype.defaultOptions = {
			bgColor: '#28343a',
			fgColor: '#ffffff',
			title: 'Top Social Content',
			transitionOutDuration: 1000,
			transitionInDuration:  1000,
			spinDelay: 30000,
			displayCount: 5,
			reverseInitial: true
	};
	
	BLVDSTATUS.Widget.prototype.setForeground = function( color ) {
		this.options.fgColor = color;
		this.colorsChanged();
	};
	
	BLVDSTATUS.Widget.prototype.setBackground = function( color ) {
		this.options.bgColor = color;
		this.colorsChanged();
	};
	
	BLVDSTATUS.Widget.prototype.setDisplayCount = function( count ) {
		var widget = this;
		if( this.spinning ) {
			setTimeout( function() {
				widget.setDisplayCount( count );
			}, 100 );
		}
		else {
			clearTimeout( this.intervalId );
			this.options.displayCount = count;
			this.spinArticles();
		}
	};
	
	BLVDSTATUS.Widget.prototype.setSpinDelay = function( delay ) {
		var widget = this;
		if( this.spinning ) {
			setTimeout( function() {
				widget.setSpinDelay( delay );
			}, 100 );
		}
		else {
			clearTimeout( this.intervalId );
			this.options.spinDelay = delay;
			this.spinAfterDelay();
		}
	};
	
	BLVDSTATUS.Widget.prototype.setTitle = function( title ) {
		this.options.title = title;
		this.addTitle();
	};
	
	BLVDSTATUS.Widget.prototype.colorsChanged = function() {
		blvdwidgetjq( '#BLVD_BlockParty .BLVD_wtitle,' +
				   '#BLVD_BlockParty .BLVD_wtitle h2,'+
				   '#BLVD_BlockParty .BLVD_wlfooter' )
				   .css( { "background-color":this.options.bgColor, "color":this.options.fgColor } );
		blvdwidgetjq( '#BLVD_BlockParty .BLVD_wlfooter a,' +
				   '#BLVD_BlockParty .BLVD_wlfooter a:hover' )
				   .css( 'color', this.options.fgColor );
	};
	
	BLVDSTATUS.Widget.prototype.addTitle = function() {
		var titleElement = this.blockparty.parent().find( '.BLVD_wtitle h2' );
		if( titleElement.length == 0 ) {
			this.blockparty.parent().prepend( '<div class="BLVD_wtitle"><h2>' + this.options.title + '</h2></div>' );
		} else {
			titleElement.html(this.options.title);
		}
	};
	
	BLVDSTATUS.Widget.prototype.addFooter = function() {
		var widget = this.blockparty.parent();
		if( widget.find(".BLVD_wlfooter").length == 0 ) {
			widget.append('<div class="BLVD_wlfooter"><a href="http://www.blvdstatus.com/block-party.php">Block Party, by BLVD Status &raquo; Get Yours</a></div>');
		}
	};
	
	BLVDSTATUS.Widget.prototype.knownHosts = ['digg', 'twitter', 'facebook', 'delicious', 'reddit', 'stumbleupon', 'mixx', 'tipd', 'sphinn'];
	BLVDSTATUS.Widget.prototype.init = function() {
		var widget = this;
		this.blockparty = blvdwidgetjq("#BLVD_BlockParty .BLVD_wcontent");
		this.addTitle();
		this.addFooter();
		
		this.shareBox = new BLVDSTATUS.ShareBox(this);
		
		// [mb] requires jsonp
		blvdwidgetjq.ajax({
			   	url: 'http://stats.blvdstatus.com/blvdstatus/api?m=getReferrers&tid='+this.options.tid,
				type: "GET",
				dataType: 'jsonp',
				cache: false,
				//jsonpCallback: "BLVDSTATUS.Widget.getCallback",
				success: function(data) {
					widget.content = data.DATA.ROWS;
					widget.initArticles();
					widget.intervalId = setInterval( 
						function() {
							widget.spinArticles() 
						}, widget.options.spinDelay );
				}
		});		
	};
	
	BLVDSTATUS.Widget.prototype.spinAfterDelay = function( delay ) {
		clearTimeout( this.intervalId );
		var widget = this;
		if( typeof delay == 'undefined' )
			delay = widget.options.spinDelay;
		
		widget.intervalId = setTimeout( 
				function() {
					widget.spinArticles();
				},	delay );
	};
	
	BLVDSTATUS.Widget.prototype.createArticleDiv = function( idx, prepend ) {
		var article = this.content[idx];
		var domain = article.refdomain;
		var dotIdx = domain.lastIndexOf( '.' );
		if( dotIdx >= 0 ) {
			domain = domain.substring( 0, dotIdx );
		}
		var displayTitle = article.title;
		if( displayTitle.length > this.maxTitleLength ) {
			displayTitle = displayTitle.substring( 0, this.maxTitleLength-3 ) + '...';
		}
		article.domain = domain;
		var known = false;
		for( var i=0; i < this.knownHosts.length; i++ ) {
			if( this.knownHosts[i] == domain )
				known = true;
		}
		article.icon = known ? domain : 'blank'
		
		var cls = idx%2==0 ? 'even' : 'odd';
		var row = "<div class='BLVD_wrow "+cls+"' id='BLVD_warticle_" + idx + "' style=display:none;'>";
		if( article.hot ) {
			row += '<div class="BLVD_whot" />';
		}
		row += '<span class="BLVD_wltitle"><a href="'+article.url+'" target="_blank">' + displayTitle + '</a></span>';
		
		if(article.icon != "blank") {
			row += '<a class="BLVD_icon '+article.icon+'" href="'+article.refurl+'" target="_blank" />';
		}
		
		row += '<div class="BLVD_wlinks">';
		if( article.refcount > 0 ) {
			if( article.domain == 'twitter' ) {
				row += '<strong>'+article.refcount+'</strong> tweets | ';
			} else if( article.domain == 'facebook' ) {
				row += '<strong>'+article.refcount+'</strong> shares | ';
			} else if( article.domain == 'digg' ) {
				row += '<strong>'+article.refcount+'</strong> diggs | ';	
			}
		}

		if(article.icon != "blank") {
			row += 'recent visit from  '+article.icon;
		} else {
			row += 'being read right now';
		}
		
		row += ' | <span class="BLVD_wshare">Share</span></div>';
		
		row += "</div>";
		
		if( prepend ) {
			this.blockparty.prepend( row );
		} else {
			this.blockparty.append( row );
		}
		this.addShareHandlers( idx );
		//this.addPopupHandlers( this.blockparty.find("#BLVD_warticle_"+idx+" a") );
		return row;
	};
	
	BLVDSTATUS.Widget.prototype.initArticles = function() {
		// Empty spinner, add all the articles we are going to show at a time
		this.start = 0;
		this.blockparty.html('');
		for( var i=0; i < this.options.displayCount && i < this.content.length; i++ ) {
			this.createArticleDiv( i, !this.options.reverseInitial );
			this.blockparty.children( "#BLVD_warticle_"+i ).show(100);
			this.end = i;
			this.initialCount = i+1;
		}
		var count = Math.min( this.options.displayCount, this.initialCount );
		this.currentDisplayCount = count;
		var total = 51*count;
		this.blockparty.animate( {height:total}, 100 );
	};
	
	BLVDSTATUS.Widget.prototype.spinArticles = function() {
		if( this.pauseCount == 0 ) {
			this.attempted = false;
			if( this.options.displayCount != this.currentDisplayCount ) {
				this.initArticles();
				this.spinAfterDelay();
			}
			else if( this.end < this.content.length-1 ) {
				this.complete = false;
				this.spinning = true;

				// Close the share box if it is open
				this.shareBox.close();
				
				// Remove the last one and add another
				var toRemove = this.start;
				if( this.start < this.initialCount && this.options.reverseInitial ) {
					toRemove = this.initialCount - this.start - 1;
				}
				this.animateOut( toRemove );
				this.start++;
				this.end++;
			} else {
				this.complete = true;
			}
		} else {
			this.attempted = true;
		}
	};
	
	BLVDSTATUS.Widget.prototype.resume = function() {
		if( this.pauseCount > 0 ) {
			this.pauseCount--;
			if( this.attempted && this.pauseCount == 0 ) {
				this.spinAfterDelay(500);
			}
		}
	};
	
	BLVDSTATUS.Widget.prototype.pause = function() {
		this.pauseCount++;
	};
	
	BLVDSTATUS.Widget.prototype.animateOut = function( idx ) {
		var widget = this;
		this.idxOut = idx;
		var removing = this.blockparty.children( "#BLVD_warticle_"+idx );
		removing.animate( {opacity:0}, {duration:this.options.transitionOutDuration, complete:function() {
			removing.remove();
			widget.animateIn( widget.end );
		}} );
	};
	
	BLVDSTATUS.Widget.prototype.animateIn = function( idx ) {
		this.createArticleDiv(idx, true);
		var newFirst = this.blockparty.children( "#BLVD_warticle_" + idx );
		var widget = this;
		newFirst.css( 'opacity', 0 )
				.show( this.options.transitionInDuration )
				.animate( {'opacity':1}, {duration:this.options.transitionInDuration} );
		setTimeout( function() { widget.spinning = false; }, this.options.transitionInDuration );
		this.spinAfterDelay(this.options.spinDelay + this.options.transitionInDuration);
	};
	
	BLVDSTATUS.Widget.prototype.addShareHandlers = function( idx ) {
		var widget = this;
		var shareLink = this.blockparty.find("#BLVD_warticle_"+idx+" .BLVD_wshare");
		shareLink
			.click( function() {
				widget.share( widget.content[idx], idx );
			} );
		this.blockparty.find("#BLVD_warticle_"+idx)
			.mouseover( function() {
				if( widget.idxOut != idx )
					widget.pause();
			} )
			.mouseout( function() {
				widget.resume();
			} );
	};
	
	BLVDSTATUS.Widget.prototype.addRule = function( selector, rule ) {
		if( !this.stylesheet ) {
			var stylesheet = document.createElement( 'style' );
			stylesheet.type = "text/css";
			stylesheet.id = "BLVD_widgetCustomStyles";
			this.head.appendChild( stylesheet );
			
			this.stylesheet = document.styleSheets[document.styleSheets.length-1] || document.getElementById( "BLVD_widgetCustomStyles" );
		}
		
		// Internet Explorer
		if( this.stylesheet.addRule ) {
			var styles = selector.split( ',' );
			for( var i=0; i < styles.length; i++ ) {
				this.stylesheet.addRule( styles[i], rule );
			}
		}
		// Everyone else
		else {
			this.stylesheet.innerText += selector + "{" + rule + "}";
		}
	};
	
	BLVDSTATUS.Widget.prototype.addCss = function() {
		var link = document.createElement( 'link' );
		link.type = "text/css";
		link.rel = 'stylesheet';
		link.href = 'http://www.blvdstatus.com/widget/v3/widget/css/spinner.css';
		this.head.appendChild( link );
		
		this.addRule(		
				'#BLVD_BlockParty .BLVD_wtitle,' +
				'#BLVD_BlockParty .BLVD_wtitle h2,'+
				'#BLVD_BlockParty .BLVD_wlfooter',
					'background:'+ this.options.bgColor +';' +
					'color:' + this.options.fgColor + ';' );
		this.addRule(
				'#BLVD_BlockParty .BLVD_wlfooter a,' +
				'#BLVD_BlockParty .BLVD_wlfooter a:hover',
					'color:' + this.options.fgColor +';' );
	};
	
	BLVDSTATUS.Widget.prototype.share = function( article, idx ) {
		this.shareBox.open( idx );
	};
})();

// BLVD Share Box
(function() {
	if( BLVDSTATUS.ShareBox ) { return; }
	BLVDSTATUS.ShareBox = function( widget ) {
		this.widget = widget;
		this.div = blvdwidgetjq("#BLVD_wShareBox");
		if( this.div.length > 0 ) { return; }
		var body = blvdwidgetjq("body");
		body.append( 
			'<div id="BLVD_wShareBox" style="display:none; position:absolute; top:0px; left:0px;">' +
				'<div class="BLVD_wtitle"><span class="BLVD_icon close">X</span><h2>Share on:</h2></div>' +
				'<table>' +
					'<tr>' +
						'<td nowrap="nowrap" class="BLVD_wShareLink"><span class="BLVD_icon digg"/>Digg</td>' +
						'<td nowrap="nowrap" class="BLVD_wShareLink"><span class="BLVD_icon twitter"/>Twitter</td>' +
						'<td nowrap="nowrap" class="BLVD_wShareLink"><span class="BLVD_icon facebook"/>Facebook</td>' +
					'</tr>' +
					'<tr>' +
						'<td nowrap="nowrap" class="BLVD_wShareLink"><span class="BLVD_icon delicious"/>Del.icio.us</td>' +
						'<td nowrap="nowrap" class="BLVD_wShareLink"><span class="BLVD_icon reddit"/>Reddit</td>' +
						'<td nowrap="nowrap" class="BLVD_wShareLink"><span class="BLVD_icon stumbleupon"/>StumbleUpon</td>' +
					'</tr>' +
					'<tr>' +
						'<td nowrap="nowrap" class="BLVD_wShareLink"><span class="BLVD_icon mixx"/>Mixx</td>' +
						'<td nowrap="nowrap" class="BLVD_wShareLink"><span class="BLVD_icon tipd"/>Tip\'d</td>' +
						'<td nowrap="nowrap" class="BLVD_wShareLink"><span class="BLVD_icon sphinn"/>Sphinn</td>' +
					'</tr>' +
				'</table>' +
			'</div>' );
		this.div = blvdwidgetjq("#BLVD_wShareBox");
		var box = this;
		blvdwidgetjq("#BLVD_wShareBox .close").click( function() {
			box.close();
		});
		this.width = 310;
		this.addClickHandlers();
	};
	
	BLVDSTATUS.ShareBox.prototype.addClickHandlers = function() {
		var box = this;
		this.div.find(".BLVD_wShareLink").click( function() {
			var popup_options = {};
			var title = escape( box.article.title );
			var url = escape( box.article.url );
			var icon = blvdwidgetjq(this).find(".BLVD_icon");
			if( icon.hasClass("digg") ) {
				popup_options.windowURL = "http://digg.com/submit?url="+url+"&title="+title;
				popup_options.windowName = "digg";
			} else if( icon.hasClass("twitter") ) {
				var text = "";
				var separator = " | ";
				var title_len = 140-(box.article.url.length+separator.length);
				if( box.article.title.length > title_len ) {
					title = escape(box.article.title.substring(0, title_len-3) + "...");
				}
				text = title + escape(separator) + url;
				popup_options.windowURL = "http://twitter.com/home?status="+text;
				popup_options.windowName = "twitter";
			} else if( icon.hasClass("facebook") ) {
				popup_options.windowURL = "http://www.facebook.com/sharer.php?&u="+url+"&t="+title;
				popup_options.windowName = "facebook";
			} else if( icon.hasClass("delicious") ) {
				popup_options.windowURL = "http://del.icio.us/post?v=4&url="+url+"&title="+title;
				popup_options.windowName = "delicious";
			} else if( icon.hasClass("reddit") ) {
				popup_options.windowURL = "http://reddit.com/submit?&url="+url+"&title="+title;
				popup_options.windowName = "reddit";
			} else if( icon.hasClass("stumbleupon") ) {
				popup_options.windowURL = "http://www.stumbleupon.com/submit?&url="+url+"&title="+title;
				popup_options.windowName = "stumbleupon";
			} else if( icon.hasClass("mixx") ) {
				popup_options.windowURL = "http://www.mixx.com/submit?page_url="+url;
				popup_options.windowName = "mixx";
			} else if( icon.hasClass("tipd") ) {
				popup_options.windowURL = "http://tipd.com/submit.php?url="+url;
				popup_options.windowName = "tipd";
			} else if( icon.hasClass("sphinn") ) {
				// TODO: looks like sphinn is broken right now ...
				//alert("Sorry, Sphinn's posting service is temporarily broken.");
				//return;
				popup_options.windowURL = "http://sphinn.com/submit.php?url="+url;
				popup_options.windowName = "sphinn";
			}
			
			//[mb] normal popup
			window.open(popup_options.windowURL);
		});
	};
	
	BLVDSTATUS.ShareBox.prototype.open = function( idx ) {
		this.widget.pause();
		this.idx = idx;
		this.article = this.widget.content[idx];
		var shareLink = blvdwidgetjq("#BLVD_warticle_"+idx+" .BLVD_wshare");
		var offset = shareLink.offset();
		offset.top += shareLink.height();
		var pageWidth = blvdwidgetjq(window).width();
		if( offset.left + this.width > pageWidth-10 ) {
			offset.left = pageWidth-10-this.width;
		}
		this.div.css({top:offset.top,left:offset.left});
		this.div.find("table").css('width', this.width);
		this.div.show();
	};
	
	BLVDSTATUS.ShareBox.prototype.close = function() {
		this.widget.resume();
		this.div.hide();
	};
})();