// JavaScript Document
var globalSearchString = '';
var formSearchFields = Array();
var home_data;
var removedItems = new Array();

formSearchFields.push('price_min');
formSearchFields.push('price_max');
formSearchFields.push('beds');
formSearchFields.push('baths');
formSearchFields.push('city');
formSearchFields.push('state');
formSearchFields.push('PostalCode');
formSearchFields.push('acres');
formSearchFields.push('neighborhood');
formSearchFields.push('offset');
formSearchFields.push('condo');
formSearchFields.push('townhouse');
formSearchFields.push('single_fam');
formSearchFields.push('c_0');
formSearchFields.push('c_1');
formSearchFields.push('c_2');
formSearchFields.push('c_3');
formSearchFields.push('c_4');
formSearchFields.push('c_5');
formSearchFields.push('c_6');
formSearchFields.push('c_7');
formSearchFields.push('c_8');
formSearchFields.push('c_9');
formSearchFields.push('c_10');
formSearchFields.push('c_11');
formSearchFields.push('c_12');
formSearchFields.push('c_13');
formSearchFields.push('c_14');
formSearchFields.push('c_15');
formSearchFields.push('c_16');
formSearchFields.push('c_17');
formSearchFields.push('c_18');
formSearchFields.push('c_19');
formSearchFields.push('c_20');
formSearchFields.push('c_21');
formSearchFields.push('c_22');
formSearchFields.push('c_23');
formSearchFields.push('c_24');
formSearchFields.push('c_25');
formSearchFields.push('c_26');
formSearchFields.push('c_27');
formSearchFields.push('c_28');
formSearchFields.push('c_29');
formSearchFields.push('c_30');
formSearchFields.push('built_start');
formSearchFields.push('built_end');
formSearchFields.push('street');
formSearchFields.push('StreetDirSuffix');
formSearchFields.push('garage');
formSearchFields.push('market_from');
formSearchFields.push('market_more');
formSearchFields.push('elevator');
formSearchFields.push('basement');
formSearchFields.push('hoafee');
formSearchFields.push('fireplace');
formSearchFields.push('hs_dist');
formSearchFields.push('ms_dist');
formSearchFields.push('es_dist');
formSearchFields.push('sort_order');
formSearchFields.push('sort_asc_desc');
formSearchFields.push('display_type');
formSearchFields.push('exactBeds');
formSearchFields.push('exactBaths');
formSearchFields.push('per_page');
formSearchFields.push('newConstruction');
formSearchFields.push('walkoutBasement');
formSearchFields.push('fsqf');
formSearchFields.push('publicComments');
formSearchFields.push('fixerUpper');
formSearchFields.push('MLS');
formSearchFields.push('asIsCondition');
formSearchFields.push('fixerUpper');
formSearchFields.push('needsWork');
formSearchFields.push('shell');
formSearchFields.push('rehab');
formSearchFields.push('toBeBuilt');
formSearchFields.push('underConstruction');
formSearchFields.push('busStop');
formSearchFields.push('metroStation');
formSearchFields.push('commRail');
formSearchFields.push('metroRemarks');
formSearchFields.push('priceDrop');


formSearchFields.push('downpayment');
formSearchFields.push('interestrate');
formSearchFields.push('monthly_min');
formSearchFields.push('monthly_max');
formSearchFields.push('home_price_monthly_switch');

formSearchFields.push('removeItemsField');

formSearchFields.push('foreclosures');

var current_page = 1;


if (document.layers)
    document.captureEvents(Event.KEYPRESS);
  document.onkeypress = function (evt) {
    var keyCode = window.event ? event.keyCode :
                  evt.which ? evt.which :
                  evt.keyCode ? evt.keyCode :
                  evt.charCode;
   if (keyCode == 13) {
     updateNum();
     citiesSuggest();
     uListings();
     return false;
   }
   else
     return true;
  }; 


function inArray(needle, haystack)
{
for (h in haystack) {
if (haystack[h] == needle) {
return true;
// return h;

}
}

return false;
} 


function readonlyCityState() {
  $("city").disabled = true;
  $("state").disabled = true;
  $("unlockCityState").style.display = "inline";
}

function editCityState() {

  Element.hide("suggestCities");
  
  $("city").disabled = false;
  $("state").disabled = false;

  $("city").value = '';
  $("state").value = 'n/a';

  $("unlockCityState").style.display = "none";

  for (var i=0; i<30; i++) {
    var cityFieldName = "c_" + i;
    $(cityFieldName).checked = false;
  }

}

function showCities(req) {
	$('showCities').innerHTML = req.responseText;
}

function showNumCity(req) {
	if ($("city").value == '') {
		Element.hide('suggestCities');
	}
	else {
		Element.show('suggestCities');
		$('nCity').innerHTML = req.responseText;
	}
}


function showListings(req) {

	setTimeout("new Element.scrollTo('results_anchor')",1000);
//	document.location.hash = 'results_anchor';

	var outputData = '';

	if ($F('display_type') == 'compact') {

		home_data = req.responseText.parseJSON();

		num_only = home_data[0];

		for (var i=1; i<home_data.length; i++) {
			
			var divClassName = '';
                        
			if (i%2) 
				divClassName = 'compactResultLight';

			else
			
				divClassName = 'compactResultDark';
				
			if (home_data[i]['ListingStatus'] == 'Pending')
				divClassName = 'compactResultGray';
				
    			outputData += '<div id="' + home_data[i]['ListingID'] + '_compact_container" class="' + divClassName +'">';
    			outputData += '<div style="float: left;">';


			outputData += '<a id="' +  home_data[i]['ListingID'] + '_hash"</a><a class="thumbnail" onClick="showCompactDetails(\'' + home_data[i]['ListingID'] + '\', document.getElementById(\'' + home_data[i]['ListingID'] + '_details\'));"><img src="' + home_data[i]['img_url'] + '" width="25px" height="25px" /><span><img src="' + home_data[i]['img_url'] + '" style="border-width: 2px;" /></span></a>';

outputData += '</div>';

    			outputData += '<div style="float: left">';

			if (home_data[i]['ListingStatus'] == 'Pending') {
				outputData += '<font style="font-weight: bold;">This property is no longer active and is currently</font> <font style="font-weight: bold; color:#AC2248;">under contract</font><br>'
			}
				
    	 		outputData += home_data[i]['ListPrice'] + ' - <font style="font-weight: bold; color:#AC2248;">' + home_data[i]['addy'] + ', ' + home_data[i]['city'] + ', ' + home_data[i]['state'] + ', ' + home_data[i]['PostalCode'] + '</font> <b>MLS#: </b>' + home_data[i]['ListingID'] + ' <b>Lot: </b>' + home_data[i]['LotAreaAcre'] + ' acre';

    outputData += '<br><b>Beds: </b>' + home_data[i]['Beds'] +', <b>Baths:</b> ' + home_data[i]['Baths'] +', <b>Listing Office:</b> ' + home_data[i]['ListOffice'] + ' <b>Sq. Ft: </b>' + home_data[i]['LivingArea'] 
    + '</div>'

    + '<div style="text-align: right">'
    + '<a href="javascript:;" class="compact_link" onClick="showCompactDetails(\'' + home_data[i]['ListingID'] + '\', this);" id="' + home_data[i]['ListingID'] + '_details">More Details &nbsp;<img src="/assets/images/more_details_icon.gif"></a>'
	+ '<br>';
	
	if (inArray(home_data[i]['ListingID'], removedItems)) {
		outputData += '<a class="compact_link" href="javascript:;" onClick="removeRestore(\'' + home_data[i]['ListingID'] + '\', this);" id="' + home_data[i]['ListingID'] + '_remove">Restore To List &nbsp;<img src="/assets/images/restore_icon.gif"></a>'
	}
	
	else {
		outputData += '<a class="compact_link" href="javascript:;" onClick="removeRestore(\'' + home_data[i]['ListingID'] + '\', this);" id="' + home_data[i]['ListingID'] + '_remove">Remove From List &nbsp;<img src="/assets/images/remove_from_list_icon.gif"></a>'
	}

    outputData += '</div>';

    outputData += '<div class="clear"></div>';

    outputData += '<div style="display: none; margin-top: 10px;" id="' + home_data[i]['ListingID'] + '_container">'

        + '<div style="text-align: center" id="' + home_data[i]['ListingID'] + '_working"></div>'

    + '</div>'

    + '<div style="display: none" id="contactInfo_' + home_data[i]['ListingID'] +'>'
      + '<p style="text-align:center">';

    outputData += '</div>'
    + '</div>';

		}

        outputData += '<div style="margin-top: 5px;text-align: right;">';

	if (current_page > 1) {
		outputData += '<img src="assets/images/arrow_left.gif" /> <a href="javascript: navigate(0, 0);">Previous</a>&nbsp;';
	}
				var i = current_page -2;
				var shown = 0;
				
				var per_page = $('per_page').value;

				var total_pages = (num_only/per_page) + 0;

				while (shown < 5) {
						var where_to = current_page - i;
						if (i == current_page) {
							outputData += i + '&nbsp;';
							shown++;
							i++;
						}
						else if (i > 0) {
							if (per_page * (i-1) < num_only) 
								outputData += '<a onClick="topage(' + i + ');">' + i + '</a>&nbsp;';
							shown++;
							i++;
						}
						else {
							i++;
						}
				}

        if (current_page < total_pages) 
		outputData += '&nbsp;&nbsp;<a href="javascript: navigate(1, 0);">Next</a> <img src="assets/images/arrow_right.gif" /></div>';

	$('listingsResults').innerHTML = outputData;

	}

	else {
		$('listingsResults').innerHTML = req.responseText;
	}


	fullurl = document.URL;
	
//		if ($F("MLS") != '') {
		if (fullurl.indexOf("?search=")!=-1) {
			var ListingId = home_data[1]['ListingID'];
			var ListingDiv = ListingId + '_details';
			showCompactDetails(ListingId, document.getElementById(ListingDiv));
		}

}

function updateNum() {

	function done(t) {
		 new Effect.Highlight('num',{ duration:3.5, startcolor:'#ffff99', endcolor:'#ffffff', restorecolor:'#ffffff'});
	}

	var searchString = 'placeholder=1';

	formSearchFields.each(function(value) {
		searchString += "&" + value + "=" + escapeplus($F(value));
	});


	Element.show('count');	

	$('num').innerHTML = 'OK hold on a second...<br>I\'m checking how many homes match your search criteria.';

	var switchNum;
	if ($F("price_min") == 'n/a' && $F("price_max") == 'n/a' && $F("beds") == '0' && $F("baths") == '1' && $F("city") == '' && $F("state") == 'n/a') {
		switchNum = 0;
	} else {
		switchNum = 1;
	}

	searchString += "&switch=" + switchNum;
	searchString += "&display_type=count";

	new Ajax.Updater(
      		    'num',
				'/common/php/ajax/update.listings.results.php',
				{
					hronous:true,
					frequency:1,
			  		method:'post',
					postBody: searchString,
					onComplete: done
				});
}

function updateCities() {

		var switchNum = 1;
if ($F("state") != "n/a") {
		new Ajax.Updater(
      		    'showCities',
				'/common/php/ajax/update.show.cities.php',
				{
					hronous:true,
					frequency:1,
			  		method:'post',
					postBody:'price_min=' + $F("price_min") + '&price_max=' + $F("price_max") + '&beds=' + $F("beds") + '&baths=' + $F("baths") + '&city=' + $F("city") + '&state=' + $F("state") + '&acres=' + $F("acres") + '&neighborhood=' + $F("neighborhood") + '&switch=' + switchNum + '&condo=' + $F("condo") + '&townhouse=' + $F("townhouse") + '&single_fam=' + $F("single_fam") + '&c_0=' + $F("c_0") + '&c_1=' + $F("c_1") + '&c_2=' + $F("c_2") + '&c_3=' + $F("c_3") + '&c_4=' + $F("c_4") + '&c_5=' + $F("c_5") + '&c_6=' + $F("c_6") + '&c_7=' + $F("c_7") + '&c_8=' + $F("c_8") + '&c_9=' + $F("c_9") + '&c_10=' + $F("c_10") + '&c_11=' + $F("c_11") + '&c_12=' + $F("c_12") + '&c_13=' + $F("c_13") + '&c_14=' + $F("c_14") + '&c_15=' + $F("c_15") + '&c_16=' + $F("c_16") + '&c_17=' + $F("c_17") + '&c_18=' + $F("c_18") + '&c_19=' + $F("c_19") + '&c_20=' + $F("c_20") + '&c_21=' + $F("c_21") + '&c_22=' + $F("c_22") + '&c_23=' + $F("c_23") + '&c_24=' + $F("c_24") + '&c_25=' + $F("c_25") + '&c_26=' + $F("c_26") + '&c_27=' + $F("c_27") + '&c_28=' + $F("c_28") + '&c_29=' + $F("c_29") + '&c_30=' + $F("c_30") + '&built_start=' + $F("built_start") + '&built_end=' + $F("built_end") + '&street=' + $F("street") + '&StreetDirSuffix=' + $F("StreetDirSuffix") + '&garage=' + $F("garage") + '&market_from=' + $F("market_from") + '&market_more=' + $F("market_more") + '&foreclosures=' + $F("foreclosures") + '&elevator=' + $F("elevator") + '&basement=' + $F("basement") + '&hoafee=' + $F("hoafee") + '&fireplace=' + $F("fireplace") + '&hs_dist=' + $F("hs_dist") + '&ms_dist=' + $F("ms_dist") + '&es_dist=' + $F("es_dist") + "&exactBeds=" + $F("exactBeds") + "&exactBaths=" + $F("exactBaths") + "&home_price_monthly_switch=" + $F("home_price_monthly_switch") + "&downpayment=" + $F("downpayment") + "&interestrate=" + $F("interestrate") + "&monthly_min=" + $F("monthly_min") + "&monthly_max=" + $F("monthly_max"),  
					onComplete:showCities
				});
}
}

function updateNumCities() {
		var switchNum = 1;
if ($F("state") != "n/a") {
		new Ajax.Updater(
      		    'nCity',
				'/common/php/ajax/update.num.cities.php',
				{
					hronous:true,
					frequency:1,
			  		method:'post',
					postBody:'price_min=' + $F("price_min") + '&price_max=' + $F("price_max") + '&beds=' + $F("beds") + '&baths=' + $F("baths") + '&state=' + $F("state") + '&PostalCode=' + $F("PostalCode") + '&acres=' + $F("acres") + '&neighborhood=' + $F("neighborhood") + '&switch=' + switchNum + '&city=' + $F("city") + '&condo=' + $F("condo") + '&townhouse=' + $F("townhouse") + '&single_fam=' + $F("single_fam") + "&home_price_monthly_switch=" + $F("home_price_monthly_switch") + "&downpayment=" + $F("downpayment") + "&interestrate=" + $F("interestrate") + "&monthly_min=" + $F("monthly_min") + "&monthly_max=" + $F("monthly_max"),
					onComplete:showNumCity
				});
}
}

function getMLSnumbers() {
	//submit the form, display the results in a popup

	Element.show('MLS_list_working');

	var searchString = globalSearchString;
	
	new Ajax.Request("/common/php/ajax/update.listings.results.php", {
	 onSuccess : function(resp) {
		var  disp_setting="toolbar=yes,location=no,directories=yes,menubar=yes,";
		disp_setting+="scrollbars=yes,width=650, height=600";
		var docprint=window.open("","",disp_setting); 
		docprint.document.write(resp.responseText);
		docprint.document.close(); 		
		Element.hide('MLS_list_working');
	},
	 onFailure : function(resp) {
	   alert("Oops, there's been an error.");
	 },
	 parameters : searchString + "&MLS_List=1"
	});
	
}



function loadDirectSearch(id) {

	post_params = "id=" + id;

  new Ajax.Request("/common/php/ajax/load.direct.search.php", {
  onSuccess : function(resp) {  

	var jsonData = eval('(' + resp.responseText + ')');

	$('price_min').value = jsonData['price_min'];
	$('price_max').value = jsonData['price_max'];
	$('beds').value = jsonData['beds'];
	$('baths').value = jsonData['baths'];	
	$('state').value = jsonData['state'];	
	
	if (jsonData['city'])
		$('city').value = jsonData['city'];	

	if (jsonData['PostalCode'])
		$('PostalCode').value = jsonData['PostalCode'];	

	if (jsonData['MLS'])
		$('MLS').value = jsonData['MLS'];	

	if (jsonData['condo'] == 'condo')
		$('condo').checked = true;

	else
		$('condo').checked = false;	

	if (jsonData['townhouse'] == 'townhouse')
		$('townhouse').checked = true;

	else
		$('townhouse').checked = false;	

	if (jsonData['single_fam'] == 'single fam')
		$('single_fam').checked = true;

	else
		$('single_fam').checked = false;

	if (jsonData['publicComments'])
		$('publicComments').value = jsonData['publicComments'];


	$('fireplace').value = jsonData['fireplace'];
	$('acres').value = jsonData['acres'];
	$('garage').value = jsonData['garage'];
	$('built_start').value = jsonData['built_start'];
	$('built_end').value = jsonData['built_end'];
	$('hoafee').value = jsonData['hoafee'];	
	$('fsqf').value = jsonData['fsqf'];	

	if (jsonData['basement'] != "undefined")
		$('basement').checked = true;
	else
		$('basement').checked = false;	
		
	if (jsonData['walkoutBasement'] != "undefined")
		$('walkoutBasement').checked = true;
	else
		$('walkoutBasement').checked = false;
		
	if (jsonData['elevator'] != "undefined")
		$('elevator').checked = true;
	else
		$('elevator').checked = false;	

	if (jsonData['exactBeds'] != "undefined")
		$('exactBeds').checked = true;
	else
		$('exactBeds').checked = false;	

	if (jsonData['exactBaths'] != "undefined")
		$('exactBaths').checked = true;
	else
		$('exactBaths').checked = false;	
		

	if (jsonData['neighborhood'])
		$('neighborhood').value = jsonData['neighborhood'];

	if (jsonData['street'])
		$('street').value = jsonData['street'];
		
	if (jsonData['StreetDirSuffix'])
		$('StreetDirSuffix').value = jsonData['StreetDirSuffix'];		


	if (jsonData['hs_dist'])
		$('hs_dist').value = jsonData['hs_dist'];

	if (jsonData['ms_dist'])
		$('ms_dist').value = jsonData['ms_dist'];

	if (jsonData['es_dist'])
		$('es_dist').value = jsonData['es_dist'];
		
	
	['busStop', 'metroStation', 'commRail', 'metroRemarks', 'foreclosures'].each(function(value) {
		if (jsonData[value] != "undefined")
			$(value).checked = true;
		else
			$(value).checked = false;
	});

	
	$('priceDrop').value = jsonData['priceDrop'];
	$('market_from').value = jsonData['market_from'];
	$('market_more').value = jsonData['market_more'];

	['toBeBuilt', 'underConstruction', 'newConstruction', 'asIsCondition', 'fixerUpper', 'needsWork', 'shell', 'rehab'].each(function(value) {
		if (jsonData[value] != "undefined")
			$(value).checked = true;
		else
			$(value).checked = false;
	});
	
	
	$('removeItemsField').value = jsonData['removed_items'];
	
	
		updateNumCities();
		citiesSuggest();
		readonlyCityState();
		updateNum();
		uListings();

},
 onFailure : function(resp) {
   alert("Oops, there's been an error.");
 },
 parameters : post_params 
});


}


function escapeplus( str ){
	var tmp = escape( str );
        return tmp.replace( /\+/g, '%2B' );
}


function updateListings() {


var searchString = 'placeholder=1';

formSearchFields.each(function(value) {
	if ($F(value) != '')
		searchString += "&" + value + "=" + escapeplus($F(value));

});

globalSearchString = searchString;

		$('listingsResults').innerHTML = '<center><br><br>Please Wait - It is a lot of work to compile all this data!<br><br><img src="/assets/images/indicator_medium.gif">';	
		switchNum = 1;

new Ajax.Request("/common/php/ajax/update.listings.results.php", {
 onSuccess : function(resp) {
   showListings(resp);
 },
 onFailure : function(resp) {
   alert("Oops, there's been an error.");
 },
 parameters : searchString 
});



}

function citiesSuggest() {
    c = $F('city');
    s = $F('state');
    z = $F('PostalCode');

	if ((s != 'n/a' ) || (z != '')){
		Effect.BlindDown('suggestCities', { duration: 1.0 });
		Effect.Appear('suggestCities', { duration: 3.0 });
		updateNumCities();
		city = $F("city");
		updateCities();
	}

}

function uListings () {
	
	document.getElementById("submitButton").value = "Update the List of Matching Homes"; 
	document.forms.searchForm.offset.value == 0;

		new Effect.BlindDown('results', { duration: 1.0 });
		new Effect.Appear('listingsResults', { duration: 5.0 });
		updateListings();

		setTimeout("new Element.scrollTo('results_anchor')",1000);
		
		
}

function updateHidden(txt, li) {
    hiddenName = txt.name.replace("_","");
    id = li.id.replace("auto_","");
}



function navigate(direction, page_num) {
	var form = document.forms.searchForm;
	var offset = form.offset;

	var per_page = $F("per_page");

	if(direction == 0) {
		offset.value = offset.value - (per_page * 1);
		current_page -= 1;
	} else if(direction == 1) {
		offset.value = (offset.value * 1) + (per_page * 1);
		current_page += 1;
	} else if(direction == -1) {
		offset.value = (page_num * per_page) - (per_page * 1);
	}
	updateListings();
  }


function topage(page_num) {

	var form = document.forms.searchForm;
	var offset = form.offset;
	var per_page = $F("per_page");
	offset.value = (page_num * per_page) - (per_page * 1);
	current_page = page_num;
	updateListings();

}

  
function dis(id,id_2) {
		new Effect.Appear(id);
	document.getElementById(id_2).style.display = 'none';
}



function switchCompactTab(ListingID, section, clicked_tab) {

	var tab_div_id = ListingID + '_compact_tab_current';
        var switch_tab_div_id = ListingID + '_' + section;
	$(tab_div_id).innerHTML = $(switch_tab_div_id).innerHTML;
	tabmenu_id = ListingID + '_tabmenu';

        var children = $(tabmenu_id).childNodes;

   	for (var i = 0; i < children.length; i++) 
   	{
     		children[i].className = 'inactive';
   	}
	
	$(clicked_tab).className = 'active';
}


function punctuated(n){
	var s=(''+n).split('.');
	s[0]=s[0].split('').reverse().join('').match(/\d{1,3}/gi).join(',').split('').reverse().join('');
	return(s.join('.'));
}


function showCompactDetails(ListingID, linkObj) {
	var containerName = ListingID + '_container';
	var workingContainerName = ListingID + '_working';
	
	new Element.scrollTo(ListingID + '_hash');

	document.getElementById(containerName).innerHTML = '<center><img src="/assets/images/indicator_small.gif"></center>';

	if (!(Element.visible(containerName))) {
	  new Ajax.Updater(
      	  containerName,
	  'common/php/ajax/update.compact.listings.details.php',
	  {
	  asynchronous:true,
	  frequency:1,
	  method:'post',
	  postBody:'ListingID=' + ListingID,
	  evalScripts:true, 
	  onComplete: Element.show(containerName) 
				});
	  linkObj.innerHTML = 'Hide &nbsp;<img src="/assets/images/hide_details_icon.gif">';
        }
      else {
        Element.hide(containerName);
	linkObj.innerHTML = 'More Details &nbsp;<img src="/assets/images/more_details_icon.gif">';
        }
}


/*var geocoder = new GClientGeocoder();

function createMarker(point, text) {
  var marker = new GMarker(point);
  GEvent.addListener(marker, "click", function() {
	marker.openInfoWindowHtml(text);
  });
  return marker;
}*/

function showAddress(address, theMap, id) {
  var dirText;
  geocoder.getLatLng(
    address,
    function(point) {
	theMap.addOverlay(createMarker(point, (dirText)));	
	 GDownloadUrl("/common/php/ajax/map.popup.php?id=" + id, function(data, responseCode) {
		dirText = data;	
		theMap.addOverlay(createMarker(point, (dirText)));		
	});
    }
  );
}

function showNearby(map, current) {
	var bounds = new GLatLngBounds();
	for (var i=1; i<home_data.length; i++) {
		if (home_data[i]['Latitude'] > 35) {
		var point = new GLatLng(home_data[i]['Latitude'], home_data[i]['Longitude']);
		bounds.extend(point);				
		if (home_data[i]['ListingID'] != current) {
			map.addOverlay(createMarker(point, home_data[i]['popupHTML']));	
		}
		}
	}
	map.setCenter(bounds.getCenter());
	map.setZoom(map.getBoundsZoomLevel(bounds));
}


/*function showGoogleMap(ListingID, address) {
    var containerName = ListingID + '_compact_tab_current';
    var newMapContainerName = ListingID + '_google_map';
    $(containerName).innerHTML = '<div id="' + newMapContainerName + '" style="height: 300px; width: 400px;"></div>';
    var map = new GMap2(document.getElementById(newMapContainerName));
    map.addControl(new GSmallMapControl());
    //alert('hello');
    //showAddress(address, map);
}*/


function exactBedsClicked() {
  var bedOptions = $('beds').options;

  if ($('exactBeds').checked) {
    for (var i=0; i<bedOptions.length; i++ ) {
      bedOptions[i].text = bedOptions[i].text.replace(/\+/g,"");
    }
  }

  else {
    for (var i=0; i<bedOptions.length; i++ ) {
      bedOptions[i].text = bedOptions[i].text.replace(/\+/g,"");
      bedOptions[i].text += "+";
    }
  }
}


function exactBathsClicked() {
  var bathOptions = $('baths').options;
  if ($('exactBaths').checked) {
    for (var i=0; i<bathOptions.length; i++ ) {
      bathOptions[i].text = bathOptions[i].text.replace(/\+/g,"");
    }
  }

  else {
    for (var i=0; i<bathOptions.length; i++ ) {
      bathOptions[i].text = bathOptions[i].text.replace(/\+/g,"");
      bathOptions[i].text += "+";
    }
  }
}

function pageLoad() {
  new Ajax.Autocompleter("ms_dist", "msd_choices", "/common/php/ajax/auto.complete.ms.php", {});
  new Ajax.Autocompleter("es_dist", "est_choices", "/common/php/ajax/auto.complete.elem.php", {});
  new Ajax.Autocompleter("hs_dist", "hsd_choices", "/common/php/ajax/auto.complete.hs.php", {});

  preload_image = new Image(25,25); 
  preload_image.src="/assets/images/indicator_small.gif"; 

  editCityState();

  if (GetCookie('email') == '') {
        $('meetAudrey').innerHTML = '<b><a onClick="showAudreyLogin();"></a><a onClick="showAudreyLogin();">Meet Audrey, your virtual real estate assistant! She can help you find your next home.</a></b>';
  }
  
  else {
			loadMeetAudrey(GetCookie('email'));
  }

	switch_home_price_monthly();

}


function AudreyLogout() {
        $('meetAudrey').innerHTML = '<b><a onClick="showAudreyLogin();"></a><a onClick="showAudreyLogin();">Meet Audrey, your virtual real estate assistant! She can help you find your next home.</a></b>';
  var exp = new Date();
  exp.setTime(exp.getTime() + (30*24*60*60*1000));
  SetCookie("email","",exp);
	showAudreyLogin();
}


function AudreyLogin(name,email,phone) {

  post_params = 'email=' + email + '&name=' + name + '&phone=' + phone;

  new Ajax.Request("/common/php/ajax/audrey.login.php", {
  onSuccess : function(resp) {
    $('AUDREY_login').innerHTML = resp.responseText;
		if (!(resp.responseText.match("Sorry"))) {
    	var exp = new Date();
    	exp.setTime(exp.getTime() + (30*24*60*60*1000));
	if (email != '') {
    		SetCookie("email",email,exp);
		loadMeetAudrey(email);
	}
		}
 },
 onFailure : function(resp) {
   alert("Oops, there's been an error.");
 },
 parameters : post_params
});

}


function switchThumb(ListingID, src) {
  var img_cont_name = 'compact_img_' + ListingID;
  $(img_cont_name).src = src;
}

function switchAdvSearchTab(id) {

	$('advSearch_property_tab_content').style.display = 'none';
	$('advSearch_neighborhood_tab_content').style.display = 'none';
	$('advSearch_schools_tab_content').style.display = 'none';
	$('advSearch_metro_tab_content').style.display = 'none';
	$('advSearch_bargain_tab_content').style.display = 'none';

	$('advSearch_property_tab').className = 'inactive';
	$('advSearch_neighborhood_tab').className = 'inactive';
	$('advSearch_schools_tab').className = 'inactive';
	$('advSearch_metro_tab').className = 'inactive';
	$('advSearch_bargain_tab').className = 'inactive';

	$(id).className = 'active';

	var toSwitch = id + '_content';
	$(toSwitch).style.display = 'block';
}

function showVirtualTour(ListingID, url, linkObj) {
	var tourDivID = 'VirtualTour_' + ListingID;
	if (!(Element.visible(tourDivID))) { 
		Element.show(tourDivID);
		$(tourDivID).src = url;
		linkObj.innerHTML = 'Hide Virtual Tour';
	}
	else {
		Element.hide(tourDivID);
		linkObj.innerHTML = 'Take a Virtual Tour';
	}
}



function clearSearchCriteria() {

	$("publicComments").value = ''
	$("fireplace").value = '0';	
	$("built_start").value = '1900';	
	$("built_end").value = '2007';	
	$("acres").value = '0';	
	$("hoafee").value = 'n/a';	
	$("garage").value = '0';	
	$("fsqf").value = '0';	
	$("basement").checked = false;
	$("walkoutBasement").checked = false;
	$("elevator").checked = false;
	$("exactBeds").checked = false;
	$("exactBaths").checked = false;

	$("price_min").value = 'n/a';
	$("price_max").value = 'n/a';
	$("baths").value = '1';
	$("beds").value = '1';
	$("condo").checked = true;
	$("townhouse").checked = true;
	$("single_fam").checked = true;
	$("city").value = '';
	$("state").value = 'n/a';
	$("PostalCode").value = '';
	$("MLS").value = '';
	$("monthly_min").value = 'n/a';
	$("monthly_max").value = 'n/a';

	$("neighborhood").value = '';
	$("street").value = '';
	$("StreetDirSuffix").value = '0';
	

	$("hs_dist").value = '';
	$("ms_dist").value = '';
	$("es_dist").value = '';

	$("busStop").checked = false;
	$("metroStation").checked = false;
	$("commRail").checked = false;
	$("metroRemarks").checked = false;

	$("priceDrop").value = '';
	$("market_from").value = '0';
	$("market_more").value = '5000';
	$("foreclosures").checked = false;
	$("toBeBuilt").checked = false;
	$("underConstruction").checked = false;
	$("newConstruction").checked = false;
	$("asIsCondition").checked = false;
	$("fixerUpper").checked = false;
	$("needsWork").checked = false;
	$("shell").checked = false;
	$("rehab").checked = false;

	editCityState();

}


function loadMeetAudrey(email) {

	post_params = 'email=' + email + '&fn=name';

  new Ajax.Request("/common/php/ajax/audrey.fns.php", {
    onSuccess : function(resp) {
				name = resp.responseText; 
      $('meetAudrey').innerHTML = '<b><a onClick="showMyAudrey()">Welcome back, ' + name + ' - Click here to view the homes you\'ve ranked for Audrey.</a></b>';
      $('meetAudrey').innerHTML += '<br><a onClick="AudreyLogout();">Not ' + email + '?</a>';
 },

 onFailure : function(resp) {
   alert("Oops, there's been an error.");
 },

 parameters : post_params

});

}



function sendSearchToFriend(sendersname, sendersemail, recsname, recsemail, comments, sendmecopy, id) {

	var expDays = 30;
	var exp = new Date();
	var realtor = '';
	exp.setTime(exp.getTime() + (expDays*24*60*60*1000));
	SetCookie("name", sendersname, exp);
	SetCookie("email", sendersemail, exp);

	post_params = "sendersname=" + sendersname + "&sendersemail=" + sendersemail + "&recsname=" + recsname + "&recsemail=" + recsemail + "&comments=" + comments +  "&sendmecopy=" + sendmecopy + "&id=" + id;
	
  new Ajax.Request("/common/php/ajax/send.search.to.friend.php", {
    onSuccess : function(resp) {
        $('box').innerHTML = '<img id="close" src="/assets/images/close.gif" onclick="hideBox()" alt="Close" title="Close this window" /><br>' + resp.responseText;
 },

 onFailure : function(resp) {
   alert("Oops, there's been an error.");
 },

 parameters : post_params

});
}



function sendPropertyToFriend(sendersname, sendersemail, recsname, recsemail, PropertyID) {

	post_params = 'ListingID=' + PropertyID + "&sendersname=" + sendersname + "&sendersemail=" + sendersemail + "&recsname=" + recsname + "&recsemail=" + recsemail;

  new Ajax.Request("/php/send.property.to.friend.php", {
    onSuccess : function(resp) {
        $('box2').innerHTML = '<div style="height: 30px"><img id="close" src="/close_window_icon.gif" onclick="hidebox2()" alt="Close" title="Close this window" /><br>' + resp.responseText + '</div>';
 },

 onFailure : function(resp) {
   alert("Oops, there's been an error.");
 },

 parameters : post_params

});
}

function SelectAll(id)
{
document.getElementById(id).focus();
document.getElementById(id).select();
}

function showSendSearchResultsToFriend() {

	var saved_search_data;

	hideAllSelects();

	var escaped_string = globalSearchString.replace(/&/g,'^$');
	
	var handlerFunc = function(t) {
		var jsonData = eval('(' + t.responseText + ')');
		$('box').innerHTML = '  <a style="text-decoration: none">>> Email these search results to a friend</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a onClick="hideBox();"><img src="/assets/images/close_window_icon.gif" /></a><br><hr size=1><br /><div id="AUDREY_login">' +
	'<table>' +
	'<tr><td>Your Name:</td><td><input name="sendersname" id="sendersname"></td></tr>' +
	'<tr><td>Your Email:</td><td><input name="sendersemail" id="sendersemail"></td></tr>' +
	'<tr><td>Send me a copy of the email too:</td><td><input type="checkbox" name="sendmecopy" id="sendmecopy"></td></tr>' +
	'<tr><td>Your Friend\'s Name:</td><td><input name="recsname" id="recsname"></td></tr>' +
	'<tr><td>Your Friend\'s Email:</td><td><input name="recsemail" id="recsemail"></td></tr>' +
	'<tr><td>Comments:</td><td><textarea name="comments" id="comments"></textarea></td></tr>' +
	'</table>' +
	'<input onclick="sendSearchToFriend(document.getElementById(\'sendersname\').value,document.getElementById(\'sendersemail\').value,document.getElementById(\'recsname\').value,document.getElementById(\'recsemail\').value,document.getElementById(\'comments\').value, document.getElementById(\'sendmecopy\').checked,' + jsonData['id'] + ');" value="Submit Request" type="button">' +
	'<hr>Here\'s the results link we\'ll be sending: http://tbhse.com/?direct_search=' + jsonData['id'] +
	'<br>Search criteria: ' + jsonData['html'] +
	'<br><a onClick="getMLSnumbers()">View MLS Numbers</a> ' +
	'<img src="/assets/images/indicator_small.gif" style="display: none" id="MLS_list_working">' +
	'</div>' 
		
		$('overlay').show();
		$('box_cont').show();
		center('box_cont');
		$('overlay').style.height = document.body.clientHeight + 'px';
		$('sendersemail').value = GetCookie('email');
		$('sendersname').value = GetCookie('name');	 
	}

  	new Ajax.Request('/common/php/ajax/save.search.php', {parameters:'searchString='+escaped_string+'&removed_items=' + removedItems.toString() + ',' + $("removeItemsField").value, onSuccess:handlerFunc});
	
}



function showSendPropertyToFriend(alink, PropertyID) {
    $('box2').innerHTML = '<a style="text-decoration: none">>> Email this property to a friend</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a onClick="hideBox();"><img src="/close_window_icon.gif" /></a><br><hr size=1><br /><div id="AUDREY_login">' +
'<div id="email_form">' +
'<div class="email_row"><div class="email_left">Your Name: </div><div class="email_right"><input name="sendersname" id="sendersname"></div></div>' +
'<div class="email_row"><div class="email_left">Your Email: </div><div class="email_right"><input name="sendersemail" id="sendersemail"></div></div>' +
'<div class="email_row"><div class="email_left">Your Friend\'s Name: </div><div class="email_right"><input name="recsname" id="recsname"></div></div>' +
'<div class="email_row"><div class="email_left">Your Friend\'s Email: </div><div class="email_right"><input name="recsemail" id="recsemail"></div></div>' +
'</div>' +
'<input onclick="sendPropertyToFriend(document.getElementById(\'sendersname\').value,document.getElementById(\'sendersemail\').value,document.getElementById(\'recsname\').value,document.getElementById(\'recsemail\').value,\'' + PropertyID + '\')" value="Submit Request" type="button">' +
'</div>';
    $('overlay').show();
    $('box2_cont').show();
	$('box2_cont').makePositioned();
	var alinkpos = findPos($(alink));
	center('box2_cont');
	$('box2_cont').style.left = alinkpos[0] + "px";
	$('box2_cont').style.top = alinkpos[1] + "px";
    $('overlay').style.height = document.body.clientHeight + 'px';
    $('sendersemail').value = GetCookie('email');
    $('sendersname').value = GetCookie('name');
}

function showMonthlyPayment(alink, loan) {
    $('box2').innerHTML = 'Based on the following assumptions&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a onClick="hideBox();"><img src="/close_window_icon.gif" /></a><br><hr size=1><br /><div id="AUDREY_login">' +
'<table>' +
'<tr><td>Loan Amount:</td><td>$'+loan+'</td></tr>' +
'<tr><td>Interest Rate:</td><td>6%</td></tr>' +
'<tr><td>Term:</td><td>30 years</td></tr>' +
'</table>' +
'</div>';
    $('overlay').show();
    $('box2_cont').show();
	$('box2_cont').makePositioned();
	var alinkpos = findPos($(alink));
	center('box2_cont');
	$('box2_cont').style.left = alinkpos[0] + "px";
	$('box2_cont').style.top = alinkpos[1] + "px";
  $('overlay').style.height = document.body.clientHeight + 'px';

}


function showAudreyRankBox(ListingID, alink) {
	if (GetCookie('email') == '') {
		showAudreyLogin(alink);
    	return;
	} 
	
    $('box').innerHTML = '<img id="close" src="/assets/images/close.gif" onclick="hideBox()" alt="Close" title="Close this window" />';
	$('box').innerHTML += "<a style=\"text-decoration: none\">>> Welcome to Audrey</a>";
	$('box').innerHTML += "<p>You are ranking homes under the login: " + GetCookie('email') + "</p>";
	$('box').innerHTML += $(ListingID + '_Audrey_rankbox').innerHTML;
    $('overlay').show();
    $('overlay').style.height = document.body.clientHeight + 'px'; 
	$('box_cont').makePositioned();
	center('box_cont');
	var alinkpos = findPos($(alink));
	$('box_cont').style.left = alinkpos[0] + "px";
	$('box_cont').style.top = alinkpos[1] + "px";
	$('box_cont').show();	
}


function showAudrey(ListingID, rank, alink) {

  post_params = 'ListingID=' + ListingID + '&rank=' + rank;

  new Ajax.Request("/common/php/ajax/audrey.rank.home.php", {
  onSuccess : function(resp) {
    $('box').innerHTML = '<img id="close" src="/assets/images/close.gif" onclick="hideBox()" alt="Close" title="Close this window" />' + resp.responseText;
},
 onFailure : function(resp) {
   alert("Oops, there's been an error.");
 },
 parameters : post_params 
});

}


function showAudreyLogin(alink) {
    $('box').innerHTML = '<a style="text-decoration: none">>> We\'d like you to meet Audrey</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a onClick="hideBox();"><img src="/assets/images/close_window_icon.gif" /></a><br><hr size=1><br /><div id="AUDREY_login">' + '<div id="AUDREY_login">Audrey is your virtual assistant, and she\'ll help you find your next home.  But first, you\'ll need to train her. On each listing you can tell Audrey if you Love a home, if it\'s just OK, or if you Hate it. Once Audrey learns the types of homes you like, she will start emailing you similar homes when they are listed on the MLS.  You can just sit back and have Audrey send you listings!  And the more you train her, the more accurate she gets. To have her search for you, just give us your information below. (We don\'t share your information with anyone, and it\'s easy to turn Audrey off if you don\'t want her to send you more homes.)<br><br>' + 
'<table>' +
'<tr><td>Name: (optional)</td><td><input name="name" id="name"></td></tr>' +
'<tr><td>Email:</td><td><input name="email" id="email"></td></tr>' +
'<tr><td>Phone: (optional)</td><td><input name="phone" id="phone"></td></tr>' +
'</table>' +
'<input onclick="AudreyLogin(document.getElementById(\'name\').value,document.getElementById(\'email\').value,document.getElementById(\'phone\').value)" value="Submit Request" type="button"><br><br>' +
'<i>(If you already have an account with us but we haven\'t recognized you, just re-submit your email and we\'ll pull your information up)</i>' + 
'</div>';
    $('overlay').show();
	$('box_cont').makePositioned();
	center('box_cont');
	var alinkpos = findPos($(alink));
	$('box_cont').style.left = alinkpos[0] + "px";
	$('box_cont').style.top = alinkpos[1] + "px";	
	$('box_cont').show();
	$('overlay').style.height = document.body.clientHeight + 'px';
}


function hideMyAudrey() {
	Element.show('meetAudrey');
	Element.hide('audreyContent');
}

function showMyAudrey() {

	hideBox();
	$('audreyContent').innerHTML = '<center><img src="/assets/images/indicator_small.gif"></center>';
	Element.show('audreyContent');
	
	Element.scrollTo('audrey_hash');
	
  post_params = '';

  new Ajax.Request("/common/php/ajax/audrey.status.php", {
  onSuccess : function(resp) {
		Element.hide('meetAudrey');
		Element.show('audreyContent');
    $('audreyContent').innerHTML = resp.responseText + '<p style="text-align: right;"><a onClick="hideMyAudrey()">[hide this section]</a></p>';
    Sortable.create('homes_list', { onUpdate : updateOrder });
 },
 onFailure : function(resp) {
   alert("Oops, there's been an error.");
 },
 parameters : post_params
});

}

function switch_home_price_monthly() {

	if($F("home_price_monthly_switch") == "Home Price") {
		Element.show("home_price_search");
		Element.hide("monthly_mortage_search");
	}

	else if($F("home_price_monthly_switch") == "Monthly Mortgage") {
		Element.hide("home_price_search");
		Element.show("monthly_mortage_search");
	}
}




            function updateOrder()
            { 
                  var love_array = Array();
                  var ok_array = Array();
                  var hate_array = Array();

                  var is_love = false;
                  var is_ok = false;
                  var is_hate = false;

                  var array_size = 0;
								
                 var h_list = document.getElementById("homes_list");                
 
		for(i = 0; i < h_list.childNodes.length; i++ ) {
		
                    for (j = 0; j < h_list.childNodes[i].attributes.length; j++ ) {
                      if(h_list.childNodes[i].attributes[j].nodeName.toLowerCase() == 'id') {

                        var id_val = h_list.childNodes[i].attributes[j].nodeValue;
							
                        if(is_love && id_val != "hate" && id_val != "ok") {
                          array_size = love_array.length;
                          love_array[array_size] = id_val;
                        } else if(is_ok && id_val != "love" && id_val != "hate") {
                          array_size = ok_array.length;
                          ok_array[array_size] = id_val;
                        } else if(is_hate && id_val != "love" && id_val != "ok") {
                          array_size = hate_array.length;
                          hate_array[array_size] = id_val;
                        }
										
		    if(id_val == "love") {
                        is_hate = false;
                        is_love = true;
                        is_ok = false;
                    } else if(id_val == "ok") {
                        is_hate = false;
                        is_love = false;
                        is_ok = true;
                    } else if(id_val == "hate") {
                        is_hate = true;
                        is_love = false;
                        is_ok = false;
                    }
                 }
              }
         }

	var love_string="love_string=";
        var hate_string="hate_string=";
        var ok_string="ok_string=";
        var email="email=";

        for(i = 0; i < love_array.length; i++)
        {
            love_string = love_string + love_array[i]+"-";
        }
         for(i = 0; i < ok_array.length; i++)
        {
            ok_string = ok_string + ok_array[i]+"-";
        }
         for(i = 0; i < hate_array.length; i++)
        {
            hate_string = hate_string + hate_array[i]+"-";
        }
      
        //aler("email:"+email);
 
        email = email + document.getElementById("current_email_address").value;

	var updated_homes_string =love_string+"&"+ok_string+"&"+hate_string+"&"+email;
	//	alert("email:"+email);
        var options = {
                        method : 'post',
                        parameters : updated_homes_string
                       };
							
        new Ajax.Request('/common/php/ajax/processor.php', options);
       }



function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}



function showShowYouProperty(alink, ListingDiv) {
	hideAllSelects();
    $('box2').innerHTML = $(ListingDiv).innerHTML;
    $('overlay').show();
	$('box2_cont').show();
	center('box2_cont');
	$('box2_cont').makePositioned();
	var alinkpos = findPos($(alink));
	$('box2_cont').style.left = alinkpos[0] + "px";
	$('box2_cont').style.top = alinkpos[1] + "px";
$('overlay').style.height = document.body.clientHeight + 'px';
}

function showMakeOffer(alink, ListingDiv, key) {
        hideAllSelects();
    //$('box2').innerHTML = $(ListingDiv).innerHTML;
    $('box2').innerHTML = '<div id="makeOfferInfo_'+key+'" class="makeOfferInfo" style="width: 270px; height: 300px;"><a style="text-decoration: none;">&gt;&gt; Make an Offer on This Property</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a onclick="hidebox2();"><img src="/close_window_icon.gif"></a><hr size="1"><br><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td><form name="form_undefined" action="/submit_form.php" method="post"><table border="0" cellpadding="0" cellspacing="3"><tbody><tr><td width="60" height="26"><b>Name</b></td><td height="26"><input name="name" value="" type="text"></td></tr><tr><td width="60" height="26"><b>Email</b></td><td height="26"><input name="email" value="" type="text"></td></tr><tr><td width="60" height="26" ><b>Phone</b></td> <td height="26"><input name="phone" value="" type="text"></td></tr><tr><td colspan="2"><p style="margin: 0pt; padding: 4pt; color: rgb(0, 0, 0);"><b><input value="0" name="realtor" type="radio">No, I don\'t have a REALTOR<br><input value="1" name="realtor" type="radio">Yes, I have a REALTOR<br><input value="2" name="realtor" type="radio">I am a REALTOR </b></p></td></tr> <tr><td colspan="2"><p style="margin: 0pt; padding: 3pt; color: rgb(0, 0, 0);"><input value="send" name="self_email" onclick="storeEmailStatus(this.form)" checked="checked" type="checkbox">Email me the property details</p></td></tr><tr><td colspan="2" height="26"><p style="margin: 0pt; padding: 5pt; color: rgb(0, 0, 0);"><input name="key" value="'+key+'" type="hidden"><input value="Submit Request" onclick="checkLeadForm(this.form, this.form.elements[\'key\'].value, \'list\')" type="button"></p></td><td align="right"><p style="margin-right: 5px;"></p></td></tr></tbody> </table><table border="0" cellpadding="0" cellspacing="0" width="100%"><tbody><tr><td><div id="div_' + key +'" width="100%"> </div></td></tr></tbody></table></form></td></tr></tbody></table></div><table border="0" cellpadding="0" cellspacing="0" width="100%"><tbody><tr><td><div style="height: 100px" id="div_' + key +'" width="100%"> </div></td></tr></tbody></table></form></td></tr></tbody></table></div>';   
  
    $('overlay').show();
        $('box2_cont').show();
        center('box2_cont');
        $('box2_cont').makePositioned();
        var alinkpos = findPos($(alink));
        $('box2_cont').style.left = alinkpos[0] + "px";
        $('box2_cont').style.top = alinkpos[1] + "px";
$('overlay').style.height = document.body.clientHeight + 'px';
}

function showContactMe(alink, ListingDiv, key) {
        hideAllSelects();
    //$('box2').innerHTML = $(ListingDiv).innerHTML;
    $('box2').innerHTML = '<div id="makeOfferInfo_'+key+'" class="makeOfferInfo" style="width: 270px; height: 300px;"><a style="text-decoration: none;">&gt;&gt; Please have an agent contact me</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a onclick="hidebox2();"><img src="/close_window_icon.gif"></a><hr size="1"><br><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td><form name="form_undefined" action="/submit_form.php" method="post"><table border="0" cellpadding="0" cellspacing="3"><tbody><tr><td width="60" height="26"><b>Name</b></td><td height="26"><input name="name" value="" type="text"></td></tr><tr><td width="60" height="26"><b>Email</b></td><td height="26"><input name="email" value="" type="text"></td></tr><tr><td width="60" height="26" ><b>Phone</b></td> <td height="26"><input name="phone" value="" type="text"></td></tr><tr><td colspan="2"><p style="margin: 0pt; padding: 4pt; color: rgb(0, 0, 0);"><b><input value="0" name="realtor" type="radio" >    No, I don\'t have a REALTOR<br><input value="1" name="realtor" type="radio">    Yes, I have a REALTOR<br><input value="2" name="realtor" type="radio">    I am a REALTOR </b></p></td></tr> <tr><td colspan="2"></td></tr><tr><td colspan="2" height="26"><p style="margin: 0pt; padding: 5pt; color: rgb(0, 0, 0);"><input name="key" value="'+key+'" type="hidden"><input value="Submit Request" onclick="checkLeadForm(this.form, this.form.elements[\'key\'].value, \'list\')" type="button"></p></td><td align="right"><p style="margin-right: 5px;"></p></td></tr></tbody> </table><table border="0" cellpadding="0" cellspacing="0" width="100%"><tbody><tr><td><div id="div_' + key +'" width="100%"> </div></td></tr></tbody></table></form></td></tr></tbody></table></div><table border="0" cellpadding="0" cellspacing="0" width="100%"><tbody><tr><td><div id="div_' + key +'" width="100%"> </div></td></tr></tbody></table></form></td></tr></tbody></table></div>';   
  
    $('overlay').show();
        $('box2_cont').show();
        center('box2_cont');
        $('box2_cont').makePositioned();
        var alinkpos = findPos($(alink));
        $('box2_cont').style.left = alinkpos[0] + "px";
        $('box2_cont').style.top = alinkpos[1] + "px";
$('overlay').style.height = document.body.clientHeight + 'px';
}

function hidebox2() {
    $('box2_cont').hide();
    $('overlay').hide();
    showAllSelects();
    return false;
}


function showNewAddress(map, address, htmlcontent) {

var icon = new GIcon();
icon.image = "/assets/images/iconb.png";
icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
icon.shadowSize = new GSize(22, 20);
icon.iconAnchor = new GPoint(6, 20);
icon.infoWindowAnchor = new GPoint(5, 1);


function showErrorMessage() {
	geocoder.getLatLng(
		'1267 N. Van Dorn St., Suite 100, Alexandria, VA 22304',
		function(point) {
			map.setCenter(point, 8);
			var marker = new GMarker(point, icon);
			map.addOverlay(marker);
			map.openInfoWindow(map.getCenter(),'The Address For This Property Could Not Be Mapped.');
		}
	  );
}
	var point = new GLatLng(40.98, -77.13);
	map.setCenter(point, 4);
        var marker = new GMarker(point, icon);
	map.addOverlay(marker);

/*
geocoder.getLatLng(
    address,
    function(point) {
      if (!point) {
			showErrorMessage();
      } else {
        map.setCenter(point, 9);
        var marker = new GMarker(point, icon);
        map.addOverlay(marker);
		if (htmlcontent != '') 
			map.openInfoWindow(map.getCenter(),htmlcontent);
      }
    }
  );
*/
}


function showMarker(map, htmlcontent) {
	var point = new GLatLng(37.441944, -122.141944);
        var marker = new GMarker(point);
        map.addOverlay(marker);
		if (htmlcontent != '') 
			map.openInfoWindow(map.getCenter(),htmlcontent);
}


function showFullMap(id, address) {
	Element.show('map_' + id);
	var map = new GMap(document.getElementById('map_' + id));
    map.addControl(new GSmallMapControl());
	showNewAddress(map, address, $(id + '_map_popup').innerHTML);	
}








//station overlay code





function Station(name,lat,lng,type){
	this.name = name;
	this.lat = lat;
	this.lng = lng;
	this.stationtype = type;
}
	
function LineNode(name,lat,lng,offset){
	this.name = name;
	this.lat = lat;
	this.lng = lng;
	this.offset = offset;
}

function CreateStationMarker(the_map, name, point, icon){

	var marker = new GMarker(point,icon);

	// Show this marker's index in the info window when it is clicked
	var html = "<DIV CLASS='stationoverlay'><b>" + name + "</b></div>";
	GEvent.addListener(marker, "click", function() {
		the_map.recenterOrPanToLatLng(point);
		marker.openInfoWindowHtml(html);
				});

	return marker;
}

	function DrawStations(the_map){

	var zoomlevel = the_map.getZoomLevel();

	//alert(zoomlevel);

	var normalstationiconurl = "";
	var normalstationiconsize = -1;

	var transferstationiconurl = "";
	var transferstationiconsize = -1;

	if(zoomlevel<=4){
		normalstationiconurl = "ns";
		normalstationiconsize = 18;
		transferstationiconurl = "ts";
		transferstationiconsize = 30;
	}
	else if((zoomlevel==5)||(zoomlevel==6)){
		normalstationiconurl = "ns_smaller";
		normalstationiconsize = 9;
		transferstationiconurl = "ts_smaller";
		transferstationiconsize = 15;
	}
	else if((zoomlevel==7)||(zoomlevel==8)){
		transferstationiconurl = "ts_smallest";
		transferstationiconsize = 9;
		normalstationiconurl = "ns_smallest";
		normalstationiconsize = 5;
	}

	if(navigator.userAgent.toLowerCase().indexOf('msie')==-1){
		transferstationiconurl = '/assets/images/' + transferstationiconurl + '.png';
		normalstationiconurl = '/assets/images/' + normalstationiconurl + '.png';
	}else{
		transferstationiconurl = '/assets/images/' + transferstationiconurl + '.gif';
		normalstationiconurl = '/assets/images/' + normalstationiconurl + '.gif';
	}


	if(normalstationiconsize!=-1){

		var halfnormalstationsize = Math.floor(normalstationiconsize / 2);
		var halftransferstationsize = Math.floor(transferstationiconsize / 2);

		//create the station icons
		var normalStationIcon = new GIcon();
		normalStationIcon.image = normalstationiconurl;
		normalStationIcon.shadow = "images/blank.gif";
		normalStationIcon.iconSize = new GSize(normalstationiconsize,normalstationiconsize);
		normalStationIcon.shadowSize = new GSize(10,10);
		normalStationIcon.iconAnchor = new GPoint(halfnormalstationsize,halfnormalstationsize);
		normalStationIcon.infoWindowAnchor = new GPoint(halfnormalstationsize,halfnormalstationsize);
		normalStationIcon.infoShadowAnchor = new GPoint(0,0);

		var transferStationIcon = new GIcon();
		transferStationIcon.image = transferstationiconurl;
		transferStationIcon.shadow = "images/blank.gif";
		transferStationIcon.iconSize = new GSize(transferstationiconsize,transferstationiconsize);
		transferStationIcon.shadowSize = new GSize(10,10);
		transferStationIcon.iconAnchor = new GPoint(halftransferstationsize,halftransferstationsize);
		transferStationIcon.infoWindowAnchor = new GPoint(halftransferstationsize,halftransferstationsize);
		transferStationIcon.infoShadowAnchor = new GPoint(0,0);

		for(var i=0;i<stations.length;i++){

			var point = new GPoint( parseFloat(stations[i].lat), parseFloat(stations[i].lng) );

			var marker = null;
			if(stations[i].stationtype=='transfer'){
				marker = CreateStationMarker(the_map, stations[i].name,point,transferStationIcon);
			}else{
				marker = CreateStationMarker(the_map, stations[i].name,point,normalStationIcon);
			}

			the_map.addOverlay(marker);

		}

	}
}

function DrawLines(the_map) {
	for(var lcv=0;lcv<lineNodes.length;lcv++){
		DrawLine(the_map, lineNodes[lcv],lineColors[lcv]);
	}

}

function DrawLine(the_map, linenodes,color){

	var mapSpan = the_map.getSpanLatLng();
	
	var mapdivheight = parseFloat('300');
	var mapdivwidth = parseFloat('600');
	
		
	var xlineScale = (((LINE_WIDTH)/2)/mapdivheight) * mapSpan.width;
	var ylineScale = (((LINE_WIDTH)/2)/mapdivwidth) * mapSpan.height;

	var metrolinePoints = [];
	for(var i=0;i<(linenodes.length-1);i++){
		var offsetFlag1 = parseFloat(linenodes[i].offset);
		var offsetFlag2 = parseFloat(linenodes[i+1].offset)

		var point1x = parseFloat(linenodes[i].lat);
		var point1y = parseFloat(linenodes[i].lng);
		var point2x = parseFloat(linenodes[i+1].lat);
		var point2y = parseFloat(linenodes[i+1].lng);

		if((offsetFlag1!=0)&&(offsetFlag2!=0)){

			var rise = (point2y - point1y);
			var run = (point2x - point1x);

			var xoffset, yoffset;

			//horizontal line
			if(rise==0){
				xoffset = 0;
				yoffset = (-1) * offsetFlag1;

			}
			//vertical line
			else if(run==0){	
				xoffset = (-1) * offsetFlag1;
				yoffset = 0;

			}
			//all others
			else{

				var slope = (rise / run);

				var normalslope = (-1/slope);

				xoffset = Math.sqrt( 1 / (1 + (normalslope*normalslope)) );
				yoffset = xoffset * normalslope;

				//flip offsetflag if slope is negative (due to Math.sqrt always returning positive)
				if(slope<0){
					offsetFlag1 = offsetFlag1 * -1;
				}


				//apply offset flag
				xoffset = xoffset * offsetFlag1;
				yoffset = yoffset * offsetFlag1;

			}

			//scale offset by previously determined factor
			xoffset = xoffset * xlineScale;
			yoffset = yoffset * ylineScale;

			point1x = point1x + xoffset;
			point1y = point1y + yoffset;

			point2x = point2x + xoffset;
			point2y = point2y + yoffset;

		}

		var point1 = new GPoint(point1x,point1y);
		var point2 = new GPoint(point2x,point2y);

		metrolinePoints.push(point1);
		metrolinePoints.push(point2);
		
	}
	var newLine = new GPolyline(metrolinePoints,color,LINE_WIDTH);
	
	the_map.addOverlay(newLine);

}


Array.prototype.remove=function(s){
  for(i=0;i<this .length;i++){
    if(s==this[i]) this.splice(i, 1);
  }
}


function removeRestore(id, linkObj) {
	
	var div_id = id + '_compact_container';
	var details_div = id + '_details';
	
	if (!(inArray(id, removedItems))) {
		
		if (GetCookie('removeClicked') == '') {
			showBox('removeRestore');
			var exp = new Date();
			  exp.setTime(exp.getTime() + (30*24*60*60*1000));			
     		SetCookie("removeClicked","1",exp);
		}
		
		$(div_id).style.backgroundColor = '#E3FFAA';
		$(div_id).style.padding = '5px 0px 5px 5px';
		$(details_div).style.backgroundColor = '#E3FFAA';
		$(details_div).style.padding = '5px 0px 5px 5px';
		
		removedItems.push(id);
		linkObj.innerHTML = 'Restore To List &nbsp;<img src="/assets/images/restore_icon.gif">';
	}

	else {
		removedItems.remove(id);
		linkObj.innerHTML = 'Remove From List &nbsp;<img src="/assets/images/remove_from_list_icon.gif">';
		$(div_id).style.backgroundColor = '';
//		$(div_id).style.padding = '5px 0 10px 0';
		$(div_id).style.padding = '5px 0 5px 0';
		$(details_div).style.backgroundColor = '';
//		$(details_div).style.padding = '5px 0 10px 0';
		$(details_div).style.padding = '5px 0 15px 0';
	}
	
}


