var player = '';

$(document).ready(function() {
  player = $('#music-player').get(0);

  // set the player's volume to 0.5 by default
  player.volume = 0.5;

  // on music track click
  $('.now-playing-list').on('click', '.music-track', function() {
    // change selected track
    changeSelectedTrack(this);
  });

  // on album art click
  $('.music-album').on('click', '.thumbnail', function() {
    // change selected album
    changeSelectedAlbum(this);
  });

  // on track end
  player.on('ended', function() {
    // find selected track
    changeSelectedTrack($('.music-track.selected').next());
  });
});

function changeSelectedAlbum(albumElem) {
  var oldSelected = $('.music-album.selected');
  var newSelected = $(albumElem).parent();

  if (oldSelected.data('albumid') != newSelected.data('albumid')) {
    // remove selected class from the old element and add it to the new one
    oldSelected.removeClass('selected');
    newSelected.addClass('selected');

    // change album info
    getAlbumInfo(albumElem);
    // change available songs
    getAlbumSongs(albumElem);
  }
}

function getAlbumInfo(albumElem) {
  albumElem = $(albumElem).parent();

  $.get('/apiv1/music/album-info/' + albumElem.data('albumid'), function(data) {
    var json = $.parseJSON(data);

    // change album artwork
    $('#album-artwork').attr('src', json.album_art);
    // change album title
    $('#album-title').text(json.title);
    // change album release date
    $('#album-release span').text(formatReleaseDate(json.release_date));
    // change album description
    $('#album-description').text(json.description);
  });
}

function formatReleaseDate(d) {
  var monthNames = [
    "January", "February", "March",
    "April", "May", "June", "July",
    "August", "September", "October",
    "November", "December"
  ];

  var date = new Date(d);
  var day = date.getDate();
  var monthIndex = date.getMonth();
  var year = date.getFullYear();

  return monthNames[monthIndex] + ' ' + day + ', ' + year;
}

function getAlbumSongs(albumElem) {
  albumElem = $(albumElem).parent();

  $.get('/apiv1/music/album-songs/' + albumElem.data('albumid'), function(data) {
    var json = $.parseJSON(data);
    var playlist = $('.now-playing-list');
    playlist.empty();

    for (var i = 0; i < json.songs.length; i++) {
      var song = json.songs[i];

      var songElem = $('<li></li>')
        .addClass('music-track')
        .attr('data-trackid', song.id)
        .attr('data-title', song.title)
        .attr('data-album', song.album_id)
        .attr('data-order', song.track_order)
        .attr('data-path', song.audio_file);

      if (i === 0) {
        songElem.addClass('selected');
      }

      songElem.html('<span>' + song.track_order + '. ' + song.title + '</span>');

      playlist.append(songElem);
    }

    changeAudioSources(playlist.find('.selected'), false);
  });
}

function changeSelectedTrack(trackElem) {
  var oldSelected = $('.now-playing-list .music-track.selected');
  var newSelected = $(trackElem);

  if (oldSelected.data('trackid') != newSelected.data('trackid')) {
    // remove selected class from the old element and add it to the new one
    oldSelected.removeClass('selected');
    newSelected.addClass('selected');

    // now change the audio sources
    changeAudioSources(trackElem, true);
  }
}

function changeAudioSources(trackElem, autoplay) {
  trackElem = $(trackElem);
  var playerSources = $('#music-player source');

  if (autoplay === null) {
    autoplay = false;
  }

  // retrieve audio file path from selected element
  var audioFilePath = trackElem.data('path');

  // loop through the audio player source elements
  playerSources.each(function() {
    // jQuery-ize the element
    source = $(this);

    if (source.attr('type') == 'audio/ogg') {
      // OGG source file
      source.attr('src', audioFilePath + '.ogg');
    } else if (source.attr('type') == 'audio/mpeg') {
      // MP3 source file
      source.attr('src', audioFilePath + '.mp3');
    }
  });

  // change track title
  $('#track-title').text(trackElem.data('title'));

  // reload music player
  player.load();

  if (autoplay) {
    // start playing new song
    player.play();
  }
}
