/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Chromeless player has no controls.
 */

// Update a particular HTML element with a new value
function updateHTML(elmId, value) {
  //console.log(elmId + ' ' + value);
  document.getElementById(elmId).innerHTML = value;
  //$('#'+elmId).html(value);
}

// This function is called when an error is thrown by the player
function onPlayerError(errorCode) {
  alert("An error occured of type:" + errorCode);
}

// This function is called when the player changes state
function onPlayerStateChange(newState) {
    if (newState == 1 && $('#videoPlay').hasClass('unstarted')) { // detect pressing the giant play button on the video on first load
        //console.log('statechange forcing playing addclass')
        $('#videoPlay').addClass('playing').removeClass('unstarted');
    }
}

// Display information about the current state of the player
function updatePlayerInfo() {
  // Also check that at least one function exists since when IE unloads the
  // page, it will destroy the SWF before clearing the interval.
  
  if(ytplayer && ytplayer.getDuration) {
    updateHTML("duration", toTime(ytplayer.getDuration()));
    updateHTML("current", toTime(ytplayer.getCurrentTime()));
    //updateHTML("volume", ytplayer.getVolume());
    
    // status bar
    $('#elapsedBar').width(((ytplayer.getCurrentTime()/ytplayer.getDuration())*100)+'%');

  }
    
}
function toTime(seconds){
    var m=Math.floor(seconds/60)<10?"0"+Math.floor(seconds/60):Math.floor(seconds/60);
    var s=Math.floor(seconds-(m*60))<10?"0"+Math.floor(seconds-(m*60)):Math.floor(seconds-(m*60));
    return m + ':' + s;
}

// Allow the user to set the volume from 0-100
function setVideoVolume() {
  var volume = parseInt(document.getElementById("volume").value);
  if(isNaN(volume) || volume < 0 || volume > 100) {
    //alert("Please enter a valid volume between 0 and 100.");
  }
  else if(ytplayer){
    ytplayer.setVolume(volume);
  }
}

function playVideo() {
  if (ytplayer) {
    ytplayer.playVideo();
  }
}

function pauseVideo() {
  if (ytplayer) {
    ytplayer.pauseVideo();
  }
}

function muteVideo() {
  if(ytplayer) {
    ytplayer.mute();
  }
}

function unMuteVideo() {
  if(ytplayer) {
    ytplayer.unMute();
  }
}


// This function is automatically called by the player once it loads
function onYouTubePlayerReady(playerId) {
  ytplayer = document.getElementById("ytPlayer");
  // This causes the updatePlayerInfo function to be called every 250ms to
  // get fresh data from the player
  setInterval(updatePlayerInfo, 250);
  updatePlayerInfo();
  ytplayer.addEventListener("onStateChange", "onPlayerStateChange");
  ytplayer.addEventListener("onError", "onPlayerError");
  //Load an initial video into the player
  //ytplayer.cueVideoById("FPTEi0ejULQ");
  ytplayer.cueVideoById($("#video-holder .thumb.current:first").attr('rel'));
}

function loadControls() {
  // hook up play button
  $('#videoPlay').click(function(e) {
      e.preventDefault();
      if ($('#videoPlay').hasClass('playing')) {
        pauseVideo();  
      } else {
        playVideo();
      }
      $('#videoPlay').toggleClass('playing');
  });
  
  // hook up volume 
  $('#volume').click(function(e) {
     e.preventDefault();
     if ($('#volume').hasClass('muted')) {
         unMuteVideo();
     }
     else {muteVideo();}
     $('#volume').toggleClass('muted');
  });
  
  // hook up progress bar sliding to seek time
    $('#progressBar').click(function(e){
            // When a click occurs on the progress bar, seek to the
            // appropriate moment of the video.
            e.preventDefault();
            var ratio = (e.pageX-$('#progressBar').offset().left)/$('#progressBar').outerWidth();
            $('#progressBar #elapsedBar').width(ratio*100+'%');
            ytplayer.seekTo(Math.round(ytplayer.getDuration()*ratio), true);
    });
    
    // respond to thumbnail clicks
    $('#thumbs a.thumb').click(function(e){
        e.preventDefault();
        var vid = $(e.target).parent('a').attr('rel');
        ytplayer.pauseVideo();
        $('#videoPlay').removeClass('playing');
        $('.thumb.current').removeClass('current');
        $(e.target).parent('a').addClass('current');
        ytplayer.cueVideoById(vid);
        $('#videoPlay').click();
    });
}

// The "main method" of this sample. Called when someone clicks "Run".
function loadPlayer() {
  // Lets Flash from another domain call JavaScript
  var params = {allowScriptAccess: "always"};
  // The element id of the Flash embed
  var atts = {id: "ytPlayer"};
  // All of the magic handled by SWFObject (http://code.google.com/p/swfobject/)
  swfobject.embedSWF("http://www.youtube.com/apiplayer?" +
                     "version=3&enablejsapi=1&playerapiid=player1", 
                     "videoDiv", "406", "242", "9", null, null, params, atts);
  loadControls();
}

$(document).ready(function(){
    loadPlayer();  
});

