/* =============================================================

File: jquery.flick.js
Version: 1.0
Created: July 29 2009
Author: Ben Williams  http://somethingchanged.com

Description:

A jQuery plugin to dynamically generate image galleries from Flickr feeds.  Features template control of the galleries and photos, and configuration of feed parameters and size of the returned images.

Usage:

1. include this file and jquery 1.3
2. setup options
3. call the plugin with $(SELECTOR).flickr(options);

Available options:

flickr_id           The alphanumeric id of the account (this parameter is required).
feed_type           Either 'faves' or 'public'.  Defaults to 'public'.
tags                Comma-delimted tags to match in feed.  Only applies to public feed.
gallery_format      HTML snippet for the gallery.  Available tokens are [ALBUM_TITLE] and [PHOTOS].
photo_format	    HTML snippet for each photo.  Available tokens are [ID], [TITLE], [DESCRIPTION], [PHOTO_URL], [THUMB_URL], [WIDTH] and [HEIGHT].
max_items		    Integer value of the maxium number of items to show.  Defaults to all returned pictures.
repeat			    Number of times the images are shown.  Default is 1.
thumbnail_type      The image shape and size shown.  Available opions are square (75x75px), small (max dimension of 100px), medium (max 240px), large (max 1024px) and original.
clickthrough_type   The image linked to in the image's HREF.  Available opions as for thumbnail_type, with the adition of flickr, to lead to the Flickr page for the image.
thumbnail_size		width and height of the thumbnail.  Default is unset, i.e. the thumbnail displays at the native size. Only useful for square thumbnails.


============================================================= */


var settings;
var matchingElements;

function replaceTokens(i, from, to)
{
	var element = settings['photo_format'];

	element = element.replace('[ID]', 'photo' + i);

	for (i = 0; i < from.length; i++)
		element = element.replace(from[i], to[i]);
	
	return element;
}

var get_link = function(pic, preferred_type)
{
	switch (preferred_type)
	{
		case 'flickr':
			return pic.link;	
		case 'square':
			return (pic.media.m).replace("_m.jpg", "_s.jpg");	
		case 'small':
			return (pic.media.m).replace("_m.jpg", "_t.jpg");	
		case 'medium':
			return pic.media.m;	
		case 'large':
			return (pic.media.m).replace("_m.jpg", "_b.jpg");	
		case 'original':
			return (pic.media.m).replace("_m.jpg", "_o.jpg");	
		default:
			return (pic.media.m).replace("_m.jpg", "_t.jpg");	
	}
}

var jsonFlickrFeed = function(json)
{
	$("#output").append(json.title);
	
	var gallery = settings['gallery_format'].replace('[ALBUM_TITLE]', json.title);
	var photos = '';

	counter = 0;

	for (i = 0; i < settings['repeat']; i++)
    {
		$.each(json.items, function(i, pic) { 
			if (settings['max_items'] != '' && i >= settings['max_items'])
				return false;
			
			clickthrough = get_link(pic, settings['clickthrough_type']);
			thumbnail = get_link(pic, settings['thumbnail_type']);
			

			if (settings['centre_image'] == 'yes')
			{
				var anImage = new Image();
				anImage.src = thumbnail;
				anImage.parent_id = 'photo' + ++counter;
				
				anImage.onload = function() 
				{ 
					xpadding = 0;
					ypadding = 0;	
					ixpadding = 0;
					iypadding = 0;
					$('#' + anImage.parent_id + ' img').each(function() 
					{ 
						ixpadding = parseInt($(this).css('paddingLeft')) + parseInt($(this).css('paddingRight')) + parseInt($(this).css('borderLeftWidth')) + parseInt($(this).css('borderRightWidth'));
						iypadding = parseInt($(this).css('paddingTop')) + parseInt($(this).css('paddingBottom')) + parseInt($(this).css('borderTopWidth')) + parseInt($(this).css('borderBottomWidth'));
					});
					
					$('#' + anImage.parent_id).each(function()
					{
						xpadding = ($(this).width() - anImage.width - ixpadding)/2;
						ypadding = ($(this).height() - anImage.height - iypadding)/2
					});

					$('#' + anImage.parent_id + ' img').each(function() 
					{ 
						$(this).css('margin-left', xpadding).css('margin-right', xpadding).css('margin-top', ypadding).css('margin-bottom', ypadding); 
						this.src = anImage.src; 
					});
				};
			}
				
			if (settings['thumbnail_size'] != '')
			{
				photos +=  
				replaceTokens(counter, 
					['[TITLE]', '[DESCRIPTION]', '[PHOTO_URL]', '[THUMB_URL]', '[WIDTH]', '[HEIGHT]'], 
					[pic.title, pic.description, clickthrough, thumbnail, settings['thumbnail_size'], settings['thumbnail_size']]
					);				
			}	
			else
			{
				photos +=  
				replaceTokens(counter, 
					['[TITLE]', '[DESCRIPTION]', '[PHOTO_URL]', '[THUMB_URL]'], 
					[pic.title, pic.description, clickthrough, thumbnail]
					); 				
			}
		});
	}
		
	gallery = gallery.replace('[PHOTOS]', photos);
	matchingElements.append(gallery);
	
	console.log(gallery);
	
	if (settings['postload_function'] != '')
		settings['postload_function'].call();
}

jQuery.fn.flickr = function(options) {
	var galleryFormat = '<div class="title">[ALBUM_TITLE]</div>[PHOTOS]';
	var photoFormat = 
		  '<div class="photo" id="[ID]" rel="gallery">' 
		+ '<a href="[PHOTO_URL]"><img src="[THUMB_URL]" width="[WIDTH]" height="[HEIGHT]"></a>' 
		+ '</div>';
		
  	settings = jQuery.extend({
		flickr_id: '',
		feed_type: 'public',
		tags: '',
		gallery_format: galleryFormat,
		photo_format: photoFormat,
		max_items: '',
		repeat: 1,
		thumbnail_type: 'thumbnail',
		clickthrough_type: 'large',
		thumbnail_size: '',
		centre_image: 'no',
		postload_function: ''
		}, options);
		
	matchingElements = this;
		
	json_feed = 'http://api.flickr.com/services/feeds/photos_' + settings['feed_type'] + '.gne?id=' + settings['flickr_id'] + '&tags=' + settings['tags'] + '&format=json&jsoncallback=?';		
	$.getJSON(json_feed, jsonFlickrFeed);

	return this;
};
