
function showdiv(pass) { 
var el = document.getElementById(pass);
el.style.display='none'; 
el.style.display='block';
//  var divs = document.getElementsByTagName('div'); 
//  for(i=0;i<divs.length;i++) { 
//   if(divs[i].id.match(pass)) { 
//    if (document.getElementById) 
//      divs[i].style.visibility="visible"; 
//    else 
//    if (document.layers) // Netscape 4 
//      document.layers[divs[i]].display = 'visible'; 
//    else // IE 4 
//      document.all.hideshow.divs[i].visibility = 'visible'; 
//   } 
//  } 
} 
function hidediv(pass) {
var el = document.getElementById(pass); 
el.style.display='block';
el.style.display='none'; 

//  var divs = document.getElementsByTagName('div');
//  for(i=0;i<divs.length;i++) {
//   if(divs[i].id.match(pass)) {
//    if (document.getElementById)
//      divs[i].style.visibility="hidden";
//    else
//    if (document.layers) // Netscape 4
//      document.layers[divs[i]].display = 'hidden';
//    else // IE 4
//      document.all.hideshow.divs[i].visibility = 'hidden';
//   }
//  }
}


//READ PARAMETERS -------------------------------
var qsParm = new Array();
function qs() {
  var query = window.location.search.substring(1);
  var parms = query.split('&');
  for (var i=0; i<parms.length; i++) {
    var pos = parms[i].indexOf('=');
    if (pos > 0) {
      var key = parms[i].substring(0,pos);
      var val = parms[i].substring(pos+1);
      qsParm[key] = val;
    }
  }
}


//AJAX METHODS ----------------------------------
function ajaxObject(url, callbackFunction) {
  var that=this;      
  this.updating = false;
  this.abort = function() {
    if (that.updating) {
      that.updating=false;
      that.AJAX.abort();
      that.AJAX=null;
    }
  }
  this.update = function(passData,postMethod) { 
    if (that.updating) { return false; }
    that.AJAX = null;                          
    if (window.XMLHttpRequest) {              
      that.AJAX=new XMLHttpRequest();              
    } else {                                  
      that.AJAX=new ActiveXObject("Microsoft.XMLHTTP");
    }                                             
    if (that.AJAX==null) {                             
      return false;                               
    } else {
      that.AJAX.onreadystatechange = function() {  
        if (that.AJAX.readyState==4) {             
          that.updating=false;                
          that.callback(that.AJAX.responseText,that.AJAX.status,that.AJAX.responseXML);        
          that.AJAX=null;                                         
        }                                                      
      }                                                        
      that.updating = new Date();                              
      if (/post/i.test(postMethod)) {
        var uri=urlCall+'?'+that.updating.getTime();
        that.AJAX.open("POST", uri, true);
        that.AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        that.AJAX.setRequestHeader("Content-Length", passData.length);
        that.AJAX.send(passData);
      } else {
        var uri=urlCall+'?'+passData+'&timestamp='+(that.updating.getTime()); 
        that.AJAX.open("GET", uri, true);                             
        that.AJAX.send(null);                                         
      }              
      return true;                                             
    }                                                                           
  }
  var urlCall = url;        
  this.callback = callbackFunction || function () { };
}


// The following block implements the string.parseJSON method
(function (s) {
  // This prototype has been released into the Public Domain, 2007-03-20
  // Original Authorship: Douglas Crockford
  // Originating Website: http://www.JSON.org
  // Originating URL    : http://www.JSON.org/JSON.js

  // Augment String.prototype. We do this in an immediate anonymous function to
  // avoid defining global variables.

  // m is a table of character substitutions.

  var m = {
    '\b': '\\b',
    '\t': '\\t',
    '\n': '\\n',
    '\f': '\\f',
    '\r': '\\r',
    '"' : '\\"',
    '\\': '\\\\'
  };

  s.parseJSON = function (filter) {

    // Parsing happens in three stages. In the first stage, we run the text against
    // a regular expression which looks for non-JSON characters. We are especially
    // concerned with '()' and 'new' because they can cause invocation, and '='
    // because it can cause mutation. But just to be safe, we will reject all
    // unexpected characters.

    try {
//      if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.
//        test(this)) {

          // In the second stage we use the eval function to compile the text into a
          // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
          // in JavaScript: it can begin a block or an object literal. We wrap the text
          // in parens to eliminate the ambiguity.

          var j = eval('(' + this + ')');

          // In the optional third stage, we recursively walk the new structure, passing
          // each name/value pair to a filter function for possible transformation.

          if (typeof filter === 'function') {

            function walk(k, v) {
              if (v && typeof v === 'object') {
                for (var i in v) {
                  if (v.hasOwnProperty(i)) {
                    v[i] = walk(i, v[i]);
                  }
                }
              }
              return filter(k, v);
            }

            j = walk('', j);
          }
          return j;
 //       }
      } catch (e) {

      // Fall through if the regexp test fails.
	alert(e);
      }
      //throw new SyntaxError("parseJSON");
    };
  }
) (String.prototype);
// End public domain parseJSON block


//--------------------------------------------------------
var markersQuery = '/search/cgi-bin/getmarkers.cgi';
// var getlatlongQuery = '/search/cgi-bin/getlatlong.cgi';
function getMarkers(querystring,parametersstring) {
   var ajaxRequest = new ajaxObject(querystring);
   ajaxRequest.callback = function (responseText) {
//alert(responseText);
     JSONData = responseText.parseJSON();
     processData(JSONData);    
   }
   ajaxRequest.update(parametersstring, "POST");
}

var beginLatDB = 0;
var beginLngDB = 0;
var beginZoomDB = 0;

function processData(JSONData) {
	var zoom_text = "";;	
	if (JSONData.numbers[0].disp < JSONData.numbers[0].total)
	{
		zoom_text = " <BR>(zoom&nbsp;in&nbsp;to&nbsp;see&nbsp;more)";
	}
	if (JSONData.numbers[0].total > 20000)
	{
		JSONData.numbers[0].total = "20000+";
	}

//	beginLatDB = JSONData.agent_latlong[0].alat;
//	beginLngDB = JSONData.agent_latlong[0].along;
//	beginZoomDB =  1 * JSONData.agent_latlong[0].zoom;
//alert("beginLatDB in pd "+beginLatDB);
//f (beginLatDB != 0)
//{
//    var beginZoomNumDB = 1 * beginZoomDB; //hack to convert string to number
//    var initLatLngDB = new GLatLng(beginLatDB, beginLngDB);
//    map.setCenter(initLatLngDB, beginZoomNumDB);
//}

	document.getElementById('maxcount').innerHTML="Displaying&nbsp;"+JSONData.numbers[0].disp+"&nbsp;of&nbsp;"+JSONData.numbers[0].total+zoom_text;

    for (var i = 0; i < (JSONData.markers.length-1); i++) {
      showAddress(JSONData.markers[i].latitude,JSONData.markers[i].longitude,JSONData.markers[i].text,JSONData.markers[i].category,20,20,JSONData.markers[i].photo);
    }
   hidediv('loading');
   hidediv('loading2');
//   hidediv('logo');
}

    var map = null;
    var markers_mapped = [];  //DB ids of all markers mapped / cache / not just those in window
    var markers_html = [];
    var markers_category = [];
    
    var geocoder = null;
    var svOverlay = null;
    var myPano = null;

    var beginLat = 36.0000;
    var beginLng = - 97.000;
    var beginZoom = 4;

//    var beginLatDB = 0;
//    var beginLngDB = 0;
//    var beginZoomDB = 0;

    function load() {
      qs();
      if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"),{mapTypes:[G_PHYSICAL_MAP,G_NORMAL_MAP, G_SATELLITE_MAP, G_HYBRID_MAP]});
	//map.setMapType(G_PHYSICAL_MAP);
	map.setMapType(G_NORMAL_MAP);
	//map.setMapType(G_HYBRID_MAP);
	geocoder = new GClientGeocoder();
       	map.addControl(new GLargeMapControl());
	map.addControl(new GScaleControl());
        map.addControl(new GMapTypeControl());

	if (qsParm['maplat'] != null) {
		beginLat = qsParm['maplat'];
	}
	if (qsParm['maplong'] != null) {
        beginLng = qsParm['maplong'];
    }
	if (qsParm['mapzoom'] != null) {
        beginZoom = qsParm['mapzoom'];
    }
	

	var beginZoomNum = 1 * beginZoom; //hack to convert string to number
	var initLatLng = new GLatLng(beginLat, beginLng);
        map.setCenter(initLatLng, beginZoomNum); 

	//get markers in bound box
	var bounds = map.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();
	//var northWest = new GLatLng( northEast.lat(), southWest.lng() );
	//var southEast = new GLatLng( southWest.lat(), northEast.lng() );

	//k2009 added cat_19...
	var boundParams = 'long1=' + northEast.lng() + '&lat1=' + northEast.lat() + '&long2=' + southWest.lng() + '&lat2=' + southWest.lat();  // + '&cat_19=true&cat_1=true&cat_18=true&cat_2=true&cat_3=true&cat_4=true&cat_7=true&cat_6=true&cat_5=true&cat_17=true&cat_8=true&cat_9=true&cat_22=true';
	boundParams = boundParams + '&minprice=' + document.mapform.minprice.value + '&maxprice=' + document.mapform.maxprice.value;
	boundParams = boundParams + '&minsqft=' + document.mapform.minsqft.value + '&maxsqft=' + document.mapform.maxsqft.value;
        boundParams = boundParams + '&minbeds=' + document.mapform.minbeds.value + '&maxbeds=' + document.mapform.maxbeds.value;
        boundParams = boundParams + '&minbaths=' + document.mapform.minbaths.value + '&maxbaths=' + document.mapform.maxbaths.value;
//        boundParams = boundParams + '&minacres=' + document.mapform.minacres.value + '&maxacres=' + document.mapform.maxacres.value;

        var showcats = "";
        for(i=0; i<document.mapform.elements.length; i++) {
//			var formelem = document.mapform.elements[i]; 
//			var formname = formelem.name + "22";
//                if (formname.substr(0,4) == "cat_") {
//                   showcats = showcats + '&' + formelem.name + '=' + formelem.value;
                if (document.mapform.elements[i].type == "checkbox") {
                   showcats = showcats + '&' + document.mapform.elements[i].name + '=' + document.mapform.elements[i].checked;
                }
        }

	getMarkers(markersQuery, boundParams+showcats);

//alert("beginLatDB in load "+beginLatDB);
//if (beginLatDB != 0)
//{
//    var beginZoomNumDB = 1 * beginZoomDB; //hack to convert string to number
//    var initLatLngDB = new GLatLng(beginLatDB, beginLngDB);
//    map.setCenter(initLatLngDB, beginZoomNumDB);
//}

	try {
          svOverlay = new GStreetviewOverlay();
          //map.addOverlay(svOverlay);
          myPano = new GStreetviewPanorama(document.getElementById("pano"));
	  myPOV = {yaw:370.64659986187695,pitch:-10};
	  myPano.setLocationAndPOV(initLatLng, myPOV);
          GEvent.addListener(map,"click", function(overlay,latlng) {
	    if (latlng !== undefined) {
          	myPano.setLocationAndPOV(latlng);
	    }
          });
          GEvent.addListener(myPano, "error", handleNoFlash);
	} catch (e) {
	}


        GEvent.addListener(map, "dragend", function() {
	  refreshMap();
        });
        GEvent.addListener(map, "zoomend", function() {
          refreshMap();
        });

	//showAddress(30.287791,-97.738581, 'University of Texas at Austin', 'ut',24,28);
	//showAddress(30.273541,-97.740684, 'Capital of Texas', 'capital',23,30);

      }
    }

    function loadAgentURL() {
	qs();
	if (qsParm['agent_url'] != null) {
                document.mapform.agent_url.value = qsParm['agent_url'];
		showdiv('agent_url');
        }
    }

    function handleNoFlash(errorCode) {
      if (errorCode == 603) {
        alert("Error: Flash doesn't appear to be supported by your browser");
        return;
      }
    }

    function refreshMap() {
   showdiv('loading');
   showdiv('loading2');
//   showdiv('logo');
	map.clearOverlays();
	setBounds();
	//document.mapform.centerlat.value = map.getCenter().lat();
	//document.mapform.centerlong.value = map.getCenter().lng();
	markersParams = 'long1=' + document.mapform.long1.value + '&lat1=' + document.mapform.lat1.value + '&long2=' + document.mapform.long2.value + '&lat2=' + document.mapform.lat2.value;
	markersParams = markersParams + '&minprice=' + document.mapform.minprice.value + '&maxprice=' + document.mapform.maxprice.value;
	markersParams = markersParams + '&minsqft=' + document.mapform.minsqft.value + '&maxsqft=' + document.mapform.maxsqft.value; 
	markersParams = markersParams + '&minbeds=' + document.mapform.minbeds.value + '&maxbeds=' + document.mapform.maxbeds.value;
	markersParams = markersParams + '&minbaths=' + document.mapform.minbaths.value + '&maxbaths=' + document.mapform.maxbaths.value;
//	markersParams = markersParams + '&minacres=' + document.mapform.minacres.value + '&maxacres=' + document.mapform.maxacres.value;
	//markersParams = markersParams + '&recentonly=' + document.mapform.recentonly.checked;
//put back in when checkboxes in//	markersParams = markersParams + '&cat_25=' + document.mapform.cat_25.checked + '&cat_27=' + document.mapform.cat_27.checked + '&cat_24=' + document.mapform.cat_24.checked + '&cat_19=' + document.mapform.cat_19.checked + '&cat_21=' + document.mapform.cat_21.checked; // + '&cat_1=' + document.mapform.cat_1.checked + '&cat_18=' + document.mapform.cat_18.checked + '&cat_2=' + document.mapform.cat_2.checked + '&cat_3=' + document.mapform.cat_3.checked + '&cat_4=' + document.mapform.cat_4.checked + '&cat_7=' + document.mapform.cat_7.checked + '&cat_6=' + document.mapform.cat_6.checked + '&cat_5=' + document.mapform.cat_5.checked + '&cat_17=' + document.mapform.cat_17.checked + '&cat_8=' + document.mapform.cat_8.checked + '&cat_9=' + document.mapform.cat_9.checked + '&cat_22=' + document.mapform.cat_22.checked;

 //       var showcats = "";
        for(i=0; i<document.mapform.elements.length; i++) {
//            var formelem = document.mapform.elements[i];
 //           var formname = formelem.name + "22";
  //              if (formname.substr(0,4) == "cat_") {
  //                 showcats = showcats + '&' + formelem.name + '=' + formelem.value;
                if (document.mapform.elements[i].type == "checkbox") {
                   markersParams = markersParams + '&' + document.mapform.elements[i].name + '=' + document.mapform.elements[i].checked;
                }
//alert('REFRESH ' + markersParams);
        }

	getMarkers(markersQuery, markersParams);
    }

    function setBounds() {
        var bounds = map.getBounds();
        var southWest = bounds.getSouthWest();
        var northEast = bounds.getNorthEast();
        //var lngSpan = northEast.lng() - southWest.lng();
        //var latSpan = northEast.lat() - southWest.lat();

        document.mapform.long1.value = northEast.lng();
        document.mapform.long2.value = southWest.lng();
        document.mapform.lat1.value = northEast.lat();
        document.mapform.lat2.value = southWest.lat();
        document.mapform.zoom1.value = map.getZoom();
        document.mapform.maptype.value = getActiveMapType();

    }

function getActiveMapType() {
	var mapTypes = map.getMapTypes();
	var actType = map.getCurrentMapType();
	var mapName = "G_NORMAL_MAP";
	if (actType == mapTypes[1])
	{
		mapName = "G_SATELLITE_MAP";
	}
	else if (actType == mapTypes[2])
		{mapName = "G_HYBRID_MAP";}
	return mapName;
	//G_STREET_TYPE
}
	
function addMeMarker(address, zoom) {
	var icon = new GIcon();
	icon.image = "/search/images/me.gif";
	icon.shadow = "/search/images/shadow.png";
	icon.iconSize = new GSize(20, 34);
	icon.shadowSize = new GSize(22, 20);
	icon.iconAnchor = new GPoint(6, 20);
	icon.infoWindowAnchor = new GPoint(5, 1);

          geocoder.getLatLng(
                address,
                function(point) {
		if (point) {
                    var marker = new GMarker(point, icon);
                    map.addOverlay(marker);
		    map.setCenter(point, zoom);
		}
                }
	   );
	}

function gotoMeAddress(address) {
    var icon = new GIcon();
	icon.image = "/search/images/me.gif";
	icon.shadow = "/search/images/shadow.png";
	icon.iconSize = new GSize(20, 34);
	icon.shadowSize = new GSize(22, 20);
	icon.iconAnchor = new GPoint(6, 20);
	icon.infoWindowAnchor = new GPoint(5, 1);

	  geocoder.getLatLng(
		address, 
		function(point) {
		  if (!point) {
		    alert("sorry, " + address + " was not found");
		  } else {
		    var marker = new GMarker(point);
		    marker.icon = icon;
		    map.addOverlay(marker);
		    map.panTo(point);
		    map.setZoom(14);
		  }
		}
	  );	
}

function gotoAddress(address) {
	geocoder.getLatLng(
	address,
	function(point) {
	 if (!point) {
	   alert("sorry, " + address + " was not found");
	 } else {
	   map.panTo(point);
	   map.setZoom(14);
	 }
	}
	);
}

function gotoAddressMarker(address, category) {

        var geocoder = new GClientGeocoder();
          geocoder.getLatLng(
                address,
                function(point) {
                  if (!point) {
                    alert("sorry, " + address + " was not found");
                  } else {
                    map.panTo(point);
                    map.setZoom(14);
		    map.setBounds();
		    //createMarker(point, '', category, 20, 20); 
                  }
                }
          );

        }
	function showAddress(latitude, longitude, text, category, width, height) {
	  showAddress(latitude, longitude, text, category, width, height, "");
	}

	function showAddress(latitude, longitude, text, category, width, height, photourl) {
       	  var point = new GLatLng(latitude, longitude);
	  map.addOverlay(createMarker(point, text, category, width, height, photourl));
	}

        function createMarker(point, text, category, width, height, photourl) {
	var icon = new GIcon();
	icon.image = "/search/images/" + category + ".gif";
	icon.iconSize = new GSize(height, width);
	//if (category == "res") {
	//	icon.image = "/search/" + photourl;
	//	icon.iconSize = new GSize(30, 30);
	//}
	icon.iconAnchor = new GPoint(6, 20);
	icon.infoWindowAnchor = new GPoint(5, 1);

        var marker = new GMarker(point, icon);

            GEvent.addListener(marker, "mouseover", function() {
            	//marker.openInfoWindowHtml( text, {pixelOffset:2});
		//K 2009
		//map.openInfoWindowHtml(marker.getLatLng(), text, {pixelOffset: new GSize(0,-10)});
		map.openInfoWindowHtml(marker.getLatLng(), text, {pixelOffset: new GSize(0,-10)});
		myPano.setLocationAndPOV(marker.getLatLng(),null);
            });

          return marker;
        }

function onNewLocation(lat, lng) {
  var latlng = new GLatLng(lat, lng);
  marker.setLatLng(latlng);
}


