// $Id: map.js,v 1.4 2005/11/20 04:14:41 curt Exp $

var debug=0;
var gmap;
var baseIcon;
var home_pt;
var home_marker;
var rsp;
var cur_idx;
var timer;
var delay = 5000;

function dbg(msg) {
  if (debug) {
    alert("debug: " + msg);
  }
}

function cancelTimer() {
  try {
    clearTimeout(timer);
  }
  catch(err) {}
}

function overHandler( obj) {
  obj.style.backgroundColor='#009933';
}  
function outHandler( obj) {
  obj.style.backgroundColor='#B0B0B0';
}  

function geoPt( city, state, country, ccode, qal, lat, lon ) {
  this.city    = city;
  this.state   = state;
  this.country = country;
  this.ccode   = ccode;
  this.qal     = qal;
  this.gPt     = new GPoint(lon, lat);
}

// Given a geo Pt format the text
function mkTxt( pt) {
  var txt;
  var city;

  if ( pt.city.length > 0) {
    city = pt.city;
    if ( pt.state.length > 0) {
      city = city + ", " + pt.state;
    }
  }
  txt = "<b>" + city + "</b>";
  if ( pt.country.length > 0) {
    txt = txt + "<br>" + pt.country;
  }
  
  return txt;

}

// Processes HTML response and returns a
// data structure of the processed data
function processRsp( xmlDoc) {

  var rsp = new Object();
  var markers = xmlDoc.documentElement.getElementsByTagName("ip");
  var mapPts = new Array();
  var lat_min, lat_max;
  var lon_min, lon_max;
  lat_min = 100.0;
  lat_max = -100.0;
  lon_min = 200.0;
  lon_max = -200.0
  npt = markers.length;
  dbg("recieved num IPs: " + markers.length);
  for (var i = 0; i < npt; i++) {
    lon = parseFloat(markers[i].getAttribute("lon"));
    lat = parseFloat(markers[i].getAttribute("lat"));
    dbg("recieved lat/lon: " + lon + ", " + lat);
    if ( lon < lon_min) {
      lon_min = lon;
    }
    if ( lat < lat_min) {
      lat_min = lat;
    }
    if ( lon > lon_max) {
      lon_max = lon;
    }
    if ( lat > lat_max) {
      lat_max = lat;
    }
    //    pname    = markers[i].getAttribute("name");
    //    paddr    = markers[i].getAttribute("addr");
    pcity    = markers[i].getAttribute("city");
    pstate   = markers[i].getAttribute("state");
    //    pzip     = markers[i].getAttribute("zip");
    pcountry = markers[i].getAttribute("country");
    pccode   = markers[i].getAttribute("ccode");
    pqal     = markers[i].getAttribute("qal");

    var newPt = new geoPt( pcity, pstate, pcountry, pccode, pqal, lat, lon);
    mapPts.push( newPt);
  }

  rsp.mapPts  = mapPts;
  rsp.lat_min = lat_min;
  rsp.lat_max = lat_max;
  rsp.lon_min = lon_min;
  rsp.lon_max = lon_max;

  return rsp;
}

// Creates a marker whose info window displays the given number
function createMarker(idx, point, txt) {

  var letter = String.fromCharCode("A".charCodeAt(0) + idx);
  var icon = new GIcon(baseIcon);
  icon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
  var marker = new GMarker(point, icon);

  // Show this marker's index in the info window when it is clicked
  var html = txt;
  GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowHtml(html);
  });

  return marker;
}

function boxmap(center, span, map) {
  var spec = map.spec;
  var zoom = spec.getLowestZoomLevel(center, span, map.viewSize);
  //  map.zoomTo( zoom);
  //  map.recenterOrPanToLatLng( center);
  map.centerAndZoom( center, zoom);
}

function draw_cur_pt( rsp) {
  var pt = rsp.mapPts[cur_idx];
  var txt = mkTxt( pt);
  var marker = createMarker( cur_idx, pt.gPt, txt);
  gmap.addOverlay(marker);
  gmap.zoomTo( 12);
  gmap.recenterOrPanToLatLng( pt.gPt);
}

function draw_next_pt( rsp) {

  cur_idx++;

  if ( cur_idx < rsp.mapPts.length) {
    var prev_pt = rsp.mapPts[cur_idx-1];
    var cur_pt  = rsp.mapPts[cur_idx];
    var pts = [];

    pts.push( prev_pt.gPt);
    pts.push( cur_pt.gPt);
  
    gmap.addOverlay(new GPolyline(pts));

    draw_cur_pt( rsp);

    timer = setTimeout( "draw_next_pt( rsp)", delay);
  }
  else {
    var width = (rsp.lon_max-rsp.lon_min)*1.1;
    var height = (rsp.lat_max-rsp.lat_min)*1.1;
    if ( width < 1) {
      width = 1;
    }
    if ( height < 1) {
      height = 1;
    }
    var span = new GSize( width, height); 
    boxmap( new GPoint( (rsp.lon_max+rsp.lon_min)/2.0, (rsp.lat_max+rsp.lat_min)/2.0), span, gmap);
    try {
      working = document.getElementById("working");
      working.src="clear.gif";
    }
    catch(err) {}
  }
}

function renderRsp( rsp) {
  var npt = rsp.mapPts.length;

  dbg("primary render called");

  if ( npt == 0) {
    try {
      working = document.getElementById("working");
      working.src="clear.gif";
    }
    catch(err) {}
    alert("I couldn't read the list of IP addresses.\nTry listing the IP addresses one per line\n");
  }
  else if ( npt > 1) {
    cur_idx = 0;
    draw_cur_pt(rsp);
    timer = setTimeout( "draw_next_pt(rsp)", delay);
  }
  else {
    // single point - just pan/recenter
    var pt = rsp.mapPts[0];
    var txt = mkTxt( pt);
    var marker = createMarker( 0, pt.gPt, txt);
    try {
      working = document.getElementById("working");
      working.src="clear.gif";
    }
    catch(err) {}
    gmap.addOverlay(marker);
    gmap.zoomTo( 6);
    gmap.recenterOrPanToLatLng( rsp.mapPts[0].gPt);
  }
}

function sendReq(cmd_type, render) {

  var cmd;
  var base = "http://www.cucy.net/cgi-bin/ip.pl";
  var req = "";

  cancelTimer();

  if ( cmd_type == 1) {
    cmd = "tr";
    ip = document.getElementById("text_ip");
    dbg("entered ip: " + ip.value);
    req = req + "ip=" + escape(ip.value) + "&";
  }
  else if ( cmd_type == 2) {
    cmd = "ref";
    dbg("entered self look up");
  }
  else if ( cmd_type == 3) {
    cmd = "list";
    iplist = document.getElementById("text_iplist");
    dbg("entered iplist: " + iplist.value);
    req = req + "iplist=" + escape(iplist.value) + "&";
  }
  req = req + "cmd=" + cmd;
  req = base + "?" + req;
  dbg("req: " + req);
  var request = GXmlHttp.create();
  dbg("before request.open()");
  request.open("GET", req, true);
  request.setRequestHeader("X-Map", "Cucy");
  dbg("before request.onreadystatechange()");
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      rsp = processRsp( request.responseXML);
      render( rsp);
    }
  }

  try {
    working = document.getElementById("working");
    working.src="Blue_and_white2.gif";
  }
  catch(err) {}

  dbg("before request.send()");
  request.send(null);

}

function init_render( rsp) {

  dbg("init_render called");

  gmap = new GMap(document.getElementById("map"));
  gmap.setMapType( G_HYBRID_TYPE);
  gmap.addControl(new GLargeMapControl());
  gmap.addControl(new GMapTypeControl());

  home_pt     = rsp.mapPts[0];
  gmap.centerAndZoom( home_pt.gPt, 12);
  //  home_marker = createMarker( 0, home_pt.gPt, mkTxt( home_pt));
  //  gmap.addOverlay(home_marker);

}

// Create initial map instance
function init_map() {

  // Create a base icon for all of our markers that specifies the shadow, icon
  // dimensions, etc.
  baseIcon = new GIcon();
  baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
  baseIcon.iconSize = new GSize(20, 34);
  baseIcon.shadowSize = new GSize(37, 34);
  baseIcon.iconAnchor = new GPoint(9, 34);
  baseIcon.infoWindowAnchor = new GPoint(9, 2);
  baseIcon.infoShadowAnchor = new GPoint(18, 25);

  sendReq( 2, init_render);

}

function clearip() {

  cancelTimer();

  try {
    working = document.getElementById("working");
    working.src="clear.gif";
  }
  catch(err) {}

  iplist = document.getElementById("text_iplist");
  iplist.value = "";
  gmap.clearOverlays();

  gmap.centerAndZoom( home_pt.gPt, 12);
  //  home_marker = createMarker( 0, home_pt.gPt, mkTxt( home_pt));
  //  gmap.addOverlay(home_marker);

}

