/*
=============================================================
	Site: creativewebspecialist.co.uk
	Version: 1.0.0
	Author: Warren Buckley
	Site: http://www.creativewebspecialist.co.uk

	This script uses AJAX to retrieve the album
	cover from Last.FM

=============================================================
*/


$(document).ready(function() {
	// do stuff when DOM is ready

	//For each li within the UL of class "LastFMRecent"
	$("ul.LastFMRecent li").each(function() {

		//Get values from HTML within the LI tag and store in variables	
		var ArtistName = $(this).find("span.ArtistName").text();
		var AlbumName = $(this).find("span.AlbumName").text();
		var TrackName = $(this).find("strong.TrackName").text();


		//Need to URLEncode the variables as these will build up the album art url
		var ArtistNameEncoded = urlencode(ArtistName);
		var AlbumNameEncoded = urlencode(AlbumName);	


		//Build up album art URL variable
		var albumURL = "http://ws.audioscrobbler.com/1.0/album/" + ArtistNameEncoded + "/" + AlbumNameEncoded + "/info.xml";


		//Setup variable for "this" as it cant be used in the ajax success function
		var tH = $(this);


		//Lets do our ajax CALL for the remote XML
		$.ajax({
			type: "GET",
			url: "/usercontrols/remotexml.aspx?url=" + albumURL,
			dataType: "xml",
			error: function(xhr,err,e){

				//If there is an error it displays in a popup
        			alert('Error:' + err);
			},
			success: function(xml) {

				//Find xml coverart/medium	
				imageURL = $(xml).find("coverart").find("large").text();

				//For Debug
				//alert(imageURL);
				
				//Check imageURL variable is empty
				if(imageURL == '')
				{
					//NO album art found, display noimage found graphic
					var strHTML = "<img src='/images/no_image.gif' width='126' height='126'/><br/>"
	
				}
				else
				{
					//Found artwork URL, use in image
					var strHTML = "<img src='" + imageURL + "' width='126' height='126'/><br/>"

				}

				//Prepend the strHTML variable to the current li item	
				$(tH).prepend(strHTML);
			}
		});

	});
            
});

//Function to urlencode characters
function urlencode(str) {
	str = escape(str);
	str = str.replace('+', '%2B');
	str = str.replace('%20', '+');
	str = str.replace('*', '%2A');
	str = str.replace('/', '%2F');
	str = str.replace('@', '%40');
	return str;
}
