/***************
 ** Variables **
 ***************/

var cLocation = new satsLOCATION();

/**
 * toggleLOCATIONS
 * 
 * Toggle tools functionality.
 * 
 */
function toggleLOCATION() {

  if (!cLocation.isON()) {
    showWindow('locationOverlay');
    windowControl('locationOverlay');
    cLocation.ON();
    Drag.init(document.getElementById("locationHandle"), document.getElementById("locationOverlay"), null, null, null, null, true);
  } // if  
  else {
    hideWindow('locationOverlay');
    showControl('controlLOCATION', 'off');
    cLocation.OFF();
  } // else
  
  return;
} // toggleLOCATION

function satsLOCATION() {
  this.on = false;
  this.loading = 0;
  this.pause = false;
  this.running = false;
  this.timerId = 0;
} // satsLOCATION::Constructor

satsLOCATION.prototype.ON = function() {
  if (this.on)
    return;

  if (!this.running)
    this.Update();

  this.running = true;

  this.on = true;
} // satsLOCATION::ON

satsLOCATION.prototype.isON = function() {
  return this.on;
} // satsLOCATION::isON

satsLOCATION.prototype.OFF = function() {
  if (!this.on)
    return false;

  window.clearTimeout(this.timerId);

  this.running = false;
  this.on = false;
} // satsLOCATION::OFF

satsLOCATION.prototype.SnapTo = function(lat, lng) {
  map.setCenter(new GLatLng(parseFloat(lat), parseFloat(lng)));

  return;
} // satsLOCATION::isON

/**
 * aprsFRIENDS::Update
 *
 * Update the currently displayed map.
 *
 */
satsLOCATION.prototype.Update = function(){
  // Load any new stations
  this.Refresh();

  // set the timer
  this.timerId=window.setTimeout('cLocation.Update()', 60000);
} // satsLOCATION::Update

/** 
 * satsLOCATION::Add
 *
 * Load's a help article into the help window.
 *
 */
satsLOCATION.prototype.Add = function() {
  var request = createXMLHttpRequest();
  var me = this;

  if (!loggedIn) {
    changeById('satsLOCATION:Error', 'You must be logged in to use this feature.');
    return;
  } // if

  // reset error fields
  changeById('satsLOCATION:Error', '');

  /**
   * Default Variables
   *
   * Span through the possible field values
   * and set our variable list accordingly.
   *
   */
  var ids = {
    "n": "satsLOCATION:Form:Name",
    "la": "satsLOCATION:Form:Latitude",
    "lo": "satsLOCATION:Form:Longitude"
  }

  var dfts = {
    "n": "",
    "la": "",
    "lo": ""
  }

  var var_list = createURI(document, false, ids, dfts);

  var queryString = "/ajax/opensats/locations/add.php?&h="
                    + seed
                    + var_list;

  disableField('satsLOCATION:Form:Add');
  
  request.open("GET", queryString, true);
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      var xmlDoc = request.responseXML;
 

      var retData = new Array();
      xmlArray("/openaprs/reply", xmlDoc, retData);
      for (i=0; i < retData.length; i++) {
        if (retData[i]["done"] == "yes") {
          changeById('satsLOCATION:Error', retData[i]["response"]);
          ClearField('satsLOCATION:Form:Name');
          ClearField('satsLOCATION:Form:Latitude');
          ClearField('satsLOCATION:Form:Longitude');
        } // if
        else {
          if (retData[i]["field"] != 'satsLOCATION:Error')
            changeById('satsLOCATION:Error', 'There was an error processing your request.');

          changeById(retData[i]["field"], retData[i]["response"]);
        } // else
      } // for

      enableField('satsLOCATION:Form:Add');
      me.Refresh();
    } // if
  
  } // function()
    
  request.send(null);
} // satsLOCATION::Add

/** 
 * satsLOCATION::Remove
 *
 * Load's a help article into the help window.
 *
 */
satsLOCATION.prototype.Remove = function(id, name) {
  var request = createXMLHttpRequest();
  var me = this;

  if (!loggedIn) {
    changeById('satsLOCATION:Error', 'You must be logged in to use this feature.');
    return;
  } // if

  // reset error fields
  changeById('satsLOCATION:Error', '');

  var queryString = "/ajax/opensats/locations/remove.php?&h="
                    + seed
                    + "&id="
                    + encodeURIComponent(id)
                    + "&n="
                    + encodeURIComponent(name);

  disableField('satsLOCATION:Form:Add');

  request.open("GET", queryString, true);
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      var xmlDoc = request.responseXML;
 

      var retData = new Array();
      xmlArray("/openaprs/reply", xmlDoc, retData);
      for (i=0; i < retData.length; i++) {
        if (retData[i]["done"] == "yes")
          changeById('satsLOCATION:Error', retData[i]["response"]);
        else {
          if (retData[i]["field"] != 'satsLOCATION:Error')
            changeById('satsLOCATION:Error', 'There was an error processing your request.');

          changeById(retData[i]["field"], retData[i]["response"]);
        } // else
      } // for

      enableField('satsLOCATION:Form:Add');
      me.Refresh();
    } // if
  
  } // function()
    
  request.send(null);
} // satsLOCATION::Remove

/** 
 * satsLOCATION::Change
 *
 * Load's a help article into the help window.
 *
 */
satsLOCATION.prototype.Change = function(id, name) {
  var request = createXMLHttpRequest();
  var me = this;

  if (!loggedIn) {
    changeById('satsLOCATION:Error', 'You must be logged in to use this feature.');
    return;
  } // if

  // reset error fields
  changeById('satsLOCATION:Error', '');

  var queryString = "/ajax/opensats/locations/change.php?&h="
                    + seed
                    + "&id="
                    + encodeURIComponent(id)
                    + "&n="
                    + encodeURIComponent(name);

  disableField('satsLOCATION:Form:Add');

  request.open("GET", queryString, true);
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      var xmlDoc = request.responseXML;

      var retData = new Array();
      xmlArray("/openaprs/reply", xmlDoc, retData);
      for (i=0; i < retData.length; i++) {
        if (retData[i]["done"] == "yes")
          changeById('satsLOCATION:Error', retData[i]["response"]);
        else {
          if (retData[i]["field"] != 'satsLOCATION:Error')
            changeById('satsLOCATION:Error', 'There was an error processing your request.');

          changeById(retData[i]["field"], retData[i]["response"]);
        } // else
      } // for

      enableField('satsLOCATION:Form:Add');
      me.Refresh();
    } // if
  
  } // function()
    
  request.send(null);
} // satsLOCATION::Change

/** 
 * satsLOCATION::Lookup
 *
 * Load's a help article into the help window.
 *
 */
satsLOCATION.prototype.Lookup = function() {
  var request = createXMLHttpRequest();
  var me = this;

  if (!loggedIn) {
    changeById('satsLOCATION:Error', 'You must be logged in to use this feature.');
    return;
  } // if

  /**
   * Default Variables
   *
   * Span through the possible field values
   * and set our variable list accordingly.
   *
   */
  var ids = {
    "find": "satsLOCATION:Form:Find"
  }

  var dfts = {
    "find": ""
  }

  // reset error fields
  changeById('satsLOCATION:Error', '');

  var var_list = createURI(document, false, ids, dfts);

  var queryString = "/ajax/opensats/locations/lookup.php?&h="
                    + seed
                    + var_list;

  disableField('satsLOCATION:Form:Lookup');

  request.open("GET", queryString, true);
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      var xmlDoc = request.responseXML;
 
      var retData = new Array();
      xmlArray("/openaprs/locations/location", xmlDoc, retData);
      for (i=0; i < retData.length; i++) {
        changeFieldById('satsLOCATION:Form:Name', retData[i]["city"]);
        changeFieldById('satsLOCATION:Form:Latitude', retData[i]["latitude"]);
        changeFieldById('satsLOCATION:Form:Longitude', retData[i]["longitude"]);
        changeById('satsLOCATION:Error', 'Found ' + retData[i]["city"] + ', ' + retData[i]["state"] + ' (' + retData[i]["locator"] + ')');
      } // for

      if (retData.length == 0) {
        var find = document.getElementById("satsLOCATION:Form:Find");
        if (find == null)
          changeById('satsLOCATION:Error', 'Location not found.');
        else
          me.Geocode(find.value);
      } // if

      enableField('satsLOCATION:Form:Lookup');
    } // if
  
  } // function()
    
  request.send(null);
} // satsLOCATION::Lookup

/**
 * satsLOCATION::Refresh
 *
 * Redraws the current list of stations.
 *
 */
satsLOCATION.prototype.Refresh = function() {
  var request = GXmlHttp.create();
  var now = new Date();
  var me = this;

  // reset error messages
  //changeById('satsLOCATION:Error', '');

  if (!loggedIn) {
    clearRows('locationTable');
    changeById('satsLOCATION:Error', 'You must be logged in to use this feature.');
    return;
  } // if

  if (this.loading)
    return;
  else
    this.loading = now.getTime();

  var queryString = "/ajax/opensats/locations/view.php?h="
                    + seed;

  changeById('locationSTATUS', 'Updating');

  // ### PROFILING: START
  var start_date = new Date();

  request.open("GET", queryString, true);
  request.onreadystatechange = function() {

    if (request.readyState == 4) {
      var xmlDoc = request.responseXML;
      var numLocations = 0;

      var retData = new Array();
      xmlArray("/openaprs/locations/location", xmlDoc, retData);

      clearRows('locationTable');

      for (i=0; i < retData.length; i++) {  
        var chatArray = [];

        var aCell = new cellStruct;
        aCell.text = retData[i]["image"];
        chatArray.push(aCell);

        var aCell = new cellStruct;
        aCell.text = retData[i]["link"];
        chatArray.push(aCell);

        var aCell = new cellStruct;
        aCell.text = retData[i]["remove"];
        chatArray.push(aCell);

        addRow2('locationTable', chatArray.reverse());

      } // for

      var numLocations = retData.length;

      // ### PROFILING: END
      var end_date = new Date();
      var diff = parseFloat((end_date.getTime()/1000) - (start_date.getTime()/1000));

      logById('logContainer', 'logTable', 'satsLOCATION: UPDATED (xml:'+diff.toRound(3)+' seconds)');
      changeById("locationSTATS", numLocations +" locations (" + diff.toRound(3) +" secs)");
      changeById('locationSTATUS', 'Idle');
      me.loading = 0;
    } // if
  } // function()

  request.send(null);
} // satsLOCATION::Refresh

/**
 * satsLOCATION::Refresh
 *
 * Redraws the current list of stations.
 *
 */
satsLOCATION.prototype.Geocode = function(address) {
  if (geocoder) {
    geocoder.getLatLng(
      address,
      function(point) {
        if (!point) {
          changeById("satsLOCATION:Error", "Location not found.");
          enableField('satsLOCATION:Form:Lookup');
          logById('logContainer', 'logTable', "LOCATE: Unable to locate ["+address+"]");
        } // else
        else {
          changeById("satsLOCATION:Error", "Address located...");
          logById('logContainer', 'logTable', "LOCATE: Found location ["+address+"]");
          changeFieldById("satsLOCATION:Form:Name", '');
          changeFieldById('satsLOCATION:Form:Latitude', point.lat());
          changeFieldById('satsLOCATION:Form:Longitude', point.lng());
          //map.setCenter(point, 12);
          //var marker = new GMarker(point);
          //map.addOverlay(marker);
          //marker.openInfoWindowHtml(address);
        } // else
      } // function
    );
  } // if
} // satsLOCATION::Geocode


