var Playlist = function (instance, playlist) {

    var self = this;

    this.instance = instance; // String: To associate specific HTML with this playlist
    this.playlist = playlist; // Array of Objects: The playlist

    this.options = {
        ready:function () {
            self.displayPlaylist();
            self.playlistInit(false); // Parameter is a boolean for autoplay.
        },
        ended:function () {
            self.playlistNext();
        },
        play:function () {
            $(this).jPlayer("pauseOthers");
            self.playing = true;
        },
        pause: function() {
            self.playing = false;
        },
        swfPath:"js",
        supplied:"oga, mp3"
    }; // Object: The jPlayer constructor options for this playlist

    this.current = 0;
    this.playing = false;

    this.cssId = {
        jPlayer:"jquery_jplayer_",
        interface:"jp_interface_",
        playlist:"jp_playlist_"
    };
    this.cssSelector = {};

    $.each(this.cssId, function (entity, id) {
        self.cssSelector[entity] = "#" + id + self.instance;
    });

    if (!this.options.cssSelectorAncestor) {
        this.options.cssSelectorAncestor = this.cssSelector.interface;
    }

    $(this.cssSelector.jPlayer).jPlayer(this.options);

    $(this.cssSelector.interface + " .jp-previous").click(function () {
        self.playlistPrev();
        $(this).blur();
        return false;
    });

    $(this.cssSelector.interface + " .jp-next").click(function () {
        self.playlistNext();
        $(this).blur();
        return false;
    });
};

Playlist.prototype = {
    displayPlaylist:function () {
        var self = this;
        $(this.cssSelector.playlist + " ul").empty();
        for (i = 0; i < this.playlist.length; i++) {
            var listItem = "<li class='jp-playlist-item" + ((i === this.playlist.length - 1) ? " jp-playlist-last" : "") + "'>";
            listItem += "<div class='hairline'></div><a href='#' tabindex='1' class='jp-playlist-song'>" + this.playlist[i].name + ' <span style="color: #c2d8f3; font-style: italic;">by</span> <span style="color:#999;">' + this.playlist[i].artist +"</span></a> <a href='#' class='deleteBT'></a>";

            /**
             * Do you care about this stuff?  This looks like it may have been cut and pasted in from an example, and you probably don't need it.
             * Uncomment it if you want it though.
             */
            // Create links to free media
            /*if (this.playlist[i].free) {
                var first = true;
                listItem += "<div class='jp-free-media'>(";
                $.each(this.playlist[i], function (property, value) {
                    if ($.jPlayer.prototype.format[property]) { // Check property is a media format.
                        if (first) {
                            first = false;
                        } else {
                            listItem += " | ";
                        }
                        listItem += "<a id='" + self.cssId.playlist + self.instance + "_item_" + i + "_" + property + "' href='" + value + "' tabindex='1'>" + property + "</a>";
                    }
                });
                listItem += ")</span>";
            }*/

            listItem += "</li>";

            // Associate playlist items with their media
            $(this.cssSelector.playlist + " ul").append(listItem);

            /**
             * Do you care about this stuff?  This looks like it may have been cut and pasted in from an example, and you probably don't need it.
             * Uncomment it if you want it though.
             */
            // Disable free media links to force access via right click
            /*if (this.playlist[i].free) {
                $.each(this.playlist[i], function (property, value) {
                    if ($.jPlayer.prototype.format[property]) { // Check property is a media format.
                        $(self.cssSelector.playlist + "_item_" + i + "_" + property).data("index", i).click(function () {
                            var index = $(this).data("index");
                            $(self.cssSelector.playlist + "_item_" + index).click();
                            $(this).blur();
                            return false;
                        });
                    }
                });
            }*/
        }

        // Push an {index} data item onto each playlist entry
        $("li.jp-playlist-item").each(function(index) {
            $(this).data("index", index);
			$(this).fadeTo('fast', 0.5);
        });

		$("li.jp-playlist-item").hover(
			function() {$(this).fadeTo('fast', 1);},
			function() {$(this).fadeTo('fast', 0.5);}
		);

        // Make each song clickable
        $("li.jp-playlist-item > a.jp-playlist-song").click(function() {
            var index = $(this).parent().data("index");
            if (self.current !== index) {
                self.playlistChange(index);
            } else {
                $(self.cssSelector.jPlayer).jPlayer("play");
            }
            $(this).blur();
            return false;
        });

        // Make delete buttons clickable
        $("li.jp-playlist-item > a.deleteBT").click(function() {
            self.playlistRemove($(this).parent().data("index"));
            $(this).blur();
            return false;
			
        });

        // Make the list sortable
        // see : http://docs.jquery.com/UI/Sortable
        $(this.cssSelector.playlist + " ul").sortable({
            axis: 'y',
            update: function(event, ui) {
                var newPlaylist = [];
                var newCurrent = 0;
                // Build a new playlist using the {index} data from each sortable item, in the new order
                $(this).children().each(function() {
                    var index = $(this).data('index');
                    var song = self.playlist[index];
                    newPlaylist.push(song);
                    if(self.current == index) newCurrent = newPlaylist.length - 1;
                });
                self.playlist = newPlaylist;
                self.current = newCurrent;
                // Redraw the playlist
                self.displayPlaylist();
				Cufon.refresh();
            }
        });

        // Make sure to maintain the current track marker
        this.playlistMarkCurrentTrack(this.current);
    },

    playlistInit:function (autoplay) {
        if (autoplay) {
            this.playlistChange(this.current);
        } else {
            this.playlistConfig(this.current);
        }
    },
    playlistConfig:function (index) {
        this.playlistMarkCurrentTrack(index);
        this.current = index;
        if(this.playlist[this.current])
        {
            $(this.cssSelector.jPlayer).jPlayer("setMedia", this.playlist[this.current]);
        }
    },
    playlistMarkCurrentTrack:function(currentIndex) {
        // These lines should do the same thing the previous ones did (commented below), but without the ids, since I removed those in favor of data.
        $("li.jp-playlist-current").removeClass("jp-playlist-current").children().removeClass("jp-playlist-current");
        var newTrack = $(this.cssSelector.playlist + " ul").children()[currentIndex]
        $(newTrack).addClass("jp-playlist-current").children().addClass("jp-playlist-current");
        //$(this.cssSelector.playlist + "_item_" + this.current).removeClass("jp-playlist-current").parent().removeClass("jp-playlist-current");
        //$(this.cssSelector.playlist + "_item_" + index).addClass("jp-playlist-current").parent().addClass("jp-playlist-current");

        // Also change the name displayed above the controls
        if(this.playlist[currentIndex]) {
            $("#currentTrackTitle").text(this.playlist[currentIndex].name);
            $("#currentTrackArtist").text(this.playlist[currentIndex].artist);
            $("#currentTrackListing").fadeTo('fast', 1);
        } else {
            $("#currentTrackListing").fadeTo('fast', 0);
        }
    },
    playlistChange:function (index, play) {
        play = play !=  null ? play : true;
        index = index < this.playlist.length ? index : 0;
        this.playlistConfig(index);
        if(play) $(this.cssSelector.jPlayer).jPlayer("play");
    },
    playlistNext:function () {
        var index = (this.current + 1 < this.playlist.length) ? this.current + 1 : 0;
        this.playlistChange(index);
    },
    playlistPrev:function () {
        var index = (this.current - 1 >= 0) ? this.current - 1 : this.playlist.length - 1;
        this.playlistChange(index);
    },
    playlistAdd:function (name, artist, oga) {
        /* Push the new song onto the playlist array */
        this.playlist.push({name:name, artist: artist, oga:oga});
        // If the playlist was empty, reset the player's list
        if(this.playlist.length == 1) $(this.cssSelector.jPlayer).jPlayer("setMedia", this.playlist[this.current]);
        // Re-render the visual playlist
        this.displayPlaylist();
		Cufon.refresh();
    },
    playlistRemove:function (index) {
        // Remove the song at {index} from the playlist array
        this.playlist.splice(index, 1);
        // If the index to remove if the currently playing song, skip to the next track
        if(index == this.current) {
            this.playlistChange(this.current, this.playing);
        } else if(index < this.current) {
            this.current--;
        }
        // If the playlist is now empty, clear the player
        if(this.playlist.length <= 0) $(this.cssSelector.jPlayer).jPlayer("setMedia", {name: "", oga: ""});
        // Re-render the visual playlist
        this.displayPlaylist();
		Cufon.refresh();
    }
};

