/*---------------
 * jQuery Last.Fm Plugin by Engage Interactive, stripped down by Yoni Samlan and enhanced
 * with joiner/lastjoiner behavior
 * 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: 10,
            username: 'droppedd',
            apikey: 'e27a208d7e867ba430118d81328ad5fc',
            artSize: 'medium',
            noart: 'images/noartwork.gif',
            joiner: ', ',
            lastjoiner: ' and ',
            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) {
            
                // Make sure we only have one item per artist
				var tracks = [];
			    var artists = [];
                $.each(data.recenttracks.track,
                function(i, item) {
                    var artist = item.artist['#text'];
                    if ($.inArray(artist, artists)==-1) {
                        artists.push(artist);
						tracks.push(item);
                    }
                });

                $.each(tracks,
                function(i, item) {

                    url = stripslashes(item.url);
					song = item.name;
                    artist = item.artist['#text'];
					album = item.album['#text'];
					
                    $this.append(container);					
					
					var joiner;
					if (i==0) { joiner = ""; }
					else if (i < tracks.length - 1) { joiner = settings.joiner; }
					else { joiner = settings.lastjoiner; }
					
					var $current = $this.children(':last');
						$current.find('[class=lfm_joiner]').append(joiner);
                        $current.find('[class=lfm_artist]').append(artist);
                        if (item.image[1]['#text'] != '') {
                        	var art = stripslashes(item.image[imgSize]['#text']);
                            $current.find('[class=lfm_art]').append("<img src='" + art + "' alt='Artwork for " + album + "'/>");
                        }
                        $current.find('a').attr('href', url).attr('title', 'Listen to ' + song + ' on Last.FM').attr('target', '_blank');
                });
            });
        });
        settings.onComplete.call(this);
    };

    //Clean up the URL's
    function stripslashes(str) {
		return (str+'').replace(/\0/g, '0').replace(/\\([\\'"])/g, '$1');
    }
})(jQuery);
