/*
 * jTumblr 2.6 - Tumblr Feed for jQuery
 *
 * Copyright (c) 2010, 2011 designdisorder.com
 *
 * Licensed under the GPL license:
 *   http://www.gnu.org/licenses/gpl.html
 *
 * URL:
 *   http://designdisorder.com/stacks/tumblr/
 *
 * Author URL:
 *   http://designdisorder.com/about
 *
 * This function generates a tumblr blog on a webpage with all the usual features like
 * detail view, pages, tag search and text search.
 *
 * It also adds commenting capabilities based on the Echo service
 *
 */

(function($)
{
 	$.extend(
 	{
		// This is the core function that creates the actual HTML
		generateTumblr: function(options)
		{			
			// merge options with defaults
			var opts = jQuery.extend({}, jQuery.generateTumblr.defaults, options);
			
			// populate the config defaults
			var extConfig = jQuery.extend({}, jQuery.generateTumblr.extendedConfig, extendedConfig);

			// get the page parameter
			opts.page = $.url.param("page");
			if (opts.page)
				opts.page = parseInt(opts.page);
			else
				opts.page = 1;
					
			// get the requested page
			opts.postId = $.url.param("postid");
			
			// get tag param if not preset
			if (!opts.filterTag) opts.filterTag = $.url.param("tag");
			
			// get search param if not preset
			if (!opts.filterSearch) opts.filterSearch = $.url.param("search");
			
			// will contain the generated HTML
			var html = [];
			var ptr = 0;
			
			// retrieve the tumblr feed 
			$.getTumblr(opts,
				
				// generate the html
				function(feed)
				{	
					// Check for errors
					if(!feed) return false;
							
					// Extract the feed url
					var blogLink = $.url.protocol() + '//' + $.url.host() + $.url.pathname();

					// Display header if required
					if (extConfig.show_header)
					{
						html[ptr++] = '<div class="tumblr-header">';
						html[ptr++] = '<h2 class="tumblr-title"><a href="' + blogLink + '">' + feed.tumblelog.name + '</a></h2>';
						html[ptr++] = '<h3 class="tumblr-slogan">"' + feed.tumblelog.description + '"</h3>';
						html[ptr++] = '</div>';
					}

					// Generate the feed posts
					for (var i=0; i < feed.posts.length; i++) 
					{
						var post = feed.posts[i];
						
						// Generate post div
						html[ptr++] = '<div class="tumblr-post">';
						
						// generate the permalink to the post
						var permaLink = $.url.protocol() + '//' + $.url.host() + $.url.pathname() + "?postid=" + post.id;
						
						// store the social link info
						var socialLink = permaLink;
						var socialTitle = "";

						// handle the different post types
						switch (post.type)
						{
							// a normal blog post
							case 'regular':
								html[ptr++] = '<div class="tumblr-post-text"><div class="icon-' + extConfig.icon_set + '"><a href="' + permaLink + '"><div class="tumblr-post-icon"></div></a></div></div><h2 class="tumblr-post-title"><a href="' + permaLink + '">' + post['regular-title'] + '</a></h2>';
								
								regularBody = post['regular-body'];
								
								// shorten the post to preview size if not in detail mode & previewSize != 0
								if (!opts.postId && (opts.previewSize != 0) && (regularBody.length > opts.previewSize))
								{
									previewSize = opts.previewSize;
									while (regularBody.charAt(previewSize) != ' ')
									{
										previewSize--;
									}
									regularBody = regularBody.substr(0, previewSize) + ' ... <a href="' + permaLink + '">' + extConfig.more_text + '</a>';
								}
								
								html[ptr++] = '<div class="tumblr-body">' + regularBody + '</div>';
								socialTitle = post['regular-title'];
								break;

							// a answer blog post
							case 'answer':
								html[ptr++] = '<div class="tumblr-post-answer"><div class="icon-' + extConfig.icon_set + '"><a href="' + permaLink + '"><div class="tumblr-post-icon"></div></a></div></div><h2 class="tumblr-post-title"><a href="' + permaLink + '">' + post['question'] + '</a></h2>';
								html[ptr++] = '<div class="tumblr-body">' + post['answer'] + '</div>';
								socialTitle = post['question'];
								break;

							// a quote from the net
							case 'quote':
								html[ptr++] = '<div class="tumblr-post-quote"><div class="icon-' + extConfig.icon_set + '"><a href="' + permaLink + '"><div class="tumblr-post-icon"></div></a></div></div>';
								html[ptr++] = '<blockquote class="tumblr-quote"><p>' + post['quote-text'] + '</p></blockquote>';
								html[ptr++] = '<div class="tumblr-body">' + post['quote-source'] + '</div>';
								socialTitle = 'Edit Tweet'; // post['quote-text'];
								break;

							// a link on the net
							case 'link':
								html[ptr++] = '<div class="tumblr-post-link"><div class="icon-' + extConfig.icon_set + '"><a href="' + permaLink + '"><div class="tumblr-post-icon"></div></a></div></div><h2 class="tumblr-post-title"><a href="' + post['link-url'] + '">' + post['link-text'] + '</a></h2>';
								html[ptr++] = '<div class="tumblr-link-desc">' + post['link-description'] + '</div>';
								socialTitle = post['link-text'];
								break;

							// a conversation ?!?!
							case 'conversation':
								html[ptr++] = '<div class="tumblr-post-chat"><div class="icon-' + extConfig.icon_set + '"><a href="' + permaLink + '"><div class="tumblr-post-icon"></div></a></div></div><h2 class="tumblr-post-title"><a href="' + permaLink + '">' + post['conversation-title'] + '</a></h2>';
								html[ptr++] = '<pre>' + post['conversation-text'] + '</pre>';
								socialTitle = post['conversation-title'];
								break;
								
							// a photo post	
							case 'photo':

								// Is this a photoset?
								if (post.photos.length)
								{
									var idStart = post['photo-url-75'].indexOf('tumblr_');
									var idEnd = post['photo-url-75'].indexOf('o1_75');
									var photoset = 'http://' + options.tumblrId + '.tumblr.com/post/' + post.id + '/photoset_xml/' + post['photo-url-75'].substring(idStart, idEnd) + '/500';
									html[ptr++] = '<div class="tumblr-post-photoset"><div class="icon-' + extConfig.icon_set + '"><a href="' + permaLink + '"><div class="tumblr-post-icon"></div></a></div></div><div class="tumblr-photoset">';
									html[ptr++] = '<embed class="photoset" width="500" height="375" flashvars="showLogo=false&showVersionInfo=false&dataFile=' + photoset + '" quality="high" bgcolor="#000000" src="http://' + opts.tumblrId + '.tumblr.com/swf/photoset.swf" type="application/x-shockwave-flash"/>';			
									
									/*
									// Modify monoslide settings
									html[ptr++] = '<script type="text/javascript">'
									+ 'var flashvars = {xml: "<album>'
									+ '<configuration backgroundColor=\'#ffffff\'>'
									+ '<transition direction=\'topToBottom\' time=\'1.5\' type=\'swap\'/>'
									+ '<controller autoHide=\'false\' backgroundRoundness=\'10\' iconHeight=\'20\' iconWidth=\'20\' iconSpacing=\'0\' margin=\'25,25,25,25\' position=\'bottomRight\' showNavigationButton=\'false\' showNextButton=\'false\' showPreviousButton=\'false\' showScrubBar=\'false\' strokeWidth=\'0\'>'
									+ '<scrubBar/>'
									+ '<shadow/>'
									+ '</controller>'
									+ '</configuration>'
									+ '</album>",'
									+ 'dataFile: ' + photoset + ','
									+ 'showLogo: "false",'
									+ 'showRegistration: "false",'
									+ 'showVersionInfo: "false"'
									+ '};'
									+ 'var params = {allowScriptAccess: "always"};'
									+ 'var attributes = {bgColor: "ffffff", id: "monoslideshow", name: "monoslideshow"};'
									+ 'swfobject.embedSWF('
									+ '"http://designdisorder.tumblr.com/swf/photoset.swf", "flashContent",'
									+ '"500", "375", "9", false,'
									+ 'flashvars, params, attributes'
									+ ');'
									+ '</script>';
									*/

									html[ptr++] = '</div>';			
								}
								else
								{
									// Use the link through URL or find the largest photo to link to
									var photoUrl = post['photo-link-url'];
									
									if (!photoUrl)
										photoUrl = post['photo-url-1280'];
									if (!photoUrl)
										photoUrl = post['photo-url-500'];
									if (!photoUrl)
										photoUrl = post['photo-url-400'];
									if (!photoUrl)
										photoUrl = post['photo-url-200'];
									if (!photoUrl)
										photoUrl = post['photo-url-100'];
									if (!photoUrl)
										photoUrl = post['photo-url-75'];
										
									html[ptr++] = '<div class="tumblr-post-photo"><div class="icon-' + extConfig.icon_set + '"><a href="' + permaLink + '"><div class="tumblr-post-icon"></div></a></div></div><div class="tumblr-photo"><a href="' + photoUrl + '"><img src="' + post['photo-url-400'] + '"></a></div>';
								}
								html[ptr++] = '<div class="tumblr-caption">' + post['photo-caption'] + '</div>';
								socialTitle = 'Edit Tweet'; // post['photo-caption'];
								break;
								
							// a video post	
							case 'video':
								html[ptr++] = '<div class="tumblr-post-video"><div class="icon-' + extConfig.icon_set + '"><div class="tumblr-post-icon"></div></div></div><div class="tumblr-video-player">' + post['video-player'] + '</div>';
								// html[ptr++] = '<a href="' + post['video-source'] + '">' + post['video-source'] + '</a>';
								html[ptr++] = '<div class="tumblr-caption">' + post['video-caption'] + '</div>';
								socialTitle = 'Edit Tweet'; // post['video-caption'];
								break;
								
							// and finally the audio post	
							case 'audio':
								html[ptr++] = '<div class="tumblr-post-audio"><div class="icon-' + extConfig.icon_set + '"><div class="tumblr-post-icon"></div></div></div><div class="tumblr-audio-player">' + post['audio-player'] + '</div>';
								html[ptr++] = '<div class="tumblr-caption">' + post['audio-caption'] + '</div>';
								socialTitle = 'Edit Tweet'; // post['audio-caption'];
								break;
					
							default:
								break;
						}
						// render post tags						
						html[ptr++] = '<div class="tumblr-tags">' + extConfig.tags_text + ' ';
						
						// handle tags
						var tags = post['tags'];
						if (tags)
						{
							for (var j=0; j < tags.length; j++) 
							{
								html[ptr++] = '<a href="' + blogLink + '?tag=' + tags[j] + '">' + tags[j] + '</a>';
								// separate tags with commas
								//if (j < tags.length-1) html[ptr++] = ', ';
							}
						}
						html[ptr++] = '</div>';

						// render post date
						var date = new Date(post['unix-timestamp'] * 1000);
						
						html[ptr++] = '<div class="tumblr-date">' + extConfig.posted_on_text + ' ' + date.toLocaleString() + '</div>';

						// Add social plugins for twitter and facebook
						html[ptr++] = '<div class="tumblr-social">';

						if (extConfig.twitter_account && extConfig.twitter_account.length)
						{
							html[ptr++] = '<a href="http://twitter.com/share" class="twitter-share-button" data-url="' + socialLink + '" data-text="' + socialTitle + '" data-count="horizontal" data-via="' + extConfig.twitter_account + '">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>';
						}

						if (extConfig.likeit)
						{
							html[ptr++] = '<iframe src="http://www.facebook.com/plugins/like.php?href&amp;layout=button_count&amp;show_faces=false&amp;width=&amp;action=like&amp;font&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; height:21px;" allowTransparency="true"></iframe>';
						}
						html[ptr++] = '</div>';

						// Add permalink
						html[ptr++] = '<a class="tumblr-permalink" href="' + permaLink + '">' + extConfig.permalink_text + '</a> ';

						// Add editLink if specified
						if (extConfig.editlink_text.length)
						{
							html[ptr++] = extConfig.separator_text + '<a class="tumblr-permalink" href="http://www.tumblr.com/edit/' + post.id + '?redirect_to=' + encodeURIComponent(document.location.href) + '">' + extConfig.editlink_text + '</a> ';
						}

						// Handle comments if required?
						if (extConfig.disqus_shortname && extConfig.disqus_shortname.length)
						{
							// Show disqus box if in details view and specified
							if (opts.postId)
							{
								html[ptr++] = '<div id="disqus_thread"></div>';
								html[ptr++] = '<script src="http://' + extConfig.disqus_shortname + '.disqus.com/embed.js"></script>';
							}

							// Show comments link if not in details view
							else
							{
								html[ptr++] = extConfig.separator_text + '<a class="tumblr-comments" href="' + permaLink + '#disqus_thread">' + extConfig.comments_text + '</a>';
								html[ptr++] = '<script src="http://disqus.com/forums/' + extConfig.disqus_shortname + '/count.js"></script>';
							}
						}

						// Close post div
						html[ptr++] = '</div>';
					}
					
					// Generate page navigator if not in detail view
					if (!opts.postId)
					{
						html[ptr++] = '<div class="tumblr-navigator">';
						
						// Are we on page 1?
						if (opts.page == 1)
						{
							if (feed['posts-total'] > opts.pageSize)
								html[ptr++] = '<a href="' + blogLink + '?page=2' + '">' + extConfig.prev_posts_text + '</a>';
						}
						
						// Do we need a Newer Post link?
						else if (opts.page >= feed['posts-total'] / opts.pageSize)
						{
							html[ptr++] = '<a href="' + blogLink + '?page=' + (opts.page - 1) + '">' + extConfig.next_posts_text + '</a>';
						}
						
						// Generate the navigator link
						else
						{
							html[ptr++] = '<a href="' + blogLink + '?page=' + (opts.page + 1)  + '">' + extConfig.prev_posts_text + '</a>' + extConfig.separator_text;
							html[ptr++] = '<a href="' + blogLink + '?page=' + (opts.page - 1)  + '">' + extConfig.next_posts_text + '</a>';						
						}
						
						html[ptr++] = '</div>';
					}
					
					if (extConfig.poweredby)
					{
						html[ptr++] = '<br/><p style="text-align: center;">Powered by <img src="' + opts.assetPath + '/tumblr-logo.png"></p>';
					}
					
					// Finally append the generated code to the div
					$(opts.dest).append(html.join(' '));
				}
			);
		},

		// This is the function that requests the blog data in JSON via the Tumblr API
		getTumblr: function(options, fnk)
		{			
			// Make sure tumblr id is defined
			if(options.tumblrId == null)  
			{
				// Do some error handling
				$(options.dest).append("Something went wrong...<br/>No blog ID has been specified!<br/>Please check the blog ID ...");
				return false;
			}
		
			// Build Google Feed API URL
			var url = "http://"+ options.tumblrId +".tumblr.com/api/read/json?";
			if(options.page != null) url += "&start=" + (options.page-1) * options.pageSize;
			if(options.pageSize != null) url += "&num=" + options.pageSize;
			if((options.filterType != null) && (options.filterType.length)) url += "&type=" + options.filterType;
			if((options.postId != null) && (options.postId != 0)) url += "&id=" + options.postId;
			if((options.filterTag != null) && (options.filterTag.length > 1)) url += "&tagged=" + options.filterTag;
			if((options.filterSearch != null) && (options.filterSearch.length)) url += "&search=" + options.filterSearch;
			url += "&callback=?";

			var params = {format: 'json'};
			
			// call the API
			return $.getJSON(url, params, fnk);
		}
 		
	});
})
(jQuery);


// The generateTumblr defaults used by the getTumblr()
jQuery.generateTumblr.defaults = {
	dest: "tumblr-blog",
	assetPath: "files",
	tumblrId: "designdisorder",
	filterTag: null,
	filterSearch: null,
	page: 1,
	pageSize: 5,
	previewSize: 200,
	postId: null
}

jQuery.generateTumblr.extendedConfig = {
	show_header: false,
	icon_set: 'white',
	filter_tag: null,
	filter_search: null,
	more_text: 'continue',
	prev_posts_text: '<< Older Posts',
	next_posts_text: 'Newer Posts >>',
	posted_on_text: 'Posted on',
	tags_text: 'Tags: ',
	permalink_text: 'Permalink',
	editlin_text: 'Edit',
	comments_text: 'Comments',
	separator_text: ' | ',
	poweredby: true,
	twitter_account: 'designdisorder',
	likeit: 'true',
	disqus_shortname: 'designdisorder',
	disqus_develmode: false,
}

jQuery.fn.log = function (msg) {
  console.log("%s: %o", msg, this);
  return this;
};

