// Open a new window.
function reqWin(desktopURL, alternateWidth, alternateHeight, noScrollbars)
{
  if ((alternateWidth && self.screen.availWidth * 0.8 < alternateWidth) || (alternateHeight && self.screen.availHeight * 0.8 < alternateHeight))
  {
    noScrollbars = false;
    alternateWidth = Math.min(alternateWidth, self.screen.availWidth * 0.8);
    alternateHeight = Math.min(alternateHeight, self.screen.availHeight * 0.8);
  }
  else
    noScrollbars = typeof(noScrollbars) != "undefined" && noScrollbars == true;

  window.open(desktopURL, 'requested_popup', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=' + (noScrollbars ? 'no' : 'yes') + ',width=' + (alternateWidth ? alternateWidth : 480) + ',height=' + (alternateHeight ? alternateHeight : 700) + ',resizable=yes');

  // Return false so the click won't follow the link ;).
  return false;
}

function dump(arr,level) {
  var dumped_text = "";
  if(!level) level = 0;
  
  //The padding given at the beginning of the line.
  var level_padding = "";
  for(var j=0;j<level+1;j++) level_padding += "    ";
  
  if(typeof(arr) == 'object') { //Array/Hashes/Objects 
    for(var item in arr) {
      var value = arr[item];
      
      if(typeof(value) == 'object') { //If it is an array,
        dumped_text += level_padding + "'" + item + "' ...\n";
        dumped_text += dump(value,level+1);
      } else {
        dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
      }
    }
  } else { //Stings/Chars/Numbers etc.
    dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
  }
  return dumped_text;
}

var gCurrentSeconds;

function fmtTime(ts)
{
  var year = String(ts.getFullYear()).substr(2,2);
  var month = ts.getMonth() + 1;
  var day = ts.getDate();  
  var currentHours = ts.getHours ( );
  var currentMinutes = ts.getMinutes ( );
  var currentSeconds = ts.getSeconds ( );  
    
  month = ( month < 10 ? "0" : "" ) + month;
  day = ( day < 10 ? "0" : "" ) + day;  
  currentHours = ( currentHours < 10 ? "0" : "" ) + currentHours;
  currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;  
  currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;      

  var currentTimeString=year+month+day+" "+currentHours + ":" + currentMinutes + ":" + currentSeconds; // + " "; // + timeOfDay;
  return currentTimeString;
}

function getTime()
{
  var currentTime = new Date ( );
  gCurrentSeconds=currentTime.getSeconds ( );  
  return fmtTime (currentTime);
}

function updateClock (st,ut,ba,bia)
{ 
  var currentTimeString=getTime();
  
  document.getElementById("clock").firstChild.nodeValue = currentTimeString;  
  if (st)
  {
    w=st+1;   
    ct=ut;
    c=0;
    a=ba;
    ia=bia;
    au=-1;    
    if (ut==0)
    {       
      au=0;      
      $("#upd").html("<br><br><div class='buttons'><button disabled class='positive'>"+a+"</button></div>");
    }    
    else if (ut>=1)
    {
      au=1;      
      $("#upd").html("<br><br><div class='buttons'><button disabled class='positive'>"+ia+" "+c+"/"+ct+"</button></div>");      
    }
  }
  v=Math.round(w-gCurrentSeconds);
  if (v<0) 
    v+=60;
  if (v>59) 
    v-=60;
  $("#cdown").text(v);   
  if (au==1)
  {   
    if (c==ct)
    {     
      au=0;
    }
    
    if (c<ct && v==0)
    {
      c++;      
      $("#upd").html("<br><br><div class='buttons'><button disabled class='positive' onclick='location.href = \"?action=channel\"'>"+ia+" "+c+"/"+ct+"</button></div>");      
      $("#graph").attr("src","?action=x1&a="+new Date().getTime());  
      var oldclass = $("#tbody0 tr:first").attr("class");
      if (oldclass!=null)
      {      
        $.getJSON("?action=x2",
          function(data){          
            $("#last").text(data[0][0]);          
            data=data[1];          
            str='';          
            for (var r in data)
            {
              str+="<tr class='"+oldclass+"'>";
              for (var c in data[r])
              {
                str+="<td>"+data[r][c]+"</td>";
              }
              str+="<tr>";
            }          
            $("#tbody0").html(str);          
        });
      }
    }
  }
  else if (au==0)
  {
     if (v==0)       
       $("#upd").html("<br><br><div class='buttons'><button class='positive' onclick='location.href = \"\"'>"+a+"</button></div>");
  }
}

function clock (st,ut,ba,bia) {  
  $(document).ajaxError(function(event, request, settings){location.reload();});
  updateClock(st,ut,ba,bia);
  setInterval("updateClock()", 1000)
}


function updateCd (init)
{
  if (init)
  {  
    v=init;       
  }
  else
  {
    v--;
  }
  $("#cdown").html(v);
}
  
function cd(init) {  
  updateCd(init);
  setInterval("updateCd()", 1000)
}


function cb()
{    
    items=cb.arguments.length;    
    if (items!=0)
    {       
      memitems=items;
      memchk=Array.prototype.slice.call(arguments);
    }    
    x=$("#input_num").get(0).selectedIndex;
    for (i=0;i<memitems;i++)
    {
      if (x==memchk[i])
      {
        $("#dy1").show();    
        return;
      }
    }
    $("#dy1").hide();
}

function cbinit() {
  x=Array.prototype.slice.call(cbinit.arguments); 
 $(document).ready(
 function()
 {   
   cb.apply(this,x);   
   $("#input_num").change(
   function()
   {    
    cb();
   }
  );
 }
 )
}

function aefields(si){if(si==0)$("#dy1,#dy2,#dy3,#dy4,#dy5,#dy6,#dy7,#dy8,#dy9").hide();if(si==1){$("#dy3,#dy4,#dy5,#dy6,#dy7,#dy8").hide();$("#dy1,#dy2,#dy9").show();}if(si==2){$("#dy1,#dy2,#dy3,#dy4,#dy5,#dy6,#dy7,#dy8,#dy9").show();$("#dy2").hide();}}
function afields(si,sj){if (si==2){h=1;si=0;sj=0}if (si==3){h=0;si=$("select:eq(1) :eq(0)").attr("selected");sj=$("select:eq(1) :eq(1)").attr("selected")}if(h!=2){if(si){$("#dy2").show();}else{$("#dy2").hide()}if(sj){$("#dy3").show();}else{$("#dy3").hide()}if(sj|si){$("#dy4").show();}else{$("#dy4").hide()}}if(h==1)h=2}
function afields2(){if ($.inArray(parseInt($("select:eq(0) :selected").val()),arguments)!=-1) afields(2,0); else afields(3,0)}
function afields3(si){if(si)$("#dy8").show();else $("#dy8").hide()}
function showTooltip(x, y, contents) {$('<div id="tooltip">' + contents + '</div>').css( {position: 'absolute',display: 'none',top: y + 5,left: x + 5,border: '1px solid #fdd',padding: '2px','background-color': '#fee',opacity: 0.80}).appendTo("body").fadeIn(200);}
var previousPoint = null;
//function pH(b,c,a){if(a){if(previousPoint!=a.datapoint){previousPoint=a.datapoint;$("#tooltip").remove();a.datapoint[0].toFixed(0);b=a.datapoint[1].toFixed(1);showTooltip(a.pageX,a.pageY,b+" "+u[a.seriesIndex])}}else{$("#tooltip").remove();previousPoint=null}};
function pH(b,d,a){if(a){if(previousPoint!=a.datapoint){previousPoint=a.datapoint;$("#tooltip").remove();b=a.datapoint[1];i=a.seriesIndex;i_et=a.dat.length-1;ty[i_et]==1&&i_et--;if(i<i_et&&i!=0)for(c=i-1;c>=0;){b-=a.dat[c].datapoints.points[a.dataIndex*a.dat[c].datapoints.pointsize+1];c--}showTooltip(a.pageX,a.pageY,b.toFixed(1)+" "+u[i])}}else{$("#tooltip").remove();previousPoint=null}};
var pp = null;
function pCr()
{
  $("#lbl1").html("Senaste 24 timmarna");pp=null;return true;
}
function pC(b,a,c){if(c)if(pp!=c.dataIndex){pp=c.dataIndex;b=pp+st;a=m1;if(b>dm1){b-=dm1;a++;if(a>12)a=1}$("#lbl1").html("Timmar "+b+"/"+a+" (klicka <a onClick='pCr();g(-1,0);return false;'href='#'>h\u00e4r</a> f\u00f6r senaste 24 timmarna)");g(pp,0)}};
function g(h,j){var f=Array(d.length),e=Array(d.length),k=Array(d.length),a;for(a in d){f[a]=[];e[a]=[];if(j==0)if(h==-1)var i=d[a].slice(d[a].length-24,d[a].length),b=d[a].length%24;else{i=d[a].slice(h*24,(h+1)*24);b=0}else{i=d[a];b=h}for(var c in i){f[a][c]=Array(2);f[a][c][0]=c;f[a][c][1]=i[c];e[a][c]=Array(2);e[a][c][0]=c;switch(j){case 0:e[a][c][1]=b!=0?b:"0";b++;if(b==24)b=0;break;case 1:e[a][c][1]=b;b++;if(b>dm1)b=1;break;case 2:ti="";if(m1<10)ti="0";ti+=m1.toString();if(b<10)ti+="0";ti+=b.toString();e[a][c][1]=ti;b++;if(b>12){b=1;m1++}}}switch(ty[a]){case 0:k[a]={label:l[a],data:f[a],stack:true,bars:{show:true,barWidth:0.7,align:"center"}};break;case 1:k[a]={label:l[a],data:f[a],yaxis:2,stack:false,lines:{show:true},bars:{show:false}}}}o={yaxis:{min:0},xaxis:{ticks:e[0]},legend:{backgroundOpacity:0.8,position:'nw'},grid:{hoverable:true,clickable:j==1}};$.plot($(p),k,o);$(p).bind("plothover",pH);$(p).bind("plotclick",pC)};

function MC(){$("body").append('<div id="Tip"></div>');$("#Img").mousemove(function(a){$(this).position();var b=$(this).offset(),c=a.pageX-b.left;b=a.pageY-b.top;$("#Tip").show().css({left:a.pageX+16,top:a.pageY+16}).html("x: "+c+" y: "+b)});$("#Img").mouseout(function(){$("#Tip").hide()})};


