function handle_error(error) {
}

function open_win(url) {
try {
 window.open(url,"_blank","directory=no, height=500,width=572,location=no, menubar=no, resizable=no, toolbar=no",false);
}
catch (error) {
 handle_error(error);
}
}

function get_xmlhttp() {
 var xmlhttp
 /*@cc_on @*/
 /*@if (@_jscript_version >= 5)
 try {
   xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
  try {
   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  } catch (E) {
   xmlhttp=false;
  }
 }
 @else
 xmlhttp=false
 @end @*/
 if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
  try {
   xmlhttp = new XMLHttpRequest();
  } catch (e) {
   xmlhttp=false;
  }
 }
 if (!xmlhttp && window.createRequest) {
  try {
   xmlhttp = window.createRequest();
  } catch (e) {
   xmlhttp=false;
  }
 }
 return xmlhttp;
}

function validate(id) {
try {
 if (element[id].xmlhttp.readyState==4) {
  if (! element[id].xmlhttp.responseText) {
   return false;
  }
  if (element[id].xmlhttp.status == 200) {
   return true;
  }
  else if (element[id].xmlhttp.status == 0) {
   return true;
  }
 }
}
catch (error) {
 handle_error(error);
}
 return false;
}

function resolve_info() {
try {
 id = "info";
 if (validate(id)) {
  split = element[id].xmlhttp.responseText.split("|");
  for (i in split) {
   div = split[i].split("=");
   if (div.length == 2) {
    document.getElementById(div[0]).innerHTML=div[1];
   }
  }
 }
}
catch (error) {
 handle_error(error);
}
}

function createWeightTd(insert_row, position, str,url) {
try {
 td = insert_row.insertCell(position);
 td_table = document.createElement("table");
 td_table.width = "100%"
 td_row = td_table.insertRow(0);
 use_url = false;
 if (str.length == 0) {
  td_row_td = td_row.insertCell(0);
 }
 else {
  for (str_index = 0; str_index < str.length; str_index++) {
    td_row_td = td_row.insertCell(str_index);
   if (str.charAt(str_index) == 'R') {
    td_row_td.bgColor="Red";
    use_url = true;
   } else if (str.charAt(str_index) == 'Y') {
    td_row_td.bgColor="Yellow";
    use_url = true;
   } else if (str.charAt(str_index) == 'G') {
    td_row_td.bgColor="Lime";
    use_url = true;
   } else if (str.charAt(str_index) == 'B') {
    td_row_td.bgColor="Blue";
    use_url = true;
   } else if (str.charAt(str_index) == 'U') {
    td_row_td.bgColor=insert_row.bgColor;
   }
   else {
    // error
   }
   td_row_td.height = 30;
   td_row_td.appendChild(document.createElement("br"));
  }
 }
 if (url && str.length > 0 && use_url) {
  td_table.onclick = function() { open_win(url) };
  td_table.onmouseover = function() { document.body.style.cursor='pointer';  document.body.style.cursor='hand';};
  td_table.onmouseout = function() { document.body.style.cursor='default'; };
  
 }
 td.appendChild(td_table);
}
catch (error) {
 handle_error(error);
}
 return td;
}

function resolve_monitor() {
try {
 id = "monitor";
 if (validate(id)) {
  // store checkbox states
  stations_checked = new Array();
  i = 0;
  while (button = document.getElementById("station"+i)) {
   stations_checked[i] = button.checked;
   i++; 
  }
  section_checked = new Array();
  i = 0;
  while (button = document.getElementById("section"+i)) {
   section_checked[i] = button.checked;
   i++; 
  }

  lines = element[id].xmlhttp.responseText.split("\n"); // first element is for the stations, remaining are for the error sections (weights, etc..)

  table = document.getElementById("monitor");
  // clean table
  while (table.firstChild) {
   table.removeChild(table.firstChild);
  }
  // station row
  station = lines[0].split(" ");
  row = new Array();
  row[0] = table.insertRow(0);
  cell = row[0].insertCell(0);
  anchor = document.createElement("a");
  anchor.href = "help-general.html";
  anchor.appendChild(document.createTextNode("Help"));
  cell.appendChild(anchor);
  for (i = 0; i < station.length; i++) {
   //cell = row[0].insertCell(i+1);
   cell = document.createElement("th")
   cell.colSpan = 2;
   button = document.createElement("input");
   button.type = "checkbox";
   button.id = "station"+i;
   cell.appendChild(button);
   button.onclick=update_log;
   if (i >= stations_checked.length || stations_checked[i]) {
    button.checked = true;
   }
   else {
    button.checked = false;
   }
   cell.appendChild(document.createTextNode(station[i]));
   row[0].appendChild(cell);
  }

  // factor rows
  for (sec = 0; sec < sections.length; sec++) {
   weights = lines[sec + 1].split(" ");

   // create the actual weight display  tables
   row[sec+1] = table.insertRow(sec+1);
   cell = document.createElement("th");

   next_position = 1;
   reference_station = 0;
   if (sections[sec] == "X Corr. to" || sections[sec] == "X Hand Corr. to") {
    reference_info = weights[0].split(";");
    reference_station = parseInt(reference_info[0]);
    reference_integrations = parseInt(reference_info[1]);
    if (reference_station == -1) {
     weights.length = weights.length - 1;
     weights[0] = weights[1];
     make_link = false;
     cell.appendChild(document.createTextNode(sections[sec]));
     cell.appendChild(document.createElement("br"));
     cell.appendChild(document.createTextNode("No reference station"));
    }
    else {
     make_link = true;
     for (copy_index = 0; copy_index < reference_station; copy_index++) {
      weights[copy_index] = weights[copy_index+1];
     }
     cell.appendChild(document.createTextNode(sections[sec] + " " + station[reference_station]));
     cell.appendChild(document.createElement("br"));
     cell.appendChild(document.createTextNode("#integrations: " + reference_integrations));
    }
   }
   else {
    cell.appendChild(document.createTextNode(sections[sec]));
   }
   // create checkbox for log filtering weights
   button = document.createElement("input");
   button.type = "checkbox";
   button.id = "section"+sec;
   button.onclick=update_log;
   cell.appendChild(button);
   if ((section_checked.length == 0) || section_checked[sec]) {
    button.checked = true;
   }
   else {
    button.checked = false;
   }
   row[sec+1].appendChild(cell);

   for (weight_station = 0; weight_station < weights.length; weight_station++) {
    if ((sections[sec] == "X Corr. to" || sections[sec] == "X Hand Corr. to") && weight_station == reference_station) {
     empty_cell = row[sec+1].insertCell( next_position++);
     empty_cell.appendChild(document.createTextNode("Ref"));
     empty_cell.colSpan = 2;
    }
    else {
     pol = weights[weight_station].split(";");
     nr_polarizations = (sections[sec] == "Data rate"?1:pol.length);
     for (pol_index = 0; pol_index < nr_polarizations; pol_index++) {
      pol_text = (nr_polarizations>1?"_"+pol_index:"");
      if (sections[sec] == "Autocorr.") { 
       url_text = "show_plot.html?data=autocorr"+weight_station+pol_text+".data";
      } else if (sections[sec] == "X Corr. to" && make_link) {
       url_text = "show_plot.html?data=reference"+weight_station+pol_text+".data";
      } else if (sections[sec] == "X Hand Corr. to" && make_link) {
       url_text = "show_plot.html?data=crosshand"+weight_station+pol_text+".data";
       } else if (sections[sec] == "Data rate") {
       url_text = "show_plot.html?data=data_rate_history"+weight_station+".data"
      } else if (sections[sec] == "Weights") {
       url_text = "show_plot.html?data=weight_history"+weight_station+pol_text+".data"
      } else if (sections[sec] == "Sampler stats") {
        url_text = "show_plot.html?data=sampler_stats_history"+weight_station+pol_text+".data"      
      }
      else {
       url_text = false;
      } 
      td = createWeightTd(row[sec+1], next_position++, pol[pol_index],url_text);
      td.colSpan = 3 - nr_polarizations;
     }
    }
   }
  }
  // set checked stati one more time for the sake of microsoft
  for (i = 0; i < sections.length; i++) {  
   document.getElementById("section"+i).checked = (section_checked.length > 0 ? section_checked[i] : true );
  }
  for (i = 0; i < station.length; i++) {
   document.getElementById("station"+i).checked = (stations_checked.length > 0 ? stations_checked[i] : true );
  }
 }
}
catch (error) {
 handle_error(error);
}
}

function update_log() {
try {
 var text = "";
 if (log_message) {
  for (i = 0; i < log_message.length; i++) {
   if ((document.getElementById("station"+log_message[i].station) && document.getElementById("station"+log_message[i].station).checked) &&
       (document.getElementById("section"+log_message[i].section) && document.getElementById("section"+log_message[i].section).checked)) {
    text = text + log_message[i].message + "<br>";
   }
  }
 }
 document.getElementById("log").innerHTML=text;
}
catch (error) {
 handle_error(error);
}
}

function resolve_log() {
try {
 id = "log";
 if (validate(id)) {
  log_message = new Array();
  response_text = element[id].xmlhttp.responseText;
  if (!response_text) {
   response_text = "";
  }
  split = response_text.split("\n");
  for (i = 0; i < split.length; i++) {
   line = split[i].split("|");
   if (line.length == 3) {
    log_message[i] = new Object();
    log_message[i].station=parseInt(line[0],10);
    log_message[i].section=parseInt(line[1],10);
    log_message[i].message=line[2];
   }
  }
  update_log();
 }
}
catch (error) {
 handle_error(error);
}
}
 
function refresh(id) {
try {
 element[id].xmlhttp.open("GET", id + ".txt?"+Math.random(),true);
 element[id].xmlhttp.onreadystatechange=element[id].resolve_function
 element[id].xmlhttp.send(null);
}
catch (error) {
 handle_error(error);
}
setTimeout("refresh('" + id + "')", element[id].timeout);
}

function init() {
try {
 for (i in element) {
  element[i].xmlhttp = get_xmlhttp();
  element[i].resolve_function = new Function("return resolve_" +
   i + "()");
  refresh(i);
 }
}
catch (error) {
 handle_error(error);
}
}

var element = new Array();
element["info"] = new Object();
element["info"].timeout = 5000;

element["monitor"] = new Object();
element["monitor"].timeout = 5000;

element["log"] = new Object();
element["log"].timeout = 5000;

var log_message; // array containing all log messages
var sections = new Array();
sections[0] = "Weights";
sections[1] = "Autocorr.";
sections[2] = "X Corr. to";
sections[3] = "X Hand Corr. to";
sections[4] = "Data rate";
sections[5] = "Sampler stats";

