var setImage = new Image();

var updateTimerID = 0;

function updateData() {
//  alert('attempting update');
  $.ajax({
    type: "GET",
    url: "sensors.xml",
    dataType: "xml",
    success: loadData,
    error: clearData,
    complete: function() {
      // Set the timer for 5s time
      if (updateTimerID != 0) { window.clearTimeout(updateTimerID); updateTimerID = 0;}
      updateTimerID = window.setTimeout("updateData()", 5000);
    }
  });
}   

function loadData(data) {
  var sensors = $("sensors > sensor", data);
  document.getElementById('sensorcount').innerHTML = sensors.length;

  var sensorTable = document.getElementById('sensorlist');
  
  for (var index = 0; index < sensors.length; index++) {
    var sensor = sensors[index];
    var sensorID = $("id", sensor).text();
    var sensorName = $("name", sensor).text();
    var sensorRow = null;
    var needsUpdating = false;

    // Get/create the table row
    if (index + 1 < sensorTable.rows.length) {
      sensorRow = sensorTable.rows[index + 1];
    } else { 
      // Add the row to the table
      sensorRow = sensorTable.insertRow(index + 1);
      sensorRow.insertCell(0);
      sensorRow.insertCell(1);
      sensorRow.insertCell(2);
    }

    // Check if the row needs updating (sensor ID changes)
    if (sensorRow.sensorID != sensorID) {
      sensorRow.sensorID = sensorID;
      needsUpdating = true;
    }
    
    sensorRow.cells[0].innerHTML = (sensorName == "" ? "&nbsp;" : sensorName);

    if (($("output", sensor).text().toLowerCase()) == "true") {
      // Add the toggle button
      if ($("button", sensorRow.cells[2]).length == 0) {
        toggleButton = document.createElement("button");
        toggleButton.id = sensorRow.sensorID;
        toggleButton.value = "Toggle";
        sensorRow.cells[2].appendChild(toggleButton);

        // Add the event handler
        $(toggleButton).click(function() {
          toggleSensorState(this.id);
        });
      }
    }
    
    if ($("values > value", sensor).length == 0) {
      // If it doesn't have any values, just display the current value
      sensorRow.cells[1].innerHTML = $("value", sensor).text();

    } else {
      // Get the dropdown list object
      var valueList = null;
      if ($("select", sensorRow.cells[1]).length > 0) {
        valueList = $("select", sensorRow.cells[1])[0];
      } else {
        // Add it if needed
        valueList = document.createElement("select");
        valueList.id = sensorRow.sensorID;
        sensorRow.cells[1].appendChild(valueList);

        // Add the event handler
        $(valueList).change(function() {
          setSensorState(this.id, this.value);
        });
        // Set the flag to update all the values
        needsUpdating = true;
      }

      if (needsUpdating) {
        addSensorValues(valueList, $("values > value", sensor));
      }
      selectSensorValue(valueList, $("nativevalue", sensor).text());
    }
  }

  //Remove all the extra rows
  for (var index = sensors.length + 1; index < sensorTable.rows.length;) {
    sensorTable.deleteRow(index);
  }
}

function addSensorValues(valueList, values) {
  // Remove any existing values
  while (valueList.length > 0)
    valueList.remove(0);

  for (index = 0; index < values.length; index++) {
    var value = values[index];
  
    // Create the dropdown list item
    var valueItem=document.createElement('option');
    valueItem.text=$(value).text();
    valueItem.value=$(value).attr("value");

    // Add the value to the dropdown list
    try {
      valueList.add(valueItem, null); // standards compliant
    } catch(ex) {
      valueList.add(valueItem); // IE only
    }
  }
}

function selectSensorValue(valueList, value) {
  var found = false;
  for (index = 0; index < valueList.options.length; index++) {
    var option = valueList.options[index];
  
    if (option.value == value) {
      // Select it if it is the current value
      valueList.selectedIndex = index;
      found = true;
    }
  }

  if (!found) {
    valueList.selectedIndex = -1;
    // Not selected, potentially add the item here?
  }
}

function setSensorState(sensor, value) {
//alert ("Setting sensor " + sensor + " to state " + value);
  url = '/io/setsensor.htm?sensor=' + sensor + '&value=' + value + '&uniq=' + getMillis();
  setImage.src = url;
}

function toggleSensorState(sensor) {
//alert ("Toggling sensor " + sensor);
  url = '/io/setsensor.htm?sensor=' + sensor + '&uniq=' + getMillis();
  setImage.src = url;

  // Request an immediate update
  updateData()
}

function clearData() {
  //Something went wrong, remove all info
  document.getElementById('sensorcount').innerHTML = "Unavailable";

  var sensorTable = document.getElementById('sensorlist');
  //Remove all the rows
  for (index = 1; index < sensorTable.rows.length;) {
    sensorTable.deleteRow(index);
  }
}

function onLoad() {
  updateData();
}

function getMillis() {
  var d = new Date();
  return d.getTime();
}