(function($) {
    var methods = {
        init: function(options) {
            var $this = this;
            
            if(typeof options === "object") {
                $.extend($.fn.strobemediaplaylist.options, options);
                
                // Load from XML
                if(typeof $.fn.strobemediaplaylist.options.loadFromXml === "string") {
                    $this.strobemediaplaylist("loadFromXml");
                }
            }
            
            // Update container ID option
            $.fn.strobemediaplaylist.options.containerId = this.attr("id");
            
            return this;
        },
        loadFromXml: function() {
            var $this = this;
            var options = $.fn.strobemediaplaylist.options;
            
            // Load the playlist XML
            $.ajax({
                url: options.loadFromXml,
                cache: false,
                dataType: "text",
                success: function(data) {
                    // Fix xml for IE
                    if(jQuery.browser.msie) {
                        xml = new ActiveXObject("Microsoft.XMLDOM");
                        xml.async = false;
                        xml.loadXML(data);
                    } else {
                        xml = data;
                    }

                    // Process the XML
                    $this.empty();
                    var i = 0;
                    $(xml).find("channel").find("item").each(function() {
                        var id = $this.attr("id") + "_playlist_item_" + i;
                        var title = $(this).find("file").attr("title");
                        var url = $(this).find("file").attr("url"); 
                            
                        $this.strobemediaplaylist("add", {
                            id: id,
                            title: title,
                            url: url
                        });
                        
                        i++;
                    });
                    
                    $this.strobemediaplaylist("generatePlaylistHtml");
                    
                    return this;
                }
            });
        },
        add: function(item) {
            if(typeof item === "object") {
                $.fn.strobemediaplaylist.playlist[item.id] = item;
            }
        },
        generatePlaylistHtml: function() {
            var $this = this;
            var playlist = $.fn.strobemediaplaylist.playlist;
            var options = $.fn.strobemediaplaylist.options;
            
            var count = 0;
            $.each(playlist, function(i, item) {
                // Add list item
                var $listItem = $this.append($("<li></li>")
                   .append($("<a></a>")
                   .attr("id", item.id)
                   .attr("href", item.url)
                   .addClass("strobe-play")
                   .html(item.title)
                   .click(function(event){
                       if(typeof options.mediaplayer == "object") {
                           options.mediaplayer[0].setMediaResourceURL(item.url);
                           options.mediaplayer[0].play2();
                           
                           $this.children().children().removeClass("active");
                           $(this).addClass("active");
                       }

                       return false;
                   })
                ));
                
                // Play first clip (when played becomes ready)
                if(count == 0) {
                    // Keep trying to initiate the player for one second
                    var timeout = setInterval(function() {
                        if(typeof options.mediaplayer[0].setMediaResourceURL == "function") {
                            options.mediaplayer[0].setMediaResourceURL(item.url);
                            if(options.autoPlay == true) {
                                options.mediaplayer[0].play2();
                            }

                            // Add event listeners
                            options.mediaplayer[0].addEventListener("complete", "jQuery(\"" + $this.attr("id") + "\").strobemediaplaylist(\"onComplete\")");

                            clearTimeout(timeout);
                        }
                    }, 1);

                    setInterval(function(){
                        clearTimeout(timeout);
                    }, 1000);
                    
                    $listItem.children().children().addClass("active");
                }
                
                count++;
            });
        },
        onComplete: function() {
            var options = $.fn.strobemediaplaylist.options;
            var $this = $("#" + options.containerId);

            if(options.autoSkip) {
                var $nextItem = $this.find("li").find("a.active").parent().next();
                
                if($nextItem.length) {
                   options.mediaplayer[0].setMediaResourceURL($nextItem.find("a").attr("href"));
                   options.mediaplayer[0].play2();

                   $this.children().children().removeClass("active");
                   $nextItem.find("a").addClass("active");
                } else {
                   var $firstItem = $this.find("li:first").find("a"); 
                   
                   if($firstItem.length) {
                       options.mediaplayer[0].setMediaResourceURL($firstItem.attr("href"));
                       $this.children().children().removeClass("active");
                       $firstItem.addClass("active");
                   }
                }
                
                //console.log("will skip to next track here...");
            }
        }
    };
    
    // Method handler
    $.fn.strobemediaplaylist = function(method) {
        if(methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if(typeof method === "object" || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' +  method + ' does not exist on jQuery.mediaplayer');
        }
    }
    
    // Default options
    $.fn.strobemediaplaylist.options = {
        mediaplayer: null,
        autoPlay: true,
        autoSkip: true,
        containerId: ""
    };
    
    // Playlist items
    $.fn.strobemediaplaylist.playlist = {};
})(jQuery);
