var player = null, controls, timer;

var currentIndex, currentVolume, currentMuteState, currentPosition, oldPosition, currentPlayState, duration, playerHeight, playerWidth, hasCaptions, isPlaylist, playlistObject, currentCaptionState, hasPlayed, hasDownloaded;

// Initialize. Called when player ready.
function playerReady(obj) {
  player = $('#'+obj['id']).get(0);
  
  //make the player not focusable by keyboard
  $(player).attr('tabindex','-1');
  
  isPlaylist = ( player.getConfig().type == undefined ) ? true : false;
  
  getPlaylist();
  
  function getPlaylist () {
    playlistObject = player.getPlaylist();
    if ( playlistObject ) continueInit();
    else setTimeout(getPlaylist, 20);
  }
  
  function continueInit() {
    // same size as playlistObject
    // represents if the item in the playlist has been played
    hasPlayed = [];
    for ( var i = playlistObject.length; i--; ) {
      hasPlayed[i] = false;
    }

    currentIndex = 0;  
    currentVolume = player.getConfig().volume;
    currentMuteState = player.getConfig().mute;
    currentPosition = player.getConfig().start;
    player.hideCaptions(true);
    if ( isPlaylist ) {
      hasCaptions = playlistObject[0].captions ? true : false;
    } else {
      hasCaptions = player.getConfig().captions ? true : false;
    }
    
    currentCaptionState = false;
      
    oldPosition = currentPosition;
    duration = playlistObject[0].duration;
    playerHeight = player.getConfig().height;
    playerWidth = player.getConfig().width;
    
    controls = createControls();
    timer = createTimer();
    timer.current.find('strong').text(formatTime(currentPosition));
    timer.duration.find('strong').text(formatTime(duration));
    
    if ( isPlaylist ) {
      createPlaylist();
    }
    
    updateVolume();
    updateMuteState();
    
    addListeners();
    
    setInterval(updateTimer, 500);
  
    // Timeprogress
    timer.progress.click(function(e) {
      // relative click position inside the div
      var x = e.pageX - Math.ceil($(this).offset().left);
  	  var calcpos = duration * ( x / $(this).innerWidth() );
  	  
  	  player.sendEvent("SEEK", calcpos);
    });  
  
    // Play
    controls.play.click(function() {
      player.sendEvent("PLAY");
      return false;
    });
    
    // Stop
    controls.stop.click(function() {
      player.sendEvent("STOP");
      if ( type != 'sound' && !controls.resize.hasClass('smallSize') )
        controls.resize.trigger('click');
      return false;
    });
    
    // Go back by 5% of length, unless that is less than 10 seconds
    controls.seekBackward.click(function() {
      var skiptime = 10;
      if (duration / 20 > 10) {
        skiptime = Math.floor(eval(duration / 20));
      } 
      var calcpos = currentPosition - skiptime;
      player.sendEvent("SEEK", calcpos);
      return false;
    });
    
    // Go forward by 5% of length, unless that is less than 10 seconds
    controls.seekForward.click(function() {
      var skiptime = 10;
      if (duration / 20 > 10) {
        skiptime = Math.floor(eval(duration / 20));
      } 
      var calcpos = currentPosition + skiptime;
      player.sendEvent("SEEK", calcpos);
      return false;
    });
    
    // Volume Bar
    controls.volume.click(function(e) {
      // relative click position inside the div
      var x = e.pageX - Math.ceil($(this).offset().left);
  	  var volume = Math.round(100 * ( x / $(this).innerWidth() ));
  	  
      player.sendEvent("VOLUME", volume);
    });
    
    // Volume Down
    controls.volumeDown.click(function() {
      var volume = currentVolume - 10;
      volume = ( volume <= 0 ) ? 0 : volume;
      player.sendEvent("VOLUME", volume);
      return false;
    });
    
    // Volume Up
    controls.volumeUp.click(function() {
      var volume = currentVolume + 10;
      volume = ( volume >= 100 ) ? 100 : volume;
      player.sendEvent("VOLUME", volume);
      return false;
    });
    
    // Mute
    controls.mute.click(function() {
      player.sendEvent("MUTE");
      return false;
    });
    
    // Resize
    if ( type != 'sound' ) {
      controls.resize.click(function() {
        if ( $(this).hasClass('smallSize') ) {
          $(this)
            .removeClass('smallSize')
            .attr('title', lang['shrink'])
            .html('<span class="hidden">'+lang['shrink']+'</span>');
          $('#mediaPlayer').addClass('bigSize');
          var bigHeight = Math.floor(920 / (playerWidth / playerHeight));
          $('#objectWrapper').css( { width: '920px', height: bigHeight+'px', verticalAlign: 'middle'} );
        } else {
          $(this)
            .addClass('smallSize')
            .attr('title', lang['enlarge'])
            .html('<span class="hidden">'+lang['enlarge']+'</span>');
          $('#mediaPlayer').removeClass('bigSize');
          $('#objectWrapper').css( { width: playerWidth+'px', height: playerHeight+'px'} );
        }
        return false;
      });
    }
    
    // Captions
    if ( controls.captions ) {
      controls.captions.click(function() {
        if ( currentCaptionState == false ) {
          player.hideCaptions(false);
          currentCaptionState = true;
          $(this)
            .addClass('on')
            .attr('title', lang['captionsOff'])
            .html('<span class="hidden">'+lang['captionsOff']+'</span>');
        } else {
          player.hideCaptions(true);
          currentCaptionState = false;
          $(this)
            .removeClass('on')
            .attr('title', lang['captionsOn'])
            .html('<span class="hidden">'+lang['captionsOn']+'</span>');
        }
        return false;
      });
    }
  }
  
  function createControls () {
    $('#objectWrapper').after('<div id="mediaControlPanel"><span class="hidden">Videosteuerung</span><ul id="mediaControls" class="clearfix"></ul></div>');
    if ( type == 'sound' ) {
       $('#objectWrapper').css( { height: playerHeight+'px', opacity: 0} );
       $('#mediaControlPanel').css({marginTop: '-20px'}).find('span').text('Audiosteuerung');
    }
    $('#mediaControlPanel').width(playerWidth+'px');
    var controls = $('#mediaControls');
    var controlsObject = {};
    var defineControls = {
      play: '<li class="mediaPlayControls"><a id="mediaplay" title="'+lang['play']+'" href="#"><span class="hidden">'+lang['play']+'</span></a></li>',
      stop: '<li class="mediaPlayControls"><a id="mediastop" title="'+lang['stop']+'" href="#"><span class="hidden">'+lang['stop']+'</span></a></li>',
      seekBackward: '<li class="mediaPlayControls"><a id="mediaseekBackward" title="'+lang['backward']+'" href="#"><span class="hidden">'+lang['backward']+'</span></a></li>',
      seekForward: '<li class="mediaPlayControls"><a id="mediaseekForward" title="'+lang['forward']+'" href="#"><span class="hidden">'+lang['forward']+'</span></a></li>',
      volumeDown: '<li class="mediaVolumeControls"><a id="mediavolumeDown" title="'+lang['quieter']+'" href="#"><span class="hidden">'+lang['quieter']+'</span></a></li>',
      volume: '<li class="mediaVolumeControls" id="mediavolume"><span class="hidden"></span><div id="mediavolumeInner" /></li>',
      volumeUp: '<li class="mediaVolumeControls"><a id="mediavolumeUp" title="'+lang['louder']+'" href="#"><span class="hidden">'+lang['louder']+'</span></a></li>',
      mute: '<li class="mediaVolumeControls"><a id="mediamute" title="'+lang['mute']+'" href="#"><span class="hidden">'+lang['mute']+'</span></a></li>'
    };
    
    if ( type != 'sound' ) {
      defineControls['resize'] = '<li class="mediaExtrasControls"><a id="mediaresize" title="'+lang['enlarge']+'" href="#" class="smallSize"><span class="hidden">'+lang['enlarge']+'</span></a></li>';
      defineControls['captions'] = '<li class="mediaExtrasControls"><a id="mediacaptions" title="'+lang['captionsOn']+'" href="#"><span class="hidden">'+lang['captionsOn']+'</span></a></li>';
    }
    
    $.each(defineControls, function(key, value) {
      controls.append(value);
      controlsObject[key] = controls.find('#media'+key);
    });
    
    if ( type != 'sound' && !hasCaptions ) {
      controlsObject.captions.parent().hide();
    }
    
    $('.mediaPlayControls').wrapAll('<ul id="mediaPlayControls"></ul>');
    $('.mediaVolumeControls').wrapAll('<ul id="mediaVolumeControls"></ul>');
    $('.mediaExtrasControls').wrapAll('<ul id="mediaExtrasControls"></ul>');
    
    $('#copyright').remove().clone().appendTo('#mediaControlPanel').show();
    
    return controlsObject;
  }
  
  function createTimer () {
    $('#mediaControls').before('<div id="mediaTimer" class="clearfix"></div>');
    var timer = $('#mediaTimer');
    var timerObject = {};
    
    $.each({
      current: '<div id="timercurrent"><span class="hidden">'+lang['currentPosition']+'</span> <strong></strong></div>',
      progress: '<div id="timerprogress"><div id="timerinnerProgress"></div></div>',
      duration: '<div id="timerduration"><span class="hidden">'+lang['duration']+'</span> <strong></strong></div>'
    }, function(key, value) {
      timer.append(value);
      timerObject[key] = timer.find('#timer'+key);
    });
    
    return timerObject;
  }
  
  function createPlaylist () {
    $('#mediaControlPanel').addClass('isPlaylist').prepend('<ol id="playlist"></ol>');
    var playlist = $('#playlist');
    
    $.each(playlistObject, function(i, item) {
      playlist.append('<li class="clearfix"><a href="#" id="playlistItem'+i+'">'+item.title+'</a> <span>'+formatTime(item.duration)+'</span></li>');
    });
    
    playlist.find('li').each(function(i) {
      $(this)
      .hover(
        function() {
          $(this).addClass('hover');
        },
        function() {
          $(this).removeClass('hover');
        }
      )
      .click(function() {
        playlist.find('li').removeClass('active');
        $(this).addClass('active');
        player.sendEvent("ITEM", i);
        return false;
      });
      
      if ( i == 0 ) $(this).addClass('active');
      
      if ( type == 'sound' && $('.audioDownload').length ) {
        updateAudioDownload(playlistObject[0]);
      }
    });
  }
  
  function updateTimer () {
    if (currentPosition != oldPosition) {
      var percent = ((currentPosition / duration)*100) + '%';
      $('#timerinnerProgress').css('width', percent);
      timer.current.find('strong').text(formatTime(currentPosition));
    }
    
    oldPosition = currentPosition;
  }
}

/*---------- Listeners ------------- */

// add Eventlisteners
function addListeners () {
  if ( player ) {
    player.addModelListener('STATE', 'playListener');
    player.addModelListener("TIME", "timeListener");
    player.addControllerListener("ITEM", "itemListener");
    player.addControllerListener("VOLUME", "volumeListener"); 
    player.addControllerListener("MUTE", "muteListener");
  } else {
    setTimeout(addListeners, 100);
  }
}

// Listen to Play
function playListener (obj) {
  currentPlayState = obj.newstate;
  
  var isPlay = ( currentPlayState == 'PLAYING' || currentPlayState == 'BUFFERING' ) ? true : false;
  
  if ( isPlay ) {
    controls.play
      .addClass('pause')
      .attr('title', lang['pause'])
      .html('<span class="hidden">'+lang['pause']+'</span>');
  } else {
    controls.play
      .removeClass('pause')
      .attr('title', lang['play'])
      .html('<span class="hidden">'+lang['play']+'</span>');
  }
}

// Listen to changed Playlistitem Event
function itemListener (obj) {
  var index = obj.index,
      item = playlistObject[index],
      isLocal = ( item.file.match(/media\/audio/) || item.file.match(/media\/video/) );
  currentIndex = index;
  
  if ( !hasPlayed[index] && isLocal ) {
    hasPlayed[index] = true;
    analytics.loadTrack('playMedia', { name: item.file });
  }
  
  duration = item.duration;
  timer.duration.find('strong').text(formatTime(duration));
  
  if ( type == 'sound' ) {
    updateAudioDownload(item);
    return;
  } 
  
  var getCaptions = isPlaylist ? item.captions : player.getConfig().captions
  hasCaptions = getCaptions ? true : false;
  
  if ( hasCaptions ) {
    controls.captions.parent().show();
    if ( currentCaptionState ) {
      player.hideCaptions(false);
    }
  } else {
    controls.captions.parent().hide();
    player.hideCaptions(true);
  }

}

// Listen to Volumechanges
function volumeListener (obj) {
  currentVolume = obj.percentage;
  updateVolume();
}

// Listen to Mutechanges
function muteListener (obj) {
  currentMuteState = obj.state;
  updateMuteState();
}

// Listen to Timechanges
function timeListener (obj) {
  currentPosition = obj.position;
}

/*---------- Helper Functions ------------- */

// Format a time in seconds
function formatTime (seconds) {
  var pos = Math.floor(seconds);
  
  var curSec = Math.floor(pos%60)+'';
  curSec = curSec.length == 1 ? '0'+curSec : curSec;
  var curMin = Math.floor(pos/60)+'';
  curMin = curMin.length == 1 ? '0'+curMin : curMin;
  
  return ( curMin + ':' + curSec );
}

function updateMuteState () {
  var volumeElement = $('#mediavolume');
  if ( currentMuteState == true ) {
    controls.mute
      .addClass('unmute')
      .attr('title', lang['unmute'])
      .html('<span class="hidden">'+lang['unmute']+'</span>');
    volumeElement.attr('title', lang['volume']+': '+lang['silent']).children().addClass('muted');
  } else {
    controls.mute
      .removeClass('unmute')
      .attr('title', lang['mute'])
      .html('<span class="hidden">'+lang['mute']+'</span>');
    volumeElement.children().removeClass('muted');
    updateVolume();
  }
}

function updateVolume () {
  var volumeElement = $('#mediavolume');
  var volumeText = lang['volume']+': '+currentVolume+'%';
  volumeElement
    .attr('title', volumeText)
    .children('span').text(volumeText)
    .next('#mediavolumeInner').css('width', currentVolume+'%');
}

// update Download Link of Audio Playlists
function updateAudioDownload (item) {
  $('.audioDownload a').attr('href', item.file+'/download');
}
