// The Global "markers" array contains the property data. eg: markers[0].mls contains the mls number of the first property displayed in the list
// the global markerObj array contains the google maps marker objects synced to the markers array
// so that we can change the map marker and the array data at the same time
// 
//
// set globals
 //GEvent.addListener(map.getInfoWindow(), 'maximizeend', testTomsIdea());

//var centerLatitude = $!p.latitude;
//var centerLongitude = $!p.longitude;

// need to re- setup this default location to avoid starting in africa
// Default map center and size
var startLat = 44.95;
var startLng = -93.2;
var startZoom = 10;
var heightdefault = 350; 
var map;
var mapMode = 0; // designates weather map should be requerried to show only results in window
var markers = new Array();
var plotsize = 25;  // no. of markers to plot. if changed also change the "selected" option in the form
var page = 1;      // map marker pager. page = offset
var movehandle = "";
var searchDesc = "";
var searchTotal = "";
var searchReturned = "";
var nosave = "";
//var sortLinkNames = new Array('sort-house', 'sort-address', 'sort-price', 'sort-city', 'sort-bed', 'sort-bath', 'sort-year', 'sort-days');
var sortLinkNames = new Array('sort-days', 'sort-price', 'sort-city', 'sort-bed', 'sort-bath', 'sort-year');
var markerObj = new Array();
var searchParamsCookie = new Object(); // contains key value pairs saved in the 'searchParams' form cookie. see function readCookie
//var sidbarTabs = new Array('searchTab', 'resultsTab', 'SavedTab', 'taggedTab');
var mwindowIDs = new Array('mapSearch', 'quickFind');
var myGroups = {"love": [], "hate": [], "unsure": []};
var myGroupsLables = {"love": "Love", "hate": "Hate", "unsure": "Not Sure"};

var iconImgDefault = 'images/maps/markGreen.png';
var iconImgActive = 'images/maps/markGreen.png';
var iconImgSold = 'images/maps/markRed.png';
var iconImgViewed = 'images/maps/markBlue.png';
var iconLabO = 'images/maps/icono.png';

//var searchSaveState = new array();

//var currentHeight = '';
window.onresize = handleResize;

window.onload = init;
var deselectCurrent = function() {}; // empty function

// set up Icon as a global??? should this be in a function??
function iconSetup () {
	var icon = new GIcon(G_DEFAULT_ICON); //starting with G_DEFAULT_ICON so I don't have to set transparent & imageMap properties needed for GIcon.label
	icon.image = iconImgDefault;
	icon.iconSize = new GSize(15, 22);
	icon.iconAnchor = new GPoint(8, 22);
	icon.shadow = 'images/maps/shadow50.png';
	icon.shadowSize = new GSize(37, 21);
	icon.infoWindowAnchor = new GPoint(8, 1);
	// now to change icon color we can do this
	//icon =  new GIcon(icon, 'images/maps/markYellow.png' );
	return icon;
}
icon = iconSetup();
iconOH = iconSetup();
iconOH.label = {"url":'images/maps/icono.png', "anchor":new GPoint(2,5),"size":new GSize(10,10)};


// This function formats numbers for price by adding commas
function numberFormat(nStr,prefix){
  var prefix = prefix || '';
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1))
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  return prefix + x1 + x2;
}

function setNumMarkers() {
 // GLog.write("function setNumMarkers function");
 page = 1; 
 plotsize = document.numMarkers.num.options[document.numMarkers.num.selectedIndex].value;
 redrawList();     
}

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("handleResize ");
	if (mapmode == "full") {   
		var height = windowHeight() - document.getElementById('toolbar').offsetHeight - document.getElementById('masthead').offsetHeight - 25;
		document.getElementById('map').style.height = height + 1 + 'px'; // 1px extra for tool border
		document.getElementById('sidebar').style.height = height + 'px';
		checkMWindow();
	}
}

function checkMWindow() {
	//GLog.write("checkMWindow");
	if (mwindowIDcurrent != 'none') {
		//GLog.write("checkMWindow OK to resize");
		var height = windowHeight() - document.getElementById('toolbar').offsetHeight - document.getElementById('masthead').offsetHeight - 70;
		
		// This does not work in IE6 when triggered by a window resize event.  
		// I think it has something to do with IE6 firing multiple event when the user resizes the window
		// It does work in IE6 when the window is first opened.
		// if (document.getElementById(mwindowIDcurrent + '-content').style.height != 'auto')
			document.getElementById(mwindowIDcurrent + '-content').style.height = 'auto';
		
		if (document.getElementById(mwindowIDcurrent + '-content').offsetHeight > height) {
			document.getElementById(mwindowIDcurrent + '-content').style.height = height + 'px';
			//GLog.write("checkMWindow RESIZED " + mwindowIDcurrent + '-content  to ' + height + 'px');
		} 
	}
}


var mwindowIDcurrent = 'none';
function toggleMWindow(name) {
	var oDiv = document.getElementById(name)
	if(oDiv.style.display == "none") {
		for(var i = 0;i<mwindowIDs.length;i++) {
			//GLog.write(i + " " + mwindowIDs.length + " " + mwindowIDs[i]);
			var oClose = document.getElementById(mwindowIDs[i]);
			oClose.style.display = "none";
		}
		oDiv.style.display = "block";
		mwindowIDcurrent = name;
		checkMWindow();
	} else {
		oDiv.style.display = "none";
		mwindowIDcurrent = 'none';
	}
}

function changeBodyClass(from, to) {
     document.body.className = document.body.className.replace(from, to);
     return false;
}


function sortClassList(id, field, isnum) {
  // GLog.write("Got to function sortClassList ID: "+ id + " Field: "+ field + " Class Name: " + document.getElementById(id).className);
  if((document.getElementById(id).className == "asc") || (document.getElementById(id).className == "no")) {
    var ul = document.getElementById('sort-controls');
     for(var i = 0; i < sortLinkNames.length ; i++) {
       var oLink = document.getElementById(sortLinkNames[i]);
       // GLog.write(oLink);
       oLink.className = 'no';
     }

    document.getElementById(id).className = 'dsc';
    tableSort( field, "1", isnum);
  } else {
    document.getElementById(id).className = 'asc';
    tableSort( field, "0", isnum);
  }
  redrawList();
  // return false;
}



// this kludgy solution involves tableSort() setting the global col var:
var globalCol;

function columnNumericSortASC(a,b)
{
	//GLog.write(b[col]+ " "+ a[col]);
	return ( a[globalCol] - b[globalCol]);
}

function columnNumericSortDESC(a,b)
{ 
	//GLog.write(b[col]+ " "+ a[col]);
	return ( b[globalCol] - a[globalCol]);
}

function columnStringSortASC(a,b)
{
	//GLog.write(b[col]+ " "+ a[col]);
    return (a[globalCol]<b[globalCol])?-1:(a[globalCol]>b[globalCol])?1:0;
}

function columnStringSortDESC(a,b)
{
	//GLog.write(b[col]+ " "+ a[col]);
	return (a[globalCol]>b[globalCol])?-1:(a[globalCol]<b[globalCol])?1:0;
}

// oooh look at the fancy sort function
// use  'colname', 0=assending, 1= is a number 
function tableSort(col,order,isnum)
{
	globalCol = col;
	// the table here is the global markers array
	//GLog.write("Got to function tableSort  Col: "+ col + " Order: " + order + " IsNum: " + isnum);
    
	// now just sort using a function defined above.  
	if(isnum==1){ // use numeric comparison 
		 //GLog.write("Using Numaric Comparison");
        if(order==0){ // ascending 
            //GLog.write("ASC");
			markers.sort(columnNumericSortASC);
			return true;
        }
        else { // descending 
            //GLog.write("DESC");
			markers.sort(columnNumericSortDESC);
			return true;
        }
    } else { // use string comparison
		//GLog.write("Using String Comparison");
        if(order==0){ // ascending 
            //GLog.write("ASC");
			markers.sort(columnStringSortASC);
			return true;
        }
        else{ // descending 
            //GLog.write("DESC");
			markers.sort(columnStringSortDESC);
			return true;
        }
    }
}


function pagenext() {
 page++;
 redrawList();
}

function pageprev() {
 page--;
 redrawList();
}

function init() { 
 // GLog.write("Function init called"); 

////////////////////////////////////////////////////////////////////// 
//// Disabling cookies for forms because of google analitics conficts
 // readCookie('searchParams');
 // loadFormFromCookie();
/////////////////////////////////////////////////////////////////////
 //fieldSetValue("zipcode", "55555", "text");
 //for(x in searchParamsCookie) {
 //	GLog.write('INIT - ' +	x + " is set to " + searchParamsCookie[x]);
 //}
 if (mapmode == 'full') {
 document.getElementById('button-sidebar-hide').onclick = function() { return changeBodyClass('sidebar-right', 'nosidebar'); };
 document.getElementById('button-sidebar-show').onclick = function() { return changeBodyClass('nosidebar', 'sidebar-right'); };
 }
 
 //document.getElementById('button-savedsearch-hide').onclick = function() { toggleChunk("savedsearch"); };
 //document.getElementById('button-savedsearch-show').onclick = function() { toggleChunk("savedsearch"); };

 //document.getElementById('button-form-hide').onclick = function() { toggleChunk("form"); };
 //document.getElementById('button-form-show').onclick = function() { toggleChunk("form"); };

 //document.getElementById('button-results-hide').onclick = function() { toggleChunk("results"); };
 //document.getElementById('button-results-show').onclick = function() { toggleChunk("results"); };

 //document.getElementById('button-tagged-hide').onclick = function() { toggleChunk("tagged"); };
 //document.getElementById('button-tagged-show').onclick = function() { toggleChunk("tagged"); };

 //document.getElementById('map-mode-on').onclick = function() { setMapMode("1"); };
 //document.getElementById('map-mode-off').onclick = function() { setMapMode("0"); };

 //document.getElementById('sort-house').onclick = function() { return sortClassList('sort-house', 'house', "1"); }; 
 //document.getElementById('sort-address').onclick = function() { return sortClassList('sort-address', 'address', "0"); }; 
 // these were all set to use sort class list changed to tableSort
 //document.getElementById('sort-price').onclick = function() { return sortClassList('sort-price', 'price', "1"); }; 
 document.getElementById('sort-price').onclick = function() { return sortClassList('sort-price', 'price', "1"); }; 
 document.getElementById('sort-city').onclick = function() { return sortClassList('sort-city', 'city', "0"); }; 
 document.getElementById('sort-bed').onclick = function() { return sortClassList('sort-bed', 'bed', "0"); }; 
 document.getElementById('sort-bath').onclick = function() { return sortClassList('sort-bath', 'bath', "0"); }; 
 document.getElementById('sort-year').onclick = function() { return sortClassList('sort-year', 'year', "0"); }; 
 document.getElementById('sort-days').onclick = function() { return sortClassList('sort-days', 'days', "0"); }; 
 handleResize();

 map = new GMap2(document.getElementById("map"));
 map.addControl(new GLargeMapControl());
 map.addControl(new GMapTypeControl());
 map.addControl(new GScaleControl());
 map.addControl(new GOverviewMapControl());
 map.setCenter(new GLatLng(startLat, startLng), startZoom); // tomp extend this as points are added
 // map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);

 // Get the markers data
 retrieveMarkers(searchId, searchType);
 refreshSavedsearch();
 //GLog.write('searchReturned is: ' + searchReturned);
 //GLog.write('nosave is: ' + nosave);
 //GLog.write('searchId is: ' + searchId);
 //GLog.write('searchType is: ' + searchType);
 
} // function init




// Map Mode re-querries whenever the map is moved 
// or zoomed for only properties that fall in map bounds
function setMapMode(state){
	// Map mode will requerry for results every time the map is moved. 
  // GLog.write("function setMapMode function");
  // show right button 
  var mapModeButtonOn  = document.getElementById("map-mode-on")  
  var mapModeButtonOff = document.getElementById("map-mode-off")  
  //set map mode state
    mapMode = state;
  if  (mapMode == 1) {
    mapModeButtonOff.style.display = "block";
    mapModeButtonOn.style.display = "none";
    // listen for zooms
    zoomhandle = GEvent.addListener(map, 'zoomend', function() {
      reSearch();
    });
    // and listen for moves
     movehandle = GEvent.addListener(map, 'moveend', function() {
      reSearch();
    });
  } else {
    mapModeButtonOff.style.display = "none";
    mapModeButtonOn.style.display = "block";
    GEvent.removeListener(zoomhandle);
    GEvent.removeListener(movehandle);
  }
  // also requerry no if set to 1
  if (mapMode == 1) reSearch() ;
}

//function showtab(name) {
//	sidbarTabs;
//	for(i=0;i<sidbarTabs.length;i++) {
//		//show name
//		//hide others
//	}
//}

function toggleChunk(name)
{
  var buttonShow = document.getElementById("button-" + name + "-show");
  var buttonHide = document.getElementById("button-" + name + "-hide");
  var oDiv = document.getElementById(name + "-content");

  if(oDiv.style.display == "none")
  {
    // show
    buttonShow.style.display = "none";
    buttonHide.style.display = "block";
    oDiv.style.display = "block";
  }
  else
  {
    // hide
    buttonShow.style.display = "block";
    buttonHide.style.display = "none";
    oDiv.style.display = "none";
  }
}

function toggleDiv(name, action) {
	//GLog.write(name);
	var div = document.getElementById(name);
	if(action == 'hide'){
		div.style.display = "none";
	}else{
		div.style.display = "block";
	}
}

function toggleSearchFormItems(name, action) {
	//var numItems = 9;
	//for (var i = 1; i < numItems; i++) {
	//	toggleDiv(( name + i), action);
	//}
}

function toggleClass(theClass,element,value) {
	//documentation for this script at http://www.shawnolson.net/a/503/
	var cssRules;
	if (document.all) {
		cssRules = 'rules';
	}
	else if (document.getElementById) {
		cssRules = 'cssRules';
	}
	for (var S = 0; S < document.styleSheets.length; S++){
		for (var R = 0; R < document.styleSheets[S][cssRules].length; R++) {
			if (document.styleSheets[S][cssRules][R].selectorText == theClass) {
				document.styleSheets[S][cssRules][R].style[element] = value;
			}
		}
	}	
}


function redrawList() {
 // if results exist switch to results tab.
 if (document.getElementById('sidebarParentTabber')){ 
  if (markers.length > 0) {document.getElementById('sidebarParentTabber').tabber.tabShow(1);}
 }
 // GLog.write("redrawList Function call");
 // need to remove old list first
 var ul = document.getElementById('sidebar-list');
 if (markers.length > 0){
  document.getElementById('list-controls').style.display = "block";
 }
 while(ul.firstChild) ul.removeChild(ul.firstChild); //clears results
 // reading about memory leaks... may want to remove listener too??
 // remove the markers this removes all overlays. 
 // may later want to change this to remove only the markers? 
 // or beter yet... reorder the list without redrawing the markers.
 map.clearOverlays(); //clears map
 var bounds = new GLatLngBounds();
 //GLog.write("Plot Start: " + (((page * plotsize)-1) - (plotsize -1)));
 //GLog.write("Plot End:   " + (( page * plotsize) - 1 ));
 for (var i = 0; i < markers.length; i++) { // for each marker
	icon.image = iconImgDefault; // reset default color
	var lng = markers[i].lng;
	var lat = markers[i].lat;
	//check for lng and lat so MSIE does not error
	//on parseFloat of a null value
	var latlng = new GLatLng(parseFloat(lat),parseFloat(lng));
	var plink = markers[i].proplink;
	var status = markers[i].status;
	var viewed = markers[i].viewed;
	var oh = markers[i].oh;
	
	//GLog.write(i);
	// ##### Markers on Map #######
	// this determans "markes" get a marker on the map. only props on current page are on map
	if (i >= (((page * plotsize)-1) - (plotsize -1)) && i <= (( page * plotsize) - 1 ) ) {
		 if((lng && lat) && (parseFloat(lat) + parseFloat(lng) != 0)) { // if lat & lng values exist
			// set color of icon 
			if (status == "Sold" || status == "Comp Sold"){ icon.image = iconImgSold; }
			if (viewed == 1){ icon.image = iconImgViewed; }
			sidebarLayout(markers[i], i, 1); // if on map add indicator, 3rd parm
			markerLayout(markers[i], i);
			var marker = createMarker(latlng, html, listHtml, plink, status, i);
			markerObj[i] = marker; // put the marker object in array so we can refer to it later (hide)
			map.addOverlay(marker);
			// extend bounds of map to includ this point
			bounds.extend(latlng);
	// ##### end Markers on Map #######
		 }else{
			// bad geocode, not on map
			sidebarLayout(markers[i], i); // if not on map no 3rd parm
			createListItem(listHtml, plink);
		 }
	}else{
	 sidebarLayout(markers[i], i); // if not on map no 3rd parm
	 createListItem(listHtml, plink);
	}
 } //for each marker

 // if there is a marker resize and recenter
 if(mapMode != 1) {  // don't mess with bounds if in map mode
  if (  markers.length > 0) {
   map.setZoom(map.getBoundsZoomLevel(bounds));
   var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
   var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
   map.setCenter(new GLatLng(clat,clng));
   map.setCenter(bounds.getCenter());
  }
 }
 updateinfo();
 //updateFeedback('save-search', saveSearchFormLayout() );
} //end function redrawList


function getCorners() {
 // test for rectangular search:
 var bounds = map.getBounds();
 var windowBounds = 
    'minLat=' + bounds.getSouthWest().lat()
    + '&maxLat=' + bounds.getNorthEast().lat()  
    + '&minLon=' + bounds.getSouthWest().lng() 
    + '&maxLon=' + bounds.getNorthEast().lng() ;
 //GLog.writeUrl('rectangleSearch.do?' + windowBounds);
 return windowBounds;
}

function updateinfo() {
 var prevlink = '&nbsp;';
 var nextlink = '&nbsp;';
 var pagerbut = '';
 var warn = '';
 var avail = '';
/*
 if (plotsize >= markers.length)
 {
     var showing = "All results are shown on the map.";
 } else { // not all results are on the map
   // Pager
   if(page != 1 ){ // Pager Previous - if not first page
     prevlink = '<a href="#" onclick="pageprev();">Plot previous ' + plotsize + '</a>';
   }
   //GLog.write((page * plotsize) );
   //GLog.write( markers.length);
   if( (page * plotsize)  < markers.length ){ // Pagent next -  if not last page
     var nextnum = plotsize;
     if ((page * plotsize) > (markers.length - plotsize)){ // if second to the last page
       nextnum = (markers.length - (page * plotsize));
     } 
     nextlink = '<a href="#" onclick="pagenext();">Plot next ' + nextnum + '</a>';
   }
   // Warn if we dont have all the results of the seach
   // GLog.write(searchTotal + "tot - ret" + searchReturned );
   if ( parseFloat(searchTotal) > parseFloat(searchReturned)){ // if Not all results shown
    // WARNING: Not all results listed! NNN properties match your search. 
    //NNN of the newest properties are listed. Please narrow your search to see all results.
    // XXX externalize the warning css
     var warn = '<div style="color:#cf262d; background-color:#FFFDBF; border: solid 1px #cf262d; padding: 1px 5px;"><strong>WARNING:</strong> Not all results listed! <strong>'
       + searchTotal
       + '</strong> properties match your search. <strong>'
       + searchReturned
       + '</strong> of the newest properties are listed. Please narrow your search to see all results.'
       + '</div>'
     ;
     // GLog.write(warn );
   }
   // What is on the map
   var showing = "<strong>" + "Results "
     + ((page * plotsize) - ((plotsize) -1)) 
     + " through " 
     + (page * plotsize) 
     + "</strong> from the sorted list are shown on the map. "
     + "Showing page " + page + ". "
     + prevlink + " "
     + nextlink 
   ;
 } // end if/else plotsize
*/
/*
 var infostring = "Searching for <strong>" 
    + searchDesc 
    + "</strong> we found <strong>"
    + markers.length
    + "</strong> properties. " 
    + showing;
*/
/*
* // Listing NNN results of your seach for NNN.
*  var infostring = warn
*    + "Listing <strong>"
*    + markers.length
*    + "</strong> results of your search for "
*    + searchDesc
*    + "</strong>. "
*    + showing;
*/


	// Search description in masthead
	var infostring = searchDesc
	updateFeedback("resultsInfo" , infostring); 

	// Search Results info & controls "25-50 of 500 (12874 Matches) Next 25 Previous 25"
	// figure out second number to show in marked range
	// GLog.write( searchReturned );
	if ( searchReturned > 0 ) { // only if there are results
		var to = "";
		if ((page * plotsize) >= searchReturned){ 
		  	to = searchReturned;
		} else {
			to = page * plotsize;
		}

		// Pager
		if(page != 1 ){ // Pager Previous - if not first page
			prevlink = '<a href="#" onclick="pageprev();">Prev ' + plotsize + '</a>';
		}
		if( (page * plotsize)  < markers.length ){ // Pagent next -  if not last page
			var nextnum = plotsize;
			if ((page * plotsize) > (markers.length - plotsize)){ // if second to the last page
				nextnum = (markers.length - (page * plotsize));
			}
		 	nextlink = '<a href="#" onclick="pagenext();">Next ' + nextnum + '</a>';
		}
		// build pager button list
		pagerbut = '<div id="res-prev">' + prevlink + '</div><div id="res-prev">' + nextlink + '</div> <br style="clear:both; />';
	
		// Show total matches if not all in list
		if ( parseFloat(searchTotal) > parseFloat(searchReturned)){ // if Not all results shown
			avail = " (" + searchTotal + " Matches)";
		}
		// build selection list
		var select = [5,10,15,20,25,30,40,50,75,100,125,150,200];
		var options ='';
	    for (var i = 0; i < select.length; i++){
			options += '<option value="' + select[i] + '"';
        	if (select[i] == plotsize ) options += ' selected';
        	options += '>' +  select[i] + '</option>';
			//GLog.write(i + ' SEPERATOR '+ select[i] )
		}

		var searchinfostring = '<form name="numMarkers">'	
			+ ((page * plotsize) - ((plotsize) -1)) + ' - ' + to + " of " + searchReturned
			+ avail
			+ ' - Map <select onchange="setNumMarkers()" name="num">'
			+ options
			+'</select></form>'
			+ pagerbut;
 		updateFeedback("search-info" , searchinfostring);
	} // if results
	changeBodyClass('loading', 'standby'); 
} // end function updateinfo()

function markerLayout(mdat, id){
	var morelink = '<a href="#" onclick="map.getInfoWindow().maximize()">More Info</a> ';
		// we could iterate though a list of tags/groups and add a link for each existing tag love, hate, etc
	var open = '';
	if (mdat.oh == 1 ) {
		open = '<div class="infobubbleopen">'
		+ 'Open: '+mdat.ohd+' - '+mdat.ohf+' to '+mdat.oht
		+ '</div>';
	}

	// we could iterate though a list of tags/groups and add a link for each existing tag love, hate, etc
	html = '<div class="infobubble">'
	 + '<div class="ibtoolbar">'
	 + morelink
	//	 + '<a href="#" onClick="showhide(' + id + ')">hide</a> '
	// shows taggin links
	//	 + '<a href="#" onClick="addToGroup(\'love\', ' + id + ')">' + myGroupsLables['love'] +'</a> '
	//	 + '<a href="#" onClick="addToGroup(\'hate\', ' + id + ')">'+ myGroupsLables['hate'] + '</a> '
	//	 + '<a href="#" onClick="addToGroup(\'unsure\', ' + id + ')">'+ myGroupsLables['unsure'] +'</a> '
	 + '</div>'
			
	 + '<div  class="infobubblehead">'
	 + mdat.house + " " + mdat.address + ", " + mdat.city
	 + '</div>'
	 + '<img style="float:left ; height:68px;" width="96" border="0" alt=" " src="'
	 + mdat.src
	 + '" />'
	 + '<div class="infobubbleodd"><strong>'
	 + numberFormat(mdat.price,'$')
	 + '</strong></div>'
	 + '<div class="infobubbleeven">'
	 + mdat.bed + " Bedrooms"
	 + '</div>'
	 + '<div class="infobubbleodd">'
	 + mdat.bath + " Bathroom"
	 + '</div>'
	 + '<div class="infobubbleeven">'
	 + mdat.garage + " Car Garage"
	 + '</div>'
	 + '<div class="infobubbleodd">'
	 + "Year Built " + mdat.year
	 + '</div>'
	 + open
	 + '</div>';
	
	// When we lay out a special max info page for this we can include the link at the top
	// '<a href="#" onclick="map.getInfoWindow().restore()">Less Info</a>'

    return html;
}

// i added for debuging purposes
function sidebarLayout(mdat, i, onMap){
  // Layout markup for sidebar list item
  if(onMap) {
    listHtml = '<img src="' + icon.image + '" id="p'+ i +'" alt="On Map" border="0" align="left" width="8" height="11" /> ';
  }else{
    listHtml = '';
  }

  var bricon = '';
  if(mdat.brt == 'br') {
	bricon = '<img src="' + brUrl + '" alt="Broker Reciprocity" border="0" align="right" width="24" height="21" />';
  } else if (mdat.brt == 'ih') {
	bricon = '<img src="' + ihUrl + '" alt="Our Listing" border="0" align="right" width="24" height="21" />';
  }
	
	var open = '';
	if (mdat.oh == 1 ) {
		open = ' <span class="openlab">Open</span>';
	}
  listHtml += bricon
	+ '[' + (i + 1) 
    + '] <strong>'
    + numberFormat(mdat.price,'$')
    + '</strong> - '
    + mdat.house + " " + mdat.address + ", " + mdat.city;
    if (mapmode == "full") {
    listHtml += '<br />';
    }
    listHtml += ' <span>'
    + mdat.bed + " Bed"
    + ", "
    + mdat.bath + " Bath"
    + ", "
    + mdat.garage + " Garage"
    + ", "
    + "Yr Blt " + mdat.year
    + '</span>'
	+ open;

    return listHtml;
}

// creates list item only
function createListItem(listHtml, infoUrl) {
	var listItem = document.createElement('li');
	var listItemLink = listItem.appendChild(document.createElement('a'));
	listItemLink.href = "#";
	listItemLink.innerHTML = listHtml;
	document.getElementById('sidebar-list').appendChild(listItem);
}

function showhide(id){
 	marker = markerObj[id];
	if (marker.isHidden()) {
		marker.show();
	} else {
		marker.hide();
	}
}

// This is not yet implimented or tested
//function printGroupLinks(id, openTag, closeTag) {
function printGroupLinks() {
	var links = 
		// '<ul><li>' 
		'<a href="#" onClick="addToGroup(\'love\', ' + lastMarkerId + ')">Love</a> '
		// + '</li><li>'
    	+ '<a href="#" onClick="addToGroup(\'hate\', ' + lastMarkerId + ')">Hate</a> '
		// + '</li><li>'
    	+ '<a href="#" onClick="addToGroup(\'unsure\', ' + lastMarkerId + ')">Unsure</a> '
		// + '</li></ul>'
	;
	updateFeedback('maxinfonav', links );
} 

function addToGroup(group, id){
	// if we want to add groups dyamically *tags* we have to figure out how to 
	// test if myGroup[tag] exists and add it (push) if not

	// check if prop is already in this group
	var add = 1;
	for (var i = 0; i < myGroups[group].length; i++) {
		// GLog.write("I "+ group + " mlsId:"+ myGroups[group][i].mls);
		if (myGroups[group][i].mls == markers[id].mls) {
			add = 0;
			alert('This property is already tagged as "' + myGroupsLables[group] + '"');
		}
	}
	if ( add == 1 ) {
		myGroups[group].push(markers[id]);
		drawGroups();
	}
}

function drawGroups () { // draws the List of tagged props in sidebar
	var taghtml='';
	//var groups = ["love", "hate", "unsure"];
	for (tag in myGroups) {
		taghtml += "<strong>" + myGroupsLables[tag] + ":</strong><br />"
			+ '<ul id="tagged-list">';
		for  (i = 0; i < myGroups[tag].length; i++) {
			//GLog.write('#');
			//taghtml += "<li>" + myGroups[tag][i].mls + "</li>";
        	sidebarLayout( myGroups[tag][i], i, 1); // if on map add indicator, 3rd parm
			taghtml += '<li><a href="#">' + listHtml + "</a></li>";
		}
		taghtml += "</ul>";
	}
	updateFeedback("tagged-content" , taghtml);
}

// Creates marker and list item
function createMarker(latlng, html, listHtml, infoUrl, status, id) {
	// set up colors for marker and list link border
	if (status == "Sold"){
		// icon.image = 'images/maps/markRed.png';
		var currentClass = 'currentSold';
	}	else {
		var currentClass = 'current';
	}
	if (markers[id].oh == 1) {
		var marker = new GMarker(latlng, iconOH);
	}else{
		var marker = new GMarker(latlng, icon);
	}
	var listItem = document.createElement('li');
	var listItemLink = listItem.appendChild(document.createElement('a'));
	listItemLink.href = "#";
	listItemLink.innerHTML = listHtml;

	var focusPoint = function() {
		deselectCurrent();
		listItem.className = currentClass;
		deselectCurrent = function() { listItem.className = ''; }
		// XXX ask.
		// have to pop out of map mode here because when you open the info windo whe map moves
		// which redraws, which closes the window :(
		if(mapMode == 1) {setMapMode(0);}    
		// GEvent.removeListener(movehandle);
		// GLog.write(status);	
		// if(status.toLowerCase() == "active"){ 
		// this was how you did it with undocumented maxUrl which was no longer supported after 2.83
		//marker.openInfoWindowHtml(html, {maxUrl:infoUrl});
		var maxContentDiv = document.createElement('div');
		maxContentDiv.innerHTML = 'Loading...';
		marker.openInfoWindowHtml(html, {maxContent: maxContentDiv});
		var iw = map.getInfoWindow();
		GEvent.addListener(iw, "maximizeclick", function() {
			GDownloadUrl(infoUrl, function(data) {
				maxContentDiv.innerHTML = data;
			});
		});
				
		lastMarkerId = id;
		// }else{
		//   marker.openInfoWindowHtml(html);
		// }
		map.panTo(latlng);
		markers[id]['viewed'] = 1; // in the array, tag this record as viewed
		marker.setImage(iconImgViewed); //Change the map icon to the Viewed Icon
		var oImg = document.getElementById('p'+id); // and the list item image
		oImg.src = iconImgViewed;
		return false;
	}

	GEvent.addListener(marker, 'click', focusPoint);

	// This listens for the maxUrl opening and inserts content when done
	// GEvent.addListener(map.getInfoWindow(), 'maximizeend', function()
	//        {setTimeout("printGroupLinks()",0)} );

	listItemLink.onclick = focusPoint;

	document.getElementById('sidebar-list').appendChild(listItem);

	return marker;
	//return focusPoint;
} // createMarker



function sortByFirstName(a, b) {
    var x = a.FirstName.toLowerCase();
    var y = b.FirstName.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function updateFeedback(id, str) {
 var oSpan = document.getElementById(id);
 oSpan.innerHTML = str;
}

function reSearch(formname)  // preform a search from the map form
{
	changeBodyClass('standby', 'loading');
	
	//updateFeedback('save-search', saveSearchFormLayout() );

	//showLoading();
	page = 1; 
	// GLog.write( "function reSearch called ");
	//GLog.write( "formname is: " + formname );
	// get value
	var parameter = ""; // name value pair

	var oField;
	var fieldValue;
	//var searchUrl = 'propertySearch.do';
	var searchUrl = 'mapSearch.do'; //<====== ************* here

	// XXX
	// Rectangle search needs to be integrated into regular search
	// When it is wee need to change this
	// right now we Ether do map or regular querry
	// remove IF later

	//   if (mapMode == 1)
	//   { 
	//     searchUrl = 'rectangleSearch.do';
	//     parameter += getCorners();
	//   }else{

	// always set rememberSearch=true so that java sets the parameters cookie
	parameter += 'rememberSearch=true&';
	
	// send different paremeters depending on which form is used
	if (formname == "searchFormQuick") {
		// street
		oField = document.getElementById("street");
		fieldValue = oField.value;
		if (fieldValue == 'Street'){fieldValue ="";} 
		parameter += "&street=" + fieldValue;

		// streetNum
		oField = document.getElementById("streetNum");
		fieldValue = oField.value;
		if (fieldValue == 'House#'){fieldValue ="";} 
		parameter += "&streetNum=" + fieldValue;
		
		// mlsnumbers
		oField = document.getElementById("mlsnumbers");
		fieldValue = oField.value;
		if (fieldValue == 'MLS#'){fieldValue ="";}
		parameter += "&mlsnumbers=" + fieldValue;
		
		parameter += "&status=ACT"
	
	} else if (formname == "searchFormTop") {
		//on map
		oField = document.getElementById("mapOnly");
		//fieldValue = oField.checked;  //if useing a checkbox
		fieldValue = oField.value; // if useing a hidden field
		if (mapMode == 1 ){
			parameter += getCorners() + "&";
		} else if (fieldValue == 1) {
			parameter += getCorners() + "&";
		}
 
		// price min
		oField = document.getElementById("priceRangeMin");
		fieldValue = oField.options[oField.selectedIndex].value;
		parameter += "&priceRangeMin=" + fieldValue;
		 
		// price max
		oField = document.getElementById("priceRangeMax");
		fieldValue = oField.options[oField.selectedIndex].value;
		parameter += "&priceRangeMax=" + fieldValue;
		 
		// beds
		oField = document.getElementById("bedstotal");
		fieldValue = oField.options[oField.selectedIndex].value;
		parameter += "&bedstotal=" + fieldValue;
		 
		// baths
		oField = document.getElementById("baths");
		fieldValue = oField.options[oField.selectedIndex].value;
		parameter += "&baths=" + fieldValue;
		
		// Open House
		oField = document.getElementById("onlyOpenHouse");
		fieldValue = oField.value;
		parameter += "&onlyOpenHouse=" + fieldValue;
		
		// foreclosure
		oField = document.getElementById("foreclosure");
		fieldValue = oField.value;
		parameter += "&foreclosure=" + fieldValue;
		 
		// Status active or sold
		oField = document.getElementById("status");
		fieldValue = oField.value;
		parameter += "&status=" + fieldValue;
		
		// alert(parameter);
	} else {
		//on map
		oField = document.getElementById("mapOnly");
		//fieldValue = oField.checked;  //if useing a checkbox
		fieldValue = oField.value; // if useing a hidden field
			if (mapMode == 1 ){
			parameter += getCorners() + "&";
		} else if (fieldValue == 1) {
			parameter += getCorners() + "&";
		} 
	
		// city
		//oField = document.getElementById("city");
		//fieldValue = oField.value;
		//parameter += "city=" + fieldValue;

		// zip code
		//oField = document.getElementById("zipcode");
		//fieldValue = oField.value;
		//parameter += "&zipcode=" + fieldValue;


		// price min
		oField = document.getElementById("priceRangeMin");
		fieldValue = oField.options[oField.selectedIndex].value;
		parameter += "&priceRangeMin=" + fieldValue;
		 
		// price max
		oField = document.getElementById("priceRangeMax");
		fieldValue = oField.options[oField.selectedIndex].value;
		parameter += "&priceRangeMax=" + fieldValue;
		 
		// year min
		oField = document.getElementById("yearMin");
		fieldValue = oField.options[oField.selectedIndex].value;
		parameter += "&yearMin=" + fieldValue;
		 
		// year max
		oField = document.getElementById("yearMax");
		fieldValue = oField.options[oField.selectedIndex].value;
		parameter += "&yearMax=" + fieldValue;
		 
		 
		// acres min
		oField = document.getElementById("acresMin");
		fieldValue = oField.options[oField.selectedIndex].value;
		parameter += "&acresMin=" + fieldValue;
		 
		// acres max
		oField = document.getElementById("acresMax");
		fieldValue = oField.options[oField.selectedIndex].value;
		parameter += "&acresMax=" + fieldValue;

		// schoolDistrict
		//oField = document.getElementById("schoolDistrict");
		//fieldValue = oField.value;
		//parameter += "&schoolDistrict=" + fieldValue;

		// status
		oField = document.getElementById("status");
		fieldValue = oField.value;
		parameter += "&status=" + fieldValue;

		// type/style
		oField = document.getElementById("stylecategory");
		fieldValue = oField.value;
		parameter += "&stylecategory=" + fieldValue;

		// fireplace 
		oField = document.getElementById("fireplace");
		fieldValue = oField.value;
		parameter += "&fireplace=" + fieldValue;

		// beds
		oField = document.getElementById("bedstotal");
		fieldValue = oField.options[oField.selectedIndex].value;
		parameter += "&bedstotal=" + fieldValue;
		 
		// baths
		oField = document.getElementById("baths");
		fieldValue = oField.options[oField.selectedIndex].value;
		parameter += "&baths=" + fieldValue;
		 
		// garagecap
		oField = document.getElementById("garagecap");
		fieldValue = oField.options[oField.selectedIndex].value;
		parameter += "&garagecap=" + fieldValue;

		//  lake
		//	oField = document.getElementById("lake");
		//	fieldValue = oField.options[oField.selectedIndex].value;
		//	parameter += "&lake=" + fieldValue;

		// special
		//	oField = document.getElementById("special");
		//	fieldValue = oField.options[oField.selectedIndex].value;
		//	parameter += "&special=" + fieldValue;

		// onlyOpenHouse
		oField = document.getElementById("onlyOpenHouse");
		fieldValue = oField.checked
		//GLog.write("oField.checked " + oField.checked);
		parameter += "&onlyOpenHouse=" + fieldValue;


		// onlyVtour
		oField = document.getElementById("onlyVtour");
		fieldValue = oField.checked;
		parameter += "&onlyVtour=" + fieldValue;
		//   } // end IF mapmode  

		//alert(parameter);
	} // end if else 

	var request = GXmlHttp.create();
	request.open('GET', searchUrl + '?' + parameter, true);
	request.send(null);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			clearMarkers();
			retrieveMarkers();
			// this is called by retrievMarkers redrawList();
			//switch to the results tab. 
		}
	}
	if(mwindowIDcurrent=="quickFind") {toggleMWindow("quickFind")};
	if(mwindowIDcurrent=="mapSearch") {toggleMWindow("mapSearch")};
	
	// Draws the save form
	

} // end function reSearch()

function clearMarkers()
{
 markers = new Array();
}

function retrieveMarkers(searchId, searchType) {
 // GLog.write("function RetrieveMarkers called");
 var request = GXmlHttp.create();
 
 //tell the request where to retrieve data from.
 var requestUrl = 'retrieveMarkers.do';

 // if this is a saved search hit the  mapShowSearch.do instead
 if (searchId){
	requestUrl = 'mapShowSearch.do?searchId=' + searchId + '&searchType=' + searchType;
	//delete searchId;
	//if (searchType != undefined){
	//	delete searchType;
	//}
 }
 
 // this is for fixing case 56428, showing public search on map
 if (typeof(publicSearch) != "undefined"){
   if( publicSearch && searchId ){
  	requestUrl = 'mapShowPublicSearch.do?searchId=' + searchId + '&searchType=' + searchType;
   }
 }
 
// delete searchId;
// delete searchType;
 
 request.open('GET', requestUrl, true);
  
 //tell the request what to do when the state changes.
 request.onreadystatechange = function() {
 	if (request.readyState == 4) {
		if (request.responseXML) { // make sure the resoponce is xml
	  		var xmlDoc = request.responseXML;
	  		var searchxml = xmlDoc.documentElement.getElementsByTagName("search");
	  		// searchDesc is global english description of search preformed
	  		searchDesc = searchxml[0].getAttribute("desc");
	  		searchTotal = searchxml[0].getAttribute("totalResults");
	  		searchReturned = searchxml[0].getAttribute("returnedResults");
	  		brUrl = searchxml[0].getAttribute("brUrl"); // the url of the broker reciprocity logo
	  		ihUrl = searchxml[0].getAttribute("ihUrl"); // the url of the in house listing logo, broker logo
	  		nosave = searchxml[0].getAttribute("nosave"); // are the results saveable. don't show form it nosave==true
			//GLog.write('nosave is: ' + nosave);
	  		// GLog.write("searchDesc " + searchDesc);
	  		var markersxml = xmlDoc.documentElement.getElementsByTagName("marker");
	  		// Markers array is global prop data
		  	for (var i = 0; i < markersxml.length; i++) {
			    markers[i] = {
			     lat:markersxml[i].getAttribute("lat"),
			     lng:markersxml[i].getAttribute("lng"),
			     house:markersxml[i].getAttribute("house"),
			     address:markersxml[i].getAttribute("address"),
			     price:markersxml[i].getAttribute("price"),
			     src:markersxml[i].getAttribute("src"),
			     //desc:markersxml[i].getAttribute("desc"),
			     status:markersxml[i].getAttribute("status"),
			     proplink:markersxml[i].getAttribute("proplink"),
			     bed:markersxml[i].getAttribute("bed"),
			     bath:markersxml[i].getAttribute("bath"),
			     days:markersxml[i].getAttribute("days"),
			     city:markersxml[i].getAttribute("city"),
			     year:markersxml[i].getAttribute("year"),
			     garage:markersxml[i].getAttribute("garage"),
			     zip:markersxml[i].getAttribute("zip"),
			     mls:markersxml[i].getAttribute("mls"),
			     brt:markersxml[i].getAttribute("brt"),  // broker reciprocit type, show which logo
				 oh:markersxml[i].getAttribute("oh"),  // if open house this is "1"
				 ohd:markersxml[i].getAttribute("ohd"),  // open house date
				 ohf:markersxml[i].getAttribute("ohf"),  // open house from time
				 oht:markersxml[i].getAttribute("oht"),  // open house to time
				 viewed:0 
	    		} // markers = 
	  		} //for
		} //if XML
   	 	redrawList();
		if (nosave != 'true') {
			updateFeedback('save-search', saveSearchFormLayout() ); // updates top of results form
		}	
 	} //if
 } // inline function
request.send(null);

}// retrieveMarkers function

/*

        Cookie forms

        The user's selections and inputs are ssaved to cookies real-time.   When the page loads, the formfields are set from the cookie.

        Note that handleSelection and clearData in the main script also address the cookies.

*/
function fieldSetValue(fieldName, value, type)
{
        var oField = document.getElementById(fieldName);
        //GLog.write('Setting ' + fieldName + ' to value: ' + value);
        if(type == "menu")
        {
                //GLog.write('Selecting in menu');
                for(i = 0; i < oField.options.length; i++)
                {
                        if(oField.options[i].value == value)
                        {
                                oField.options[i].selected = true;
                                //GLog.write('Selecting success');
                                return true;
                        }
                }
        }
        else if(type == "text")
        {
            //GLog.write('Selecting in textbox');
            oField.value = value;
            return true;
        }
        else if(type == "span")
        {
            oField.innerHTML = value;
            return true;
        }
        else if(type == "cb")
        {
            if(value == "true") {
            //if(value = "false")
			oField.checked = true;
			//GLog.write("Set " + fieldName + "checkbox to TRUE");
            } else {
				oField.checked = false;
				//GLog.write("Set " + fieldName + "checkbox to FALSE")
			}
        }
}


function stashValue(oField, type)
{
/*
        var value;
        var id = oField.id;

        if(type == "menu")
        {
                GLog.write("Stashing menu");
                if(oField.selectedIndex > -1)
                        value = oField.options[oField.selectedIndex].value;
                else
                        return false;
        }
        else if(type == "text")
        {
                GLog.write("Stashing text");
                value = oField.value;
        }
        else if(type == "span")
        {
                GLog.write("Stashing span");
                value = oField.innerHTML;
        }
        else if(type == "cb")
        {
                GLog.write("Stashing checkbox");
                value = oField.value;
        }


        if(!value || value == "")
        {
                GLog.write("DELETING!");
                jimAuld.utils.cookies.del("field_" + id);
                GLog.write("Stashed: " + "field_" + id + " " + jimAuld.utils.cookies.get("field_" + id) );
        }
        else
        {
                jimAuld.utils.cookies.set("field_" + id, value);
        }

        return true;
	*/
}


function loadFormFromCookie()
{
	/*
        // for now just mlsnumbers
        var value;


        loadFieldFromCookie("setNumMarkers", "menu");
        loadFieldFromCookie("status", "menu");
        loadFieldFromCookie("stylecategory", "menu");
        loadFieldFromCookie("city", "text");
        loadFieldFromCookie("cityName", "span");
        loadFieldFromCookie("schoolDistrictName", "span");
        loadFieldFromCookie("schoolDistrict", "text");
        loadFieldFromCookie("priceRangeMin", "menu");
        loadFieldFromCookie("priceRangeMax", "menu");
        loadFieldFromCookie("bedstotal", "menu");
        loadFieldFromCookie("baths", "menu");
        loadFieldFromCookie("garagecap", "menu");
        loadFieldFromCookie("fireplace", "menu");
        loadFieldFromCookie("yearMin", "menu");
        loadFieldFromCookie("yearMax", "menu");
        loadFieldFromCookie("acresMin", "menu");
        loadFieldFromCookie("acresMax", "menu");
        loadFieldFromCookie("zipcode", "text");
        loadFieldFromCookie("streetNum", "text");
        loadFieldFromCookie("street", "text");
        loadFieldFromCookie("mlsnumbers", "text");
        loadFieldFromCookie("onlyVtour ", "cb");

        GLog.write("LOADED");
	*/
	var searchParamsTypes = new Object();
	searchParamsTypes.minLon = "ignore";
	searchParamsTypes.minLat = "ignore";
	searchParamsTypes.maxLon = "ignore";
	searchParamsTypes.maxLat = "ignore";
	searchParamsTypes.setNumMarkers = "menu";
	searchParamsTypes.status = "menu";
	searchParamsTypes.stylecategory = "menu";
	//searchParamsTypes.city = "text";
	searchParamsTypes.city = "ignore";
	//searchParamsTypes.cityName = "span";
	searchParamsTypes.cityName = "ignore";
	//searchParamsTypes.schoolDistrictName = "span";
	searchParamsTypes.schoolDistrictName = "ignore";
	//searchParamsTypes.schoolDistrict = "text";
	searchParamsTypes.schoolDistrict = "ignore";
	searchParamsTypes.priceRangeMin = "menu";
	searchParamsTypes.priceRangeMax = "menu";
	searchParamsTypes.bedstotal = "menu";
	searchParamsTypes.baths = "menu";
	searchParamsTypes.garagecap = "menu";
	searchParamsTypes.fireplace = "menu";
	searchParamsTypes.yearMin = "menu";
	searchParamsTypes.yearMax = "menu";
	searchParamsTypes.acresMin = "menu";
	searchParamsTypes.acresMax = "menu";
	//searchParamsTypes.zipcode = "text";
	//searchParamsTypes.streetNum = "text";
	searchParamsTypes.streetNum = "ignore";
	//searchParamsTypes.street = "text";
	searchParamsTypes.street = "ignore";
	searchParamsTypes.mlsnumbers = "text";
	searchParamsTypes.onlyVtour = "cb";
	searchParamsTypes.onlyOpenHouse = "cb";
	searchParamsTypes.rememberSearch  = "ignore";
	
	for(x in searchParamsCookie) {
		if (searchParamsTypes[x] != 'ignore') {
			//GLog.write('loadFormFromCookie - ' +	x + " is set to " + searchParamsCookie[x] + " the type is " + searchParamsTypes[x] );
			//fieldSetValue(fieldName, value, type);
			fieldSetValue(x, searchParamsCookie[x], searchParamsTypes[x]);
		}
	}
	
	
	
}



function loadFieldFromCookie(fieldName, type)
{
	/*
        var value = jimAuld.utils.cookies.get("field_" + fieldName);
        if(value)
                fieldSetValue(fieldName, value, type);
	*/
}

function login(prevPage){
	// GLog.write("login function");
	var parameter = ""; // name value pair
	var oField;
	var fieldValue;
	var loginUrl = 'mapCustomerLogin.do';
	var page = "";

	// useremail
	oField = document.getElementById("useremail");
	fieldValue = oField.value;
	parameter += "useremail=" + fieldValue;

	// password
	oField = document.getElementById("password");
	fieldValue = oField.value;
	parameter += "&password=" + fieldValue;

	parameter += "&map=true";
	
	//get previous_page if it exists
	if(null != prevPage && "" != prevPage){
		parameter += "&previous_page=" + escape(prevPage);
	}
	

	var request = GXmlHttp.create();
	request.open('GET', loginUrl + '?' + parameter, true);
	request.send(null);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			page = request.responseText;
 			updateFeedback('savedsearch-content', page);
		}
	}
} // end login()


function deleteSavedSearch(id, type) {
	var url = 'mapDeleteSearch.do?searchId=' + id + '&searchType=' + type + '&map=true';
	var request = GXmlHttp.create();
	request.open('GET', url, true);
	request.send(null);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			page = request.responseText;
			updateFeedback('savedsearch-content', page);
		}
	}
}

function getSavedSearch(id, type) {
	//GLog.write(id + '  ' + type)
	changeBodyClass('standby', 'loading'); //show loading graphic
	clearMarkers();
	page=1; //start pager at 1
	showSaveForm = 0; // don't show the "save Search" form, it already saved.
	// example timeout use  setTimeout("function()",0)
	// setTimeout("retrieveMarkers('mapShowSearch.do?searchId=' + id + '&searchType=' + type)",0);
	retrieveMarkers(id, type);
	// Get this fresh to clear any previous messages.
	// we *could* avoid this extra server call to speed up by doing some fancy removal 
	// of message text later (much later:)
	refreshSavedsearch(); 
}

function refreshSavedsearch(searchName){
	// GLog.write("got to refreshSavedsearch function");
	var form = "";
	var request = GXmlHttp.create();
	//search name passed to the savedSearch Action map=true sets simple responce
	var url = 'savedSearch.do'
		+ '?map=true'
		+ '&searchName=' + searchName 
	;
	request.open('GET', url , true);
	// request.open('GET', 'savedSearch.do?map=true&searchName=' + searchName , true);
	request.onreadystatechange = function() {
	if (request.readyState == 4) {
		form = request.responseText;
		// GLog.write(form);
		updateFeedback('savedsearch-content', form);
		//document.getElementById('savedsearch-content').appendChild(form);
	}
	}
	request.send(null);
} // function refreshSavedsearch

function saveSearch(){
    var parameter = ""; // name value pair
    var oField;
    var fieldValue;
    var loginUrl = 'mapCustomerLogin.do';
    var page = "";

	// get the Name of the search
    oField = document.getElementById("searchName");
    fieldValue = oField.value;
    parameter = "searchName=" + fieldValue;

	// erase form  to prevent double saving
	//GLog.write('erasing form');
	updateFeedback('save-search', '&nbsp;');


	//var url = 'mapSaveSearch.do?' + parameter ;
	var url = 'saveSearch.do?map=true&' + parameter ;
    var request = GXmlHttp.create();
    request.open('GET', url, true);
    request.send(null);
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            //do nothing with responce
			page = request.responseText;
            		updateFeedback('savedsearch-content', page);
            		
			//refreshSavedsearch(fieldValue); // updates search tab
			//var formSaved = saveSearchFormLayout('true', fieldValue);
			// GLog.write(formSaved);
			//updateFeedback('save-search', formSaved ); // updates top of results
			
			updateFeedback('save-search', saveSearchFormLayout('true', fieldValue) ); // updates top of results
			
			// switch to the saved search tab
			document.getElementById('sidebarParentTabber').tabber.tabShow(2);
			//searchSaveState = [saved];
        }
    }
}

function saveSearchFormLayout(saved, as) {
	
	// GLog.write(  saved + as);
	// See velocity function below. need to add logic contion to show form 
	// also need to add parrameter if radious serach (not doing not)
	
	var searchForm = '';
	if (saved == 'true'){
		searchForm = 'Search saved'; 
		// searchForm = 'Hello';
		// GLog.write('searchForm is: ' + searchForm)
	} else if (nosave == 'true') {
		//GLog.write('nosave is (formlayout): ' + nosave);
	} else {
	var searchForm = 
		'<form>'
		+ '<input type="text" name="searchName" id="searchName" size="15">'
		+ '<input type="button" value="Save" onclick="saveSearch();">'
		+ '</form>'
	;
	}
	return searchForm;
// #if($pager.results.size()>0 && !$nosave)
//    <p>$msg.get("text.search.save.instructions")</p>
//    <div id="formbox"><form METHOD="GET" action="$link.setAction("saveSearch")" >
//            ## add extra parameter for radius search
//        #if($isRadiusSearch)
//        <input type="hidden" name="neighborhood" value="true">
//        #end
//    <FIELDSET><LEGEND class="borderl">$msg.get("text.save.search"):</LEGEND>
//    <div class="frmrowsave"><span class="frmcolsave">$msg.get("label.savesearch.name"):
//    <input type="text" name="searchName" size="15"  class="fmreq">&nbsp;&nbsp;&nbsp;
//    <input type="submit" value="$msg.get("label.save")"  class="submt2"></span></div>
//    </FIELDSET> </form></div>
// #end

}

function showCreateAccount(prevPage) {
	var createCustURL = 'createCustomer.do?map=true';
	if(null != prevPage && "" != prevPage){
		createCustURL += "&previous_page=" + escape(prevPage);
	}
		
	var form = "";
	var request = GXmlHttp.create();
	request.open('GET',createCustURL, true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			form = request.responseText;
			// GLog.write(form);
			updateFeedback('savedsearch-content', form);
		}
	}
	request.send(null);
} // showCreateAccount 
 
function createCustomerCommit(prevPage) {
	var request = GXmlHttp.create();
	var ccurl = 'createCustomerCommit.do'
		+ '?'
		+ "map=true"
		+ '&emailAddress=' + document.getElementById("cc-emailAddress").value
		+ '&password=' + document.getElementById("cc-password").value
		+ '&password2=' + document.getElementById("cc-password2").value
		+ '&first=' + document.getElementById("cc-first").value
		//+ '&middle=' + document.getElementById("cc-middle").value
		+ '&last=' + document.getElementById("cc-last").value
		+ '&address1=' + document.getElementById("cc-address1").value
		+ '&address2=' + document.getElementById("cc-address2").value
		+ '&city=' + document.getElementById("cc-city").value
		+ '&state=' + document.getElementById("cc-state").value
		+ '&zip=' + document.getElementById("cc-zip").value
		//+ '&zipPlusFour=' + document.getElementById("cc-zipPlusFour").value
		+ '&home=' + document.getElementById("cc-home").value
		+ '&fax=' + document.getElementById("cc-fax").value
		+ '&cell=' + document.getElementById("cc-cell").value
		;
		
		if(null != prevPage && "" != prevPage){
			ccurl += "&previous_page=" + prevPage;
		}
		
	var request = GXmlHttp.create();
	request.open('GET', ccurl, true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			//GLog.write(request.responseText);
			updateFeedback('savedsearch-content', request.responseText);
		}
	}
	request.send(null);
}



function readCookie(name) {
	// this is set up to read and parse the 'searchParams' cookie and will only work with that cookie
	// if in the future we have other cookins fomated the same way we could use this function
	//GLog.write( "got to function readCookie" );
	var cvalue = '';
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) {
			//return c.substring(nameEQ.length,c.length);
			cvalue = c.substring(nameEQ.length,c.length);
		}
		for (i=0;i < cvalue.split('&').length;i++) { // split up each pair
			if (cvalue.split('&')[i]) { //this prevents additional emty value if cookie ends in &
				//GLog.write( '|' + cvalue.split('&')[i] + '|' );
				//GLog.write( "key is: " + cvalue.split('&')[i].split('=')[0] + " - value is: " + unescape(cvalue.split('&')[i].split('=')[1]));
				var key = cvalue.split('&')[i].split('=')[0];
				//GLog.write( "key is: " + key );
				var value = unescape(cvalue.split('&')[i].split('=')[1]);
				//GLog.write( "value is: " + value );
				searchParamsCookie[key] = value;
				// if lists of values like the city names need to be parsed as well it could be done like this (untested):
				// if ( unescape(cvalue.split('&')[i].split('=')[1] == 'city') {
				// 	for ((i=0;i < unescape(cvalue.split('&')[i].split('=')[1].split('=')).length;i++) { 
				//		GLog.write( "single city code is:"  + unescape(cvalue.split('&')[i].split('=')[1].split('='))[i] );
				//	}
				// }
				
			}
		}
		
	}
	return null;
}




