var flvplayer=null;
var selezione_palinsesto=true;

function playerReady(obj) {
  var id = obj['id'];
  var version = obj['version'];
  var client = obj['client'];
  flvplayer = getPlayer(id);
  if(!flvplayer){
    setTimeout(
      "playerReady({id:'mpl',version:'"+version+"',client:'"+client+"'})",100
    );
    return;
  }
  if(flvplayer){
   flvplayer.addControllerListener("ITEM","itemListener");
   flvplayer.addModelListener("STATE","stateListener");
   flvplayer.addModelListener("ERROR","errorListener");

   flvplayer.buffer=0;
   flvplayer.load = function(obj){
    //try{ console.log("load: ",obj); }catch(e){}
    flvplayer.sendEvent("LOAD",obj);
   }
   var goTimer=null;
   flvplayer.go = function(idx,seek,play){
    //try{ console.log("go: idx=%d, seek=%d, play=%s",idx,seek,play); }catch(e){}
    if(goTimer){ clearTimeout(goTimer); }
    if(idx>=0){ flvplayer.sendEvent('ITEM',idx?idx:0); }
    goTimer=setInterval(
     function(){
      if(flvplayer.state!="PLAYING"){ return; }
      clearTimeout(goTimer);
      //try{ console.log("seek+play: seek=%d, play=%s",seek,play); }catch(e){}
      setTimeout(
        function(){
          flvplayer.sendEvent('SEEK',seek);
          setTimeout(
            function(){
              flvplayer.sendEvent('PLAY',play?'true':'false');
            },50
          );
        },50
      );
     },
     50
    );
   }
   flvplayer.play = function(){
    //try{ console.log("play"); }catch(e){}
    flvplayer.sendEvent('PLAY','true');
   }
   flvplayer.pause = function(){
    //try{ console.log("pause"); }catch(e){}
    flvplayer.sendEvent('PLAY','false');
   }
  }else{
   msg+= "\nno flvplayer?";
  }
  //alert(msg);
};
function getPlayer(gid) {
 if(navigator.appName.indexOf("Microsoft")!=-1){
  return window[gid];
 }else{
  return document[gid];
 }
};
function itemListener(obj){
 //try{ console.log("itemListener: %d",obj.index); }catch(e){}
 flvplayer.item=obj.index;
 if(flvplayer.getPlaylist().length>1 && selezione_palinsesto){
   seleziona_video_palinsesto(obj.index);
 }
}
function stateListener(obj){
 //try{ console.log("stateListener: %s -> %s",obj.oldstate,obj.newstate); }catch(e){}
 flvplayer.state=obj.newstate;
 var l=flvplayer.getPlaylist();
 if((l.length>1)&&(obj.newstate=="COMPLETED")){
  if(flvplayer.item==l.length-1){
   //when we reach the end of our playlist, we reload it from the server
   loadContent("palinsesto","/palinsesto/",{});
  }else{
   flvplayer.go(flvplayer.item+1,0,1);
  }
 }
}
function errorListener(obj){
/*
 if(obj.message=="This file has no seekpoints metadata."){
   try{ console.log("let's go() again!"); }catch(e){}
 }
*/
}
