class window.Player
  
  bar_width: 263
  jp: null
  scrobbled: false
  albums: []
  playlist: []
  
  initJplayer: ->
    self = this
    
    @jp = $("#jplayer")
    @jp.jPlayer
      swfPath: "/js"
      supplied: "mp3"
      cssSelectorAncestor: ""
      cssSelector:
        play: ".player .play"
        pause: ".player .pause"
        stop: ""
        videoPlay: ""
        seekBar: ""
        playBar: ""
        mute: ""
        unmute: ""
        volumeBar: ""
        volumeBarValue: ""
        currentTime: ""
        duration: ""
    
    @jp.bind $.jPlayer.event.timeupdate, (e) ->
      data = e.jPlayer.status
      if not _player.scrobbled and data.currentPercentAbsolute > 50
        $obj = $('.playlist li.now')
        self.scrobble _player.getTrackInfo $obj.attr('data-id')
        _player.scrobbled = true
      $('.player .progress .loaded').width(data.seekPercent * self.bar_width / 100)
      $('.player .progress .played').width(data.currentPercentAbsolute * self.bar_width / 100)
    
    @jp.bind $.jPlayer.event.ended, (e) ->
      next = self.nextTrack()
      if not next
        $('#jplayer').jPlayer 'clearMedia'
        $('.player .now-playing').html 'Nothing left to <strike>lose</strike> play'
        $('.player .loaded, .player .played').width 0
        $('.playlist li').removeClass 'now'
      else
        self.setTrack next
    false
  
  addTracks: (tracks, autoplay) ->
    if not autoplay?
      autoplay = false
    initial_count = $('.playlist li').length
    for item in tracks
      $('.playlist').append '
      <li id="i' +Math.round(Math.random() * 999999)+ '" data-id="'+item.id+'">
        <div class="song-duration">' +item.duration+ '</div>
        <div class="remove">remove</div>
        <div class="artist-name">' +item.artist+ '</div>
        <div class="song-title">' +item.name+ '</div>
      </li>'
      _player.playlist.push item
    $('.playlist').sortable axis: 'y', cursor: 'move'
    if initial_count == 0 and not _player.hasTrack()
      _player.setTrack($('.playlist li').first().attr('id').split('i')[1])
    false
  
  getDataFromLi: (obj) ->
    id = $(obj).attr 'data-id'
    track_name = $(obj).find('.trackname').html()
    length = $(obj).find('.length').html()
    id: id, name: track_name, length: length
  
  setTrack: (id) ->
    $obj = $('#i' +id)
    track = _player.getTrackInfo $obj.attr('data-id')
    query = track.artist+ ' &mdash; ' +track.name
    
    $('.player .loaded, .player .played').width 0
    $('.player .now-playing').html query
    $('.playlist li').removeClass 'now'
    $obj.addClass 'now'
    _vk_music.search track.artist, track.name, track.duration, (url) ->
      _player.playSource url
    this.updateNowListening track
    false
  
  getTrackInfo: (id) ->
    for track in _player.playlist
      if parseInt(track.id, 10) == parseInt(id, 10)
        return track
    false
  
  hasTrack: ->
    if $('#jplayer audio').length > 0
      return $('#jplayer audio').attr('src')? and $('#jplayer audio').attr('src') != ''
    else if $('#jplayer object').length > 0
      $('#jplayer').jPlayer 'play'
      true
    false
  
  playSource: (url) ->
    @scrobbled = false
    $('#jplayer').jPlayer 'setMedia', mp3: url
    $('#jplayer').jPlayer 'play'
    false
  
  nextTrack: (manual) ->
    manual = manual?
    cnt = $('.playlist li').length
    if not this.onShuffle()                              # Shuffle off
      if $('.playlist .now').next().length == 0              # Last track and repeat is on
        if _player.onRepeat() or manual                      # Repeat or manual click
          return $('.playlist li').first().attr('id').split('i')[1]
        else
          false
      else
        return $('.playlist .now').next().attr('id').split('i')[1]
    else if cnt == 1                                # Single track in the playlist
      return $('.playlist li').first().attr('id').split('i')[1]
    else                                      # Shuffle on
      while true
        rnd = Math.floor(Math.random() * (cnt + .999))
        $li = $('.playlist li').eq rnd
        if $li.length > 0 and not $li.hasClass 'now'
          return $li.attr('id').split('i')[1]
    false
  
  prevTrack: ->
    cnt = $('.playlist li').length
    if not _player.onShuffle()                            # Shuffle off
      if $('.playlist .now').prev().length == 0              # First track in the playlist
        return $('.playlist li').last().attr('id').split('i')[1]
      else
        return $('.playlist .now').prev().attr('id').split('i')[1]
    else if cnt == 1                                # Single track in the playlist
      return $('.playlist li').first().attr('id').split('i')[1]
    else                                      # Shuffle on
      while true
        rnd = Math.floor(Math.random() * (cnt + .999))
        $li = $('.playlist li').eq rnd
        if $li.length > 0 and not $li.hasClass 'now'
          return $li.attr('id').split('i')[1]
    false
  
  onShuffle: ->
    return $('.shuffle').hasClass 'on'
  
  onRepeat: ->
    return $('.repeat').hasClass 'on'
  
  updateNowListening: (track) ->
    if _session.getUser().lastfm_username
      _session.query '/lastfm/listening?r=' +Math.random(), track
    false
  
  scrobble: (track) ->
    if _session.getUser().lastfm_username
      _session.query '/lastfm/scrobble?r=' +Math.random(), track
    false


# Player Controls

$('.player .prev').live 'click', ->
  _player.setTrack _player.prevTrack()
  false

$('.player .next').live 'click', ->
  _player.setTrack _player.nextTrack(true)
  false

$('.player .play').live 'click', ->
  if $('.playlist li').length > 0 and not _player.hasTrack()
    _player.setTrack $('.playlist li').first().attr('id').split('i')[1]
  false

$('.player .progress').live 'click', (e) ->
  $('#jplayer').jPlayer 'playHead', Math.round((e.offsetX / _player.bar_width) * 100)
  false

# Player Additional Controls

$('.repeat, .shuffle').live 'click', ->
  $(this).toggleClass 'on'
  false

$('.do_empty').live 'click', ->
  if confirm('Are you sure?')
    $('.playlist li').remove()
    $('#jplayer').jPlayer 'clearMedia'
    $('.player .now-playing').text 'Add some music to playlist'
    $('.player .loaded, .player .played').width 0
  false

# Playlist Actions

$('.playlist li .artist-name, .playlist li .song-title, .playlist li .song-duration, .playlist li .remove').live 'mousemove mouseover mouseout', (e) ->
  if e.type in ['mouseover', 'mousemove'] and $('.playlist').offset().left + $('.playlist').outerWidth() - e.clientX < 60
    $(this).parent().find('.song-duration').hide()
    $(this).parent().find('.remove').show()
  else
    $(this).parent().find('.remove').hide()
    $(this).parent().find('.song-duration').show()
  false

$('.playlist li .remove').live 'click', (e) ->
  $li = $(this).parent()
  if $li.hasClass 'now'
    $('#jplayer').jPlayer 'clearMedia'
    $('.player .now-playing').text '...'
    $('.player .loaded, .player .played').width 0
  $li.remove()
  e.preventDefault()
  false

$('.playlist li').live 'click', ->
  _player.setTrack $(this).attr('id').split('i')[1]
  false
  
# Adding To Playlist actions

$('.add-album').live 'click', ->
  artist = $('.artist-info h2').text()
  album = _player.albums[$(this).attr('data-album-id')]
  for item in album.tracks
    item['artist'] = artist
    item['album'] = album.name
  _player.addTracks album.tracks
  false