var vid = document.getElementById("ra");           
//defined by html template 
// var radio_server=rs;
// var listen_url=lis;
// var channel=chan;
vid.autoplay=true;                               
window.onload = function(){                        
  radioUpdate();

  function radioUpdate(){                          
  d3.json(radio_server +"/status-json.xsl")
    .timeout(10000)
    .get(function(e,d){                      
      if(e !=undefined){
        console.warn("sin conxion"); 
        offline();}
      else{
        if(d.icestats.source!=undefined){           
          if(d.icestats.source.listenurl == listen_url){
          console.log("transmitiendo"); 
          online(d); } 
          else {
          console.warn("otro canal");
          offline(); }}                                 
        else {
          console.warn("fuera de línea"); 
          offline();
          }
  } }); };
  

  function dataUpdate(){                          
  d3.json(radio_server+"/status-json.xsl")
    .timeout(10000)
    .get(function(e,d){                      
      if(e !=undefined){ console.warn("sin datos radio"); }
      else{
        if(d.icestats.source!=undefined){           
          if(d.icestats.source.listenurl == listen_url ){
          d3.select("#now").text(d.icestats.source.title); 
      }}}

    d3.select("#ra").transition().on("end",dataUpdate).delay(60000);
}); 
};
  

  function offline(){
    d3.selectAll("article.offline").style("display","block");
    d3.selectAll("article.online").style("display","none");
    d3.select("#spot").style("background-color","red"); 
    d3.select("#now").text(""); 
    console.log("desconectado"); 
    d3.select("#ra").transition().on("end",radioUpdate).delay(90000);
  };

  function online(d){
    d3.select("#spot").style("background-color","green"); 
    d3.select("#prof").text(d.icestats.source.server_name);
    d3.select("#now").text(d.icestats.source.title); 
    d3.selectAll("article.online").style("display","block");
    d3.selectAll("article.offline").style("display","none");
    vid.src=radio_server+channel;
    vid.load();
    console.log("conectado"); 
    dataUpdate();
}

  function cerr(e){ console.warn("stream "+ e);
    vid.pause();
    d3.select("#ra").transition()
      .on("end",function(){ vid.play(); })
      .delay(1000);
  };

  function err(e){
    console.warn("stream "+e);
    d3.select("#ra").transition().on("end",radioUpdate).delay(5000);
  }

  // if error try reloading

  vid.onerror=function(e){ err("error")};
  vid.onended=function(){ err("end")};
  //vid.onstalled=function(){ cerr("st")};
  vid.onemptied=function(){ cerr("empty")};
  //vid.onsuspend=function(){ cerr("sus")};
  vid.onabort=function(){ err("abort")};
}
