

// ---------------------------------------------------------------------------------
// 
// ---------------------------------------------------------------------------------
function createHLmarker() {
  function hlzindex (hlmarker,b) {
    return GOverlay.getZIndex(hlmarker.getPoint().lat()) + hlmarker.importance*1000000;
  }
  
  var hlpoint = new GLatLng(0.00,0.00);
  hlmarker = new GMarker(hlpoint,{icon:IconHot,zIndexProcess:hlzindex}); 
  hlmarker.importance = 2;
  
  hllisten = GEvent.addListener(hlmarker, "click", function() { });
  map.addOverlay(hlmarker);
  hlmarker.hide(); // Tis created, now hide it
}


// ---------------------------------------------------------------------------------
// 
// ---------------------------------------------------------------------------------
function showHLmarker(num,imgIdx) {  
  // The highlight marker already exists - just reposition and change the html
  GEvent.removeListener(hllisten); 
  
  if (hlmarker.isHidden()) { hlmarker.show(); }
  // Note: The marker MUST be showing before you change the image or IE6 absolutely Flips Out!! (thanks again Bill)
  hlmarker.setImage(markerImageHot[imgIdx]);
  
  hlmarkernum = num;
  
  //GEvent.removeListener(hllisten); 
  hlmarker.setPoint(points[num]);
  
  hllisten = GEvent.addListener(hlmarker, "click", function() {
    if (hliwopen) {
      mcprocess = true;
      map.closeInfoWindow();
      hlmarker.hide();
      hliwopen = false;
      hliwopennum = -1;
      mcprocess = false;
    } else {
      hlmarker.openInfoWindowHtml(htmls[num]);
      hliwopen = 1;
      hliwopennum = num;
    }
  });
  
}


// ---------------------------------------------------------------------------------
function openHLIW(nbr) {
  hlmarker.openInfoWindowHtml(htmls[nbr]);
  hliwopen = true;
  hliwopennum = nbr;
}

// ---------------------------------------------------------------------------------
function closeHLIW(nbr) {
  map.closeInfoWindow();
  hliwopen = false;
  hliwopennum = -1;
}

// ---------------------------------------------------------------------------------
// Handle a click on a regular marker (not a Highlight marker)
// ---------------------------------------------------------------------------------
function markerClick(nbr,imgIdx) {
  mcprocess = true;
  
  if (hliwopen) { map.closeInfoWindow(); }
  
  showHLmarker(nbr,imgIdx);
  openHLIW(nbr);
  
  mcprocess = false;
}


// ---------------------------------------------------------------------------------
// 
// ---------------------------------------------------------------------------------
function sbMouseOver(num,imgIdx) {
  if (hliwopen && (num != hliwopennum)) {
    map.closeInfoWindow(); 
    hliwopen = false;
  }
  
  if (!hlmarker.isHidden() && (num == hlmarkernum)) {
    // same entry ... leave it alone
  } else {
    showHLmarker(num,imgIdx);
  }
}


// ---------------------------------------------------------------------------------
// 
// ---------------------------------------------------------------------------------
function sbMouseOut(num) {
  if (!hliwopen){ 
    hlmarker.hide();
    hlmarkernum = -1;
  }
}


// ---------------------------------------------------------------------------------
// 
// ---------------------------------------------------------------------------------
function sbclick(num,imgIdx) {
  sbcprocess = true;
  
  if (hliwopen) { // A highlight infowindow is open
    if (num == hlmarkernum) { // The infowindow for this SB entry is already open, close it on the click
      closeHLIW(num);
      
    } else { // An infowindow is open, but not for the SB entry that was clicked
      closeHLIW(num);
      openHLIW(num);
    }
    
  } else { // No infowindow is open, so just open the one for the SB entry click
    openHLIW(num);
  }
  
  sbcprocess = false;
}



// ---------------------------------------------------------------------------------
// Load the sidebar data.
// ---------------------------------------------------------------------------------
function loadSideBar(latlng,lmode) {
  //locsFound = false;
  
  function createMarker(point,name,html,number,imgIdx) {
    var marker = new GMarker(point, {icon:IconBase}); 
    GEvent.addListener(marker, "click", function() { // Add an event listeners for the marker
      markerClick(number,imgIdx);
    });
    
    GEvent.addListener(marker, "mouseover", function() {
      marker.setImage(markerImageHot[imgIdx]);
    });
    
    GEvent.addListener(marker, "mouseout", function() {
      marker.setImage(markerImageCold[imgIdx]);
    });
    return marker;
  }
  
  sideBarLocations = new Object();
  
  sideBarLocations.Read = function(xml) { // xml from Ajax.Request as this.request.response.responseXML.documentElement
    var type = xml.getAttribute('type');
    
    LIDremains = 0;
    var LIDidx = 0;
    restorehl = false;
    hlmarkerLID = -1;
    
    switch(type) { 
      // ---------------------------------------------------------------------------------
      case "nonefound":
        // Clear any markers and sidebar
        if (dspAlert) { alert("NONE FOUND"); }
        sidebar_html = '<div id="sbentries"></div>';
        e("sidebar").innerHTML = sidebar_html;
        map.clearOverlays();
        createHLmarker(); // Re-create the highlight marker
        map.setCenter(latlng, map.getZoom());
        platlng = latlng;
        // put the assembled sidebar_html contents into the sidebar div
        e("sidebar").innerHTML = sidebar_html;
        sfHover(); // now doing it for all so I can use a specific technique.  Thanks Dog.
        break; 
        
      // ---------------------------------------------------------------------------------
      case "noreload":
        if (dspAlert) { alert("NO RELOAD"); }
        platlng = latlng;
        break; 
        
      // ---------------------------------------------------------------------------------
      case "clearsb":
        if (dspAlert) { alert("CLEAR SB"); }
        sidebar_html = '<div id="sbentries"></div>';
        e("sidebar").innerHTML = sidebar_html;
        map.clearOverlays();
        createHLmarker(); // Re-create the highlight marker
        
        var center = map.getCenter();
        var dist = center.distanceFrom(latlng);
        dist = Math.round(dist/1670);
        
        var bounds = map.getBounds(); 
        if (bounds.containsLatLng(latlng)) {
          map.panTo(latlng);
        } else {
          map.setCenter(latlng, map.getZoom());
        }
        
        platlng = latlng;
        break; 
        
      // ---------------------------------------------------------------------------------
      case "success":
        hold_state = "";
        if (dspAlert) { alert("SUCCESS"); }
        success = true;
        // lmode can be "initial" or "refresh"
        if (lmode == "refresh") {
          if (!hlmarker.isHidden()) { 
            hlmarkerLID = LID[hlmarkernum];
            restorehl = true;
          }
          if (hliwopen) { var restoreiw = 1; } else { restoreiw = 0; }
          gmarkers = [];
          htmls = [];
          brands = [];
          points = [];
          LID = [];
          map.clearOverlays();
          createHLmarker(); // Re-create the highlight marker
        }
        
        //locsFound = true;
        
        var locations = xml.getElementsByTagName("location");
        sidebar_html = '<div id="sbentries">';
        for (i = 0; i < locations.length; i++) {
          maxI = i;
          // Get the data for each location
          var name      = locations[i].getAttribute("name");
          var address   = locations[i].getAttribute("address");
          var city      = locations[i].getAttribute("city");
          var state     = locations[i].getAttribute("state");
          var zip       = locations[i].getAttribute("zip");
          var phone     = locations[i].getAttribute("phone");
          var lat       = parseFloat(locations[i].getAttribute("lat"));
          var lng       = parseFloat(locations[i].getAttribute("lng"));
              LID[i]   = parseFloat(locations[i].getAttribute("lid"));
              brands[i] = locations[i].getAttribute("vendor");
          var locurl    = locations[i].getAttribute("url");
          
          hold_state = state;
          
          if (LID[i] == hlmarkerLID) { 
            LIDremains = 1;
            LIDidx = i;
          }
          
          
          // Set the image index according to the brand
          imgIdx = -1;
          for ( var bidx in brandIDX) {
            if (brands[i] == brandIDX[bidx]) {
              imgIdx = bidx;
              break;
            }
          } 
          if (imgIdx < 0) { 
             // the last hot/cold entry should be a default and should be the same number hot vs cold
            imgIdx = markerImageCold.length-1;
          }
          
          
          
          var point = new GLatLng(lat,lng);
          var label = "Load Me " + i;/*markers[i].getAttribute("label");*/
          var html = '';
          
          html  = '<div class="iw">';
          html += '<span class="locName">' + name + '</span><br />';
          html += '<span class="locAddr">' + address + '<br />' + 
                      city + ', ' + state + ' ' + zip +'</span><br />';
          html += '<span class="locPhone">' + phone + '</span>';
          if (locurl != '') {
            html += '<span class="locUrl"><a href="' + locurl + '">website</a></span>';
          }
          html += '</div>';
          
          htmls[i] = html;
          points[i] = point;
          
          // create the marker
          var marker = createMarker(point,label,html, i, imgIdx);
          map.addOverlay(marker);
          marker.setImage(markerImageCold[imgIdx]); // Apply the image after it is added.
          gmarkers[i] = marker;
          
          // ==== Each time a point is found, extend the bounds to include it with ... =====
          // ............ bounds.extend(point);
          
          sidebar_html += '<p class="sbnum" align="right">' + (i+1) + '</p>';
          sidebar_html += '<span onmouseover="sbMouseOver('+i+','+imgIdx 
                        +')" onmouseout="sbMouseOut('+i+','+imgIdx+')"  onclick="sbclick('+i+','+imgIdx+')">';
          sidebar_html += '<div class="sbentry">';
          
          sidebar_html += '<span class="locName">' + name + '</span><br />';
          sidebar_html += '<span class="locAddr">' + address + '<br />' + 
                            city + ', ' + state + ' ' + zip +'</span><br />';
          sidebar_html += '<span class="locPhone">' + phone + '</span>';//<br /><br />';
          sidebar_html += '</div></span>';
          
        }
        
        sidebar_html += '</div>';
        
        if ( (lmode == "refresh") && (restorehl) ) {
          if (LIDremains) {
            sbclick(LIDidx);
          }
        }
        
        var zoomed = map.getZoom();
        
        if (zoomed == basezoom) { 
          if (hold_state == "HI") {
            map.setCenter(latlng, zoomed+2);
          } else {
            map.setCenter(latlng, zoomed+3);
          }
        } else {
          var bounds = map.getBounds(); 
          if (bounds.containsLatLng(latlng)) {
            map.panTo(latlng);
          } else {
            map.setCenter(latlng, zoomed);
          }
        }
        
        platlng = map.getCenter();
        e("sidebar").innerHTML = sidebar_html; // put the assembled sidebar_html contents into the sidebar div
        sfHover(); // now doing it for all so I can use a specific technique.  Thanks Dog.
        break;
        
      // ---------------------------------------------------------------------------------
      default:
        if (dspAlert) { alert("DEFAULT"); }
        // Really?  The eleven point turn?!?
        platlng = latlng;
    } // switch
    
    
    if (initialMap) {
      e("sboxdesc").innerHTML = use_sbd; // Set the search box description to Used.
      GEvent.removeListener(initmap); 
      initialMap = false;
    }
    
    //if (inGC) { inGC = false; }    
    
  } // End of XML Read
  
  
  
  // ===== Start with an empty GLatLngBounds object =====     
  var bounds = new GLatLngBounds();
  
  
  switch(lmode) { 
    // ---------------------------------------------------------------------------------
    case "initial":
      plat = 0;
      plng = 0;
      break; 
      
    // ---------------------------------------------------------------------------------
    case "initialsbox":
      lmode == "initial"; // Later plans for this segment
      plat = 0;
      plng = 0;
      break; 
      
    // ---------------------------------------------------------------------------------
    case "refresh":
      plat = clat;
      plng = clng;
      break; 
      
    // ---------------------------------------------------------------------------------
    case "refreshsbox":
      plat = 0;
      plng = 0;
      map.clearOverlays();
      createHLmarker(); // Re-create the highlight marker
      lmode == "initial"; // override refreshsbox for now ... really gotta clean this up
      break; 
      
    default:
      lmode == "initial"; // Cause I don't know what was planned.
      plat = 0;
      plng = 0;
  } // switch
  
  
  // Read the xml file for the sidebar information.
  
  
  clat = latlng.lat();
  clng = latlng.lng();
  
  var success = false;
  
  
  var locRequest = "sbserver.php?"
      + "tid=" + reqtid
      + "&clat=" + ( Math.round( 1000000*clat) / 1000000 ) + "&clng=" + ( Math.round( 1000000*clng) / 1000000 )
      + "&plat=" + ( Math.round( 1000000*plat) / 1000000 ) + "&plng=" + ( Math.round( 1000000*plng) / 1000000 );
  
  if (dspAlert) { alert(locRequest); }
  //Ajax.Request = function(method, url, callback)
  Ajax.Request('GET', locRequest, sideBarLocations.Read); // Make the xml request
  
} // end of loadSideBar



// ---------------------------------------------------------------------------------
// Geocode a zip or state or city/state...
// ---------------------------------------------------------------------------------
function wiaGC(gctid,gcstr,entry) {
  //validGC = false;
  
  geoCoder = new Object();
  
  geoCoder.Read = function(xml) { // xml from Ajax.Request as this.request.response.responseXML.documentElement
    var type = xml.getAttribute('type');
    
    if (type != 'success') { // No joy, try Google's geocoder
      //googleGC(gcstr);
      googleGC(entry);
      
    } else { // Success
      //validGC = true;
      var rows = xml.getElementsByTagName('row'); // There should only be one result
      
      for (i = 0; i < rows.length; i++) {
        if (gctid == "st") {
          var gcstatename = rows[i].getAttribute('statename');
          var gczoom  = parseFloat(rows[i].getAttribute('mapzoom'));
          var gcaddress = gcstatename;
        }
        
        if (gctid == "zip" || gctid == "cityst") {
          var gccity      = rows[i].getAttribute("city");
          var gcstate     = rows[i].getAttribute("st");
          var gczip       = rows[i].getAttribute("zip");
          var gczoom = 7;
          var gcaddress = gccity + ", " + gcstate + ", " + gczip;
        }
        
        var gclat   = parseFloat(rows[i].getAttribute('lat'));
        var gclng   = parseFloat(rows[i].getAttribute('lng'));
        
        processGC(gclat,gclng,gczoom,gcaddress);
      }
    }
  }
  
  //Ajax.Request = function(method, url, callback)
  Ajax.Request('GET', "wiagc.php?" + gcstr, geoCoder.Read); // Make the xml request
}


// ---------------------------------------------------------------------------------
// Basic Geocode didn't work (or wasn't tried), go to Google ...
// ---------------------------------------------------------------------------------
function googleGC(entry) {
  //validGC = false;
  
  var address = '"'+entry.value+'"';
  geocoder.getLocations(address, function (result) { 
    if (result.Status.code == G_GEO_SUCCESS) { // Was successful
      //validGC = true; // We'll assume that the first placemark is the one we want
      var p = result.Placemark[0].Point.coordinates;
      var addr = result.Placemark[0].address;
      var gcaddress = addr;
      var gclat=p[1];
      var gclng=p[0];
      var gczoom = map.getZoom();
      if (gczoom >= 12) { gczoom = 7; }
      processGC(gclat,gclng,gczoom,gcaddress);
    }
    // ====== Decode the error status ======
    else {
      // === if we were sending the requests too fast, try this one again and increase the delay
      if (result.Status.code == G_GEO_TOO_MANY_QUERIES) {
        
      } else {
        var reason="Code "+result.Status.code;
        if (reasons[result.Status.code]) {
          reason = reasons[result.Status.code]
        }
      }   
    }
  });
  
}


// ---------------------------------------------------------------------------------
// Return a string for very basic GC
// ---------------------------------------------------------------------------------
function getGCString(loc) {
  var gcstr = false;
  var len = loc.value.length;
  var zip;
  
  if (isNumeric(loc)) {
    if (len == 9) { 
      gcstr = "tid=zip&gcloc=" + loc.value.substring(0,5); // 9 numeric - Zip + 4 ?
    }
    if (len == 5) { 
      gcstr = "tid=zip&gcloc=" + loc.value; // 5 numeric - Zip Code?
    }
    
  } else if (isAlphabetic(loc)) {
    if (len == 2) { 
      gcstr = "tid=st&gcloc=" + loc.value; // Probably a state abbreviation
    }
    
  } else if (isAlphabeticWC(loc)) {
    //alert("Is WC"); 
    var c = "";
    if (charCount(loc.value,",") == 1) { c = ","; } //alert("Is WC 1"); 
    else if (charCount(loc.value," ") == 1) { c = " "; } //alert("Is WC 2"); 
    
    if (c != "") { //alert("Is WC3"); 
      var a = trim(loc.value.split(c, 2)[0]);
      var b = trim(loc.value.split(c, 2)[1]);
      //alert("A: " + a + " B: " + b ); 
      if (b.length == 2) { 
  if (a == "oklahoma city") { a = "oklahoma%20city"; }
        gcstr = "tid=cityst&gccity=" + a + "&gcst=" + b; // Possibly a City/State
        //alert("GCSTR: " + gcstr); 
      }
      
    } else if ( (charCount(loc.value,",") == 0) && (charCount(loc.value," ") > 1) ) { //alert("Is WC 4"); 
      // No commas, but more than one blank - test to see if the end might be a state
      var wrkcityst = new Array();
      wrkcityst = splitLast(loc.value," ");
      var a = trim(wrkcityst[0]);
      var b = trim(wrkcityst[1]);
      
      if (b.length == 2) { // Possibly a City/State
        //alert("Is WC 5"); 
        gcstr = "tid=cityst&gccity=" + a + "&gcst=" + b;
      } else {
        // Failed last city/State test
      }
      
    }
    
  } // isNumeric
  
  return gcstr;
}


// ---------------------------------------------------------------------------------
// Process the geocode results
// ---------------------------------------------------------------------------------
function processGC(gclat,gclng,gczoom,gcaddress) {  
  //inGC = true;
  
  document.searchBox.reset();
  if (map.getZoom() != gczoom) { map.setZoom(gczoom); }

  gclatlng = new GLatLng(gclat,gclng);
  loadSideBar(gclatlng,gclmode)
  
  gclmode = "refreshsbox";
  ////inGC = false;
}


// ---------------------------------------------------------------------------------
// Check the search box and see if we can find a location for what they entered.
// ---------------------------------------------------------------------------------
function findLoc(entry) {
  gcaddress = "";
  //validGC = false;
  
  if (gclmode == "") { gclmode = "initialsbox"; }
  if (entry.value != "") { entry.value = trim(entry.value); }
  var len = entry.value.length;
  
  if (len >= 2) {
    var gcstr = getGCString(entry);
    if (gcstr) { // Got a string back, we'll try the internal basic processing
      var curtid = gcstr.substring( gcstr.indexOf("=") +1, gcstr.indexOf("&") );
      //alert("CurTID: " + curtid + " GCStr: " + gcstr + " Entry: " + entry);
      wiaGC(curtid,gcstr,entry);
    } else if (len >= 4) {
      googleGC(entry); // Did NOT pass the simple test - will have to use outside service
    }
  }
  
}



// ---------------------------------------------------------------------------------
// 
// Yeah, I got work to do.  I just kinda threw this together at the last minute 
// with various pieces I've been messing around with.
// 
// - Mel
// ---------------------------------------------------------------------------------


// ====== Array for decoding the failure codes ======
var reasons=[];
reasons[G_GEO_SUCCESS]            = "Success";
reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
reasons[403]                      = "Error 403: Probably an incorrect error caused by a bug in the handling of invalid JSON.";


// ---------------------------------------------------------------------------------
// WIA01.js Globals ....
var map;
var geocoder;

var hlmarker;

var hliwopen = false;
var hliwopennum = -1;

var hlmarkernum = -1;
var hllisten;

var hlmarkerLID = -1;

var basezoom = 4;

var initialMap = true;
var initialLoad = true;

var dspAlert = false;

//var validGC = false;

var gclatlng;
var gclat;
var gclng;
var gczoom;
var gclmode;


var browserType;
var browserVersion;
var browserOS;

//var locsFound = false;
//var inGC = false;
// ---------------------------------------------------------------------------------

// ===================================================================================

// ---------------------------------------------------------------------------------
// Wgetdata.js Globals ....
// Create the custom Icons
var IconHot = new GIcon();
//alert("Path: " + commonpath);
//alert("Image: " + commonpath+"/images/marker_base.png");
IconHot.image = commonpath+"/images/marker_base.png";
IconHot.iconSize = new GSize(30, 36);
IconHot.iconAnchor = new GPoint(1, 36);
IconHot.infoWindowAnchor = new GPoint(20, 3);
IconHot.transparent = commonpath+"/images/marker_transparent.png";
IconHot.imageMap=[1,1,1,33,5,29,30,28,30,1]

var IconBase = new GIcon();
IconBase.image = commonpath+"/images/marker_base.png";
IconBase.iconSize = new GSize(30, 36);
IconBase.shadow = commonpath+"/images/marker_shadow.png";
IconBase.shadowSize = new GSize(49, 36);
IconBase.iconAnchor = new GPoint(1, 36);
IconBase.infoWindowAnchor = new GPoint(20, 3);
IconBase.transparent = commonpath+"/images/marker_transparent.png"; 
IconBase.imageMap=[1,1,1,33,5,29,30,28,30,1]

var geocoder = new GClientGeocoder();
geocoder.setBaseCountryCode("US");

var gcaddress;



var plat = 0;
var plng = 0;
var platlng;
var count = 0;

var latlng;

var gmarkers = [];
var htmls = [];
var brands = [];
var points = [];
var LID = [];
var i = 0;
var maxI = 0;
var mcprocess = false; // marker click process flag
var sbcprocess = false; // sidebar click process flag





//var init_sb_html  = '<div class="sbinit">Click the map to<br />select a location</div>';
var init_sb_html  = '<div class="sbinit">Enter a location above<br /> or just click the map</div>';
var init_sbd  = 'Enter an address, city, state, ZIP code, or click on the map';
var use_sbd  = 'Enter an address, city, state, or ZIP code';


// -----------------------------------------------------------------------------------
// Functions.
// ===================================================================================







// ---------------------------------------------------------------------------------
// 
// ---------------------------------------------------------------------------------
function checkDist(clat, clng, plat, plng) {
  var R = 6371; // km
  var dLat = (lat2-lat1).toRad();
  var dLon = (lon2-lon1).toRad(); 
  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
          Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * 
          Math.sin(dLon/2) * Math.sin(dLon/2); 
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
  var d = R * c;
  return d;
}



// ---------------------------------------------------------------------------------
// Close and Open the info panel.
// ---------------------------------------------------------------------------------
function ipClose() {
  e('right').style.display = 'none';
  cssjs('swap',e('brarrow'),'ipOpen','ipClosed');
  cssjs('swap',e('blarrow'),'ipOpen','ipClosed');
  cssjs('swap',e('bar'),'ipOpen','ipClosed');
  cssjs('swap',e('left'),'ipOpen','ipClosed');
  map.checkResize();
}

function ipOpen() {
  e('right').style.display = 'inline';
  cssjs('swap',e('blarrow'),'ipClosed','ipOpen');
  cssjs('swap',e('brarrow'),'ipClosed','ipOpen');
  cssjs('swap',e('bar'),'ipClosed','ipOpen');
  cssjs('swap',e('left'),'ipClosed','ipOpen');
  map.checkResize();
}



// ---------------------------------------------------------------------------------
// 
// ---------------------------------------------------------------------------------
function setHeight() {
  var windowHeight = getWindowHeight(); // Get current height of the window
  var headerHeight = e('header').offsetHeight; // Get height of the header
  var mainHeight = windowHeight - headerHeight - 17; // Set the heights of the main divs
  
  if (mainHeight > 0) {
    e('left').style.height = mainHeight + 'px';
    e('bar').style.height = mainHeight + 'px';
    e('right').style.height = mainHeight + 'px';
    
    // Now set the position of the arrow
    var barrowPos = (mainHeight/2) - (12/2); // gotta get the second dimension automatically some day.
    var anchors = document.getElementsByTagName('img');
    for (var n=0;n<anchors.length;n++) {
      if (anchors[n].attributes['class'] &&  anchors[n].attributes['class'].nodeValue == "barrow") {
        anchors[n].style.top = barrowPos + 'px';
      }
    }
  }
}



// ---------------------------------------------------------------------------------
// 
// ---------------------------------------------------------------------------------
sfHover = function() {
  var sfEls = e("sbentries").getElementsByTagName("div");
  for (var n=0; n<sfEls.length; n++) {
    sfEls[n].onmouseover=function() {
      this.className+=" sfhover";
    }
    sfEls[n].onmouseout=function() {
      this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
    }
  }
}



function pointInMapBounds(map, point) {
  var bounds = map.GLatLngBounds();
  if( point.x < bounds.minX || point.y < bounds.minY ||
       point.x > bounds.maxX || point.y > bounds.maxY ) {
      return false;
  } else {
      return true;
  }
}

function latlngInMapBounds(map, lat, lng) {
  var bounds = map.GLatLngBounds();
  if( lat < bounds.minY || lat > bounds.maxY ||
       lng < bounds.minX || lng > bounds.maxX ) {
      return false;
  } else {
      return true;
  }
}


// ---------------------------------------------------------------------------------
// Reset the map ...
// ---------------------------------------------------------------------------------
function resetMap() {
  platlng = 0;
  document.searchBox.reset();
  document.searchBox.searchString.focus();
  map.clearOverlays();
  createHLmarker(); // Re-create the highlight marker
  map.setCenter(new GLatLng(36.5000, -96.0000), basezoom);
  
  e("sboxdesc").innerHTML = init_sbd;
  
  e("sidebar").innerHTML = init_sb_html;
  initialMap = true;
  
  initmap = GEvent.addListener(map, "click", function (overlay,latlng) {
    if (latlng) {
      initialMap = false;
      GEvent.removeListener(initmap); 
      loadSideBar(latlng,"initial");
    }
  }); 
}


// ---------------------------------------------------------------------------------
// The OnLoad Portion ...
// ---------------------------------------------------------------------------------
function onLoad() {
  
  browserType = BrowserDetect.browser;
  browserVersion = BrowserDetect.version;
  browserOS = BrowserDetect.OS;
  
  setHeight();
  window.onresize = setHeight;
  // Load the map - div must be active and not totally percentage base to "play nice"
  // with Google Maps ... even though you can then resize them.
  
  document.searchBox.reset();
  document.searchBox.searchString.focus();
  
  
  cssjs('add',e('right'),'ipOpen');
  cssjs('add',e('blarrow'),'ipOpen');
  cssjs('add',e('brarrow'),'ipOpen');
  cssjs('add',e('bar'),'ipOpen');
  cssjs('add',e('left'),'ipOpen');
  
  if (GBrowserIsCompatible()) {
    map = new GMap2(e("left"), {draggableCursor: 'default'/*'pointer'*//*'crosshair'*/, draggingCursor: 'pointer'});
    geocoder = new GClientGeocoder(); // Create new geocoding object
    
    map.setCenter(new GLatLng(36.5000, -96.0000), basezoom);
    // for testing map.setCenter(new GLatLng(35.8000, -96.0000), basezoom);
    
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl()); // Standard Map/Sat/Hybrid
    map.addMapType(G_PHYSICAL_MAP); // Adds Terrain selection
    map.enableScrollWheelZoom();
    
    gclatlng = new GLatLng(36.5000, -96.0000);
    
    GEvent.addListener(map,"infowindowclose", function() {
      
      if (sbcprocess) {
        // Don't do anything
        
      } else {
        
        if (hliwopen){ hliwopen = false; }
        //alert("IW Close Listener A mcprocess " + mcprocess);
        
        if ( (!mcprocess) && (!hlmarker.isHidden()) ) {
          // Don't do this when it's the marker click process - kludgy I know ...
          hlmarker.hide();
          hlmarkernum = -1;
          //alert("IW Close Listener B mcprocess " + mcprocess);
        }
      }
    });
    
    
    GEvent.addListener(map, "dragend", function() {
      if (initialMap) {
        var center = map.getCenter();
        loadSideBar(center,"initial");  // Load the results based on the stopping point
        
      } else if (platlng) {
        var center = map.getCenter();
        var dist = center.distanceFrom(platlng);
        dist = Math.round(dist/1670);
        if (dist > 50) { 
          loadSideBar(center,"refresh");  // Reload the results based on the stopping point
        }
      }
    });
    
    
    
    createHLmarker(); // Create the highlight marker
    map.checkResize();
    
    e("sboxdesc").innerHTML = init_sbd;
    e("sidebar").innerHTML = init_sb_html;
    
    initmap = GEvent.addListener(map, "click", function (overlay,latlng) {
      if (latlng) {
        initialMap = false;
        e("sboxdesc").innerHTML = use_sbd;
        GEvent.removeListener(initmap); 
        loadSideBar(latlng,"initial");
      }
    }); 
  }
}
