var map;
var map_load;
var preIcons = new Object();
var preMarkers = new Object();
var ObjectTabs = new Object();
var currentObject = new String();
var mainControl;

function best_zoom(bounds, mnode, map, config ) {

  if ( config.zoom )
  {
    if (config.zoom < config.zoom_in )
    {
      return( parseInt(config.zoom_in) );
    }
    else
    {
      return( parseInt(config.zoom) );
    }
  }

  try{
    minZoom = map.getBoundsZoomLevel(bounds);
  }
  catch(e)
  {
    minZoom=11;
  }

  if ( config.zoom_in && (minZoom < config.zoom_in) ){ minZoom = config.zoom_in };

  return( parseInt(minZoom) );
}

function preOpenInfo( object_id, info )
{
  preMarkers[object_id].openInfoWindowHtml(
      '<div page="1" label="Quick Info" style="width:320px;height:83px;margin:0px;padding:0px;font-size:10pt;font-family:Arial,sans-serif;"><a target="_blank" href="http://www.planetrealestate.com/object/?ID='
      +object_id+
      '"><img align="left" border="0" width="125" height="83" style="margin-right:5px" src="http://www.planetrealestate.com/object/google_map_info.pl?OBJECT_ID='
      +object_id+
      '"/></a><b>'
      +info['kind']+
      '</b>&nbsp;&nbsp;<a target="_blank" href="http://www.planetrealestate.com/object/?ID='
      +object_id+
      '">(view)</a><br>'
      +info['name']+
      ( info['price'] ? '<br>'+info['price'] : '')+
      ( info['beds_baths'] ? '<br>'+info['beds_baths'] : '')+
      '</div>'+( String(document.cookie).match(/OPENSITE=Y/i) ? '' : '<div page="2" label="Details"></div>' ));
}

function prePopTabs( object_id, info )
{
  ObjectTabs[object_id] = new Object();
  ObjectTabs[object_id]["1"] =
   '<div page="1" label="Quick Info" style="width:320px;height:83px;margin:0px;padding:0px;font-size:10pt;font-family:Arial,sans-serif;"><a target="_blank" href="http://www.planetrealestate.com/object/?ID='
      +object_id+
      '"><img align="left" border="0" width="125" height="83" style="margin-right:5px" src="http://www.planetrealestate.com/object/google_map_info.pl?OBJECT_ID='
      +object_id+
      '"/></a><b>'
      +info['kind']+
      '</b>&nbsp;&nbsp;<a target="_blank" href="http://www.planetrealestate.com/object/?ID='
      +object_id+
      '">(view)</a><br>'
      +info['name']+
      ( info['price'] ? '<br>'+info['price'] : '')+
      ( info['beds_baths'] ? '<br>'+info['beds_baths'] : '')+'</div>'+
      ( String(document.cookie).match(/OPENSITE=Y/i) ? '' : '<div page="2" label="Details"></div>' );

  ObjectTabs[object_id]["2"] =
   '<div page="1" label="Quick Info" ></div><div page="2" label="Details" class="active" style="width:320px;height:83px;margin:0px;padding:0px;font-size:10pt;font-family:Arial,sans-serif;"><iframe src="http://www.planetrealestate.com/object/google_map_features.pl?ID='+object_id+'" width="320" height="83" marginheight="0" marginwidth="0" vspace="0" hsapce="0" scrolling="0" frameborder="0" style="width:320px;height:83px;margin:0px;padding:0px;"></iframe></div>';
}

function preLoadTab( isPage, pageNum, junk )
{
  if ( String(isPage) == String("page") )
  {
    if ( parseInt(pageNum) == 1 )
    {
      preMarkers[currentObject].openInfoWindowHtml( ObjectTabs[currentObject]["1"] );
    }
    else
    {
      preMarkers[currentObject].openInfoWindowHtml( ObjectTabs[currentObject]["2"] );
    }
  }
}

function createMarker(point, object_id, kind, info) {
 
  var kindKey = new String(kind+':'+String(info['live']));
  kindKey += ':'+info['primary'];
  if ( String(kind) == String( 'ZIP' ) )
  {
    kindKey += ':'+info['name'];
  } 
  if ( String(kind) == String( 'PROPERTY' ) )
  {
    kindKey += ':'+info['altcolor'];
  } 

  if ( !preIcons[kindKey] )
  {
    preIcons[kindKey] = new GIcon();
    if ( (String(info["live"])==String('0')) && (String(kind) == String("PROPERTY")) )
    {
      preIcons[kindKey].image = "http://images.planetrealestate.com/images/v2/object/kind/small_icon/"+String(kind).toUpperCase()+"_SOLD_50.png";
      preIcons[kindKey].transparent = "http://images.planetrealestate.com/images/v2/object/kind/small_icon/"+String(kind).toUpperCase()+"_SOLD_50.png";
      preIcons[kindKey].iconSize = new GSize(22,22);
      preIcons[kindKey].iconAnchor = new GLatLng(11,11);
      preIcons[kindKey].infoWindowAnchor = new GLatLng(0,11);
      preIcons[kindKey].imageMap = new Array( 0,0, 0,22, 22,22, 22,0, 0,0 );
    }
    else if ( String(kind) == String("ZIP") )
    {
      preIcons[kindKey].image = "http://images.planetrealestate.com/zip/"+String(info['name'])+".png";
      preIcons[kindKey].transparent = "http://images.planetrealestate.com/zip/"+String(info['name'])+".png";
      preIcons[kindKey].iconSize = new GSize(60,19);
      preIcons[kindKey].iconAnchor = new GLatLng(10,30);
      preIcons[kindKey].infoWindowAnchor = new GLatLng(5,30);
      preIcons[kindKey].imageMap = new Array( 0,0, 0,19, 60,19, 60,0, 0,0 );
    }
    else if ( (String(info["live"])==String('0')) || (String(kind).toUpperCase() != String("PROPERTY")) )
    {
      preIcons[kindKey].image = "http://images.planetrealestate.com/images/v2/object/kind/small_icon/"+String(kind).toUpperCase()+"_50.png";
      preIcons[kindKey].transparent = "http://images.planetrealestate.com/images/v2/object/kind/small_icon/"+String(kind).toUpperCase()+"_50.png";
      preIcons[kindKey].iconSize = new GSize(20,20);
      preIcons[kindKey].iconAnchor = new GLatLng(10,10);
      preIcons[kindKey].infoWindowAnchor = new GLatLng(0,10);
      preIcons[kindKey].imageMap = new Array( 0,0, 0,20, 20,20, 20,0, 0,0 );
    }
    else if ( String(info["primary"])==String('yes') )
    {
      preIcons[kindKey].image = "http://images.planetrealestate.com/images/v2/object/kind/small_icon/"+String(kind).toUpperCase()+".png";
      preIcons[kindKey].transparent = "http://images.planetrealestate.com/images/v2/object/kind/small_icon/"+String(kind).toUpperCase()+".png";
      preIcons[kindKey].iconSize = new GSize(22,22);
      preIcons[kindKey].iconAnchor = new GLatLng(11,11);
      preIcons[kindKey].infoWindowAnchor = new GLatLng(0,11);
      preIcons[kindKey].imageMap = new Array( 0,0, 0,22, 22,22, 22,0, 0,0 );
    }
    else if ( (String(info["primary"])==String('no')) && info['altcolor'] )
    {
      preIcons[kindKey].image = "http://images.planetrealestate.com/images/v2/object/kind/small_icon/"+String(kind).toUpperCase()+"_SOLD_50.png";
      preIcons[kindKey].transparent = "http://images.planetrealestate.com/images/v2/object/kind/small_icon/"+String(kind).toUpperCase()+"_SOLD_50.png";
      preIcons[kindKey].iconSize = new GSize(22,22);
      preIcons[kindKey].iconAnchor = new GLatLng(11,11);
      preIcons[kindKey].infoWindowAnchor = new GLatLng(0,11);
      preIcons[kindKey].imageMap = new Array( 0,0, 0,22, 22,22, 22,0, 0,0 );
    }
    else if ( String(info["primary"])==String('no') )
    {
      preIcons[kindKey].image = "http://images.planetrealestate.com/images/v2/object/kind/small_icon/"+String(kind).toUpperCase()+"_50.png";
      preIcons[kindKey].transparent = "http://images.planetrealestate.com/images/v2/object/kind/small_icon/"+String(kind).toUpperCase()+"_50.png";
      preIcons[kindKey].iconSize = new GSize(22,22);
      preIcons[kindKey].iconAnchor = new GLatLng(11,11);
      preIcons[kindKey].infoWindowAnchor = new GLatLng(0,11);
      preIcons[kindKey].imageMap = new Array( 0,0, 0,22, 22,22, 22,0, 0,0 );
    }
    else if ( String(info["primary"])==String('no') )
    {
      preIcons[kindKey].image = "http://images.planetrealestate.com/images/v2/object/kind/small_icon/"+String(kind).toUpperCase()+"_50.png";
      preIcons[kindKey].transparent = "http://images.planetrealestate.com/images/v2/object/kind/small_icon/"+String(kind).toUpperCase()+"_50.png";
      preIcons[kindKey].iconSize = new GSize(22,22);
      preIcons[kindKey].iconAnchor = new GLatLng(11,11);
      preIcons[kindKey].infoWindowAnchor = new GLatLng(0,11);
      preIcons[kindKey].imageMap = new Array( 0,0, 0,22, 22,22, 22,0, 0,0 );
    }
    else
    {
      preIcons[kindKey].image = "http://images.planetrealestate.com/images/v2/object/kind/small_icon/"+String(kind).toUpperCase()+".png";
      preIcons[kindKey].transparent = "http://images.planetrealestate.com/images/v2/object/kind/small_icon/"+String(kind).toUpperCase()+".png";
      preIcons[kindKey].iconSize = new GSize(22,22);
      preIcons[kindKey].iconAnchor = new GLatLng(11,11);
      preIcons[kindKey].infoWindowAnchor = new GLatLng(0,11);
      preIcons[kindKey].imageMap = new Array( 0,0, 0,22, 22,22, 22,0, 0,0 );
    }
  }

  var marker = new GMarker( point, preIcons[kindKey] );
  preMarkers[String(object_id)] = marker;
  if ( !((String(info["live"])==String('0')) && (String(kind) == String("PROPERTY"))) )
  {
    marker.zIndex = '10';
  }

  prePopTabs( object_id, info );

  GEvent.addListener(marker, "click", function() {
    currentObject = String(object_id);
    preLoadTab( "page", 1, null );
  });
    
  return marker;
}

function fixZoom( zoom_in, zoom_out )
{
  if ( zoom_in )
  {
    if ( map.getZoom() < zoom_in ){
      map.setZoom(zoom_in); 
      alert( "You are currently at the lowest zoom level.\n Click on any icons to see further details of\n that home or neighborhood." );
    }
  }
  if ( zoom_out )
  {
    if ( map.getZoom() > zoom_out ){ 
      map.setZoom(zoom_out); 
    }
  }
}

function processPoints( xmlDoc, markers, polys )
{
  //var markers = xmlDoc.documentElement.getElementsByTagName("marker");

  for (var i = 0; i < markers.length; i++) {
    var point = new GPoint(parseFloat(markers[i].getAttribute("lng")),
                           parseFloat(markers[i].getAttribute("lat")));
    var object_id  = markers[i].getAttribute("object_id");
    var kind  = String(markers[i].getAttribute("kind")).toUpperCase();
    var info = new Object();
    info['kind'] = String( kind ).toLowerCase();
    info['name'] = markers[i].getAttribute("name");
    if ( markers[i].getAttribute("beds") ) {
      info['beds_baths'] = new String(
        String(markers[i].getAttribute("beds"))+' beds / '+
        String(markers[i].getAttribute("baths"))+' baths');
    }
    if ( markers[i].getAttribute("price") ) {
      info['price'] = markers[i].getAttribute("price");
    }
    if ( !info['name'] && markers[i].getAttribute("mls") && !String(document.cookie).match(/OPENSITE=Y/i) ){
      info['name'] = 'MLS \# '+markers[i].getAttribute("mls");
    }
    if ( !info['name'] ) {
      info['name'] = 'PRE \# '+String(object_id);
    }
    info['live'] = parseInt(markers[i].getAttribute("live"));
    info['primary'] = String(markers[i].getAttribute("primary"));
    info['altcolor'] = String(markers[i].getAttribute("altcolor"));
    var marker = new createMarker(point,object_id,kind,info);
    map.addOverlay(marker);
  }

  //var polys = xmlDoc.documentElement.getElementsByTagName('poly');
  for ( var i = 0; i < polys.length; i++ )
  {
    var points = new Array();

    if ( document.all ) { points = String( polys[i].text ).split(/,/); }
                   else { points = String( polys[i].firstChild.data ).split(/,/); }

    var gPoints = new Array();
    for (var j = 0; j < points.length; j++ )
    {
      var coords = String(points[j]).split(' ');
      gPoints.push( new GLatLng( coords[1] , coords[0]) );
    }
    map.addOverlay( new GPolyline( gPoints, "\#0000ff", 5 ) );
  }
}

function fetchPoints( xmlurl )
{
  var request = GXmlHttp.create();
  request.open("GET", xmlurl, true);
  request.onreadystatechange = function() {
    if (request && (request.readyState == 4)) {
      var xmlDoc = request.responseXML;
      processPoints( xmlDoc, 
          xmlDoc.documentElement.getElementsByTagName("marker"), 
          xmlDoc.documentElement.getElementsByTagName('poly') );
    }
  }
  request.send(null);
}

/* FUNCTION createGoogleMap
   PARMS
     config { 
       map: "map_id",
       xml: "xml_url",
       types: Array( G_NORMAL_MAP, G_HYBRID_MAP, G_SATELLITE_MAP ),
       zoom_in: "minimum zoom in level",
       zoom_out: "maximum zoom out level",
       control: "small" or "large" or empty/none,
       no_dragging: true }
*/
function createGoogleMap( config )
{
  if ( config.load )
  {
    map_load = document.getElementById( config.load );
  }
  if ( !config.types ) { config.types = new Array( G_NORMAL_MAP ); }

  map = new GMap2(document.getElementById(config.map), { 'mapTypes': config.types });

  if ( config.zoom_out )
  {
    var maptype;
    //XXX maptype = map.getCurrentMapType();
    //XXX maptype.numZoomLevels = config.zoom_out;
  }
  map.disableDragging();

  if ( config.zoom && config.lat && config.lng )
  {
    map.setCenter(new GLatLng( config.lat , config.lng), parseInt(config.zoom));
  }
  else
  {
    map.setCenter(new GLatLng( 36.64197781470594 , -114.0985107421875), 9);
  }

  if ( map_load )
  {
    map.openInfoWindowHtml( map.getCenter(), 'Loading Data...' );
  }

  var request = GXmlHttp.create();
  request.open("GET", config.xml, true);
  request.onreadystatechange = function() {
    if (request && (request.readyState == 4)) {
      var xmlDoc = request.responseXML;

      var xml_more = xmlDoc.documentElement.getAttribute('xml_more');

      var bounds = new GBounds( 
        new GLatLng(parseFloat(xmlDoc.documentElement.getAttribute('lat_min')),
        parseFloat(xmlDoc.documentElement.getAttribute('lng_min'))),
        new GLatLng(parseFloat(xmlDoc.documentElement.getAttribute('lat_max')),
        parseFloat(xmlDoc.documentElement.getAttribute('lng_max'))));

      config.zoom = parseInt( xmlDoc.documentElement.getAttribute('zoom') );

      var markers = xmlDoc.documentElement.getElementsByTagName("marker");
      var polys = xmlDoc.documentElement.getElementsByTagName('poly');

      if ( !markers.length )
      {
        map.openInfoWindowHtml( map.getCenter(), '<br/>Sorry, No Search Results to map.<br/>' );
        if ( map_load ){
          map_load.innerHTML = 'finished loading data points';
        }
      }
      else
      {
        try {
          map.setCenter(new GLatLng( parseFloat(xmlDoc.documentElement.getAttribute('lat')), parseFloat(xmlDoc.documentElement.getAttribute('lng')) ), best_zoom( bounds, document.getElementById(config.map),map, config ));
        }
        catch(e){}

        processPoints( xmlDoc, markers, polys );

        if ( map_load )
        {
          map.closeInfoWindow();
        }
        if ( String(config.control) == String("large") ) {
          mainControl = new GLargeMapControl()
        } else if ( String(config.control) == String("small") ) {
          mainControl = new GSmallMapControl()
        }
        if ( mainControl )
        {
          map.addControl( mainControl );
        }
        if ( config.types.length > 1 ) { map.addControl(new GMapTypeControl()) }
        if ( !config.no_dragging ) { map.enableDragging(); }
        GEvent.addListener( map, "zoom", function() {
          fixZoom( config.zoom_in, config.zoom_out );
        } );
        GEvent.addListener( map, "maptypechanged", function() {
          if ( mainControl) {
            var maptype;
            map.removeControl(mainControl);
            //XXX maptype = map.getCurrentMapType();
            //XXX maptype.numZoomLevels = config.zoom_out;
            map.addControl(mainControl);
          }
        } );
        if ( map_load )
        {
          map_load.innerHTML = 'finished loading data points';
        }
        //XXX RIGHT HERE
        window.setTimeout("map.setCenter(new GLatLng( parseFloat(\""+String(xmlDoc.documentElement.getAttribute('lat'))+"\"), parseFloat(\""+String(xmlDoc.documentElement.getAttribute('lng'))+"\") ), parseInt(\""+String(best_zoom( bounds, document.getElementById(config.map),map, config ))+"\") );", 500);

        if ( String(xml_more) != String("") )
        {
          var more_bounds = map.getBounds();
          /*xml_more += '&LNG_MIN='+String(more_bounds.minX-0.005).replace('.','%2E')+
                      '&LNG_MAX='+String(more_bounds.maxX+0.005).replace('.','%2E')+
                      '&LAT_MIN='+String(more_bounds.minY-0.004).replace('.','%2E')+
                      '&LAT_MAX='+String(more_bounds.maxY+0.004).replace('.','%2E');*/
          xml_more += 
                      '&LAT_MAX='+String(more_bounds.getNorthEast().lat()+0.004).replace('.','%2E')+
                      '&LNG_MAX='+String(more_bounds.getNorthEast().lng()+.005).replace('.','%2E')+
                      '&LAT_MIN='+String(more_bounds.getSouthWest().lat()-0.004).replace('.','%2E')+
                      '&LNG_MIN='+String(more_bounds.getSouthWest().lng()-0.005).replace('.','%2E')
                      ;

          fetchPoints( xml_more );
        }
      }
    }

  };
  request.send(null);

  //map.centerAndZoom(new GLatLng( 37.1009 ,-113.5770), 6);

  try {
  dummy_function = function(a,b,c) {}
  iw = map.getInfoWindow(); // Forces the infowindow structure to exist, so we can add context to it
  //iw.addContext("iwstate",dummy_function);
  iw.addContext("iwstate",preLoadTab);
  iw.addContext("iwnavigate",dummy_function);
  }
  catch(e){}
}

