/*
Script: MooFlickrBadge.js
	MooFlickrBadge - MooTools based Flickr badge generator

License:
	MIT-style license.

Copyright:
	Copyright (c) 2009 [Oskar Krawczyk](http://nouincolor.com/).

Dependencies:
	- MooTools-core 1.2.1 or higher [mootools-core.js](http://www.mootools.net/download/)
	- MooTools-more 1.2.1 RC1 or higher [mootools-more.js](http://www.mootools.net/more_rc1/)
	  - Assets
	  - JSONP
*/

var MooFlickrBadge = new Class({
	Implements: [Options, Events],
	options: {		
		size: 's',
		toImage: false,
		method: 'flickr.photos.getRecent',
		// amount: 9,
		apikey: 'fde15aa46be2237f9f35367ccddd3586',
		passData: {
			extras: 'user_id'
		},
		// onProgress: $empty
		// onComplete: $empty
	},
	
	initialize: function(where, options) {
		this.setOptions(options);
		this.where 		= $(where);
		this.response 	= new Hash();
		this.loadCount 	= 0;
		this.set 		= new Hash();
		this.fetch();		
	},
	
	// fetch JSON from flickr
	fetch: function() {
		this.req = new Request.JSONP({
			url: 			'http://api.flickr.com/services/rest/',
			data: $merge({
				api_key: 	this.options.apikey,
				method: 	this.options.method,
				per_page: 	this.options.amount,
				format: 	'json'
			}, this.options.passData),
			callbackKey: 	'jsoncallback',
			onComplete: 	this.attachPhoto.bind(this)
		}).send();
	},

	// preload all photos
	preload: function(photoUrl, details) {
		new Asset.image(photoUrl, {
			onload: function(photo) {
				this.injectPhoto(photo, details);
				this.fireEvent('progress', photo);
			}.bind(this)
		});
	},
	
	// inject and display photos
	injectPhoto: function(photo, details) {
		this.loadCount++;
		
		if(this.options.toImage) this.ref = 'http://farm'+details.farm+'.static.flickr.com/'+details.server+'/'+details.id+'_'+details.secret+'.jpg';
		else this.ref = 'http://www.flickr.com/photos/'+details.owner+'/'+details.id;

		this.set[this.loadCount] = new Element('a', {
			'href': this.ref,
			'title': details.title,
			'styles': {'opacity': 0}
		}).grab(photo).inject(this.where).fade('in');

		if(this.loadCount == this.response.perpage) this.fireEvent('complete', this.set);
	},
	
	// convert data into URLs
	attachPhoto: function(response) {
		this.response = response.photos;
		response.photos.photo.each(function(photo) {
			this.preload('http://farm'+photo.farm+'.static.flickr.com/'+photo.server+'/'+photo.id+'_'+photo.secret+'_'+this.options.size+'.jpg', photo);
		}, this);
	}
});