/*
 * Monymusk Player 1.0
 * Written September 2009 by Meinhard Benn (http://benn.org/)
 *
 * Copy, rip, quote as you wish
 *
 * TODO:
 *   - Un-globalise monymuskPlayer references
 *   - Fix empty mp3 URLs
 */

function monymuskPlayer() {

  this.currentID = 0;
  this.idCounter = 0;
  this.playing = false;
  this.playlistURL = '';
  this.playlistLoading = false;
  this.songs = [];
  this.songIdPrefix = 's';

  this.addSong = function(url, title, date, description, atBeginning) {
    if (url == null) {
      // TODO: Some URLs are not properly parsed, needs fixing
      return false;
    }
    song = {
      id: this.idCounter,
      url: url,
      title: title,
      date: date,
      description: description,
      played: false
    };
    if (atBeginning) {
      this.songs.unshift(song);
    } else {
      this.songs.push(song);
    }
    this.idCounter++;
    return song;
  }

  this.markPlayed = function(id) {
    for(i in this.songs) {
      if (this.songs[i].id == id) {
        this.songs[i].played = true;
      }
    }
  }

  this.next = function() {
    if (this.playing) {
      return this.skipTo(this.positionByID(this.currentID) - 1);
    }
  }

  this.nextOnFinish = function() {
    nextResult = monymuskPlayer.next();
    if (nextResult != true) {
      // Stop player after last song
      monymuskPlayer.stop();
    }
  }

  this.play = function() {
    if (this.playing == false) {
      this.skipTo(this.songs.length - 1);
    }
  }

  this.loadPlaylist = function(data) {
    monymuskPlayer.songs = [];
    $.each(data.value.items, function(dummy, item){
      monymuskPlayer.addSong(item.link, item.title, item.pubDate, item.description);
    });
  }
 
  this.positionByID = function(id) {
    for(i in this.songs) {
      if (this.songs[i].id == id) {
        return i;
      }
    }
  }

  this.previous = function() {
    if (this.playing) {
      this.skipTo(this.positionByID(this.currentID) - 0 + 1);
    }
  }

  this.reloadPlaylistEvery = function(seconds) {
    if (this.playlistLoading == false) {
      this.reloadPlaylist();
    }
    window.setTimeout(function() {
      monymuskPlayer.reloadPlaylistEvery(seconds);
    }, seconds * 1000);
  }

  this.reloadPlaylist = function() {
    this.playlistLoading = true;
    $.getJSON(this.playlistURL, function(data) {
      monymuskPlayer.updatePlaylist(data);
      monymuskPlayer.renderPlaylist('playlist');
      monymuskPlayer.playlistLoading = false;
    });
  }

  this.renderPlaylist = function(container) {
    table = '<table id="' + container + '-table">';
    table += '<tr><th class="playlist-date">Date</th><th>Title</th><th>Description</th></tr>';
    table += '</table>';
    $("#" + container).html(table);
    $.each(this.songs, function(i, song) {
      $("#" + container + "-table").append('<tr id="playlist-item-' + song.id + '" class="playlist-item"><td class="playlist-date">' + song.date + '</td><td><a id="song-link-' + song.id + '" href="' + song.url + '">' + song.title + '</a></td>' + song.description + '</tr>');
      $("#song-link-" + song.id).click(function() {
        monymuskPlayer.skipTo(monymuskPlayer.positionByID(song.id));
        $(this).blur();
        return false;
      });
      if (monymuskPlayer.playing && monymuskPlayer.currentID == song.id) {
        $("#playlist-item-" + song.id).addClass("playlist-current");
      }
      if (song.played == false) {
        $("#playlist-item-" + song.id).addClass("playlist-unplayed");
      }
    });
  }

  this.skipTo = function(position) {
    if (position >= 0 && position < this.songs.length) {
      this.stop();
      song = this.songs[position];
      sound = soundManager.createSound({
        id: this.songIdPrefix + song.id,
        url: song.url,
        onfinish: monymuskPlayer.nextOnFinish
      });
      $("#playlist-item-" + song.id).addClass("playlist-current");
      $("#playlist-item-" + song.id).removeClass("playlist-unplayed");
      this.markPlayed(song.id);
      this.currentID = song.id;
      this.playing = true;
      $("#status").html('Playing: ' + song.title);
      sound.play();
      return true;
    }
    return false;
  }

  this.songByID = function(id) {
    for(i in this.songs) {
      if (this.songs[i].id == id) {
        return this.songs[i];
      }
    }
  }

  this.stop = function() {
    if (this.playing) {
      $("#playlist-item-" + this.currentID).removeClass("playlist-current");
      this.playing = false;
      $("#status").html('Stopped');
      soundManager.stopAll();
      soundManager.destroySound(this.songIdPrefix + this.currentID);
    }
  }

  this.updatePlaylist = function(data) {
    firstNewSong = 0;
    $.each(data.value.items.reverse(), function(dummy, item){
      songInPlaylist = false;
      $.each(monymuskPlayer.songs, function(dummy, song) {
        if (song.url == item.link) {
          songInPlaylist = true;
          return false;
        }
      });
      if (songInPlaylist == false) {
        newSong = monymuskPlayer.addSong(item.link, item.title, item.pubDate, item.description, true);
        if (firstNewSong == 0) {
          firstNewSong = newSong;
        }
      }
    });
    if (monymuskPlayer.playing == false) {
      monymuskPlayer.skipTo(monymuskPlayer.positionByID(firstNewSong.id));
    }
  }

}

var monymuskPlayer = new monymuskPlayer();
