/**
 * Plugin: jquery.zFlickrFeed
 * 
 * Version: 1.0.1
 * (c) Copyright 2010, Zazar Ltd
 * 
 * Description: jQuery plugin for display of Flickr photo feeds
 * 
 * History:
 * 1.0.1 - Corrected issue with multiple instances
 *
 **/

(function($){

	$.fn.flickrfeed = function(userid, tags, options) {	
	
		// Set pluign defaults
		var defaults = {
			limit: 3,
			header: false,
			imagesize: 'thumbnail',
			titletag: 'h4',
			title: true
		};  
		var options = $.extend(defaults, options); 
		
		// Functions
		return this.each(function(i, e) {
			var $e = $(e);

			// Add feed class to user div
			if (!$e.hasClass('flickrFeed')) $e.addClass('flickrFeed');

			// Define Flickr feed API address
			var api = 'http://api.flickr.com/services/feeds/photos_public.gne?lang=en-us&format=json&jsoncallback=?';
			if (userid != '') api += '&id=' + userid;
			if (tags != '') api += '&tags=' + tags;

			// Send request
			$.getJSON(api, function(data){

				// Process the feeds
				_callback(e, data, options);
			});				
		});
	};
	
	// Callback function to create HTML result
	var _callback = function(e, data, options) {
		if (!data) {
			return false;
		}
		var html = '';	
	
		// Add body
		html += '<div class="flickrBody">' +
			'<ul>';

		var feeds = data.items;
		var count = feeds.length;
		if (count > options.limit) count = options.limit;
		
		// Add feeds
		for (var i=0; i<count; i++) {
			
			// Get individual feed
			var photo= feeds[i];
			var link = '<a href="'+ photo.link + '" title="'+ photo.title +' (View on Flickr)">';

			// Add feed row
			html += '<li>';
			
			// Select image size
			var src = photo.media.m;
			if (options.imagesize == 'square') src = src.replace('_m', '_s');
			if (options.imagesize == 'thumbnail') src = src.replace('_m', '_t');
			if (options.imagesize == 'medium') src = src.replace('_m', '');

			html += link +'<img src="'+ src +'" alt="'+ photo.title +'" /></a>'

			// Add title if required
			if (options.title)	html += '<'+ options.titletag +'>'+ photo.title +'</'+ options.titletag +'>';
			
			//link to flickr custom
			html+= '<a class="show-more" href="'+ photo.link + '">View on Flickr</a>';
		}
		
		html += '</ul>' +
			'</div>'
		
		$(e).html(html);
	};
})(jQuery);
