/**
 * tumblrBadge
 * Original by Robert Nyman, http://www.robertnyman.com/, http://code.google.com/p/tumblrbadge/
 * Modified by Robert Gabriel, adapted to Prototype, added audio and video support
 **/
 
var tumblrBadge = Class.create({
	settings: {
		userName         : "porosity",		// Your Tumblr user name
		itemsToShow      : 10, 				// Number of Tumblr posts to retrieve
		itemToAddBadgeTo : "l_sec_1_2_c1",	// Id of HTML element to put badge code into
		imageSize        : 250,				// Values can be 75, 100, 250, 400 or 500.
		shortPublishDate : true,			// Whether the publishing date should be cut shorter
		timeToWait       : 0,				// In seconds
		newVimeoCode     : false			// Use Vimeos new video code (iframe with an JS error, but claimed to be working on iPad) or old one (object tag, no JS error)
	},
	
	initialize: function() {
		this.head = $$("head")[0];
		this.body = $$("body")[0];
		this.badgeContainer = $(this.settings.itemToAddBadgeTo);
		

		//if (head && badgeContainer) {
		if (this.badgeContainer) {
			this.badgeJSON = document.createElement("script");
			this.badgeJSON.type = "text/javascript";
			this.badgeJSON.src = "http://" + this.settings.userName + ".tumblr.com/api/read/json?callback=myTumblr.listItems&num=" + this.settings.itemsToShow;
			
			// Anonymous function to delay the server call until the page is ready
			(function() {
				this.body.appendChild(this.badgeJSON);
			}.bind(this)).delay(this.settings.timeToWait);
		}
	},
	
	listItems: function(json) {
		var posts = json.posts,
			//list = document.createElement("ul"),		// removed
			list = $(this.settings.itemToAddBadgeTo),	// added
			post,
			listItem,
			text,
			link,
			img,
			conversation,
			postLink;
		list.addClassName("tumblr");
		
		// Cache current content to append later on
		var curCont = list.childElements();
		list.update();
		for (var i=0, il=posts.length; i<il; i=i+1) {
			post = posts[i];
			
			// Only get content for text, photo, quote and link posts
			// Added audio & video support
			if (/regular|photo|quote|link|audio|video|conversation/.test(post.type)) {
				listItem = document.createElement("li");
				text = post["regular-body"] || post["photo-caption"] || post["quote-source"] || post["link-text"] || post["link-url"] || "";
				if (post.type === "photo") {
					link = document.createElement("a");
					link.href = post.url;
					img = document.createElement("img");
					// To avoid a creeping page
					img.width = this.settings.imageSize;
					img.src = post["photo-url-" + this.settings.imageSize];
					link.appendChild(img);
					listItem.appendChild(link);
					text = "<em>" + text + "</em>";
				}
				else if (post.type === "quote") {
					text = post["quote-text"] + "<em>" + text + "</em>";
				}
				else if (post.type === "link") {
					text = '<a href="' + post["link-url"] + '">' + text + '</a>';
				}
				// Audio support
				else if (post.type === "audio") {
					text  = '<p>'+post["audio-caption"]+'</p>';
					text += '<p>'+post["audio-player"]+'</p>';
				}
				// Video support
				else if (post.type === "video") {
					var width   = list.down("li").getWidth();	// Get width of containing element
					var string  = post["video-caption"]
					
					
					// Video from Vimeo?
					if (string.search(/vimeo\.com/ig) > -1) {
						var pattern = /width\s*=\s*"(\d+)"\s*height\s*=\s*"(\d+)"/ig;
						var vars    = pattern.exec(string);
						var newStr  = "";
						var newWidth  = Math.round(vars[1]/vars[1]*width);
						var newHeight = Math.round(vars[2]/vars[1]*width);
						
						// New code, Location.toString() JS error, but supposed to work on iPad, iPhone, etc
						if (this.settings.newVideoCode == true) {
							newStr  = string.replace(pattern, 'width="'+newWidth+'" height="'+newHeight+'"');
							
						}
						// Old code, doesn't throw a JS error
						else {
							var clipID, subText;
							clipID  = /http:\/\/player\.vimeo\.com\/video\/(\d+)\?/ig.exec(string)[1];
							subText = string.replace(/<p>\s*<iframe.*>\s*<\/iframe>\s*<\/p>\s*/ig, "");
							
							newStr += '<object width="'+newWidth+'" height="'+newHeight+'">';
							newStr += '	<param name="allowfullscreen" value="true" />';
							newStr += '	<param name="allowscriptaccess" value="always" />';
							newStr += '	<param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id='+clipID+'&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=00adef&amp;fullscreen=1&amp;autoplay=0&amp;loop=0" />';
							newStr += '	<embed src="http://vimeo.com/moogaloop.swf?clip_id='+clipID+'&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=00adef&amp;fullscreen=1&amp;autoplay=0&amp;loop=0" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="'+newWidth+'" height="'+newHeight+'"></embed>';
							newStr += '</object>';
							newStr += subText;
						}
					}
					
					
					// Not vimeo (e.g. Youtube)
					else {
						var newStr = "";
						var player = post["video-player"];
						var vars, newPlayer;
						
						newStr += string;
						
						var pattern1 = /width\s*=\s*"(\d+)"/gi;
						var pattern2 = /height\s*=\s*"(\d+)"/gi;
						if (player) {
							var vars = [pattern1.exec(player)[1], pattern2.exec(player)[1]];
							var newWidth  = Math.round(vars[0]/vars[0]*width);
							var newHeight = Math.round(vars[1]/vars[0]*width);
							var exp1 = new RegExp(vars[0], "g");
							var exp2 = new RegExp(vars[1], "g");
							
							// Set new width and height values
							newPlayer = player.replace(exp1, newWidth).replace(exp2, newHeight);
							
							newStr += newPlayer;
						}

					}
					
					text  = '<p>'+newStr+'</p>';
					
				}
				
				else if (post.type === "conversation") {
					//conversation = post["conversationlines"];	// Doesn't exist anymore?
					conversation = post["conversation"];
					for (var j=0, jl=conversation.length; j<jl; j=j+1) {
						text += conversation[j].label + " " + conversation[j].phrase + ((j === (jl -1))? "" : "<br>");
					}
				}
				listItem.innerHTML += text;
	
				// Create a link to Tumblr post
				postLink = document.createElement("a");
				postLink.className = "tumblr-post-date";
				postLink.href = post.url;
				postLink.innerHTML = (this.settings.shortPublishDate)? post["date"].replace(/(^\w{3},\s)|(:\d{2}$)/g, "") : post["date"];
				listItem.appendChild(postLink);
	
				// Apply list item to list
				list.appendChild(listItem);
			}
			
			curCont.each(function(ele) {
				list.appendChild(ele);
			});
		}
	}
});
