//<![CDATA[

/*
	name : lastfm
	file : jquery.lastfm.js
	author : gregory tomlinson
	(c) gregory tomlinson
	Dual licensed under the MIT and GPL licenses.
	///////////////////////////
	///////////////////////////		
	dependencies : jQuery 1.3.2
	///////////////////////////
	///////////////////////////	

*/

(function($) {

	$.fn.lastfm = function( options ) {
		// extend the defaults settings
		var el, o = $.extend(true, {}, defaults, options);
		$bod = $( document.body );
		el = this;
		connector( o.url, o.params, success );
		return this;		
		
		/**
		*	Declare any functions that require local scoping
		*
		*/
		function success(jo) {
			// access to el & o here
			if( o.params.limit > 1 && jo.recenttracks.track.length ) {
				for( i=0;i<jo.recenttracks.track.length;i++ ) {
					renderItems( jo.recenttracks.track[i] ).appendTo( el );
				}
			} else {
				// handle the non array returned
				renderItems( jo.recenttracks.track ).appendTo( el );
			}
		}
		



		function _findLargestImage(_imgarray) {
			// _imgarray is an array returned by last.fm that looks like
			// "image":[{"#text":"http:\/\/images.amazon.com\/images\/P\/B00004YYTW.02._SCMZZZZZZZ_.jpg","size":"small"},	
			// 	 			 {"#text":"http:\/\/images.amazon.com\/images\/P\/B00004YYTW.02._SCMZZZZZZZ_.jpg","size":"medium"},
			// 	 			 {"#text":"http:\/\/images.amazon.com\/images\/P\/B00004YYTW.02._SCMZZZZZZZ_.jpg","size":"large"}
			// 	 			]
	
   			_biggestYet = false;
	
    			jQuery.each(_imgarray, function(j, _img) {
     				if ('large' == _img.size) {
     					_biggestYet = _img['#text'];
     					// biggest found, get out of this loop
     					return false;
     				} else if ('medium' == _img.size) {
     					_biggestYet = _img['#text'];
     				} else if (('small' == _img.size) && ('' == _biggestYet)) {
     					_biggestYet = _img['#text'];
     				}
   			 });

			return _biggestYet;
		}


		function renderItems( itm ) {
			//alert(itm.name);
cdcover    = itm.image ? _findLargestImage(itm.image) : false;
cdcover = !cdcover || cdcover==''? "http://cdn.last.fm/depth/catalogue/noimage/cover_85px.gif":cdcover;
			var track = $("<div></div>").attr("id", "track"), n = new Date(), t=0;
			if ( typeof(itm.date) != "undefined" ) {
   				t = Math.round( (n.getTime() / 1000 - parseInt( itm.date.uts )) / 60 )
			} else {
   				t = 0;
   			}


				var ago = " ",
				cover = $("<div>")
					.attr("id", "cover").appendTo( track );
				a = $("<a> </a>")
					.attr("href", "http://last.fm/mbid/" + itm.album["mbid"])
					.attr("target", "_blank").appendTo( cover );
				img = $("<img>")
					.attr("src", cdcover)
					.attr("title", "Album: " + (itm.album["#text"]!=''?itm.album["#text"]:"unbekannt"))
					.attr("width", "34")
					.attr("height", "34").appendTo( a );
				artist = $("<div>")
					.attr("id", "artist").appendTo( track );
				a = $("<a> </a>")
					.attr("href", "http://last.fm/mbid/" + itm.artist["mbid"])
					.html( itm.artist["#text"] + " - " )
					.attr("target", "_blank").appendTo( artist );
				title = $("<div>")
					.attr("id", "title").appendTo( track );
				a = $("<a> </a>")
					.attr("href", itm.url)
					.html( itm.name )
					.attr("target", "_blank").appendTo( title );
				ago += ( t <= 1 ) ? "Now" : ( t < 60 ) ? t + " mins ago" : ( t < 3600 ) ? Math.round( t/60) + " hours ago" : Math.ceil( t/3600) + " days ago";
			var span = $("<div>")
					.html( ago )
					.attr("id", "time").appendTo( track );
			return track ;
		}		
		
	/* end the plugin function */
	}
	
	/**
	*	Declare the defaults here
	*/
	var defaults = {
	
		url : 'http://ws.audioscrobbler.com/2.0/?method=user.getRecentTracks',
		page : 'http://www.last.fm/user/',		
		user : 'gregory80', // default, override via options
		pageName : 'Recently on Last.fm',
		params : {
			limit : 5,
			format : 'json',			
			api_key : '0e08a37f63207afd22b959c4ba7a2c3e',
			user : 'gregory80'
		}
		
	}, $bod;
	
	/**
	*	JSONP Connector, get data from a remote source
	*/
	
	function connector(url, params, callback) {
		var str = $.param( params );
		$.ajax({
			dataType: 'jsonp',
			data : str,
			jsonp: 'callback',
			'url' : url,
			success: callback			
		});
	}

})(jQuery);

//]]>
