/*
---
description: MooFlick Class. Takes a container div id, Flickr userid and optional options parameter and displays latest images from the users feed

license: MIT-style

authors:
- Matthew Wells

requires:
- core/1.2.1:*
- more:1.2.4.4:Request.JSONP
- more:1.2.4.4:Assets

provides: [MooFlick]

...

18.01.2011 - extension: uses api instead of feed

1QUERY) http://api.flickr.com/services/rest/?method=flickr.photosets.getList&format=json&api_key=f5e7435f924f5e34e6874458a7263999&user_id=51768239@N03
				
1RESPONSE) jsonFlickrApi({"photosets":{"photoset":[{"id":"72157624722461749", "primary":"4944724794", "secret":"0fa42399fc", "server":"4101", "farm":5, "photos":"21", "videos":0, "title":{"_content":"Un secolo d'aviazione"}, "description":{"_content":""}}, {"id":"72157624846842198", "primary":"4944139121", "secret":"bc187a0127", "server":"4095", "farm":5, "photos":"7", "videos":0, "title":{"_content":"parapendio Monte Generoso 2010"}, "description":{"_content":""}}, {"id":"72157624722420495", "primary":"4944708192", "secret":"4f61277e14", "server":"4138", "farm":5, "photos":"81", "videos":0, "title":{"_content":"Ritom & Blues"}, "description":{"_content":""}}, {"id":"72157624722418551", "primary":"4944123571", "secret":"b73603e8c0", "server":"4117", "farm":5, "photos":"4", "videos":0, "title":{"_content":"sapori nostrani"}, "description":{"_content":""}}, {"id":"72157624846785196", "primary":"4944699344", "secret":"fb0ab78f3a", "server":"4077", "farm":5, "photos":"60", "videos":0, "title":{"_content":"summerdream 2009"}, "description":{"_content":""}}, {"id":"72157624846782888", "primary":"4944114369", "secret":"1004b41c65", "server":"4136", "farm":5, "photos":"6", "videos":0, "title":{"_content":"Locarno City Garden"}, "description":{"_content":""}}, {"id":"72157624846781268", "primary":"4944113689", "secret":"bb83604242", "server":"4076", "farm":5, "photos":"5", "videos":0, "title":{"_content":"mapplethorpe"}, "description":{"_content":""}}, {"id":"72157624846779854", "primary":"4944113025", "secret":"c4f1db9962", "server":"4100", "farm":5, "photos":"5", "videos":0, "title":{"_content":"Zoom - Cultural Museum Lugano"}, "description":{"_content":""}}, {"id":"72157624722393273", "primary":"4944696136", "secret":"bed64e76ac", "server":"4094", "farm":5, "photos":"3", "videos":0, "title":{"_content":"Calvagione"}, "description":{"_content":""}}, {"id":"72157624846776870", "primary":"4944111683", "secret":"1abf6c3aa0", "server":"4135", "farm":5, "photos":"4", "videos":0, "title":{"_content":"Cimetta"}, "description":{"_content":""}}, {"id":"72157624846769350", "primary":"4944692294", "secret":"56a3787d4e", "server":"4135", "farm":5, "photos":"20", "videos":0, "title":{"_content":"The High Street of Leventina"}, "description":{"_content":""}}, {"id":"72157624846766988", "primary":"4944691340", "secret":"73389681d5", "server":"4076", "farm":5, "photos":"3", "videos":0, "title":{"_content":"Melidestate"}, "description":{"_content":""}}, {"id":"72157624846762650", "primary":"4944105661", "secret":"66ec436d21", "server":"4097", "farm":5, "photos":"11", "videos":0, "title":{"_content":"Excursion Leit - Tremorgio"}, "description":{"_content":""}}, {"id":"72157624722365689", "primary":"4944684524", "secret":"9f58d671d8", "server":"4095", "farm":5, "photos":"28", "videos":0, "title":{"_content":"Locarno Experience - 63\u00b0 Festival del film Locarno"}, "description":{"_content":""}}, {"id":"72157624722359911", "primary":"4944681784", "secret":"fac58c0cb2", "server":"4082", "farm":5, "photos":"15", "videos":0, "title":{"_content":"Berg und seen"}, "description":{"_content":""}}, {"id":"72157624846742700", "primary":"4944680774", "secret":"4b8dd17d11", "server":"4094", "farm":5, "photos":"3", "videos":0, "title":{"_content":"nara bike park"}, "description":{"_content":""}}, {"id":"72157624722222491", "primary":"4944621334", "secret":"a684de2f81", "server":"4116", "farm":5, "photos":"324", "videos":0, "title":{"_content":"Mountains and Lakes 2010"}, "description":{"_content":""}}, {"id":"72157624722176017", "primary":"4944600132", "secret":"fbe8af55f2", "server":"4121", "farm":5, "photos":"117", "videos":0, "title":{"_content":"Berge Und Seen - Day 1"}, "description":{"_content":""}}, {"id":"72157624846520558", "primary":"4943996941", "secret":"a91a2a0426", "server":"4140", "farm":5, "photos":"108", "videos":0, "title":{"_content":"Berge Und Seen - Day 2"}, "description":{"_content":""}}, {"id":"72157624512123009", "primary":"4853469358", "secret":"eac5786ebf", "server":"4123", "farm":5, "photos":"7", "videos":0, "title":{"_content":"Open Air Val Pontrone 2010"}, "description":{"_content":"Friday 6th and Saturday 7th August beach volley tournament and open air in Pontirone"}}, {"id":"72157624534335790", "primary":"4807544921", "secret":"8004f44713", "server":"4118", "farm":5, "photos":6, "videos":"4", "title":{"_content":"Moon and Stars 2010"}, "description":{"_content":"* Stevie Wonder\n* Ben Harper &amp; Relentless7; Support act: Milow\n* Massive Attack con Martina Topley Bird; Support act: Rodrigo y Gabriela\n* ZZ Top; Support act: Jeff Beck\n* P!nk; Support act: Silbermond\n* Eros Ramazzotti\n* Jamiroquai; Support act: Corinne Bailey Rae\n* Toto; Earth, Wind &amp; Fire\n* Mark Knopfler\n* Stress; Jan Delay &amp; Disko No. 1"}}, {"id":"72157624301137217", "primary":"4763244053", "secret":"edd26258ec", "server":"4114", "farm":5, "photos":"4", "videos":0, "title":{"_content":"Moon and Stars"}, "description":{"_content":""}}, {"id":"72157624300889499", "primary":"4763154853", "secret":"0d4135d97d", "server":"4121", "farm":5, "photos":"13", "videos":0, "title":{"_content":"Locarno Film Festival"}, "description":{"_content":""}}]}, "stat":"ok"})
			
2QUERY) http://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&format=json&api_key=f5e7435f924f5e34e6874458a7263999&photoset_id=72157624722461749
			
2RESPONSE) jsonFlickrApi({"photoset":{"id":"72157624722461749", "primary":"4944724794", "owner":"51768239@N03", "ownername":"ticino2share", "photo":[{"id":"4944724794", "secret":"0fa42399fc", "server":"4101", "farm":5, "title":"image", "isprimary":"1"}, {"id":"4944724936", "secret":"6f11698b0f", "server":"4098", "farm":5, "title":"image", "isprimary":"0"}, {"id":"4944140807", "secret":"3be175aa4d", "server":"4074", "farm":5, "title":"image", "isprimary":"0"}, {"id":"4944725228", "secret":"e8cba7e3e4", "server":"4097", "farm":5, "title":"image", "isprimary":"0"}, {"id":"4944725380", "secret":"1074e0fb1b", "server":"4120", "farm":5, "title":"image", "isprimary":"0"}, {"id":"4944141215", "secret":"da0128e209", "server":"4099", "farm":5, "title":"image", "isprimary":"0"}, {"id":"4944725592", "secret":"ce7117e47a", "server":"4116", "farm":5, "title":"image", "isprimary":"0"}, {"id":"4944725734", "secret":"f3f0ca3379", "server":"4119", "farm":5, "title":"image", "isprimary":"0"}, {"id":"4944141497", "secret":"d021a631fd", "server":"4143", "farm":5, "title":"image", "isprimary":"0"}, {"id":"4944141577", "secret":"5b42d57794", "server":"4143", "farm":5, "title":"image", "isprimary":"0"}, {"id":"4944725980", "secret":"88c813a562", "server":"4139", "farm":5, "title":"image", "isprimary":"0"}, {"id":"4944141753", "secret":"7dab641754", "server":"4102", "farm":5, "title":"image", "isprimary":"0"}, {"id":"4944141881", "secret":"8d3ff70dec", "server":"4123", "farm":5, "title":"image", "isprimary":"0"}, {"id":"4944142045", "secret":"dcc32e4e36", "server":"4073", "farm":5, "title":"image", "isprimary":"0"}, {"id":"4944142117", "secret":"49c697e6f4", "server":"4095", "farm":5, "title":"image", "isprimary":"0"}, {"id":"4944142261", "secret":"4dabe9a1bb", "server":"4094", "farm":5, "title":"image", "isprimary":"0"}, {"id":"4944142401", "secret":"bde03a5906", "server":"4135", "farm":5, "title":"image", "isprimary":"0"}, {"id":"4944142487", "secret":"edfb11f927", "server":"4102", "farm":5, "title":"image", "isprimary":"0"}, {"id":"4944142611", "secret":"1570975772", "server":"4122", "farm":5, "title":"image", "isprimary":"0"}, {"id":"4944727072", "secret":"b4c33e437e", "server":"4117", "farm":5, "title":"image", "isprimary":"0"}, {"id":"4944727158", "secret":"02580408e2", "server":"4141", "farm":5, "title":"image", "isprimary":"0"}], "page":1, "per_page":500, "perpage":500, "pages":1, "total":"21"}, "stat":"ok"})
			
3QUERY) http://api.flickr.com/services/rest/?method=flickr.photos.getInfo&format=json&api_key=f5e7435f924f5e34e6874458a7263999&photo_id=4944724794&photo_secret=0fa42399fc
			
3RESPONSE) jsonFlickrApi({"photo":{"id":"4944724794", "secret":"0fa42399fc", "server":"4101", "farm":5, "dateuploaded":"1283243175", "isfavorite":0, "license":"0", "safety_level":"0", "rotation":0, "originalsecret":"9b2eac5bc0", "originalformat":"jpg", "owner":{"nsid":"51768239@N03", "username":"ticino2share", "realname":"", "location":"", "iconserver":"4080", "iconfarm":5}, "title":{"_content":"image"}, "description":{"_content":""}, "visibility":{"ispublic":1, "isfriend":0, "isfamily":0}, "dates":{"posted":"1283243175", "taken":"2003-06-22 17:20:56", "takengranularity":"0", "lastupdate":"1283243178"}, "views":"19", "editability":{"cancomment":0, "canaddmeta":0}, "publiceditability":{"cancomment":1, "canaddmeta":0}, "usage":{"candownload":1, "canblog":0, "canprint":0, "canshare":1}, "comments":{"_content":"0"}, "notes":{"note":[]}, "tags":{"tag":[{"id":"51745185-4944724794-113574", "author":"51768239@N03", "raw":"2010", "_content":"2010", "machine_tag":0}, {"id":"51745185-4944724794-42470", "author":"51768239@N03", "raw":"alto", "_content":"alto", "machine_tag":0}, {"id":"51745185-4944724794-2625", "author":"51768239@N03", "raw":"ticino", "_content":"ticino", "machine_tag":0}, {"id":"51745185-4944724794-81262", "author":"51768239@N03", "raw":"aviazione", "_content":"aviazione", "machine_tag":0}, {"id":"51745185-4944724794-155748", "author":"51768239@N03", "raw":"castelgrande", "_content":"castelgrande", "machine_tag":0}, {"id":"51745185-4944724794-3945", "author":"51768239@N03", "raw":"estate", "_content":"estate", "machine_tag":0}, {"id":"51745185-4944724794-137819", "author":"51768239@N03", "raw":"eventi", "_content":"eventi", "machine_tag":0}, {"id":"51745185-4944724794-14459", "author":"51768239@N03", "raw":"e", "_content":"e", "machine_tag":0}, {"id":"51745185-4944724794-58271", "author":"51768239@N03", "raw":"cultura", "_content":"cultura", "machine_tag":0}, {"id":"51745185-4944724794-16702", "author":"51768239@N03", "raw":"evento", "_content":"evento", "machine_tag":0}, {"id":"51745185-4944724794-281526", "author":"51768239@N03", "raw":"giorno", "_content":"giorno", "machine_tag":0}, {"id":"51745185-4944724794-34249", "author":"51768239@N03", "raw":"non", "_content":"non", "machine_tag":0}, {"id":"51745185-4944724794-3853268", "author":"51768239@N03", "raw":"protetto", "_content":"protetto", "machine_tag":0}, {"id":"51745185-4944724794-32744", "author":"51768239@N03", "raw":"sole", "_content":"sole", "machine_tag":0}, {"id":"51745185-4944724794-966", "author":"51768239@N03", "raw":"sport", "_content":"sport", "machine_tag":0}, {"id":"51745185-4944724794-69620", "author":"51768239@N03", "raw":"aria", "_content":"aria", "machine_tag":0}, {"id":"51745185-4944724794-5324", "author":"51768239@N03", "raw":"swiss", "_content":"swiss", "machine_tag":0}, {"id":"51745185-4944724794-4350", "author":"51768239@N03", "raw":"image", "_content":"image", "machine_tag":0}, {"id":"51745185-4944724794-8336", "author":"51768239@N03", "raw":"valle", "_content":"valle", "machine_tag":0}]}, "urls":{"url":[{"type":"photopage", "_content":"http:\/\/www.flickr.com\/photos\/ticino2share\/4944724794\/"}]}, "media":"photo"}, "stat":"ok"})
			
4 build URL) http://farm5.static.flickr.com/4101/4944724794_0fa42399fc_z.jpg
			
*/

// here for debugging purpose
function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}


var MooFlick = new Class({

	options: {
		'num'             : 6,
		'url'             : 'http://api.flickr.com/services/feeds/photos_public.gne?id={id}&lang=en-us&format=json',
		'delay'           : 350,
		'max_rotation'    : 8,
		'size_reduction'  : 0.4,
		'mediabox'        : false, 
		'thumb_width'     : -1, 
		'thumb_height'    : -1,
		'photoset_filter' : '',
		'flickr_api_key'  : 'f5e7435f924f5e34e6874458a7263999'
			
	},

	Implements: [Events, Options],

	initialize: function(div, user_id, options){
		
		this.user_id = user_id;
		this.update_area = document.id(div);
		this.counter = 0;
		this.setOptions(options);
		this.baseUrl = "http://api.flickr.com/services/rest/?api_key=" + this.options.flickr_api_key + "&format=json",
		this.options.url = this.options.url.substitute({id:user_id});
		this.loadedImages = 0;
		this.make_request();
		
		
	},

	build_photo_url: function(jsonPhoto, format){

		var server = jsonPhoto.server;
		var farm = jsonPhoto.farm;
		var pictureId = jsonPhoto.id;
		var secret = jsonPhoto.secret;
		var ext = "jpg";
		
		var pictureUrl = "http://farm" + farm + ".static.flickr.com/" + server + "/" + pictureId + "_" + secret + "_" + format + "." + ext; 
		
		return pictureUrl;
		
	},
	
	queue_images: function(data){
		
		var images = $A([]);
		var images_data = $A([]);
		
		
		// 1. splice, so we can avoid to handle more than "num" images
		// 2. check overall loaded images before add extra images 
		$A(data.photoset.photo.splice(0,this.options.num)).each(function(item, index){
			
			// alert("this.loadedImages: " + this.loadedImages + "; this.options.num: " + this.options.num);
			if (this.loadedImages < this.options.num){
				images[index] = this.build_photo_url(item, "s");
				images_data[index] = item;
				this.loadedImages++;
			}
			
		},this);
		
		var loaded_images = new Asset.images(images, {
				onComplete:function(item){
					this.start_chain(loaded_images, images_data);
				}.bind(this)
			}
		);
		
	},
	
	make_request_for_photoset: function(data){
		
		for (var i = 0; i < data.photosets.photoset.length; i++){
			var photoset = data.photosets.photoset[i];
				
			if (this.options.photoset_filter == "" || this.options.photoset_filter.indexOf(photoset.id) >= 0){
				var photosetPhotoListUrl = this.baseUrl + "&method=flickr.photosets.getPhotos&photoset_id=" + photoset.id;
				new Request.JSONP({
					callbackKey: 'jsoncallback',
					url: photosetPhotoListUrl,
					onComplete: function(data) {
						this.queue_images(data);
					}.bind(this)
				}).send();
				
			} else {
				// do nothing
			}
		}

	},
	
	make_request: function(){
		
		var photoalbumListUrl = this.baseUrl + "&method=flickr.photosets.getList&user_id=" + this.user_id;
		new Request.JSONP({
			callbackKey: 'jsoncallback',
			url: photoalbumListUrl,
			onComplete: function(data) {
				this.make_request_for_photoset(data);
			}.bind(this)
		}).send();
		
	},

	start_chain: function(images, images_data){
		images.each(function(item, index){
			(function() {
				this.add_image(item, images_data[index]);
			}).delay(this.options.delay*index, this);
		},this);
	},

	create_dom_thumbnail: function(thumbnail, largeImage, flickrLink, title, description){
		
		var cl = (this.counter % 2 == 0) ? 'even' : 'odd';
		// var t_img = item;

		var img = new Element("img", {
			'src': thumbnail
		});
		var a; 
		
		// outer div
		var d = new Element("div", {
			'class':'single-item '+cl,
			'styles': {
				'opacity':'0',
				'text-align':'center'
			}
		});
		
		if (this.options.mediabox) {
			// pass the IMG link
			a = new Element("a", {
				'href' : largeImage,
				'title': title		// quali altre opzioni ci sono?
			});
			a.set("rel", "lightbox[set 640 480]");
		} else {
			// pass the HTML link
			a = new Element("a", {
				'href':flickrLink,
				'title':title
			});
		}
		
		d.adopt(a.adopt(img));

		this.update_area.adopt(d);

		this.fireEvent('onAdd', img);

		this.show_image(d, img)
		
		// rescan mediabox items
		if (this.options.mediabox) {
			Mediabox.scanPage();
		}
	},
	
	add_image: function(item, data){
		
		// need to create object after discovering sizes
		var imageSizesUrl = this.baseUrl + "&method=flickr.photos.getSizes&photo_id=" + data.id;
		
		new Request.JSONP({
			callbackKey: 'jsoncallback',
			url: imageSizesUrl,
			onComplete: function(data) {
				
			
				var title = "";
				var description = "";
			
				var square = "";
				var thumbnail = "";
				var medium = "";
				var small = "";
				var large = "";
				var extralarge = "";
				var original = "";
				
				var squareUrl = "";
				var thumbnailUrl = "";
				var mediumUrl = "";
				var smallUrl = "";
				var largeUrl = "";
				var extralargeUrl = "";
				var originalUrl = "";
				
				var flickrLink = "";
				
				for (var i = 0; i < data.sizes.size.length; i++){
					var tempSize = data.sizes.size[i];
					
					if (tempSize.label == "Square"){
						square = tempSize.source;
						squareUrl = tempSize.url;
					} else if(tempSize.label == "Thumbnail"){
						thumbnail = tempSize.source;
						thumbnailUrl = tempSize.url;
					} else if(tempSize.label == "Small"){
						small = tempSize.source;
						smallUrl = tempSize.url;
					} else if(tempSize.label == "Medium"){
						medium = tempSize.source;
						mediumUrl = tempSize.url;
					} else if(tempSize.label == "Large"){
						large = tempSize.source;
						largeUrl = tempSize.url;
					} else if(tempSize.label == "ExtraLarge"){
						extralarge = tempSize.source;
						extralargeUrl = tempSize.url;
					}
					
				}
				
				
				/*
				alert("available sizes: " + 
				"\nsquare = " + square + 
				"\nthumbnail = " + thumbnail + 
				"\nmedium = " + medium + 
				"\nsmall = " + small + 
				"\nlarge = " + large + 
				"\nextralarge = " + extralarge + 
				"\noriginal = " + original);
				*/
				
				if (original != ""){
					this.create_dom_thumbnail(square, original, originalUrl, title, description);
				} else if (extralarge != ""){
					this.create_dom_thumbnail(square, extralarge, extralargeUrl, title, description);
				} else if (large != "") {
					this.create_dom_thumbnail(square, large, largeUrl, title, description);
				} else if (medium != "") {
					this.create_dom_thumbnail(square, medium, mediumUrl, title, description);
				} else if (thumbnail != "") {
					this.create_dom_thumbnail(square, thumbnail, thumbnailUrl, title, description);
				} else {
					this.create_dom_thumbnail(square, square, squareUrl, title, description);
				}
			
			}.bind(this)
		}).send();
		
	},

	show_image: function(container, img){
		var t_size = img.getSize();
		
		var dest_width;
		var dest_height;
		
		// custom width
		if (this.options.thumb_width && this.options.thumb_width > 0){
			dest_width = this.options.thumb_width
		} else {
			// legacy
			dest_width = t_size.x * this.options.size_reduction;
		}
		
		// custom height
		if (this.options.thumb_height && this.options.thumb_height > 0){
			dest_height = this.options.thumb_height
		} else {
			// legacy
			dest_height = t_size.y * this.options.size_reduction;
		}
		
		var max = (dest_height > dest_width) ? dest_height : dest_width ;
		var rot = $random(-this.options.max_rotation,this.options.max_rotation)

		img.set('styles',{
			'height':0,
			'width':0 //,
			// '-webkit-box-shadow': '3px 3px 10px rgba(0, 0, 0, 0.3)',
			// '-moz-box-shadow': '3px 3px 10px rgba(0, 0, 0, 0.3)',
			// 'box-shadow': '3px 3px 10px rgba(0, 0, 0, 0.3)'
			});
			
		
		container.set('styles',{'height':max+8,'width':max+8, 'text-align':'center'})

		container.fade('in');
		
		img.get('morph').start({
			'height':dest_height,
			'width':dest_width,
			'vertical-align':'middle'//,
			// '-moz-transform':'rotate('+rot+'deg)',
			// '-webkit-transform':'rotate('+rot+'deg)',
			// 'padding':'4px',
			// 'border':'1px solid #DDDDDD' 
		}).chain(function(){
			this.fireEvent('onShow', img)
		}.bind(this));
		
		this.counter++;
	}
})
