var map;
var marker; //this is our marker that starts in the center of the map
var urlVars = getUrlVars(); // gets the GET variables passed by the homepage, puts them into an array
var plSearchBounds;
var MarkerLocationB4Hover; //this is used for remembering pointer location when hovering over homes in the result window
var icons = Array(); //for custom marker images
var GLocalSearch; //for search businesses feature
var ToggleGLocalSearch = 0; //for search businesses feature
var SearchPages = Array(); //for loading search results
var SearchPagesURI = Array(); //for loading search results
var bounds; //used in submitSearch, but also used in GoToSearchResultsPage for page link creation
var searchWithDragzoom = false; //are we currently searching with the dragzoom boundaries?
var markerInfo = Array(); //use for storing search result's marker image, lat, lng & marker

var PriceMin, PriceMax, BedMin, BedMax, BathMin, BathMax, SqftMin, SqftMax, GarageMin, GarageMax, AgeMin, AgeMax, Type;
//These are the search variables
var centerLatitude, centerLongitude, startZoom;
//set map to last position



var AllSearchVars = Array('PriceMin','PriceMax','BedMin','BedMax','BathMin','BathMax','SqftMin','SqftMax','GarageMin','GarageMax','Type','AgeMin','AgeMax');var ShowDots = true; //used for toggling dots

//set the center to what their last center was


var ToggleDotControl = function(url) {
	this.url_ = url;
};
ToggleDotControl.prototype = new GControl(true);
ToggleDotControl.prototype.initialize = function(map) {
	var container = document.createElement("div");
	container.innerHTML = 'Toggle Dots';
	container.style.width='200px';
	container.style.border = '#000 1px solid';
	container.style.cursor = 'pointer';
	container.style.padding = '2px';
	container.style.backgroundColor= '#fff';
	url = this.url_;	
	GEvent.addDomListener(container, "click", function() {
		ToggleDots();
	});	
	map.getContainer().appendChild(container);	
	return container;
};
ToggleDotControl.prototype.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(3, 30));
};















//Create the tile layer object
var detailLayer = new GTileLayer(new GCopyrightCollection(''));

//Method to retrieve the URL of the tile
detailLayer.getTileUrl = function(tile, zoom){
    //pass the x and y position as wel as the zoom
	if(ShowDots==true){
	    var tileURL = "http://usethedots.com/MLS/Map/tilemaker.php5.php?x="+tile.x+"&y="+tile.y+"&zoom="+zoom+ConstructSearchURL();
		//GLog.writeUrl(tileURL);
	    return tileURL;
	}else{ return '';}
};


detailLayer.isPng = function() {
    //The example uses GIF's
    return true;
}

//The following code manages to add the tiles without being called in the init function.  Go figure....
//add your tiles to the normal map projection
detailMapLayers = G_NORMAL_MAP.getTileLayers();
LoadingLayerIndex = detailMapLayers.push(detailLayer); //returns new length of array after adding layer

//add your tiles to the hybrid map projection
detailMapLayers = G_HYBRID_MAP.getTileLayers();
LoadingLayerIndex = detailMapLayers.push(detailLayer); //returns new length of array after adding layer

//add your tiles to the satellite map projection
detailMapLayers = G_SATELLITE_MAP.getTileLayers();
LoadingLayerIndex = detailMapLayers.push(detailLayer); //returns new length of array after adding layer





//INITIALIZE GOOGLE MAP
function initialize() {
	//GLog.write("Initialing");
	//set the center right on top of the word "orlando" on the google map 
	//note: parseFloat is necessary to convert cookie's string to float
	!isNull(readCookie("lat"))!="" ? centerLatitude = parseFloat(readCookie("lat")) : centerLatitude=28.560400880492832;
	!isNull(readCookie("lng"))!="" ? centerLongitude = parseFloat(readCookie("lng")) : centerLongitude=-81.36611938476562;
	!isNull(readCookie("z"))!="" ? startZoom = parseFloat(readCookie("z")) : startZoom=10;
	/* Default values are now controlled by the control elements.
	!isNull(readCookie("PriceMin"))!="" ? PriceMin = readCookie("PriceMin") : PriceMin=0;
	!isNull(readCookie("PriceMax"))!="" ? PriceMax = readCookie("PriceMax") : PriceMax=300000;
	!isNull(readCookie("BedMin"))!="" ? BedMin = readCookie("BedMin") : BedMin=0;
	!isNull(readCookie("BedMax"))!="" ? BedMax = readCookie("BedMax") : BedMax=5;
	!isNull(readCookie("BathMin"))!="" ? BathMin = readCookie("BathMin") : BathMin=0;
	!isNull(readCookie("BathMax"))!="" ? BathMax = readCookie("BathMax") : BathMax=5;
	!isNull(readCookie("SqftMin"))!="" ? SqftMin = readCookie("SqftMin") : SqftMin=0;
	!isNull(readCookie("SqftMax"))!="" ? SqftMax = readCookie("SqftMax") : SqftMax=3000;
	!isNull(readCookie("GarageMin"))!="" ? GarageMin = readCookie("GarageMin") : GarageMin=0;
	!isNull(readCookie("GarageMax"))!="" ? GarageMax = readCookie("GarageMax") : GarageMax=3;
	!isNull(readCookie("AgeMin"))!="" ? AgeMin = readCookie("AgeMin") : AgeMin=0;
	!isNull(readCookie("AgeMax"))!="" ? AgeMax = readCookie("AgeMax") : AgeMax=30;
	!isNull(readCookie("Type"))!="" ? Type = readCookie("Type") : Type='S';*/
	//S-Single Family, M-Condo\Town Home, B-Mobile Home, V-Vacant Land, C-Commercial, D-Multi-Family, R-Rental	
	
	var extraURL = ConstructSearchURL();
	UpdatePriceControls('PriceMin');//update the pricing controls that appear
	UpdatePriceControls('PriceMax');
	/*
	document.getElementById('button-sidebar-hide').onclick = function() { 
		return changeBodyClass('sidebar-right', 'nosidebar'); };
	document.getElementById('button-sidebar-show').onclick = function() { 
		return changeBodyClass('nosidebar', 'sidebar-right'); };
	*/
	
	//handleResize();//This MUST go before the map is created.  Firefox will kill you if it isn't.
	
	
    map = new GMap2(document.getElementById("map_canvas"));
	map.isLoaded = function () {GLog.write("Map is loaded");}
	var centerPoint = new GLatLng(centerLatitude, centerLongitude);
    map.setCenter(centerPoint, startZoom);
	map.addControl(new DragZoomControl());// this must go above the other controls. why? otherwise IE will not display correctly
	//map.addControl(new ToggleDotControl()); //our button for dot control
    //map.setMapType(G_SATELLITE_MAP);
    //svOverlay = new GStreetviewOverlay();
	//map.addOverlay(svOverlay);//add streetview overlay
	map.enableScrollWheelZoom(); //can be annoying
	map.enableDoubleClickZoom();
	map.enableContinuousZoom();
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	//map.addControl(new GOverviewMapControl());
	map.addControl(new GScaleControl());
    geocoder = new GClientGeocoder();// necessary for go to location feature (not yet implemented)
    GLocalSearch = new google.maps.LocalSearch(); //for search businesses feature
	 
	       // This icon uses the same shape as the default Google marker
      // So we can use its details for everything except the image 
      var blueIcon = new GIcon();
      blueIcon.image = "images/markers/arrow_green.png";
      blueIcon.shadow = "images/markers/arrow_shadow.png";
      blueIcon.iconSize = new GSize(39, 34);
      blueIcon.shadowSize = new GSize(39, 34);
      blueIcon.iconAnchor = new GPoint(9, 34);
      blueIcon.infoWindowAnchor = new GPoint(9, 2);
      blueIcon.infoShadowAnchor = new GPoint(18, 25);
      blueIcon.transparent = "http://www.google.com/intl/en_ALL/mapfiles/markerTransparent.png";
      blueIcon.printImage = blueIcon.image;
      blueIcon.mozPrintImage = blueIcon.image;
	
	  icons = [];
      icons[0] = blueIcon;
	  
	//set directions information
	gdir = new GDirections(map, document.getElementById("sidebar"));
	
	//set marker start point (if a cookie is set, use that for positioning)
	var markerpoint = map.getCenter();
	var cMarkerLat = parseFloat(readCookie("markerlat"));//parseFloat is to handle any null values
	var cMarkerLng = parseFloat(readCookie("markerlng"));
	if(cMarkerLat && cMarkerLng){
		markerpoint = new GLatLng(cMarkerLat,cMarkerLng);
	}
	
	marker = new GMarker(markerpoint, {draggable: true, icon:blueIcon});
	MarkerLocationB4Hover = markerpoint; //remember this location for search results hover effects
	map.addOverlay(marker); //actually adds the marker to the map

	    //This timeout stuff is necessary to prevent a click event from happening when the user intends to double click
    var timeouts = [];
	GEvent.addListener(map, "click", function(overlay,point) { //point is not set when a marker is clicked
		timeouts.push( setTimeout( function() { 
			if(point){
				marker.setPoint(point);
				//marker.openInfoWindowHtml("Loading...."); !!!
				rememberMarkerLocation(); //stores marker location in cookie (used to center page on reload)
				refreshMarker(1); //opens marker bubble to show details of homes near marker location 
			}
		}, 250 ) );
	});
	
	
	GEvent.addListener(map, "tilesloaded", function(overlay,point) {
		//this removes the "loading" box after all tiles have been loaded
		//GLog.write("The tiles have been loaded");
		changeBodyClass('loading', 'standby'); //remove the loading div	
		});
	
	
	GEvent.addListener(map, "dblclick", function(overlay,point) {
	//this function should not be fired when a marker is double clicked
	    for (var i=0; i <timeouts.length; i++)  {
            clearTimeout(timeouts[i]);
        }
		if(point){	

		}
	});	
	
	GEvent.addListener(map, "mousedown", function(overlay,point) {
		//this is necessary when placing the InfoWindow directly on the map
		//map.closeInfoWindow(); //this doesn't work
	});
	
	GEvent.addListener(marker, "dragstart", function() { 
		map.closeInfoWindow();
		});
	
	//remember the map center cookies
	GEvent.addListener(marker, "dragend", function() { 
		rememberMarkerLocation(); //stores marker location in cookie (used to center page on reload) //removed as the marker will not move when moving the map
		refreshMarker(1); //opens marker bubble to show details of homes near marker location //removed as the marker will not move when moving the map
		rememberMapLocation(); }); //just remember, via cookie, where we stopped
	
	GEvent.addListener(map, "zoomend", function(oldLevel,newLevel) { //when we zoom in, this will recehck the marker
		rememberMapLocation(); 	
		var sizeChange = newLevel - oldLevel; 
			});
	
	GEvent.addListener(map, "zoomstart", function(oldLevel,newLevel) {
			});

	//LoadDropDownSelections(); //from ComboBox.js

	submitSearch(); //loads search in side window (this is the crazy part)
	//changeBodyClass('loading', 'standby'); //remove the loading div	//12/25/08 moved to tilesloaded event handler
}

//window.onresize = handleResize; //very important.  If this is not here, the map gets screwed up on a resize.
//window.onload = initialize; //run the google map initialize function.
//window.attachEvent("onload", initialize);








function ToggleDiv(DivName){
	Div = document.getElementById(DivName);
	if(Div.style.visibility=='hidden' || Div.style.display=='none'){
		Div.style.visibility="visible";
		Div.style.display="block";
	}else{
		Div.style.visibility="hidden";
		Div.style.display="none";
	}
	//handleResize();
}

function ToggleMapSearch(){
	if(ToggleGLocalSearch==0){
		map.addControl(GLocalSearch, new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(230,0)));
		ToggleGLocalSearch=1;
	}else{
		map.removeControl(GLocalSearch);
		ToggleGLocalSearch=0;
	}
}

function showAddress(address) {
      if (geocoder) {
        geocoder.getLatLng(
          address,
          function(point) {
            if (!point) {
              alert(address + " not found");
            } else {
              map.setCenter(point, 13);
              var AddressMarker = new GMarker(point,icons[0]);
              map.addOverlay(AddressMarker);
              //marker.openInfoWindowHtml(address);
            }
          }
        );
      }
    }


	//used for mapping directions
    function setDirections(fromAddress, toAddress, locale) {
		//sidebar = document.getElementById('sidebar');
		//CurrentText = sidebar.innerHTML;
		//document.getElementById('sidebar').innerHTML = "";
		
      gdir.load("from: " + fromAddress + " to: " + toAddress,
                { "locale": locale });
	  	//document.getElementById('sidebar').innerHTML += CurrentText;
    }



function refreshMarker(zoomOutOrIn){
	//marker.openInfoWindowHtml("Loading...");
	map.openInfoWindowHtml(marker.getPoint(),"Loading...");
	MarkerLocationB4Hover = marker.getPoint();
	if(zoomOutOrIn > 0){//we are zooming in (negative means zoom out)
		GDownloadUrl("http://usethedots.com/MLS/Map/pointinfo.php5.ext.php?"
				+ "lat=" + marker.getPoint().lat()
				+ "&lng=" + marker.getPoint().lng()
				+ "&z=" + map.getZoom()
				+ ConstructSearchURL(),
				function(data, responseCode){
					if(data!=""){ 
						//marker.openInfoWindowHtml(data);
						map.openInfoWindowHtml(marker.getPoint(),data);
					}
									//"Latitude: " + marker.getPoint().lat() + "<br>" +
									//"Longitude: " + marker.getPoint().lng() + "<br>" + 
					else{ 
						//marker.closeInfoWindow();
						map.closeInfoWindow();
					}
		}); //end of GDownloadUrl
	}//end of if we are zooming in
}




function windowHeight() {
	// Standard browsers (Mozilla, Safari, etc.)
	if (self.innerHeight)
		return self.innerHeight;
	// IE 6
	if (document.documentElement && document.documentElement.clientHeight)
		return document.documentElement.clientHeight;
	// IE 5
	if (document.body)
		return document.body.clientHeight;
	// Just in case.
	return 0;
}

function handleResize() {
	GLog.write("Resizing");
	try{
		map.checkResize();
	}catch(e){GLog.write("Failed to resize");}
}

function changeBodyClass(from, to) {
	document.body.className = document.body.className.replace(from, to);
	return false;
}
function bodyContainsClass(className){
	//GLog.write( document.body.className.indexOf(className) );
	if(document.body.className.indexOf(className)==-1){
		return false;
	}else{
		return true;
	}
}


function changeThisClass(ITEM,from, to) {
	ITEM.className = ITEM.className.replace(from, to);
	return false;
}


function rememberMapLocation(){
		//createCookie(name, value, days);
		createCookie("lat",map.getCenter().lat(),1);
		createCookie("lng",map.getCenter().lng(),1);
		createCookie("z",map.getZoom(),1);
}


function rememberMarkerLocation(){
		createCookie("markerlat",marker.getPoint().lat(),1);
		createCookie("markerlng",marker.getPoint().lng(),1);
}







function submitSearch(){
	//submits search and saves search selection

	SearchPages = Array(); //reset search results
	SearchPagesURI = Array(); //reset search result URI's
	document.getElementById('sidebar').innerHTML = "Loading....";
	
	var zoomLevel;
	var center;

	
	
		changeBodyClass('standby', 'loading');//this is reversed when tilesloaded event fires and when the right side loads
	//use try statements as the boxes will not be loaded when this script first runs	
	//you cannot use, as a variable name, the id of any of the comboboxes
		PriceMinBoxes = document.getElementsByName('PriceMin'); 
		PriceMinBox = PriceMinBoxes[0];
		PriceMaxBoxes = document.getElementsByName('PriceMax'); 
		PriceMaxBox = PriceMaxBoxes[0];
		BedMinBoxes = document.getElementsByName('BedMin'); BedMinBox = BedMinBoxes[0];
		BedMaxBoxes = document.getElementsByName('BedMax'); BedMaxBox = BedMaxBoxes[0];
		BathMinBoxes = document.getElementsByName('BathMin'); BathMinBox = BathMinBoxes[0];
		BathMaxBoxes = document.getElementsByName('BathMax'); BathMaxBox = BathMaxBoxes[0];
		GarageMinBoxes = document.getElementsByName('GarageMin'); GarageMinBox = GarageMinBoxes[0];
		GarageMaxBoxes = document.getElementsByName('GarageMax'); GarageMaxBox = GarageMaxBoxes[0];
		SqftMinBoxes = document.getElementsByName('SqftMin'); SqftMinBox = SqftMinBoxes[0];
		SqftMaxBoxes = document.getElementsByName('SqftMax'); SqftMaxBox = SqftMaxBoxes[0];
		AgeMinBoxes = document.getElementsByName('AgeMin'); AgeMinBox = AgeMinBoxes[0];
		AgeMaxBoxes = document.getElementsByName('AgeMax'); AgeMaxBox = AgeMaxBoxes[0];
		TypeBoxes = document.getElementsByName('Type'); TypeBox = TypeBoxes[0];
		

	//#####################  get the map center and blue box
	if(searchWithDragzoom==true){ //if we are using dragzoom (this is set to TRUE in the DragZoom js file
		//alert(zoomAreaPoly.getBounds());
		bounds = zoomAreaPoly.getBounds();
		zoomLevel = map.getBoundsZoomLevel(bounds);
	    center = bounds.getCenter();
		//searchWithDragzoom = false; //set back to false after a successful use of searchwithdragzoom
		map.removeOverlay(zoomAreaPoly);//remove the red search box (not to worry, it will be created again when the user uses the dragzoom function.  also, the properties of zoomAreaPoly remain in the variable even though it is not visible on the map.  before this function, zoomAreaPoly and usually plSearchBounds are on the map; this submitSearch function removes both and adds back plSearchBounds based on zoomAreaPoly or the map's boundaries pending searchWithDragzoom.)
    	map.setCenter(center, zoomLevel); 
	}else{ 
		bounds = map.getBounds();
	}
	var BoundSouthWest = bounds.getSouthWest();
	var BoundNorthEast = bounds.getNorthEast();
	var BoundNorthWest = new GLatLng(BoundNorthEast.lat(), BoundSouthWest.lng());
	var BoundSouthEast = new GLatLng(BoundSouthWest.lat(), BoundNorthEast.lng());
	var points = Array(BoundNorthWest,BoundNorthEast,BoundSouthEast,BoundSouthWest,BoundNorthWest);
	try{map.removeOverlay(plSearchBounds);}catch(e){} //may not be present on first search; this is why we try.
	plSearchBounds = new GPolyline(points);
	map.addOverlay(plSearchBounds);
	
	//#####################  end of creating the search boundary, continue with the search variables stuff
		
		PriceMinBox.value = addCommas(PriceMinBox.value);
		PriceMin = removeCommas(PriceMinBox.value);
		if(isNaN(PriceMin)){ PriceMin = 0; }		
		
		PriceMaxBox.value = addCommas(PriceMaxBox.value);
		PriceMax = removeCommas(PriceMaxBox.value);
		if(isNaN(PriceMax)){ PriceMax = 999999999999; }
		//GLog.write("");
		BedMin = BedMinBox.options[BedMinBox.selectedIndex].value;
		BedMax = BedMaxBox.options[BedMaxBox.selectedIndex].value;
		BathMin = BathMinBox.options[BathMinBox.selectedIndex].value;
		BathMax = BathMaxBox.options[BathMaxBox.selectedIndex].value;
		GarageMin = GarageMinBox.options[GarageMinBox.selectedIndex].value;
		GarageMax = GarageMaxBox.options[GarageMaxBox.selectedIndex].value;
		SqftMin = SqftMinBox.options[SqftMinBox.selectedIndex].value;
		SqftMax = SqftMaxBox.options[SqftMaxBox.selectedIndex].value;
		AgeMin = AgeMinBox.options[AgeMinBox.selectedIndex].value;
		AgeMax = AgeMaxBox.options[AgeMaxBox.selectedIndex].value;	
		Type = TypeBox.options[TypeBox.selectedIndex].value;

	//now that we have prepared the search variables, create the link to the search results and
	//Load results based on this search in right window.	
	GoToSearchResultsPage(1,1);
	

	RefreshTiles(); //update the tiles with results from the new search
	
	//saves search criteria in cookie
	//createCookie(name,value,days)
	createCookie("PriceMin",PriceMin,1);
	createCookie("PriceMax",PriceMax,1);
	createCookie("BedMin",BedMin,1);
	createCookie("BedMax",BedMax,1);
	createCookie("BathMin",BathMin,1);
	createCookie("BathMax",BathMax,1);
	createCookie("GarageMin",GarageMin,1);
	createCookie("GarageMax",GarageMax,1);
	createCookie("SqftMin",SqftMin,1);
	createCookie("SqftMax",SqftMax,1);
	createCookie("AgeMin",AgeMin,1);
	createCookie("AgeMax",AgeMax,1);
	createCookie("Type",Type,1);
}


function MarkersOrTextFromResult(SearchResults,JS){
//functions handles searchresult output (javascript is passed as string from output)
	if(!JS){JS=0;}//handle optional parameter
	
	if(JS == 1){//we want the JS piece of the result
		//substring(start,end)
		JScode = SearchResults.substring(17,SearchResults.indexOf("<!-- end JS -->"));
		return 	JScode;
	}
	if(JS == 2){//we want to execute the JS piece of code
		//markerInfo[0][0] = marker image
		//markerInfo[0][1] = latitude
		//markerInfo[0][2] = longitude
		//markerInfo[0][3] = marker object
		if(markerInfo.length > 0){//before we get new marker information, let's remove the old markers
			for (var i=0; i<markerInfo.length; i++) {
				map.removeOverlay(markerInfo[i][3]);
			}
		}
		eval(MarkersOrTextFromResult(SearchResults,1));
		
		//GLog.write("markerInfo[0][0]=" + markerInfo[0][0]);
		MarkerIcon = new GIcon(G_DEFAULT_ICON);
		
		for (var iM=0; iM<markerInfo.length; iM++) {
			MarkerIcon.image = "http://usethedots.com/MLS/Map/images/markers/marker" + (iM+1) + ".png";
			markerOptions = { icon:MarkerIcon };
			point = new GLatLng(markerInfo[iM][1],markerInfo[iM][2]);
  			markerInfo[iM].push(new GMarker(point, markerOptions));//store marker in markerInfo[iM][3]
  			map.addOverlay(markerInfo[iM][3]);//add marker to map
			//GLog.write(markerInfo[iM][3].getLatLng())
			/*GEvent.addListener(markerInfo[iM][3], "click", function() {
			    this.openInfoWindowHtml("Marker <b>" + this.getLatLng() + "</b>");
			  });*/


		}
	}
	else{//return the non-xml piece of the result
		//substr(start,[end])
		return SearchResults.substr(SearchResults.indexOf("<!-- end JS -->")+15)
	}
	
	
}

function GoToSearchResultsPage(Page,LoadOrCache){
	//this function is used to cache and show search results
	//note that if LoadOrCache == 1, we will load (show) the results. If == 0, will only store results w/o showing (this makes for lightning-fast page changes).
	if(!SearchPages[Page]){//we need to download the results (page is not in cache)
		//make page say "loading"
		if(LoadOrCache==1){	changeBodyClass('standby', 'loading'); }
		//first, create the link
		var BoundSouthWest = bounds.getSouthWest();
		var BoundNorthEast = bounds.getNorthEast();
		SearchPagesURI[Page]=	"http://usethedots.com/MLS/Map/searchresults.ext.php?"
			+ "ne=" + BoundNorthEast.toUrlValue()
			+ "&sw=" + BoundSouthWest.toUrlValue()
			+ "&PageNumber=" + Page
			+ ConstructSearchURL();		
				
		//Now, download the link we just created
		GDownloadUrl(SearchPagesURI[Page],
				function(data, responseCode){
					if(data!=""){
						SearchPages[Page] = data;
						if(LoadOrCache==1){//we need to show the results and the result markers
							document.getElementById('sidebar').innerHTML = MarkersOrTextFromResult(SearchPages[Page]);
							MarkersOrTextFromResult(SearchPages[Page],2);//execute new marker code
						}
					}
					if(LoadOrCache==1){	changeBodyClass('loading', 'standby');} //remove the loading div
				}
		); //end of GDownloadUrl
	}else{//we already have the search page loaded into memory; display it now.
		document.getElementById('sidebar').innerHTML = MarkersOrTextFromResult(SearchPages[Page]);
		MarkersOrTextFromResult(SearchPages[Page],2);//execute new marker code
	}
	//if we are showing a page, go ahead and cache the next page
	if(LoadOrCache==1){
		var NextPage = Page + 1;
		var PrevPage = Page - 1;
		if(!SearchPages[NextPage]){GoToSearchResultsPage(NextPage, 0);}
		if(PrevPage>0 && !SearchPages[PrevPage]){GoToSearchResultsPage(PrevPage, 0);}
	}
}


function RefreshTiles(){
	map.setMapType(G_SATELLITE_MAP); 
    map.setMapType(G_NORMAL_MAP); 
}


function ConstructSearchURL(){
	extraURL = "";
	for(var i in AllSearchVars){
		extraURL += '&' + AllSearchVars[i] + '=' + eval(AllSearchVars[i]);
	}//end of looping through AllSearchVars
	return extraURL;
}

function ToggleDots(){
	ShowDots = !ShowDots;
	RefreshTiles();
}



function ShowDetails(MLSID){
		
}












function dumpProps(obj, parent) {
   // Go through all the properties of the passed-in object
   for (var i in obj) {
      // if a parent (2nd parameter) was passed in, then use that to
      // build the message. Message includes i (the object's property name)
      // then the object's property value on a new line
      if (parent) { var msg = parent + "." + i + "\n" + obj[i]; } else { var msg = i + "\n" + obj[i]; }
      // Display the message. If the user clicks "OK", then continue. If they
      // click "CANCEL" then quit this level of recursion
      if (!confirm(msg)) { return; }
      // If this property (i) is an object, then recursively process the object
      if (typeof obj[i] == "object") {
         if (parent) { dumpProps(obj[i], parent + "." + i); } else { dumpProps(obj[i], i); }
      }
   }
}



function pausecomp(millis)
{
var date = new Date();
var curDate = null;

do { curDate = new Date(); }
while(curDate-date < millis);
} 

	function ShowHideResults(){
		if(bodyContainsClass('nosidebar')){
			changeBodyClass('nosidebar', 'sidebar-right'); 
		}
		else{
			changeBodyClass('sidebar-right', 'nosidebar'); 
		}
		map.checkResize();//let the map know we have changed the container's size
	}
	
	function ShowResults(){
		
		document.getElementById('HideResults').style.display='block';
		document.getElementById('ShowResults').style.display='none';	
	}

	
	function HooverEffect(box,onoff){
		if(onoff=="on"){
			var BackgroundStyle = 'url(images/header/bluebackground_on.png)';
			box.style.backgroundImage = BackgroundStyle;
			var newid = box.id + "Body";
			document.getElementById(newid).style.backgroundImage = BackgroundStyle;
		}else{
			var BackgroundStyle = 'url(images/header/bluebackground_off.png)';
			box.style.backgroundImage = BackgroundStyle;
			var newid = box.id + "Body";
			document.getElementById(newid).style.backgroundImage = BackgroundStyle;
		}
	}
	
	function getElementWidth(Elem) {
	if (ns4) {
		var elem = getObjNN4(document, Elem);
		return elem.clip.width;
	} else {
		if(document.getElementById) {
			var elem = document.getElementById(Elem);
		} else if (document.all){
			var elem = document.all[Elem];
		}
		if (op5) {
			xPos = elem.style.pixelWidth;
		} else {
			xPos = elem.offsetWidth;
		}
		return xPos;
	}
}

function UserAlert(){
	//function creates useful alerts for users  (i.e. "Q: Why are there two boxes? A: Red box notes where you wish to perform your next search, the blue box notes the current search area.")	
}

  function findPos(obj) {

	var curleft = curtop = 0;

	if (obj.offsetParent) {

		curleft = obj.offsetLeft

		curtop = obj.offsetTop

		while (obj = obj.offsetParent) {

			curleft += obj.offsetLeft

			//alert(obj.offsetTop);

			curtop += obj.offsetTop

		}

	}

	return [curleft,curtop];

}

//this adds commas and decimals to a users input. use with KeyUp for maximum effect
function addCommasForm(obj){
	var num;
	var newnum;
	var number;
	var end = '';
	num = obj.value.replace(/,/g, '');
	if(num.indexOf('.')!= -1){
		newnum = num.split('.');
		num = newnum[0];
		newnum[1] = newnum[1].substring(0,2)
		end = '.' + newnum[1];
	}
	number = addCommas(num);
	obj.value = number + end;
}

function removeCurrency( strValue ) {
/************************************************
DESCRIPTION: Removes currency formatting from
  source string.

PARAMETERS:
  strValue - Source string from which currency formatting
     will be removed;

RETURNS: Source string with commas removed.
*************************************************/
  var objRegExp = /\(/;
  var strMinus = '';

  //check if negative
  if(objRegExp.test(strValue)){
    strMinus = '-';
  }

  objRegExp = /\)|\(|[,]/g;
  strValue = strValue.replace(objRegExp,'');
  if(strValue.indexOf('$') >= 0){
    strValue = strValue.substring(1, strValue.length);
  }
  return strMinus + strValue;
}

function addCurrency( strValue ) {
/************************************************
DESCRIPTION: Formats a number as currency.

PARAMETERS:
  strValue - Source string to be formatted

REMARKS: Assumes number passed is a valid
  numeric value in the rounded to 2 decimal
  places.  If not, returns original value.
*************************************************/
  var objRegExp = /-?[0-9]+\.[0-9]{2}$/;

    if( objRegExp.test(strValue)) {
      objRegExp.compile('^-');
      strValue = addCommas(strValue);
      if (objRegExp.test(strValue)){
        strValue = '(' + strValue.replace(objRegExp,'') + ')';
      }
      return '$' + strValue;
    }
    else
      return strValue;
}

/* The following functions are declared in common.js
function removeCommas( strValue ) 
function addCommas( strValue ) 
*/



//to get rid of the effects of the polyline (zoomAreaPoly) created in dragzoom. This will tell the submitSearch function to use the maps boundaries while giving a polite message to our users
function removeDragzoomPolyLine(){
	if(searchWithDragzoom){
		map.removeOverlay(zoomAreaPoly); //make the poly area invisible on the map
		searchWithDragzoom = false;
		alert("Area selector has been removed.  Future search results (right side) will include all dots visible on the map. A new search has begun using the map boundaries as the search area.");
		submitSearch();
	}else{
		alert("Area selector has already been disabled.  Future search results (right side) will include all dots visible on the map.");		
	}

}

//-------------------------------------------------------------------
// isNull(value)
//   Returns true if value is null
//-------------------------------------------------------------------
function isNull(val){return(val==null);}

