var url = '../';
var disableSearch = false;

var globalSearchString = '';
var formSearchFields = Array();
var home_data;
var removedItems = new Array();
var checkedItems = new Array(); 
var myDomain = document.domain;


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');
formSearchFields.push('open_house');
formSearchFields.push('acres_more_less');

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 addRemoveChecked(id, linkObj) {
	if(linkObj.checked) {
		checkedItems.push(id);
	} else {
		checkedItems.remove(id);
	}
}

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 checkUncheckAll(value) {
		
	var allinputs = ($('content').getElementsByTagName('input'));
    var num = 0;

	if (value == 'select_all') { 
		/*for (node in allinputs) {
			if (allinputs[node].className == 'ListingSendCheckbox') {				
				allinputs[node].checked = true;	
				if (!(inArray(allinputs[node].value, checkedItems))) {
					checkedItems.push(allinputs[node].value);
				}
			}
			
		}*/

		while(num < allinputs.length)
		{
			if (allinputs[num].className == 'ListingSendCheckbox') {			
				allinputs[num].checked = true;	
				if (!(inArray(allinputs[num].value, checkedItems))) {
					checkedItems.push(allinputs[num].value);
				}
			}
			num++;
		}		
				
	}

	else  {
		/*for (node in allinputs) {
			if (allinputs[node].className == 'ListingSendCheckbox') {
				allinputs[node].checked = false;	
				checkedItems.remove(allinputs[node].value);
			}
		}*/

		while(num < allinputs.length) {
			if (allinputs[num].className == 'ListingSendCheckbox') {
				allinputs[num].checked = false;	
				checkedItems.remove(allinputs[num].value);
			}
			num++;
		}	
								
	}
  
}

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) {
	map_main.clearOverlays();
	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];

		map_main.checkResize();

		showNearby();

		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 !important;" /></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'] + ' - <a href="javascript:showCompactDetails(\'' + home_data[i]['ListingID'] + '\', $(\'' + home_data[i]['ListingID'] + '_details\'));" style="color:#AC2248;" class="compact_address">' + home_data[i]['addy'] + ', ' + home_data[i]['city'] + ', ' + home_data[i]['state'] + ', ' + home_data[i]['PostalCode'] + '</a> <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>Listed By:</b> ' + home_data[i]['ListOffice'] + ' <b>Sq. Ft: </b>' + home_data[i]['LivingArea'] + ' <b>Days Listed: </b>' + '<font style="font-weight: bold; color:#AC2248;">' + home_data[i]['DaysOnMarket'] + '</font>'
    + '</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="' + url + '/assets/images/more_details_icon.gif"></a>'
	+ '<br>';
	
	if (inArray(home_data[i]['ListingID'], checkedItems)) {
		outputData += 'Add <input class="ListingSendCheckbox" value="' + home_data[i]['ListingID'] + '" checked onClick="addRemoveChecked(\'' + home_data[i]['ListingID'] + '\', this);" type="checkbox">';	
	}
	else {
		outputData += 'Add <input class="ListingSendCheckbox" value="' + home_data[i]['ListingID'] + '" onClick="addRemoveChecked(\'' + home_data[i]['ListingID'] + '\', this);" type="checkbox">';
	}
	
/*	
	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="' + url + '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="' + url + '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 showRoutePopup() {
		if (checkedItems.length == 0) {
			showBox('nopropertiesselected');
		}
		else {
			var  disp_setting="toolbar=no,location=no,directories=no,menubar=no,";
			disp_setting+="scrollbars=yes,width=700, height=725";
			var docprint=window.open("/tbhse_route.php?props=" + checkedItems,"",disp_setting);
		}
}

function updateNum() {
	
	$('num').innerHTML = '';

	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;

	new Ajax.Updater(
      		    'num',
				'common/php/ajax/update.listings.count.php',
				{
					hronous:true,
					frequency:1,
			  		method:'post',
					postBody: searchString,
					onComplete: done
				});
}

function updateCities_cb(data) {
	var showCities_cb = function(req) {
		$('showCities').innerHTML = req.responseText;
		for (var i=0; i< 30; i++) {
			if (data['c_' + i] != 'undefined') 
				$('c_' + i).checked = true;
		}
		updateNum();
		uListings();
	};

		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_cb
				});
}
}

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() {
		$('nCity').innerHTML = '<center><img src="' + url + '/assets/images/indicator_small.gif"></center>';
		var switchNum = 1;
if ($F("state") != "n/a") {
		new Ajax.Updater(
      		    'nCity',
				'common/php/ajax/update.num.cities.php',
				{
					asynchronous: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 loadDirectProps(id) {

	post_params = "id=" + id;

  new Ajax.Request("common/php/ajax/load.direct.props.php", {
  onSuccess : function(resp) {  
		var text = resp.responseText;
		text = text.replace(/^\s+|\s+$/g,"");
		$('MLS').value = text;
		updateNumCities();
		citiesSuggest();
		readonlyCityState();
		updateNum();
		uListings();

},
 onFailure : function(resp) {
   alert("Oops, there's been an error.");
 },
 parameters : post_params 
});


}


function loadDirectSearch(id, type) {

	post_params = "id=" + id + "&type=" + type;


  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(jsonData);
		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="' + url + '/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(data) {
    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");
		if (data) {
			updateCities_cb(data);
		}
		else {
			updateCities();
		}
	}

}

function uListings () {
	
	current_page = 1;
	
	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);
		
		checkedItems.length = 0;
		
		
}

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="' + url + '/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="' + url + '/assets/images/hide_details_icon.gif">';
        }
      else {
        Element.hide(containerName);
	linkObj.innerHTML = 'More Details &nbsp;<img src="' + url + '/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() {
	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);				
			map_main.addOverlay(createMarker(point, home_data[i]['popupHTML']));	
		}
	}
	map_main.setCenter(bounds.getCenter());
	map_main.setZoom(map_main.getBoundsZoomLevel(bounds));
	DrawStations(map_main);
	DrawLines(map_main);
	
}


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();
  updateToolboxGreeting();
  /*

  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 switchThumb(ListingID, src, h, w) {
  var img_cont_name = 'compact_img_' + ListingID;
  $(img_cont_name).src = src;
	if (h > 263) {
		newWidth = Math.round(w*(263/h));
		$(img_cont_name).style.width = newWidth +'px';
		$(img_cont_name).style.height =  '263px';
		
	}
	
	else if (w > 350) {
		newHeight = Math.round(h*(350/w));
		$(img_cont_name).style.height = newHeight +'px';
		$(img_cont_name).style.width =  '350px';	
	}
	
	else {
		$(img_cont_name).style.width =  '' + w + 'px';	
		$(img_cont_name).style.height =  '' + h + 'px';	
	}
 
}

function switchThumbDirectSearch(ListingID, src) {
  var img_cont_name = 'compact_img_' + ListingID;
  $(img_cont_name).src = src;
  
  
  img1 = new Image();
  img1.src=src;
  h = img1.height;
  w = img1.width;
	if (h > 263) {
		newWidth = Math.round(w*(263/h));
		$(img_cont_name).style.width = newWidth +'px';
		$(img_cont_name).style.height =  '263px';
		
	}
	
	else if (w > 350) {
		newHeight = Math.round(h*(350/w));
		$(img_cont_name).style.height = newHeight +'px';
		$(img_cont_name).style.width =  '350px';	
	}
	
	else {
		$(img_cont_name).style.width =  '' + w + 'px';	
		$(img_cont_name).style.height =  '' + h + 'px';	
	}
 
}


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';

	if (id != 'hide') {
		$(id).className = 'active';
	
		var toSwitch = id + '_content';
	
		$(toSwitch).style.display = 'block';
	}
}

function showVirtualTour(ListingID, url, linkObj) {

	var  disp_setting="toolbar=no,location=no,resizable=yes,directories=no,menubar=no,";
	disp_setting+="scrollbars=yes,width=800, height=600";
	var docprint=window.open(url, "",disp_setting); 

/*
	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="showToolbox()">Welcome back, ' + name + ' - Click here to view the homes you\'ve ranked for Audrey.</a></b>';
      $('meetAudrey').innerHTML += '<br><a onClick="toolbox_logout();hideBox();">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="' + url + '/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, comment) {

	post_params = 'ListingID=' + PropertyID + "&sendersname=" + sendersname + "&sendersemail=" + sendersemail + "&recsname=" + recsname + "&recsemail=" + recsemail + '&comment=' + comment;

  new Ajax.Request("common/php/ajax/send.property.to.friend.php", {
    onSuccess : function(resp) {
        $('box2').innerHTML = '<img id="close" src="' + url + '/assets/images/close_window_icon.gif" onclick="hidebox2()" alt="Close" title="Close this window" /><br>' + resp.responseText;
 },

 parameters : post_params

});
}


function sendCheckedToFriend(sendersname, sendersemail, recsname, recsemail, id, comments) {

	post_params = 'ListingID=' + PropertyID + "&sendersname=" + sendersname + "&sendersemail=" + sendersemail + "&recsname=" + recsname + "&recsemail=" + recsemail + '&props=' + id + '&comments=' + comments;

  new Ajax.Request("common/php/ajax/send.checked.to.friend.php", {
    onSuccess : function(resp) {
        $('box2').innerHTML = '<img id="close" src="' + url + '/assets/images/close_window_icon.gif" onclick="hidebox2()" alt="Close" title="Close this window" /><br>' + resp.responseText;
 },

 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 selectAlertType() {
	
	var sendWhen; 
	var alertType;
	
	Form.getInputs('selectAlert','radio').each(function(input) { if(input.name=="sendWhen"&&input.checked) {sendWhen=input.value}; });	
	Form.getInputs('selectAlert','radio').each(function(input) { if(input.name=="alertType"&&input.checked) {alertType=input.value}; });

	var name = document.forms['selectAlert'].name.value;
	var email = document.forms['selectAlert'].email.value;
	var userFullname = document.forms['selectAlert'].userFullname.value;

	var escaped_string = globalSearchString.replace(/&/g,'^$');

	var params = 'searchString=' + escaped_string + '&sendWhen=' + sendWhen + '&alertType=' + alertType + '&name=' + name + '&email=' + email;
	
	var handlerFunc = function(t) {
		$('box2').innerHTML = t.responseText;
	}
	
  	new Ajax.Request('common/php/ajax/save.alert.php', {parameters: params, onSuccess:handlerFunc});
}


function saveSingleAlert(ListingID) {

	var sendWhen; 
	
	Form.getInputs('selectAlert','radio').each(function(input) { if(input.name=="sendWhen"&&input.checked) {sendWhen=input.value}; });	
	
	var email = document.forms['selectAlert'].email.value;
	var userFullname = document.forms['selectAlert'].userFullname.value;

	var params = '&sendWhen=' + sendWhen + '&alertType=changes&name=' + name + '&email=' + email + '&propList=' + ListingID;
	
	var handlerFunc = function(t) {
		$('box2').innerHTML = '<span class="lightbox_header">>> Alert Saved</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a onClick="hideBox();"><img src="' + url + '/assets/images/close_window_icon.gif" /></a><br><hr size=1>' + t.responseText;
	}
	
  	new Ajax.Request('common/php/ajax/save.alert.php', {parameters: params, onSuccess:handlerFunc});
}



function PropertyAlertBox(ListingID, alink) {

	if (GetCookie('email') != '') {
		PropertyAlertBoxStep2(ListingID, alink);	
	}
	else {
		PropertyAlertBoxStep1(ListingID, alink);
	}
}


function PropertyAlertBoxStep3(ListingID) {

		var sendWhen; 
		
		Form.getInputs('selectAlert','radio').each(function(input) { if(input.name=="sendWhen"&&input.checked) {sendWhen=input.value}; });	
		
		var other_addresses = document.forms['selectAlert'].other_addresses.value;
		
		var sendSelf = document.forms['selectAlert'].sendSelf.value;
		
		if (sendSelf == 'on') {
		
			var email = GetCookie('email');
		
			var params = '&sendWhen=' + sendWhen + '&alertType=changes&name=' + name + '&email=' + email + '&propList=' + ListingID + '&other_addresses=' + other_addresses;
			
			var handlerFunc = function(t) {
				$('box2').innerHTML = t.responseText;
			}
			
			new Ajax.Request('common/php/ajax/save.alert.php', {parameters: params, onSuccess:handlerFunc});
		
		}
		
		
		if (other_addresses != '') {
		
			var params2 = '&sendWhen=' + sendWhen + '&alertType=changes&name=' + name + '&email=' + email + '&propList=' + ListingID + '&other_addresses=' + other_addresses;
			
			var handlerFunc2 = function(t) {
				//$('box2').innerHTML = t.responseText;
			}
			
			new Ajax.Request('common/php/ajax/save.friends.alert.php', {parameters: params2, onSuccess:handlerFunc2});
		
		}


	
}


function PropertyAlertBoxStep2(ListingID, alink) {
	
	var email = GetCookie('email');
	
    $('box2').innerHTML = '<div id="AUDREY_login">' +
'<img src="' + url + '/assets/images/watch_property_header.gif" style="float: left;"> <span onClick="hideBox()" style="float: right"><a>close</a></span>' + 	
'<p style="clear: both; padding-top: 5px;">We will alert you when anything changes with this property.</p>' + 
'<form id=selectAlert name=selectAlert>' + 
'<table>' +

'<tr><td colspan=2>' + 
'Send Alerts: <input checked name="sendWhen" type="radio" value="As They Happen">As They Happen' +
' <input name="sendWhen" type="radio" value="Daily">Daily' +
' <input name="sendWhen" type="radio" value="Weekly">Weekly</td></tr>' +

'<tr><td colspan=2>' + 
'<b>People to alert:</b><br>' + 
' <div style="margin-left: 25px;"><input checked type="checkbox" name="sendSelf">' + email  + '<br>(<a onClick="toolbox_logout();hideBox();">Not ' + email + '?</a>)<br>' + 
' <b>Other email addreses to alert:</b><br>' + 
' <input size=40 name=other_addresses><br>' + 
' <b><i>(More than one email?  Just separate with commas)</i></b></div>' + 
'</tr></td>' +
'<tr><td colspan=2><input onclick="PropertyAlertBoxStep3(\'' + ListingID + '\');" value="Submit Request" type="button"></td></tr>' + 
'</table>' + '<br>' +
'</form>' + 

'</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 PropertyAlertBoxLogin(ListingID, alink) {
	var name = document.forms['selectAlert'].userFullname.value;
	var email = document.forms['selectAlert'].email.value;
	var phone = document.forms['selectAlert'].userPhone.value;

	if ((name == '') || (email == '') || (phone == '')) {
		alert('Please enter your Name, Email, and Phone.');	
		return;
	}

	toolbox_login(name, email, phone);
	PropertyAlertBoxStep2(ListingID, alink);	
}


function PropertyAlertBoxStep1(ListingID, alink) {
	
    $('box2').innerHTML = '<div id="AUDREY_login">' +
'<img src="' + url + '/assets/images/watch_property_header.gif" style="float: left;"> <span onClick="hideBox()" style="float: right"><a>close</a></span>' + 	
'<p style="clear: both; padding-top: 5px;">We will alert you when anything changes with this property.</p>' + 
'<form id=selectAlert name=selectAlert>' + 
'<table>' +
'<tr><td colspan=2>Step 1: Easy, Fast Registration</td></tr>' +
'<tr><td>Name:</td><td><input name="userFullname"></td></tr>' +
'<tr><td>Email:</td><td><input name="email"></td></tr>' +
'<tr><td>Phone:</td><td><input name="userPhone"></td></tr>' +
'<tr><td colspan=2><input onclick="PropertyAlertBoxLogin(\'' + ListingID + '\', \'' + alink + '\');" value="Submit Request" type="button"></td></tr>' + 
'</table>' + '</form>' + 
'If you are already signed up to receive alerts, simply enter your email address in the field above to login.' + 
'</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';
}



//Saved Search functions...
function SavedSearchAlertBox(alink) {
	
	var escaped_string = globalSearchString.replace(/&/g,'^$');

	if (GetCookie('email') != '') {
		SavedSearchAlertBoxStep2(escaped_string, alink);	
	}
	else {
		SavedSearchAlertBoxStep1(escaped_string, alink);
	}
}


function SavedSearchAlertBoxStep3() {

	var escaped_string = globalSearchString.replace(/&/g,'^$');

		var sendWhen; 
		
		Form.getInputs('selectAlert','radio').each(function(input) { if(input.name=="sendWhen"&&input.checked) {sendWhen=input.value}; });	
		
		var other_addresses = document.forms['selectAlert'].other_addresses.value;
		
		var sendSelf = document.forms['selectAlert'].sendSelf.value;

		if (sendSelf == 'on') {

			var email = GetCookie('email');
			
			var searchName = document.forms['selectAlert'].searchName.value;
		
			var params = '&sendWhen=' + sendWhen + '&alertType=search&name=' + searchName + '&email=' + email + '&searchString=' + escaped_string + '&other_addresses=' + other_addresses;
			
			var handlerFunc = function(t) {
				$('box2').innerHTML = t.responseText;
			}
			
			new Ajax.Request('common/php/ajax/save.alert.php', {parameters: params, onSuccess:handlerFunc});
		}

		if (other_addresses != '') {

			var email = GetCookie('email');
			
			var searchName = document.forms['selectAlert'].searchName.value;
		
			var params2 = '&sendWhen=' + sendWhen + '&alertType=search&name=' + searchName + '&email=' + email + '&searchString=' + escaped_string + '&other_addresses=' + other_addresses;
			
			var handlerFunc2 = function(t) {
				return;
				//$('box2').innerHTML = t.responseText;
			}
			
			new Ajax.Request('common/php/ajax/save.friends.alert.php', {parameters: params2, onSuccess:handlerFunc2});
		}
		
	
}


function SavedSearchAlertBoxStep2(escaped_string, alink) {
	var email = GetCookie('email');
    $('box2').innerHTML = '<div id="AUDREY_login">' +
'<img src="' + url + '/assets/images/custom_search_alert_header.gif" style="float: left;"> <span onClick="hideBox()" style="float: right"><a>close</a></span>' + 	
'<p style="clear: both; padding-top: 5px;">We will alert you when new properties are listed that match this search.</p>' + 
'<form id=selectAlert name=selectAlert>' + 
'<table>' +
'<tr><td>Please Name This Search: </td><td><input name="searchName"></td></tr>' +
'<tr><td colspan=2>' + 
'Send Alerts: <input checked name="sendWhen" type="radio" value="As They Happen">As They Happen' +
' <input name="sendWhen" type="radio" value="Daily">Daily' +
' <input name="sendWhen" type="radio" value="Weekly">Weekly</td></tr>' +
'<tr><td colspan=2>' + 
'<b>People to alert:</b><br>' + 
' <div style="margin-left: 25px;"><input checked type="checkbox" name="sendSelf">' + email  + '<br>(<a onClick="toolbox_logout();hideBox();">Not ' + email + '?</a>)<br>' + 
' <b>Other email addreses to alert:</b><br>' + 
' <input size=40 name=other_addresses><br>' + 
' <b><i>(More than one email?  Just separate with commas)</i></b></div>' + 
'</tr></td>' +
'<tr><td colspan=2><input onclick="SavedSearchAlertBoxStep3();" value="Submit Request" type="button"></td></tr>' + 
'</table>' + '<br>' +
'</form>' + 

'</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 SavedSearchAlertBoxLogin(alink) {
	var name = document.forms['selectAlert'].userFullname.value;
	var email = document.forms['selectAlert'].email.value;
	var phone = document.forms['selectAlert'].userPhone.value;

	if ((name == '') || (email == '') || (phone == '')) {
		alert('Please enter your Name, Email, and Phone.');	
		return;
	}
	
	toolbox_login(name, email, phone);
	SavedSearchAlertBoxStep2(alink);	
}


function SavedSearchAlertBoxStep1(string, alink) {
	
    $('box2').innerHTML = '<div id="AUDREY_login">' +
'<img src="' + url + '/assets/images/custom_search_alert_header.gif" style="float: left;"> <span onClick="hideBox()" style="float: right"><a>close</a></span>' + 	
'<p style="clear: both; padding-top: 5px;">We will alert you when new properties are listed that match this search.</p>' + 
'<form id=selectAlert name=selectAlert>' + 
'<table>' +
'<tr><td colspan=2>Step 1: Easy, Fast Registration</td></tr>' +
'<tr><td>Name:</td><td><input name="userFullname"></td></tr>' +
'<tr><td>Email:</td><td><input name="email"></td></tr>' +
'<tr><td>Phone:</td><td><input name="userPhone"></td></tr>' +
'<tr><td colspan=2><input onclick="SavedSearchAlertBoxLogin(\'' + alink + '\');" value="Submit Request" type="button"></td></tr>' + 
'</table>' +
'</form>' + 
'If you are already signed up to receive alerts, simply enter your email address in the field above to login.' + 
'</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';
}

//end saved search...


function showSendSearchResultsToFriend() {

	var saved_search_data;

	hideAllSelects();

	var escaped_string = globalSearchString.replace(/&/g,'^$');
	
	var handlerFunc = function(t) {
		var jsonData = eval('(' + t.responseText + ')');
		$('box').innerHTML = '  <span class="lightbox_header">>> Email these search results to a friend</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a onClick="hideBox();"><img src="' + url + '/assets/images/close_window_icon.gif" /></a><br><hr size=1>';
		
	if (checkedItems.length == 0) {
		$('box').innerHTML += '<span style="color: #800000">No properties were selected, so the entire search will be sent.</span><br>'
	}
		
	$('box').innerHTML += '<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:</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://' + myDomain + '/?direct_search=' + jsonData['id'] +
	'<br>Search criteria: ' + jsonData['html'] +
	'<br><a onClick="getMLSnumbers()">View MLS Numbers</a> ' +
	'<img src="' + url + '/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 = '<span class="lightbox_header">>> Email this property to a friend</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a onClick="hideBox();"><img src="' + url + '/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>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>Comment:</td><td><textarea name="comment" id="comment"></textarea></td></tr>' +
'</table>' +
'<input onclick="sendPropertyToFriend(document.getElementById(\'sendersname\').value,document.getElementById(\'sendersemail\').value,document.getElementById(\'recsname\').value,document.getElementById(\'recsemail\').value,\'' + PropertyID + '\',document.getElementById(\'comment\').value)" 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 SelectEmailSearch() {
	hideBox();
	if ($F('sendSearch') == 'on') {
		showSendSearchResultsToFriend();
	}
	else if ($F('sendChecked') == 'on') {
		showSendCheckedToFriend($('email_properties_button'))	
	}
}

function showSelectEmailSearchForm(alink) {
	
	if (checkedItems.length == 0) {
		showSendSearchResultsToFriend($('email_properties_button'));
		return;
	}
	
    $('box2').innerHTML = '<span class="lightbox_header">>> Email Properties to a Friend</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a onClick="hideBox();"><img src="' + url + '/assets/images/close_window_icon.gif" /></a><br><hr size=1>You have selected ' + checkedItems.length + ' properties<br><br><div id="AUDREY_login">' +
'<table>' +
'<tr><td><input name="selectSearch" id="sendChecked" type="radio" value="on"></td><td>Email only selected properties to a friend:</td></tr>' +
'<tr><td><input name="selectSearch" id="sendSearch" type="radio" value="on"></td><td>Email all search results to a friend:</td></tr>' +
'</table>' + '<br>' +
'<input onclick="SelectEmailSearch()" 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';
}

function showSendCheckedToFriend(alink) {
	
		var handlerFunc = function(t) {
			var jsonData = eval('(' + t.responseText + ')');
			PropertyID = '';
			$('box2').innerHTML = '<span class="lightbox_header">>> Email checked properties to a friend</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a onClick="hideBox();"><img src="' + url + '/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>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="sendCheckedToFriend(document.getElementById(\'sendersname\').value,document.getElementById(\'sendersemail\').value,document.getElementById(\'recsname\').value,document.getElementById(\'recsemail\').value,' + jsonData['id'] + ',document.getElementById(\'comments\').value)" value="Submit Request" type="button">' +
		'<hr>Here\'s the results link we\'ll be sending: http://' + myDomain + '/?direct_props=' + jsonData['id'] +
		'</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');
		}
	
new Ajax.Request('common/php/ajax/save.props.php', {parameters:'searchString=' + checkedItems.toString(), onSuccess:handlerFunc});

}




function showAudreyRankBox(ListingID, alink) {
	if (GetCookie('email') == '') {
		showAudreyLogin(alink);
    	return;
	} 
	
    $('box').innerHTML = '<img id="close" src="' + url + '/assets/images/close.gif" onclick="hideBox()" alt="Close" title="Close this window" />';
	$('box').innerHTML += "<span class=\"lightbox_header\">>> Welcome to Audrey</span>";
	$('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="' + url + '/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) {
	hideAllSelects();	
	$('box').innerHTML = '<span class="lightbox_header">>> We\'d like you to meet Audrey</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a onClick="hideBox();"><img src="' + url + '/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 hideToolbox() {
	$('toolbox_header').style.textDecoration = 'underline';
	$('toolbox_content').innerHTML = '';
}

function showToolbox() {
	$('toolbox_header').style.textDecoration = 'none';
	//hideBox();
	$('toolbox_content').innerHTML = '<center><img src="' + url + '/assets/images/indicator_small_blue.gif"></center>';
	Element.show('toolbox');
	
  post_params = '';

  new Ajax.Request("common/php/ajax/toolbox.content.php", {
  onSuccess : function(resp) {;
    $('toolbox_content').innerHTML = resp.responseText + '<p style="text-align: right;"><a class="toolbox_show_hide"  onClick="hideToolbox()">[hide this section]</a></p>';
 },
 onFailure : function(resp) {
   alert("Oops, there's been an error.");
 },
 parameters : post_params
});
}

function showHideToolbox() {
	if ($('toolbox_content').innerHTML == '') {
		showToolbox();
	}
	
	else 
		hideToolbox();
}

function showMyAudrey() {

	hideBox();
	$('audreyContent').innerHTML = '<center><img src="' + url + '/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) {
        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 hidebox2() {
    $('box2_cont').hide();
    $('overlay').hide();
    showAllSelects();
    return false;
}


function showNewAddress(map, address, htmlcontent) {

var icon = new GIcon();
icon.image = url + "/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() {
		marker.openInfoWindowHtml(html);
				});

	return marker;
}

	function DrawStations(the_map){

	var zoomlevel = the_map.getZoom();

	//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 = url + '/assets/images/' + transferstationiconurl + '.png';
		normalstationiconurl = url + '/assets/images/' + normalstationiconurl + '.png';
	}else{
		transferstationiconurl = url + '/assets/images/' + transferstationiconurl + '.gif';
		normalstationiconurl = url + '/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 = map_main.getBounds();
	
	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(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="' + url + '/assets/images/restore_icon.gif">';
	}

	else {
		removedItems.remove(id);
		linkObj.innerHTML = 'Remove From List &nbsp;<img src="' + url + '/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';
	}
	
}

function delete_alert(id) {
	
	post_params = "fn=delete_alert&id=" + id;

  new Ajax.Request("common/php/ajax/audrey.fns.php", {
  onSuccess : function(resp) {  
  
  	//new Effect.Fade(id + '_alert_box', {duration:.4});
	showToolbox();
},
 onFailure : function(resp) {
   alert("Oops, there's been an error.");
 },
 parameters : post_params 
});
}


function hideShow_alertbox(id, img_obj) {
	
	var div_name = id + '_alert_box_details';
	
	if (!(Element.visible(div_name))) {
		Element.show(div_name);
		img_obj.src = url + "/assets/images/toolbox/btn_collapse.gif";
	}
	
	else  {
		Element.hide(div_name);
		img_obj.src = url + "/assets/images/toolbox/btn_expand.gif";
	}
}

function hideShow_toolbox_watchlist(img_obj) {
	
	var div_name = 'watch_list_container';
	
	if (!(Element.visible(div_name))) {
		Element.show(div_name);
		img_obj.src = url + "/assets/images/toolbox/btn_hide.gif";
	}
	
	else  {
		Element.hide(div_name);
		img_obj.src = url + "/assets/images/toolbox/btn_show.gif";
	}
}

function hideShow_toolbox_alertlist(img_obj) {
	
	var div_name = 'alert_list_container';
	
	if (!(Element.visible(div_name))) {
		Element.show(div_name);
		img_obj.src = url + "/assets/images/toolbox/btn_hide.gif";
	}
	
	else  {
		Element.hide(div_name);
		img_obj.src = url + "/assets/images/toolbox/btn_show.gif";
	}
}

function hideShow_toolbox_profile(img_obj) {
	
	var div_name = 'toolbox_profile_container';
	
	if (!(Element.visible(div_name))) {
		Element.show(div_name);
		img_obj.src = url + "/assets/images/toolbox/btn_hide.gif";
	}
	
	else  {
		Element.hide(div_name);
		img_obj.src = url + "/assets/images/toolbox/btn_show.gif";
	}
}

function toolbox_login_validate() {
	if (($('toolbox_login_name').value == '') || ($('toolbox_login_email').value == '') || ($('toolbox_login_phone').value == ''))
		alert ('Please enter your Name, Email, and Phone.');
	else
		toolbox_login($('toolbox_login_name').value,$('toolbox_login_email').value,$('toolbox_login_phone').value)
}


function toolbox_login(name,email,phone) {

    var exp = new Date();
    exp.setTime(exp.getTime() + (30*24*60*60*1000));
    SetCookie("email",email,exp);

if (name == undefined) 
  	name = '';
  
	
  post_params = 'email=' + email + '&name=' + name + '&phone=' + phone;

  new Ajax.Request("common/php/ajax/toolbox.login.php", {
  onSuccess : function(resp) {
		if (!(resp.responseText.match("Sorry"))) {
	if (email != '') {
			showToolbox();
			updateToolboxGreeting();
	}
		}
 },
 onFailure : function(resp) {
   alert("Oops, there's been an error.");
 },
 parameters : post_params
});
}


function toolbox_logout() {
	var exp = new Date();
    exp.setTime(exp.getTime() + (30*24*60*60*1000));
	SetCookie("email","",exp);
	showToolbox();
	updateToolboxGreeting();
}

function scrollShowToolbox() {
	hideBox();
	new Element.scrollTo('toolbox_content');
	showToolbox();
}


function update_profile() {
	new Ajax.Request("common/php/ajax/update.profile.php", {
	 onSuccess : function(resp) {
		alert('your profile has been updated.');
	},
	 onFailure : function(resp) {
	   alert("Oops, there's been an error.");
	 },
	 parameters : "&oldemail=" + GetCookie('email') + '&name=' + $F('profile_name') + '&phone=' + $F('profile_phone')
	});
}

function updateToolboxGreeting() {
	new Ajax.Request("common/php/ajax/update.toolbox.greeting.php", {
	 onSuccess : function(resp) {
		 $('toolbox_greeting').innerHTML = resp.responseText;
	},
	 onFailure : function(resp) {
	   alert("Oops, there's been an error.");
	 }
	 
	});
}

function submitenter(myfield,e) {
disableSearch = true;
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;

if (keycode == 13)
   {
	toolbox_login($('toolbox_login_name').value,$('toolbox_login_email').value,$('toolbox_login_phone').value);
   return false;
   }
else
   return true;
}

function already_registered_toolbox() {
	Element.show('toolbox_login_left');
	Element.hide('toolbox_register_left');
}


function change_alert_freq(id, value) {
	post_params = "fn=update_alert_freq&id=" + id + '&value=' + value;

  new Ajax.Request("common/php/ajax/audrey.fns.php", {
  onSuccess : function(resp) {  
	Element.show('alert_updated_' + id);
},
 onFailure : function(resp) {
   alert("Oops, there's been an error.");
 },
 parameters : post_params 
});
}

function reload_comments(ListingID) {
	var workingContainerName = $(ListingID + '_comments_div');
	$(workingContainerName).innerHTML = '<center><img src="' + url + '/assets/images/indicator_small.gif"></center>';
	new Ajax.Updater($(workingContainerName), "common/php/ajax/reload_comments.php", {
	  onSuccess : function(resp) {	  	
	  	$(ListingID + '_comments_div').innerHTML = resp.responseText;
	},
	 onFailure : function(resp) {
	   alert("Oops, there's been an error.");
	 },
	 evalScripts:true, 	 
	 parameters : 'ListingID=' + ListingID
	});
}

function add_comment(ListingID) {
	
	var formName = ListingID + '_add_comment_form';

	if ((document.forms[formName].name.value == '') || (document.forms[formName].comment.value == '')) {
		alert('Please enter all required fields');
		return;
	}
	
	var params = Form.serialize(formName);
	var ListingDiv = ListingID + '_details';
	new Ajax.Request("common/php/ajax/add_comment.php", {
	  onSuccess : function(resp) {
	  	if (resp.responseText.match('error')) {
	  		alert('The reCAPTCHA wasn\'t entered correctly. Please go back and try it again.')
	  	}
	  	
	  	else {
	  		reload_comments(ListingID);
	  	}
	  	
	},
	 onFailure : function(resp) {
	   alert("Oops, there's been an error.");
	 },
	 parameters : params 
	});
}

function flag_comment(id, ListingID) {
	new Ajax.Request("common/php/ajax/flag_comment.php", {
		onSuccess : function(resp) {
			alert('Comment Flagged!  We\'ll review it within 12 hours');
			reload_comments(ListingID);
		},
		onFailure : function(resp) {
			alert("Oops, there's been an error.");
		},
		parameters : 'id=' + id
	});
}
