/*---------------
 * jQuery Last.Fm Plugin by Engage Interactive
 * Examples and documentation at: http://labs.engageinteractive.co.uk/lastfm/
 * Copyright (c) 2009 Engage Interactive
 * Version: 1.0 (10-JUN-2009)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * Requires: jQuery v1.3 or later
---------------*/

(function($){
	$.fn.lastFM = function(options) {
		
		var defaults = {
			number: 1,
			username: 'bluezoomadc',
			apikey: 'aeecb4f0074043bcb7518f0930b66f84',
			artSize: 'small',
			noart: '/images/lfm-noart.jpg',
			onComplete: function(){}
		},
		settings = $.extend({}, defaults, options);

		var lastUrl = 'http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user='+settings.username+'&api_key='+settings.apikey+'&limit='+settings.number+'&format=json&callback=?';
		var $this = $(this);
		
		var container = $this.html();
		
		//$this.children(':first').remove();
		
		if(settings.artSize == 'small'){imgSize = 0}
		if(settings.artSize == 'medium'){imgSize = 1}
		if(settings.artSize == 'large'){imgSize = 2}

		this.each(function() {
			
			$.getJSON(lastUrl, function(data){ 
				
						
				$.each(data.recenttracks.track, function(i, item){
					
					if(i==0){
					
						if(item.image[1]['#text'] == ''){
							art = settings.noart;
						}else{
							art = stripslashes(item.image[imgSize]['#text']);
						}
	
						url = stripslashes(item.url);
						song = item.name;
						artist = item.artist['#text'] + ' - ';
						album = item.album['#text'];
						
	
						$this.empty().append(container);
						
						//var $current = $this.children(':eq('+i+')');
						
						//$current.find('[class=lfm_song]').empty().append(song);
						//$current.find('[class=lfm_artist]').empty().append(artist);
						//$current.find('[class=lfm_album]').empty().html(album);
						//$current.find('[class=lfm_art]').empty().append("<img src='"+art+"' alt='Artwork for "+album+"'/>");
						//$current.find('a').attr('href', url).attr('title', 'Listen on Last.FM').attr('target', '_blank');
						
						$('.np').empty();
						if (song != '') {
							$('.np').html('Now playing<br />at the office:');	
						}
						$('.lfm_song a').empty().append(song);
						$('.lfm_artist').empty().append(artist);
						$('.lfm_album').empty().append(album);
						$('.lfm_art').empty().append("<img src='"+art+"' alt='Artwork for "+album+"'/>");
						$('.lfm_song a').attr('href', url).attr('title', 'Listen on Last.FM').attr('target', '_blank');
						
						//callback
						if(i==(settings.number-1)){
							settings.onComplete.call(this);
						}
						
						
					
					}
					
				});
			});
		});
	};
	
	//Clean up the URL's
	function stripslashes( str ) {	 
		return (str+'').replace(/\0/g, '0').replace(/\\([\\'"])/g, '$1');
	}
})(jQuery);
