
<!-- HTML from template body goes goes here  -->
<div id='{{AUTOID}}_container_pmp' class='poodll_multiplayer'>

  <div class="button-wrapper">
    <button type='button' id='{{AUTOID}}' class='poodll_multiplayer_button'>
		<i class="fa fa-play fa-2x" aria-hidden="true"></i></button>
  </div>
  <div class="state-wrapper">
    <div id='{{AUTOID}}_time' class='poodll_onceplayer_time'></div>
    <div id='{{AUTOID}}_playtime' class="poodll_multiplayer_playtime"></div>
  </div>
  <div class="volume-control">
    <button type="button" id="{{AUTOID}}_vol-up" class="vol-up vol-but">
      <i class="fa fa-volume-up fa-1x" aria-hidden="true"></i></button>
    </button>
    <div class="meter">
      <div id="{{AUTOID}}_indicator" class="indicator"></div>
    </div>
    <button type="button" id="{{AUTOID}}_vol-down" class="vol-down vol-but">
      <i class="fa fa-volume-down fa-1x" aria-hidden="true"></i></button>
  </div>
</div>

<!-- Custom JS from template  goes goes here  -->
{{#js}}
 require(['jquery','filter_poodll/mediaparser'], function($,parser) {

//The template seems to run this code twice, possibly because of the end tag. So we check for data attr as a flag to prevent 2x running
if($('#{{AUTOID}}').data('playtime')!==undefined){return;}
//set playtime attribute
$('#{{AUTOID}}').data('playtime', {{canplaycount}});
      
//set our player
var playertemplate = "<audio id='{{AUTOID}}_player' class='onceplayerjs nomediaplugin' src='@mediaurl@' preload='auto'></audio>";
var details = parser.parse('{{AUTOID}}_original', 'audio');
$('#' + "{{AUTOID}}").prepend(playertemplate.replace('@mediaurl@',details.mediaurl));

//get our player
var aplayer = $('#' + "{{AUTOID}}").children().first();
var fa = $('#' + "{{AUTOID}}" + ' .fa');
var thestate =$('#' + "{{AUTOID}}" + '_state'); 
var thetime = $('#' + "{{AUTOID}}" + '_time');
var playcount = $('#' + "{{AUTOID}}" + '_playtime')
var volumeindicator =    $('#' + "{{AUTOID}}" + '_indicator');
var volumeupbtn=$('#' + "{{AUTOID}}" + '_vol-up');
var volumedownbtn=$('#' + "{{AUTOID}}" + '_vol-down');
var playtimer = $('#' + "{{AUTOID}}");
var lastseconds = 0;
var canplaythrough=aplayer[0].readyState===4; //can play through
var position_update_interval = 1;//each X seconds do the cookie update
var is_strict_quiz = "{{quiz_strict_mode}}"=="true" && "{{URLPARAM:attempt}}" !="";
var is_remember_pos =  is_strict_quiz &&  "{{quiz_remember_play_position}}"=="true";


 //cookies if in strict mode
//trim the cache killer or the cookiename would be different each pay load if cachekiller was in the url
 var regexp = /&?cachekiller\=[^&]+/;
 var useurl = details.mediaurl.replace(regexp,'');
 useurl = useurl.replace('?','');
 var cookiename_playcount = useurl + '_pc_' + "{{URLPARAM:attempt}}"+ '_' + "{{URLPARAM:cmid}}";
 var cookiename_position = useurl + '_pos_' + "{{URLPARAM:attempt}}"+ '_' + "{{URLPARAM:cmid}}";
 var cookiename_audiovol = 'audiovol_' + "{{URLPARAM:attempt}}"+ '_' + "{{URLPARAM:cmid}}";

  var setPlayerVolume = function(newvolume){
     aplayer[0].volume = newvolume;
     volumeindicator.css("width",(aplayer[0].volume * $('.meter').width()));
 }

  var get_last_pos =function(){
     var lastpos = getCookie(cookiename_position);
     if(lastpos && lastpos > 0 && $.isNumeric(lastpos)){
       return lastpos;
     }
     return 0;
  }

   // setting base volume for audio player
   var basevolume = '{{volume}}';
   if(basevolume!=='' && basevolume>=0 && basevolume<=1){
     setPlayerVolume(basevolume);
   }else{
     setPlayerVolume(0.4);
   }

 //---------------------------------------------------------------
//The main code runs from here
//---------------------------------------------------------------

   $(fa).removeClass('fa-minus');
   //set status
   thestate.text('- ready -');

 if(is_strict_quiz){
   //get previous play count
   var prevplaycount = getCookie(cookiename_playcount);
   if(prevplaycount!==null){
    playtimer.data('playtime',prevplaycount);
    if(prevplaycount==="0"){
       disableSubsequentPlays();
    }
   }

   //get previous audio vol
   var prevaudiovol = getCookie(cookiename_audiovol);
   if(prevaudiovol!==null){
     setPlayerVolume(prevaudiovol);
   }
 }

// Append Playtime text
playcount.empty();
var remainingplays = playtimer.data('playtime');
playcount.append('{{#str}}remainingplays,filter_poodll{{/str}}: '+remainingplays +'x');


//volume buttons
volumeupbtn.click(function(){
    if(aplayer[0].volume +0.1 > 1){return;}
    setPlayerVolume(aplayer[0].volume+0.1);
    setCookie(cookiename_audiovol, aplayer[0].volume, 1);
});
volumedownbtn.click(function(){
    if(aplayer[0].volume - 0.1 < 0){return;}
    setPlayerVolume(aplayer[0].volume-0.1);
    setCookie(cookiename_audiovol, aplayer[0].volume, 1);
});

//can play through event
 aplayer[0].addEventListener('canplaythrough',
         function(){
             canplaythrough=true;
         }
 );

 //ended event
 aplayer[0].addEventListener('ended', function(){
     playcount.empty();
     var currentplaycount = playtimer.data('playtime');
       currentplaycount--;
      //if cookies are enabled set the play count in the cookie
     if(is_strict_quiz){
         setCookie(cookiename_playcount,currentplaycount,1);
         setCookie(cookiename_position,0,1);
         lastseconds=0;
     }

      playtimer.data('playtime',currentplaycount );

     $(fa).removeClass('fa-circle-o-notch');
     $(fa).removeClass('fa-spin');
     $(fa).removeClass('fa-play');
     aplayer[0].pause();


     if(currentplaycount > 0){
         playcount.append('{{#str}}remainingplays,filter_poodll{{/str}}: '+currentplaycount+'x');
         $(fa).addClass('fa-play');
     }else{
        disableSubsequentPlays();
     }//end of if currentplaycount > 0
 });//end of ended listener

//player clicked event
$('#' + "{{AUTOID}}").click(function(){
        var playtimer = $('#' + "{{AUTOID}}");
        var currentplaycount = playtimer.data('playtime');
        if(currentplaycount==0){return;}
		play_audio();
});//end of click event



   aplayer.bind('durationchange',function(){
     if(is_remember_pos) {
       var lastpos = get_last_pos();
       var currentpos = aplayer[0].currentTime;
       if (currentpos < lastpos && currentpos > 0) {
         aplayer[0].pause();
         aplayer[0].currentTime = lastpos;
         aplayer[0].play();
       }
     }
     thetime.text(poodll_mp_fetchtime(aplayer));
   });

   //The timer display
   aplayer.on('timeupdate',function(e){
     if(is_remember_pos) {
       var currentseconds = poodll_mp_fetchseconds(aplayer);
       if (currentseconds - lastseconds > position_update_interval) {
         setCookie(cookiename_position, currentseconds, 1);
         lastseconds = currentseconds;
       }
     }
     var displaytime = poodll_mp_fetchtime(aplayer)
     thetime.text(displaytime);
   });

//show current time
 thetime.text(poodll_mp_fetchtime(aplayer));

 //---------------------------------------------------------------
// function declarations start here ------------------------------
//---------------------------------------------------------------
 function disableSubsequentPlays(){
  $('#' + "{{AUTOID}}" + '_playtime').append('{{#str}}remainingplays,filter_poodll{{/str}}: 0');
  $(fa).addClass('fa-minus');
  $('#' + "{{AUTOID}}").data("disabled", true);
 }

 function setCookie(key, value, expiry) {
   localStorage.setItem(key, value);
 }

 function getCookie(key) {
   return localStorage.getItem(key);
 }


function play_audio(){
     //if playing just continue
    if(!aplayer[0].paused){return;}

  //change visible state to playing
    thestate.text('- {{#str}}playing,filter_poodll{{/str}} -');
    $(fa).removeClass('fa-play');
    $(fa).addClass('fa-circle-o-notch');
    $(fa).addClass('fa-spin');

    //if we are remembering position, set the new position
    if(is_remember_pos) {
        var lastpos = get_last_pos();
        if (lastpos > 0) {
            //set the current time
            aplayer[0].currentTime = lastpos;

            //if we can not playthrough yet ..wait .. till we can canplaythrough
          console.log('canplaythrough?: ');
            if(!canplaythrough) {
              console.log('cantplaythrough: ');
                aplayer[0].addEventListener('canplaythrough',
                        function(){
                          console.log('nowcanplaythrough: ');
                            aplayer[0].play();
                        }
                );
              console.log('loadaudio: ');
                aplayer[0].load();
                return;
            }//end of if can play through
        } //end of if last pos
    }
  console.log('callingplay: ');
	aplayer[0].play();
}


//time display function
function poodll_mp_sec2time(seconds){
    if(seconds=='Infinity'){return "00:00:00";}
    var date = new Date(null);
    date.setSeconds(seconds); 
    return date.toISOString().substr(11, 8);
}

 function poodll_mp_fetchseconds(theplayer){
     var a_currenttime= isNaN(theplayer[0].currentTime) ? 0 : theplayer[0].currentTime;
     return a_currenttime;
 }

function poodll_mp_fetchtime(theplayer){
     var a_currenttime= isNaN(theplayer[0].currentTime) ? 0 : theplayer[0].currentTime;

    //tweak the display if this was a reload
     if(a_currenttime===0 && is_remember_pos) {
        var lastpos = get_last_pos();
        if (lastpos > 0) {
            a_currenttime = lastpos;
        }
     }

     var a_duration= isNaN(theplayer[0].duration) ? 0 : theplayer[0].duration;
     var currenttime = poodll_mp_sec2time(Math.floor(a_currenttime));
     var totaltime = poodll_mp_sec2time(Math.floor(a_duration)); 
     var displaytime = currenttime + ' / ' +  totaltime;
    return displaytime;
}

 });
{{/js}}
