/*
-----------------------------
Аудиоплеер собственной сборки
-----------------------------
*/

var ky = 0;

function MusicPlay(play_id) {
  
  //Данные из тега <audio>
  var player = document.getElementsByTagName('audio')[0];

  //Текущий трек 
  player.src = "/files/upload/music/source/"+play_id+".mp3";
  
  player.load();
  player.play(); 
  
  //Кастомный прогресс бар с перемоткой
  var progressBar = document.getElementById('audio-play');
  
  progressBar.addEventListener('click', function(event){
    
    let widthLeft = $(progressBar).offset().left;
    let x = event.pageX - widthLeft;
    let xPersent =  x / this.offsetWidth * 100;
    player.currentTime = player.duration * (xPersent / 100);
    var curtime = player.duration * (xPersent / 100);
    tick(curtime);
    player.play();
  
  });
  
  var bar = $('.audio-bar');    
  var barWidth = bar.parent().width();    
  var barChange = false;
  var perSecond = 0;
  var perPixel = 0;

  function changeBar() {
    
    bar.width(player.currentTime * perSecond);
  
  }
  
  //Начало воспроизведения
  player.addEventListener('playing', function(){ 
    
    show_play();
    
    barChange = setInterval(changeBar, 500); 
    tick(player.currentTime);
    $('.play-status-off').html('<i class="fa fa-play fa-fw"></i>');
    $('#play-status'+play_id).html('<img src="/system/AJAX/AlphaPlayer/icons/eq.gif">');
    
    PlayPause('play');
    PlayPause2('play');
    
    ky = play_id;
  
  });
  
  //Пауза
  player.addEventListener('pause', function(){ 
    
    clearInterval(barChange); barChange = false; changeBar();
    clearInterval(timer);
    $('#play-status'+play_id).html('<i class="fa fa-play fa-fw"></i>');
    
    PlayPause('pause');
    PlayPause2('pause');
  
  });
  
  //Конец воспроизведения
  player.addEventListener('ended', function(){ 

    clearInterval(timer);
    
    if (ky == play_id){
      
      var action = $('.fplay').attr('action');
      var action_id = $('.fplay').attr('id');
      
      ky = 0;
      
      player_sess(action, action_id);
    
    }
  
  });
  
  //Получение метаданных
  player.addEventListener('loadedmetadata', function(){ 
    
    perSecond = barWidth / player.duration; 
    perPixel = player.duration / barWidth;
    
    //Кнопка play
    $('#play').click(function() {
      
      player.play();
    
    });
    
    //Кнопка play
    $('#play3').click(function() {
      
      player.play();
    
    });
    
    //Кнопка pause
    $('#pause').click(function() {
      
      player.pause();
    
    });
    
    //Кнопка pause2
    $('#pause2').click(function() {
      
      player.pause();
    
    });
    
    //Кнопка pause3    
    $('#pause3').click(function() {
      
      player.pause();
    
    });
    
    //Включить звук
    $('#volumep').click(function() {
      
      var v = player.volume + 1;
      player.volume = v >= 1 ? 1 : v;
    
    });
    
    //Выключить звук
    $('#volumem').click(function() {
      
      var v = player.volume - 1;
      player.volume = v <= 0 ? 0 : v;
    
    });
    
    //Длительность трека
    var dt = duration_format(player.duration); 
    
    $('.duration').html(dt);
  
  });
  
  return false;

}

//Функция для нормального отображения часов/минут/секунд в человеческом формате
function duration_format(time){   
  
  var hrs = ~~(time / 3600);
  var mins = ~~((time % 3600) / 60);
  var secs = ~~time % 60;
  var ret = "";
  
  if (hrs > 0) {
    
    ret += "" + hrs + ":" + (mins < 10 ? "0" : "");
  
  }
  
  ret += "" + mins + ":" + (secs < 10 ? "0" : "");
  ret += "" + secs;
  
  return ret;

}

//Таймер для длительности трека по возрастанию
function tick(num) {
  
  clearInterval(timer);
  
  var sec = num;
  
  timer = setInterval(function() {
    
    sec++;
    
    document.getElementById("timer").childNodes[0].nodeValue = duration_format(sec);
  
  }, 1000);
  
}

//Включение отображения текущей дорожки вверху сайта
function show_play() {
  
  var sh_p = document.getElementById('show_play');
  var sh_p2 = document.getElementById('show_play2');
  
  sh_p.style.display = "";
  sh_p2.style.display = "";
  
}

//Отключение отображения текущей дорожки вверху сайта
function hide_play() {
  
  var sh_p = document.getElementById('show_play');
  var sh_p2 = document.getElementById('show_play2');
  
  sh_p.style.display = "none";
  sh_p2.style.display = "none";
  
}

//Передача параметров текущего трека обработчику для транслирования в плеере
$(document).on('click', 'button[class = "play-status-off play-button-style"]', function(e){
  
  var session = $(this).attr("action");
  
  $.ajax({
    
    url: session,
    cache: false,
    type: "GET",
    success: function(data) {
      
      var link = "/";
      var toLoad = link+' #play-upgrate';
      $("#play-upgrate").load(toLoad);
      
      var link2 = "/";
      var toLoad2 = link2+' #play-upgrate-big';
      $("#play-upgrate-big").load(toLoad2);
      
      var link3 = "/";
      var toLoad3 = link3+' #play-upgrate-big2';
      $("#play-upgrate-big2").load(toLoad3);

    }
  
  });
  
  e.preventDefault();
  
});

function player_sess(action_forward, action_id) {
  
  $.ajax({
    
    url: action_forward,
    cache: false,
    type: "GET",
    success: function(data) {
      
      var link = "/";
      var toLoad = link+' #play-upgrate';
      $("#play-upgrate").load(toLoad);
      
      var link2 = "/";
      var toLoad2 = link2+' #play-upgrate-big';
      $("#play-upgrate-big").load(toLoad2);
      
      var link3 = "/";
      var toLoad3 = link3+' #play-upgrate-big2';
      $("#play-upgrate-big2").load(toLoad3);
      
      MusicPlay(action_id);
    
    }
  
  });

}

//Стоп/пуск для трека в развернутом плеере
function PlayPause2(type) {
  
  var play2 = document.getElementById('play3');
  var pause2 = document.getElementById('pause3');
  
  if (type == "pause"){
    
    pause2.style.display = "none";
    play2.style.display = "";   
    
  }
  
  if (type == "play"){
    
    pause2.style.display = "";
    play2.style.display = "none";    
    
  }
  
}

//Вкл/выкл звук
var vlm = 0;

function volume(type) {
  
  var plus = document.getElementById('volumep');
  var minus = document.getElementById('volumem');

  if (vlm == 0){
    
    minus.style.display = "none";
    plus.style.display = ""; 
    
    vlm = 1;
    
  }else{
    
    minus.style.display = "";
    plus.style.display = "none"; 
    
    vlm = 0;
    
  }
  
}

//Стоп/пуск для трека в плеере
function PlayPause(type) {
  
  var play = document.getElementById('play');
  var pause = document.getElementById('pause');
  
  if (type == "pause"){
    
    pause.style.display = "none";
    play.style.display = "";   
    
  }
  
  if (type == "play"){
    
    pause.style.display = "";
    play.style.display = "none";    
    
  }
  
}

//Развернутый плеер
var open_modal_player = 0;

function modal_player_open(element_id) {
  
  if (open_modal_player == 0){ 
    
    var modal_player = element_id;
    
    $(modal_player).parents(".overlay-player").addClass("open-player");
    
    open_modal_player = 1;
    
    setTimeout( function(){
      
      $(modal_player).addClass("open-player");
    
    }, 2);
  
  }else{
    
    var $this = $(this), modal_player = element_id;
    
    $(modal_player).removeClass("open-player");
    
    setTimeout( function(){	
      
      $(modal_player).parents(".overlay-player").removeClass("open-player");
    
    }, 2);
    
    open_modal_player = 0;
  
  }
  
}

function modal_player_close(element_id) {
  
  var modal_player = element_id;
  
  $(modal_player).removeClass("open-player");
  
  setTimeout( function(){	
    
    $(modal_player).parents(".overlay-player").removeClass("open-player");
    
    open_modal_player = 0;
  
  }, 2);
	
}