/*
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.3 or higher [mootools-core.js](http://www.mootools.net/download/)
	- MooTools-more 1.2.3.1 RC1 or higher [mootools-more.js](http://www.mootools.net/more_rc1/)
	  - Assets
	  - JSONP
Modifications (DJ Sept 09)
	- Modified to pull photos from a photoset by default
	- Per Page functionality removed, replaced with "if loadCount >= amount"
		lines in Inject & Display Photos. 
		Default Amount (5) Passed from Tridion Component
*/

var MooFlickrBadge = new Class({
	Implements: [Options, Events],
	options: {		
		size: 's',
		toImage: false,
		method: 'flickr.photosets.getPhotos',
		apikey: '2f2db27bf8dc4275ded813a2a3f6e0ae',
		passData: {photoset_id: '72157615803606591'}
		// 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.amount = this.options.amount;
		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.amount > this.response.total){
	this.amount =this.response.total;
	}
			if(this.loadCount <= this.amount)
			{
				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.amount) this.fireEvent('complete', this.set);

	},
	
	// convert data into URLs
	attachPhoto: function(response) {
		this.response = response.photoset;
		response.photoset.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);
	}
});

