if (typeof UNRULY_VVC_WIDGET_COUNTER == "undefined") {
	UNRULY_VVC_WIDGET_COUNTER = 0;
}

var ViralVideoChart = function(config, showId) { 
	
	UNRULY_VVC_WIDGET_COUNTER++;
	
	this.WIDGET_ID = UNRULY_VVC_WIDGET_COUNTER;	

	if (typeof showId != "undefined") {
		this.divId = showId;
	}
	else {
		document.write('<div id="vvc_widget_' + this.WIDGET_ID + '"></div>');
		this.divId = "vvc_widget_" + this.WIDGET_ID;
	}
	
	this.SITE_URL = "http://www.viralvideochart.com";
	this.FEED_PARAM = "format=atomW";

	this.allFeeds = new Array("/", "/2006/overall", "/2006/homemade", "/2006/adverts", "/2006/news", "/2006/funny", "/2006/xmas", "/2006/celebrity", "/2006/drunk");
	this.feedPointer = 0;
	this.feed = null;

	this.numberToShow = -1;
	this.req = false;
	this.fixedHeight = false;
	this.width = 160;
	this.height = 200;
	this.showThumbnails = true;
	this.thumbnailScale = 0.5;
	this.useCssClass = false;
	this.fontSize = "10px";
	this.fontColor = "";
	this.titleFontSize = "12px";
	this.fontFamily = "verdana";
	this.background = "white";
	this.entrySpacing = "1";
	this.showChartPos = true;
	this.numbersOnThumb = false;
	this.numberPattern = "$num. ";
	this.currentStart = 0;
	this.title = "";
	this.hoverBackground = "#DDD";
	this.ruleColor = "#DDD";
	this.lightbox = false;
	this.version = 1;
	this.chartUrl = "http://www.viralvideochart.com/";

	if (typeof(config) != "undefined") {
		if (typeof(config.feedUrl) != "undefined") {
			var found = false;
			for (var i = 0; i < this.allFeeds.length; i++) {
				if (config.feedUrl == this.allFeeds[i]) {
					this.feedPointer = i;
					found = true;
					break;
				}
			}
			if (!found) {
				this.feedPointer = this.allFeeds.length;
				this.allFeeds[this.allFeeds.length] = config.feedUrl;
			}
		}

		if (typeof(config.height) != "undefined") {
		      this.height = config.height;
		      this.fixedHeight = true;
		}

		var opts = new Array(
			"numberToShow", "showThumbnails", "width", "fontSize", "fontFamily", "background", "useCssClass",
			"entrySpacing", "showChartPos", "numbersOnThumb", "numberPattern", "thumbnailScale", "title",
			"titleFontSize", "hoverBackground", "SITE_URL", "fontColor", "ruleColor", "lightbox", "version", "chartUrl"
		);

		for (var i = 0; i < opts.length; i++) {
			var opt = opts[i];

			var confOption = eval("config." + opt);
			if (typeof(confOption) != "undefined") {
				if (ViralVideoChart.VVCIsNumeric(confOption))
					eval("this." + opt + " = " + confOption + " * 1");
				else {
					if (typeof(confOption) == "boolean" || confOption == "true" || confOption == "false")
						eval("this." + opt + " = " + confOption);
					else
						eval("this." + opt + " = \"" + confOption + "\"");
				}
			}
		}

		if (this.ruleColor == "") this.ruleColor = "#DDD";
	}
	
	if((typeof window.XMLHttpRequest == 'undefined') && (typeof ActiveXObject != 'undefined')) {
		this.lightbox = false;
	}
	
	this.renderInterface = function() {
		var s = "";
		s += '<img src="' + ViralVideoChart.RESOURCES_URL + '/spinner.gif" id="vvc_spinner_' + this.WIDGET_ID + '" style="display:none; float: right"/>';
		s += '<div id="vvc_title_' + this.WIDGET_ID + '" style="' + this.getCssProperty("color", "fontColor") + ' font-size: ' + this.titleFontSize + '; font-weight: bold; text-align: center; border-bottom: solid ' + this.ruleColor + ' 2px; padding-bottom: 4px">' + this.title + '</div>';
		s += '<div id="vvc_feed_display_' + this.WIDGET_ID + '"></div>';
		s += '<div style="padding: 2px 2px 5px 2px; text-align: right">';
		s += '  <span id="vvc_prev_' + this.WIDGET_ID + '"></span><span id="vvc_next_' + this.WIDGET_ID + '"></span>';
		s += '</div>';
		s += '<div style="text-align: center;">';
		s += '<div style="border-top: solid ' + this.ruleColor + ' 1px; border-bottom: solid ' + this.ruleColor + ' 1px; padding: 4px;' + (document.all ? 'padding-bottom:8px' : '') + '">';
		s += '  <div style="float: left; width: 32%">';
		s += '	  <a href="' + this.SITE_URL + '/" style="text-decoration: none"><img src="' + ViralVideoChart.RESOURCES_URL + '/favicon.png" style="display:inline; vertical-align: middle; border: 0"></a>';
		if (this.width <= 180) s += '<br/>';
		s += '    <a href="' + this.SITE_URL + '/" style="' + this.getCssProperty("color", "fontColor") + '">Videos</a>';
		s += '  </div>';

		s += '  <div style="float: left; width: 32%">';
		s += '	  <a href="' + this.SITE_URL + '/?format=atom" style="text-decoration: none"><img src="' + ViralVideoChart.RESOURCES_URL + '/feed.gif" style="display:inline; vertical-align: middle; border: 0"></a>';
		if (this.width <= 180) s += '<br/>';
		s += '    <a href="' + this.SITE_URL + '/?format=atom" style="' + this.getCssProperty("color", "fontColor") + '">Feed</a>';
		s += '  </div>';

		s += '  <div style="float: left; width: 32%">';
		s += '	  <a href="' + this.SITE_URL + '/?format=widget" style="text-decoration: none"><img src="' + ViralVideoChart.RESOURCES_URL + '/cog.gif" style="display:inline; vertical-align: middle; border: 0"></a>';
		if (this.width <= 180) s += '<br/>';
		s += '    <a href="' + this.SITE_URL + '/?format=widget" style="' + this.getCssProperty("color", "fontColor") + '">Widget</a>';
		s += '  </div>';
		s += '  <br style="clear: left"/>';
		s += '</div>';
		s += '</div>';
		
		if (typeof this.version != "undefined" && parseInt(this.version) > 1) {
			s += '<div style="padding: 0 2px 2px 2px; color: #333; font-size: 11px; font-family: Verdana, serif">Source: <a href="'+ this.chartUrl +'" style="font-size: 11px; font-family: Verdana, serif">Viral Video Chart</a>: Powered by <a href="http://www.unrulymedia.com/" style="font-size: 11px; font-family: Verdana, serif">Unruly</a></div>';
		}

		return s;
	}

	this.getCssProperty = function(style, name) {
		var prop = eval("this." + name);
		return (prop == null || prop == "") ? '' : style + ": " + prop + ";";
	};

	this.applyJSFunctions = function() {
		var thiss = this;
		var prevA = document.getElementById('vvc_prev_a_' + this.WIDGET_ID);
		if (prevA != null) prevA.onclick = function() {thiss.showPreviousX(); return false;}

		var nextA = document.getElementById('vvc_next_a_' + this.WIDGET_ID);
		if (nextA != null) nextA.onclick = function() {thiss.showNextX(); return false;}
		
		if (this.lightbox) {
			if (typeof UNRULY != "undefined" && typeof UNRULY.jq != "undefined") {
				UNRULY.jq('td.unruly_lightbox_widget_link').each(function() {
					UNRULY.jq(this).click(function() {
						var url = UNRULY.jq(this).attr("data-vvc-url");
						__unruly_urlToLoad.url = url;
						UNRULY.jq("embed, object, iframe").css("visibility", "hidden");
						UNRULY.jq('#_unruly_vvc_widget_lighbox').trigger("vvc_click.fb");
						return false;
					});
				});
			}
		}
	};

	this.renderTableTemplate = function(feed) {
		var el = document.getElementById('vvc_feed_display_' + this.WIDGET_ID);
		var oldTable = el.getElementsByTagName("table");
		if (oldTable.length > 0) el.removeChild(oldTable[0]);

		var table = document.createElement("table");
		table.setAttribute("width", "100%");
		table.setAttribute("cellspacing", "0");
		table.setAttribute("cellpadding", "1");

		if (!this.useCssClass) {
			table.setAttribute("style", '' + this.getCssProperty("color", "fontColor") + ' font-size: ' + this.fontSize + '; font-family:' + this.fontFamily);
			table.style.color = this.fontColor;
			table.style.fontSize = this.fontSize;
			table.style.fontFamily = this.fontFamily;
		}

		var tbody = document.createElement("tbody");
		table.appendChild(tbody);

		var spacing = Math.round(this.entrySpacing / 2);

		var thiss = this;
		for (var i = this.currentStart; i < feed.entries.length; i++) {
			if (this.numberToShow != -1 && i >= this.currentStart + this.numberToShow) break;
			var entry = feed.entries[i];

			var tr = document.createElement("tr");
			tbody.appendChild(tr);
			tr.onmouseover = function() {this.style.background = thiss.hoverBackground};
			tr.onmouseout = function() {this.style.background = thiss.background};
			tr.style.margin = 0;
			tr.style.padding = 0;
			tr.setAttribute("style", "cursor: pointer");

			if (this.showThumbnails) {
				var td1 = document.createElement("td");
				tr.appendChild(td1);

				td1.setAttribute("style", "padding: " + spacing + "px 0 " + spacing + "px 0");
				td1.style.paddingTop = spacing + "px";
				td1.style.paddingBottom = spacing + "px";
				td1.setAttribute("valign", "middle");
				td1.align = "center";
				td1.style.margin = 0;
				td1.style.verticalAlign = "middle";
				var divRel = document.createElement("div");
				divRel.setAttribute("style", "position: relative");
				divRel.style.position = "relative";
				td1.appendChild(divRel);
				
				td1.setAttribute("class", "unruly_lightbox_widget_link");
				td1.className = "unruly_lightbox_widget_link";
				td1.setAttribute("data-vvc-url", entry.link + "&mode=iframe&widget=true&v3");

				var a1 = document.createElement("a");
				divRel.appendChild(a1);
				this.setLinkAction(a1, this.lightbox, entry);				
				if (!this.useCssClass) {
					a1.setAttribute("style", this.getCssProperty("color", "fontColor") + " text-decoration: none;");
					if (this.fontColor != null && this.fontColor.length > 0) a1.style.color = this.fontColor;
					a1.style.textDecoration = "none";
				}

				if (entry.thumbnailUrl != null) {
					var thumb = document.createElement("img");
					var w = 100 * this.thumbnailScale;
					var h = Math.round(75 * this.thumbnailScale);

					thumb.setAttribute("src", entry.thumbnailUrl);
					thumb.setAttribute("width", w);
					thumb.setAttribute("height", h);
					thumb.setAttribute("border", "0");

					td1.setAttribute("width", w + 5);
					td1.setAttribute("height", h);

					a1.appendChild(thumb);
				}
				else
					a1.appendChild(document.createTextNode("No Thumb"));


				if (this.numbersOnThumb) {
					var divNum = document.createElement("div");
					divNum.setAttribute("style", "position: absolute; top: 0; left: 0; background: black; color: white; text-align: center; width: 1.3em; font-size: " + this.fontSize + "; font-family:" + this.fontFamily);
					divNum.style.position = "absolute";
					divNum.style.top = 0;
					divNum.style.left = 0;
					divNum.style.background = "black";
					divNum.style.color = "white";
					divNum.style.textAlign = "center";
					divNum.style.width = "1.3em";
					divNum.style.fontSize = this.fontSize;
					divNum.style.fontFamily = this.fontFamily;
					divNum.appendChild(document.createTextNode(entry.chartPos));

					divRel.appendChild(divNum);
				}
			}

			var td2 = document.createElement("td");
			tr.appendChild(td2);
			td2.setAttribute("style", "padding: " + spacing + "px 0 " + spacing + "px 4px");
			
			td2.setAttribute("class", "unruly_lightbox_widget_link");
			td2.className = "unruly_lightbox_widget_link";
			td2.setAttribute("data-vvc-url", entry.link + "&mode=iframe&widget=true&v3");

			var a2 = document.createElement("a");
			this.setLinkAction(a2, this.lightbox, entry);
			
			td2.appendChild(a2);
			td2.setAttribute("valign", "middle");
			td2.style.margin = 0;
			td2.style.paddingTop = spacing + "px";
			td2.style.paddingBottom = spacing + "px";
			td2.style.paddingLeft = "4px";
			td2.style.verticalAlign = "middle";
			if (!this.useCssClass) {
				a2.setAttribute("style", this.getCssProperty("color", "fontColor") + " font-size: " + this.fontSize + "; font-family:" + this.fontFamily);
				if (this.fontColor != null && this.fontColor.length > 0) a2.style.color = this.fontColor;
				a2.style.fontSize = this.fontSize;
				a2.style.fontFamily = this.fontFamily;
			}

			var text = "";
			if (this.showChartPos) text += this.renderNumber(entry.chartPos) + ' ';
			text += entry.title;

			a2.innerHTML = text;
		}

		el.appendChild(table);

		this.updatePrevNext();
	};
	
	this.setLinkAction = function(el, lightbox, entry) {
		if( lightbox ) {
			el.setAttribute("onclick", "return false;");
			el.setAttribute("href","#");
		} else {
			el.setAttribute("href", entry.link);
			el.setAttribute("target", "_blank");
		}
	};
	
	this.renderNumber = function(pos) {
		return this.numberPattern.replace("$num", pos);
	};

	this.getFeedUrl = function(hideParam) {
		var url = this.SITE_URL + this.allFeeds[this.feedPointer];
		if (!hideParam) {
			if (url.indexOf("?") == -1)
				url += "?" + this.FEED_PARAM;
			else
				url += "&" + this.FEED_PARAM;
		}
		return url;
	};

	this.showNextX = function() {
		this.currentStart += this.numberToShow;
		if (this.currentStart >= this.feed.entries.length) {
			this.currentStart = this.feed.entries.length - this.numberToShow;
		}

		this.renderTableTemplate(this.feed);
	};

	this.showPreviousX = function() {
		this.currentStart -= this.numberToShow;
		if (this.currentStart < 0)
			this.currentStart = 0;

		this.renderTableTemplate(this.feed);
	};

	this.updatePrevNext = function() {

		var prevT = '&lt; prev ' + this.numberToShow;
		var nextT = 'next ' + this.numberToShow + ' &gt';
		var prevA = '<a href="#" id="vvc_prev_a_' + this.WIDGET_ID + '" style="' + this.getCssProperty("color", "fontColor") + '">' + prevT + '</a>';
		var nextA = '<a href="#" id="vvc_next_a_' + this.WIDGET_ID + '" style="' + this.getCssProperty("color", "fontColor") + '">' + nextT + '</a>';

		if (this.currentStart + this.numberToShow >= this.feed.entries.length) {
			if (this.numberToShow < this.feed.entries.length) {
				document.getElementById('vvc_prev_' + this.WIDGET_ID).innerHTML = prevA + " | ";
				document.getElementById('vvc_next_' + this.WIDGET_ID).innerHTML = nextT;
			}
			else {
				document.getElementById('vvc_prev_' + this.WIDGET_ID).innerHTML = '';
				document.getElementById('vvc_next_' + this.WIDGET_ID).innerHTML = '';
			}
		}
		else if (this.currentStart <= 0) {
			document.getElementById('vvc_prev_' + this.WIDGET_ID).innerHTML = prevT + " | ";
			document.getElementById('vvc_next_' + this.WIDGET_ID).innerHTML = nextA;
		}
		else {
			document.getElementById('vvc_prev_' + this.WIDGET_ID).innerHTML = prevA + " | ";
			document.getElementById('vvc_next_' + this.WIDGET_ID).innerHTML = nextA;
		}

		this.applyJSFunctions();
	};

	this.feedNotLoaded = function() {
		var el = document.getElementById('vvc_feed_display_' + this.WIDGET_ID);

		var div = document.createElement("div");
		div.style.textAlign = "center";

		div.innerHTML = "Sorry, the widget has gone AWOL.<br/>Tell us hello@unrulymedia.com";

		el.appendChild(div);
	};

	this.setup = function() {
		var el = document.getElementById(this.divId);

		el.style.width = this.width + "px";
		if (this.fixedHeight) {
			el.style.height = this.height + "px";
		}
		el.style.overflow = "hidden";
		if (!this.useCssClass) {
			el.style.fontFamily = this.fontFamily;
			el.style.fontSize = this.fontSize;
			if (this.fontColor != null && this.fontColor.length > 0)
				el.style.color = this.fontColor;
			el.style.background = this.background;
		}
		el.setAttribute("class", "VVCWidget");
		el.className = "VVCWidget";

		el.innerHTML = this.renderInterface();

		if (typeof vvcMyFeed == "undefined" || vvcMyFeed == null) {
			this.feedNotLoaded();
		}
		else {
			this.feed = vvcMyFeed;
			this.renderTableTemplate(this.feed);
		}
	};
	
	this.setup();

	if (this.lightbox) {
		var self = this;
		ViralVideoChart.setupAsyncLoader(function() {ViralVideoChart.createLightboxes(self); });
	}
};

ViralVideoChart.setupAsyncLoader = function(callback){
	(function(g,b,d){var c=b.head||b.getElementsByTagName("head"),D="readyState",E="onreadystatechange",F="DOMContentLoaded",G="addEventListener",H=setTimeout;
	function f(){
		if (typeof callback == 'function'){
			callback();
		}
	}
	H(function(){if("item"in c){if(!c[0]){H(arguments.callee,25);return}c=c[0]}var a=b.createElement("script"),e=false;a.onload=a[E]=function(){if((a[D]&&a[D]!=="complete"&&a[D]!=="loaded")||e){return false}a.onload=a[E]=null;e=true;f()};

	a.src="http://video.unrulymedia.com/vvc/LAB.js";

	c.insertBefore(a,c.firstChild)},0);if(b[D]==null&&b[G]){b[D]="loading";b[G](F,d=function(){b.removeEventListener(F,d,false);b[D]="complete"},false)}})(this,document);
};

ViralVideoChart.createLightboxes = function(self) {
	var lab = $LAB.noConflict();
	lab.setGlobalDefaults({AlwaysPreserveOrder: true});
	
	if (typeof UNRULY === "undefined") {
		lab.queueScript('http://video.unrulymedia.com/unruly_object_v2.js');
		lab.queueScript('http://video.unrulymedia.com/engagement_v5.js');
	} else {
		if (typeof UNRULY.jq === "undefined") {
			lab.queueScript('http://video.unrulymedia.com/engagement_v5.js');
		}
	}
	
	lab.queueScript(ViralVideoChart.RESOURCES_URL + '/vvc_jquery.fancybox-1.2.5_v1.js');
	lab.queueScript(ViralVideoChart.RESOURCES_URL + '/vvc_lightbox_widget.js');
	lab.queueWait(function() {
		var css = UNRULY.jq('<link href="' + ViralVideoChart.RESOURCES_URL + '/vvc_jquery.fancybox-1.2.5_v1.css" type="text/css" rel="stylesheet"></link>');
		UNRULY.jq('head').append(css);
	});
	
	lab.runQueue();
};

ViralVideoChart.VVCIsNumeric = ViralVideoChart.VVCIsNumeric || function(text) {
		return /^[-+]?\d+(\.\d+)?$/.test(text);
};

if (typeof _UnrulyVVCWidgetTestPage != "undefined" && _UnrulyVVCWidgetTestPage) {
	ViralVideoChart.RESOURCES_URL = "http://test.video.unrulymedia.com/vvc";
} else {
	ViralVideoChart.RESOURCES_URL = "http://video.unrulymedia.com/vvc";
}
