var MusicPlayer = function (elem, options) {
  this.elem = elem;
  this.player = $('#' + elem);
  this.options = options || {};
  this.playlist = null;
  
  for (var opt in options) {
    this[opt] = options[opt];
  }
  
  // Private
  var self = this,
      onReady = function () {
        
        // Play / Pause
        self.player.parent().find('li .track_controls a').bind('click', function () {
          var $parent = $(this).parent().parent(),
              index = $parent.index();
      
          if ($parent.hasClass('playing')) {
            $parent.removeClass('playing');
            api.pause();   
          } else {
            $parent.addClass('playing').siblings().removeClass('playing');
            api.play(index);
          }
          return false;
    
        });  
      },
  
      // Public
      api = {
        
        // Init
        init : function () {
    
          if (self.data_url) {
             api.fetchPlaylist(); 
          }
    
          self.player.jPlayer({
            ready : onReady, 
            swfPath : '/assets/player',
            nativeSupport: true
          });

        },
        
        // Fetch Playlist
        fetchPlaylist : function () {
          $.getJSON(self.data_url, api.setPlaylist);
        },
        
        // Set Playlist
        setPlaylist : function (playlist) {
          self.playlist = playlist;
        },
        
        // Play
        play : function (trackIndex) {
          self.player.jPlayer('setMedia', {
            mp3 : self.playlist[trackIndex]
          }).jPlayer("play");         
        },
        
        //  Pause
        pause : function () {
          self.player.jPlayer("pause");
        }
      };
   
       
  return api; 
};

