$(function() {
	
	$("#primary h2").prepend("<a class=\"toplink\" href=\"#page\">&uarr;</a>");
	
	// loadTumblr("#blog", "http://bensbiggig.tumblr.com/api/read/json?num=50", 2, "Blog updates");
	
	$("#twitter").tweet({
		join_text: "auto",
		avatar_size: 48,
		count: 4,
		query: "%23bensbiggig",
		loading_text: "searching Twitter...",
		auto_join_text_default: "said, ",
		auto_join_text_ed: " ",
		auto_join_text_ing: "was ",
		auto_join_text_reply: "replied to ",
		auto_join_text_url: "linked to "
	});
	
	function loadTumblr(target, feed_url, limit, title) {
		
		//Title
		if (title != "") {
			$(target).append('<h2>' + title + '</h2>');
		}

		$.getJSON(feed_url + "?callback=?", function(json) {
			
			var i = 0;
			
			var html = $('<ul class="updates"></ul>');
			
			$(json.posts).each(function(){
				
				var post = this;
				
				if(typeof(post['tags']) != 'undefined' && /featured/.test(post['tags'].join()) && i < limit) {
					
					if (/regular|photo|quote|link|conversation/.test(post.type)) {
						
						i++;

						var text = post["regular-body"] || post["photo-caption"] || post["quote-source"] || post["link-text"] || post["link-url"] || "";
						var o = "";
						
						if (post.type === "regular") {
							o += "<h3>" + '<a href="' + post.url + '">' + post["regular-title"] + "</a></h3>";
							o += text;
						}
						if (post.type === "photo") {
							o += '<a href="' + post.url + '"><img src="' + post["photo-url-250"] + '" width="' + settings.imageSize + '" /></a>';
							o += "<em>" + text + "</em>";
						}
						else if (post.type === "quote") {
							o += post["quote-text"] + "<em>" + text + "</em>";
						}
						else if (post.type === "link") {
							o += '<h3><a href="' + post["link-url"] + '">' + text + '</a></h3>';
							o += post["link-description"];
						}
						else if (post.type === "conversation") {
							var conversation = post["conversation-lines"];
							for (var j=0, jl=conversation.length; j<jl; j=j+1) {
								o += conversation[j].label + " " + conversation[j].phrase + ((j === (jl -1))? "" : "<br />");
							}
						}
						
						var metadata = $('<p class="meta"></p>')
							.append('<a href="' + post.url + '">' + post["date"].replace(/(^\w{3},\s)|(:\d{2}$)/g, "") + '</a>');
						
						var new_item = $("<li/>").append(o);

						$(new_item).find("p:gt(0)").remove();
						
						$(new_item).append(metadata);
						
						$(new_item).appendTo($(html));
						
					}
				}
			});

			$(target).append(html);
			
		});
		
	}
	
});
