var player = null;
var video_time = 0;
var currentstate = "NONE"; 
var previousstate = "NONE"; 

function playerReady(thePlayer) {
  player = document.getElementById(thePlayer.id);
  addListeners();
  if(parent.Shadowbox) {
    if(parent.s && s) {
      parent.s.disableBufferedRequests = true;
      s.disableBufferedRequests = true;
    }
    parent.Shadowbox.onClose = function () { handleClose(); }
  }
}

function addListeners() {
  if (player) { 
    player.addModelListener("state", "stateListener");
    player.addModelListener("time", "timeListener");
  } else {
    setTimeout("addListeners()",100);
  }
}

function handleClose() {
  if(previousstate == "PLAYING"){
    s.Media.stop(video_name, video_time);
  }
  removeListeners();
  parent.Shadowbox.onClose = null;
}

function removeListeners() {
  if (player) { 
    player.removeModelListener("state", "stateListener");
    player.removeModelListener("time", "timeListener");
  }
}

function timeListener(obj) { //TIME
  video_time = obj.position;
}

function stateListener(obj) { //IDLE, BUFFERING, PLAYING, PAUSED, COMPLETED
  
  var theDetail = player.getPlaylist();
  if(theDetail[0].file != 0) { 
    var video_name = theDetail[0].file;
    video_name = fixVideoName(video_name);
  }
  currentstate = obj.newstate; 
  previousstate = obj.oldstate; 
  
  if (((currentstate == "PLAYING")&&(previousstate == "BUFFERING")) ||
    ((currentstate == "PLAYING")&&(previousstate == "COMPLETED")) ||
    ((currentstate == "PLAYING")&&(previousstate == "PAUSED")) ){
    
    if(theDetail[0].duration != 0) var video_duration = theDetail[0].duration;

    if(((currentstate == "PLAYING")&&(previousstate == "BUFFERING")) ||
      ((currentstate == "PLAYING")&&(previousstate == "COMPLETED"))){
      s.Media.open(video_name, video_duration, 'JW Player');
    }        
    s.Media.play(video_name, video_time);
  }
  if (((currentstate == "PAUSED")&&(previousstate == "PLAYING")) ||
    ((currentstate == "COMPLETED")&&(previousstate == "PLAYING"))){

    if((currentstate == "COMPLETED")&&(previousstate == "PLAYING")){
      s.Media.close(video_name);
    }else{
      s.Media.stop(video_name, video_time);
    }
  }
}

function fixVideoName(video_name) {
  if (video_excludePrefix != undefined) {
    // special case for Amazon S3 videos
    if ((video_name.indexOf("media-www") != -1 || video_name.indexOf("media-streaming-www") != -1 || video_name.indexOf("media-world-www") != -1)
	    && video_excludePrefix.indexOf("cirquedusoleil/refonte/") != -1) {
      video_excludePrefix = video_excludePrefix.replace("cirquedusoleil/refonte/", "");
    }
    video_name = video_name.replace(video_excludePrefix, "");
  }
  video_name = video_name.split(".")[0]; // remove extension
  return video_name.replace("/","").replace(/\//g, " : ");
}