
/* Create a cache object */
var cache = new LastFMCache();

/* Create a LastFM object */
var lastfm = new LastFM({
    apiKey : '10b13cef8ebb67baf708ac50a30e8f71',
    apiSecret : '017645165083d8cd08c82b6a1195e7c6',
    cache : cache
});

// extend jquery with self-invoking anonymous function
(function($) 
{
    $.fn.updateLastFmImages = function(elems) 
	{
    	var imageCounter = 0; 
        $.each(
				$(elems), function() 
				{
					var artist = '';
					if ($(this).is('a'))
					{ artist = $(this).attr('name') }
					else if ($(this).is('img'))
					{ artist = $(this).attr('alt') }
					if(artist !== undefined)
					{
						if(artist !== '')
						{
							//console.log("getting lastfm data for artist: " + artist);
							updateArtistImagesWithLastFM(artist, this)							
					   } //if
					}
	    		}
		);  // each
		return this; //allow jQuery chaining
    }
})(jQuery);

/* Load some artist info. */
function updateArtistImagesWithLastFM(the_artist, tag)
{
	lastfm.artist.getInfo({artist: the_artist}, {success: function(result){
	    //console.log(result);

	    fm_artist_image = result.artist.image[2]['#text'];
		fm_artist_image_large = result.artist.image[result.artist.image.length - 1]['#text'];
	    if(fm_artist_image != '')
		{
			if($(tag).is('img'))
			{
				//console.log("setting image src " + $(tag).attr("src") + " of artist " + the_artist + " to " + fm_artist_image);
				$(tag).attr("src", fm_artist_image);
				//$(tag).attr('rel', '');		// don't update this image in the future
			}
			else if($(tag).is('a'))
			{
				//console.log("setting a href " + $(tag).attr("href") + " of artist " + the_artist + " to " + fm_artist_image_large);
				$(tag).attr("href", fm_artist_image_large);
				//$(tag).attr('rel', '');		// don't update this image in the future
			}
		}
	  }, error: function(code, message){
	  	console.log("no lastFM data found for artist " + the_artist);
	  	return null;
	}});
}
