// JavaScript Document

//************************************************
//************* GARBAGE COLLECTION  **************
//************************************************
window.addEvent("unload", function(event){
	if (App){
		//unload classes
		if (App.txtToggle){
			if (App.txtToggle.keyword != undefined) { App.txtToggle.keyword.unload(); App.txtToggle.keyword = null; }
			if (App.txtToggle.minPrice != undefined) { App.txtToggle.minPrice.unload(); App.txtToggle.minPrice = null; }
			if (App.txtToggle.maxPrice != undefined) { App.txtToggle.maxPrice.unload(); App.txtToggle.maxPrice = null; }
		}
		if (App.advSearch){
			if (App.advSearch.adsAccordion != undefined) { App.advSearch.adsAccordion.unload(); App.advSearch.adsAccordion = null; }
			if (App.advSearch.resultTabs != undefined) { App.advSearch.resultTabs.unload(); App.advSearch.resultTabs = null; }
		}
		
		if (thisPage == "search_result"){
			GUnload();
		}
		//unload local variable objects
		App.collectGarbage(App.advSearch); App.advSearch = null;
		App.collectGarbage(App.map); App.advSearch = null;
	
	}
});

//************************************************************
//************* INITIATE PAGE LEVEL COMPONENTS  **************
//************************************************************
	
		
App.advSearch.adsAccordion = null;
App.advSearch.resultTabs = null;
App.advSearch.searchString = null;
App.advSearch.searchCookie = null
App.advSearch.totalPerPage = 0;
App.advSearch.totalPages = 0;
App.advSearch.searchDelay = 500;
App.advSearch.searchDelayId = 0;
App.advSearch.region_id = [];
App.advSearch.regions = {};

window.addEvent("domready", function(){
	//force numeric
	//if ($("ads_min_price")){ $("ads_min_price").forceNumeric(true); }
	//if ($("ads_max_price")){ $("ads_max_price").forceNumeric(true); }
	App.advSearch.regions.Manhattan = {point: new GLatLng(40.77, -73.98), zoom: 12};
	App.advSearch.regions.Hamptons = {point: new GLatLng(41.00, -72.34), zoom: 10};
	App.advSearch.regions.Westchester = {point: new GLatLng(41.124, -73.743), zoom: 10};
	App.advSearch.regions.Manhattan_Hamptons_Westchester = {point: new GLatLng(41.116, -73.182), zoom: 8};
	App.advSearch.regions.Manhattan_Hamptons = {point: new GLatLng(40.859, -73.287), zoom: 8};
	App.advSearch.regions.Manhattan_Westchester = {point: new GLatLng(40.94256, -73.8212), zoom: 9};
	App.advSearch.regions.Hamptons_Westchester = {point: new GLatLng(40.8387, -73.45733), zoom: 8};
	App.map.mapCenter = {};
	
	if (thisPage == "search_result"){
			
		//========== set values and preparation
		var i = 0, j = 0, tempEl = null, frmSearch = $("advanced_search");												//declare local vars
		App.advSearch.totalPerPage = $("totalPerPage").value;							//get the total records per page	
		
		//see if the form data cookie exists, if yes, decode cookie to objects for form handling
		if (Cookie.read('searchCookie')){
			App.advSearch.searchString = new urlDecoder(Cookie.read('searchCookie'));		//convert the cookie query data to object based data
			//alert(Cookie.read('searchCookie'));
		//see if values have been passed via the URL
		} else {
			//if not cookie - take values from the URL
			if (window.location.href.split("?")[1]){
				App.advSearch.searchString = new urlDecoder(window.location.href.split("?")[1] + "&pageNo=1");
			} else {
				App.advSearch.searchString = new urlDecoder("keyword=&pageNo=1&region_id=1");
			}
		}
		
		
		//pre-load the listing snippet
		App.advSearch.preLoadSnippets();								//pre load the listing snippet data
		
		//=========== create the accordion
		App.advSearch.adsAccordion = new Accordion($$('.accordion_toggler'), $$('.accordion_content'), {
			show : -1,
			alwaysHide: true,
			multiopen: true,
			opacity: false,
			duration: 200,
			onActive: function(toggler, element){
				toggler.removeClass("accordion_toggler");
				toggler.addClass("accordion_toggler_selected");
			},
			onBackground: function(toggler, element){
				toggler.addClass("accordion_toggler");
				toggler.removeClass("accordion_toggler_selected");
			}
		});
		
		//======== create the tabs for the results
		App.advSearch.resultTabs = new Tabs({
			container: "tabbedPanel",
			tabs: "tab",
			selected: "selectedTab",
			first: "firstTab",
			last: "lastTab",
			disabled: "disabledTab",
			panels: "panel",
			defaultTab: 0,
			width: 300,
			height: null,	//optional
			onChange: function(index){
				if (index == 1){ //google map is selected
					if (!App.map.mapCreated) { 
						App.advSearch.setGoogleMapCenter();
						
						var params = {
							center: App.map.mapCenter,
							controls: [new GLargeMapControl(), new GMapTypeControl()]
						};
						App.map.createGoogleMap("map_contianer", params); 
					} 
					tempEl = $("totalPerPage"); 
					App.advSearch.totalPerPage = tempEl.value;
					tempEl.value = "5000"; tempEl = null;
					App.advSearch.sendAjaxSearchRequest(null, {pageNo: 1, startingRecord: 1, endingRecord: "5000" });
					
				} else {	//list view is selected
					//if (App.map.apiLoaded) { GUnload(); }
					tempEl = $("totalPerPage"); tempEl.value = App.advSearch.totalPerPage; tempEl = null;
					App.advSearch.sendAjaxSearchRequest(null, {pageNo: 1, startingRecord: 1, endingRecord: App.advSearch.totalPerPage });

				}
			}
		});
		
		//======= collect the form elements into DOM variables
		App.advSearch.frmTextbox = $("advanced_search").getElements('input[type=text]'); 
		App.advSearch.frmRadio = $("advanced_search").getElements('input[type=radio]');
		App.advSearch.frmCheckbox = $("advanced_search").getElements('input[type=checkbox]');
		App.advSearch.frmDropmenu = $("advanced_search").getElements('select');
		
		App.advSearch.frmRegion = $("advanced_search").getElements('input[id^=frm_region]'); 
		App.advSearch.frmListingTerms = $$($('frm_listing_terms_sales'), $('frm_listing_terms_rental'));
		
		//========== handle advanced search form events
		var formChangeAction = function(event){
			if (this.id == "property_type_comm"){
				App.advSearch.disableFieldsForCommercial(true);
			} else if (this.id == "property_type_res" || this.id == "property_type_all"){
				App.advSearch.disableFieldsForCommercial(false);
			}
			//delay the send
			$clear(App.advSearch.searchDelayId);
			App.advSearch.searchDelayId = (function(){
				App.advSearch.sendAjaxSearchRequest(event, {pageNo: 1, startingRecord: 1, endingRecord: App.advSearch.totalPerPage });
			}).delay(App.advSearch.searchDelay);
		};
		App.advSearch.frmTextbox.addEvents({ "keyup": formChangeAction }); App.storeEvents(App.advSearch.frmTextbox, "keyup"); //for garbage collection
		App.advSearch.frmRadio.addEvents({ "click": formChangeAction }); App.storeEvents(App.advSearch.frmRadio, "click"); //for garbage collection
		App.advSearch.frmCheckbox.addEvents({ "click": formChangeAction }); App.storeEvents(App.advSearch.frmCheckbox, "click"); //for garbage collection
		App.advSearch.frmDropmenu.addEvents({ "change": formChangeAction }); App.storeEvents(App.advSearch.frmCheckbox, "change"); //for garbage collection
		
		
		//============= handle the pagination form events + PAGINATION logic
		App.advSearch.frmPageSort = $('sr_sortby_top');
		App.advSearch.frmPagePrevious = $$( $('sr_previous_top'), $('sr_previous_bottom') );
		App.advSearch.frmPageNext = $$( $('sr_next_top'), $('sr_next_bottom') );
		
		//sort results 
		App.advSearch.frmPageSort.addEvents({
			"change": function(event){ 
				$("advanced_search").sortBy.value = this.value;
				App.advSearch.sendAjaxSearchRequest(event, {pageNo: 1, startingRecord: 1, endingRecord: App.advSearch.totalPerPage });
			}
		});
		App.storeEvents(App.advSearch.frmPageSort, "change"); //for garbage collection
		
		App.advSearch.frmPagePrevious.addEvents({
			"click": function(event){ 
				var pageNo = App.advSearch.searchString.items.pageNo.toInt() - 1;
				if (pageNo < 1){ 
					pageNo = 1; 
				}
				
				if (App.advSearch.searchString.items.pageNo.toInt() != pageNo){
					var startAt = pageNo*App.advSearch.totalPerPage - App.advSearch.totalPerPage + 1;
					var endAt = pageNo*App.advSearch.totalPerPage;
					App.advSearch.sendAjaxSearchRequest(event, {pageNo: pageNo, startingRecord: startAt, endingRecord: endAt });
				}
			}
		});
		App.storeEvents(App.advSearch.frmPagePrevious, "click"); //for garbage collection
		
		App.advSearch.frmPageNext.addEvents({
			"click": function(event){ 
				var pageNo = App.advSearch.searchString.items.pageNo.toInt() + 1;
				
				if (pageNo > App.advSearch.totalPages){ 
					pageNo = App.advSearch.totalPages; 
				}
				
				if (App.advSearch.searchString.items.pageNo.toInt() != pageNo){
					var startAt = pageNo*App.advSearch.totalPerPage - App.advSearch.totalPerPage + 1;
					var endAt = pageNo*App.advSearch.totalPerPage;
					App.advSearch.sendAjaxSearchRequest(event, {pageNo: pageNo, startingRecord: startAt, endingRecord: endAt });
				}
			}
		});
		App.storeEvents(App.advSearch.frmPageNext, "click"); //for garbage collection
		
		
		
		
		//============= handle form's DATA PERSISTANT STATE from saved query/URL data
		for(key in App.advSearch.searchString.items){
			//alert(key + " "  + $("advanced_search")[key] + " " + $("advanced_search")[key].type)
			//alert(frmSearch[key].get('tag') + " "  + App.advSearch.searchString.items[key]);
			
			//alert(key + " " + frmSearch[key] + " " + type + " " + App.advSearch.searchString.items[key])
			
			//if the key is not in the form - meaning custom URI param fro mteh URL
			if (!frmSearch[key]){
				//handle region_id
				if (key == 'region_id'){
					nodeKey = key+'[]';
					for (i = 0; i < frmSearch[nodeKey].length; i++){
						type = frmSearch[nodeKey][i].type;
						if (type == "checkbox"){
							if ($type(App.advSearch.searchString.items[key]) == "array"){
								for (j=0;j<App.advSearch.searchString.items[key].length;j++){
									if (frmSearch[nodeKey][i].value == App.advSearch.searchString.items[key][j]){
										frmSearch[nodeKey][i].checked = true;
									}
								}
							} else {
								if (frmSearch[nodeKey][i].value == App.advSearch.searchString.items[key]){
									frmSearch[nodeKey][i].checked = true;
								}
							}
						}
					}
				}
			
			
			//see if the item exists in the form
			} else if (frmSearch[key]){
				var type = frmSearch[key].type;	//figure out what type of input field it is
				
				if ($type(frmSearch[key]) == "element"){
					if (frmSearch[key].options){
						type = "select";
					}
				}
				
				
				
				//handle textboxes
				if (type == "text"){
					if (App.advSearch.searchString.items[key] != "Type a Neighborhood, Street Address, ZIP or Web ID" 
						&& App.advSearch.searchString.items[key] != "Web ID, Address or ZIP"
						&& App.advSearch.searchString.items[key] != "Min" 
						&& App.advSearch.searchString.items[key] != "Max"
					)
					{
						frmSearch[key].value = App.advSearch.searchString.items[key];
					}	
				}
				
				//handle regular checkboxes
				if (type == "checkbox"){
					frmSearch[key].checked = true;
					if (key == "washer_dryer" || key == "outdoor_space" || key == "loft"){
						App.advSearch.adsAccordion.open(7);
					}
				}
				
				//handle radio buttons
				if (frmSearch[key][0]){
					if (frmSearch[key][0].type == "radio"){
						for(i=0; i<frmSearch[key].length; i++){
							if (frmSearch[key][i].value == App.advSearch.searchString.items[key]){
								frmSearch[key][i].checked = true;
							}
						}
					}
				}
				
				//handle dropdown
				//if (type == "select-one"){
				if (type == "select"){
					for(j=0;j<frmSearch[key].options.length;j++){
						if (frmSearch[key].options[j].value == App.advSearch.searchString.items[key]){
							frmSearch[key].selectedIndex = j;
						}
					}
				}
				
				//handle array checkboxes
				if (frmSearch[key].length){ //array checkboxes
					
					if(key == "beds[]"){ App.advSearch.adsAccordion.open(0); }
					if(key == "baths[]"){ App.advSearch.adsAccordion.open(1); }
					if(key == "neighborhood[]"){ 
						 App.advSearch.adsAccordion.open(2);  
					}
					if(key == "ownership[]"){ App.advSearch.adsAccordion.open(3); }
					if(key == "buildingAge[]"){ App.advSearch.adsAccordion.open(4); }
					if(key == "access[]"){ App.advSearch.adsAccordion.open(5);  }
					if(key == "serviceLevel[]"){ App.advSearch.adsAccordion.open(6); }
					if(key == "petPolicy[]"){ App.advSearch.adsAccordion.open(8); }
					
					
					for (i = 0; i < frmSearch[key].length; i++){
						type = frmSearch[key][i].type;
						if (type == "checkbox"){
							if ($type(App.advSearch.searchString.items[key]) == "array"){
								for (j=0;j<App.advSearch.searchString.items[key].length;j++){
									//window.console.log(i + ". " + frmSearch[key][i].value + " " + App.advSearch.searchString.items[key][j])
									if (frmSearch[key][i].value == App.advSearch.searchString.items[key][j]){
										frmSearch[key][i].checked = true;
									}
								}
							} else {
								//alert(i + ". " + frmSearch[key][i].value + " " + App.advSearch.searchString.items[key])
								if (frmSearch[key][i].value == App.advSearch.searchString.items[key]){
									frmSearch[key][i].checked = true;
								}
							}
						}
					}
				}	
			}
		}
		
		
		//============ handle Sales vs. Rental checkboxes =======		
		var listingTermsChangeAction = function(event){
			//if (event == undefined){
				var listing_terms = 'all';
				if (App.advSearch.frmListingTerms[0].checked && App.advSearch.frmListingTerms[1].checked){ 
					listing_terms = 'all';
				} else if (App.advSearch.frmListingTerms[0].checked && !App.advSearch.frmListingTerms[1].checked){
					listing_terms = 'sale';
				} else if (App.advSearch.frmListingTerms[1].checked && !App.advSearch.frmListingTerms[0].checked){
					listing_terms = 'rental';
				}
			//} else {
			//	var listing_terms = this.value;
			//}
			
			//=======tasks
			//min. - max. price
			var el_min_price_rental = $('ads_min_price').getElements('option[rel=rental]');
			var el_min_price_sale = $('ads_min_price').getElements('option[rel=sale]');
			var el_max_price_rental = $('ads_max_price').getElements('option[rel=rental]');
			var el_max_price_sale = $('ads_max_price').getElements('option[rel=sale]');
			if (listing_terms == 'sale'){
				el_min_price_rental.addClass('invisible');
				el_min_price_rental.setProperty('disabled', 'disabled');
				el_max_price_rental.addClass('invisible');
				el_max_price_rental.setProperty('disabled', 'disabled');
				
				el_min_price_sale.removeClass('invisible');
				el_min_price_sale.removeProperty('disabled');
				el_max_price_sale.removeClass('invisible');
				el_max_price_sale.removeProperty('disabled');
			} else if (listing_terms == 'rental'){
				el_min_price_rental.removeClass('invisible');
				el_min_price_rental.removeProperty('disabled');
				el_max_price_rental.removeClass('invisible');
				el_max_price_rental.removeProperty('disabled');
				
				el_min_price_sale.addClass('invisible');
				el_min_price_sale.setProperty('disabled', 'disabled');
				el_max_price_sale.addClass('invisible');
				el_max_price_sale.setProperty('disabled', 'disabled');
			} else if (listing_terms == 'all'){
				el_min_price_sale.removeClass('invisible');
				el_min_price_sale.removeProperty('disabled');
				el_max_price_sale.removeClass('invisible');
				el_max_price_sale.removeProperty('disabled');
				
				el_min_price_rental.removeClass('invisible');
				el_min_price_rental.removeProperty('disabled');
				el_max_price_rental.removeClass('invisible');
				el_max_price_rental.removeProperty('disabled');
				
				el_max_price_rental[el_max_price_rental.length-1].addClass('invisible');
				el_max_price_rental[el_max_price_rental.length-1].setProperty('disabled');
			}
			el_price = el_rent = null;
			
			//handle property type
			var prop_type = $("advanced_search").getElements('input[name^=property_type]'); 
			if (listing_terms == 'sale' || listing_terms == 'all'){
				prop_type.removeProperty('disabled');
				prop_type[0].checked = true;
			} else if (listing_terms == 'rental') {
				prop_type[0].setProperty('disabled', 'disabled');
				prop_type[2].setProperty('disabled', 'disabled');
				prop_type[1].checked = true;
			}
			prop_type = null;
			
			//amentities
			//only furnished is disabled
			/*
			var furnished = $("ads_furnished");
			if (listing_terms == 'sale'){
				furnished.removeProperty('checked');
				furnished.setProperty('disabled', 'disabled');
			} else if (listing_terms == 'rental') {
				furnished.removeProperty('disabled');
			}
			furnished = null;
			*/
			
			//rental periods
			var rental_periods = $("advanced_search").getElements('input[name^=rental_period]'); 
			if (listing_terms == 'sale' || listing_terms == 'all'){
				rental_periods.removeProperty('checked');
				rental_periods.setProperty('disabled', 'disabled');
			} else if (listing_terms == 'rental') {
				rental_periods.removeProperty('disabled');
			}
		}
		App.advSearch.frmListingTerms.addEvent("click", listingTermsChangeAction);
		
		//========= handle location and listing terms related clicks/actions
		var regionChangeAction = function(event){
			var region_id = [], rdo_region = [], region_name = [], i = 0;
			
			/*
			//map based search is not allowed when multiple regions are selected
			if (event && App.advSearch.resultTabs.selectedTab == 1){
				App.advSearch.frmRegion.each(function(radio, index){
					radio.checked = false;
				});
				App.roar.empty();
				App.roar.alert("Map Based Search", "<div class='notice_blue'>You can only select a single region for Map based searches.<div>")
				this.checked = true;
			}
			*/
			
			//non-map based search must have at least 1 region - or more
			//if (App.advSearch.resultTabs.selectedTab == 0){
				i = 0;
				App.advSearch.frmRegion.each(function(radio, index){
					if (radio.checked) i++;
				});
				if (i == 0){ //no regions selected
					App.roar.empty();
					//this.checked = true;
					if (event){
						this.checked = true;
						//App.advSearch.resultTabs.enable(1);
						//App.roar.alert("Map Based Search", "<div class='notice_blue'>You cannot un-check all regions. At least one region must be selected.<div>");
					} else {
						App.advSearch.frmRegion[0].checked = true;
						//App.advSearch.resultTabs.enable(1);
					}
				} else if (i == 1){
					//App.advSearch.resultTabs.enable(1);
				} else if (i > 1){
					//App.advSearch.resultTabs.disable(1);
				}
			//}
			
			var i = 0;
			App.advSearch.frmRegion.each(function(radio, index){
				if (radio.checked){
					rdo_region[i] = radio;
					region_id[i] = radio.value;
					region_name[i] = radio.getProperty('rel');
					i++;
				}
			});
		
			//alert(region_id)
			App.advSearch.region_id = region_id;
			
			//handle page title 
			//var page_title = $("title_region_name"); 
			//page_title.set('html', region_name);
			
			/*
			//handle listign terms selection based on region
			var listing_terms = $("advanced_search").getElements('input[name^=listing_terms]'); 
			if (region_id == 1 || region_id == 3){
				listing_terms[0].checked = true;
			} else if (region_id == 2){
				listing_terms[1].checked = true;
			}
			listing_terms = null;
			*/
			
			//turn off all naighborhoods first so a single region can be initiated
			var showLocation = 0;
			App.advSearch.frmRegion.each(function(radio, index){
				var curr_region_id = radio.value;
				var region_block = $("neighborhoods_region_" + curr_region_id);
				if (region_block){
					if (!region_id.contains(curr_region_id)){
						var neighborhoods = region_block.getElements('input[name^=neighborhood]'); 
						neighborhoods.removeProperty('checked');
						neighborhoods = null;
						region_block.setStyle('display', 'none');
					} else {
						region_block.setStyle('display', 'block');
						if ($("neighborhoods_region_1").getParent().getCoordinates().height > 0){ //if already open
							showLocation += region_block.getCoordinates().height;
							//region_block.getParent().setStyle('height', region_block.getParent().getCoordinates().height + region_block.getCoordinates().height);
						}
					}
				}
			});
			if (showLocation){
				$("neighborhoods_region_1").getParent().setStyle('height', showLocation);
			}
				
			//do the following only when a single region is selected
			
				
			//amenities air conditioning
			var ac = $("ads_ac"); 
			if ((region_id.contains('1') || region_id.contains('3')) && !region_id.contains('2')){
				ac.removeProperty('checked');
				ac.setProperty('disabled', 'disabled');
			} else if (region_id.contains('2')){
				ac.removeProperty('disabled');
			}
			ac = null;
			
			
			//handle ownership 
			
			var ownership = $("advanced_search").getElements('input[name^=ownership]'); 
			if (region_id.contains('1') && region_id.length == 1){ //don't allow HOUSE for Manhattan
				ownership.removeProperty('disabled');
				ownership[0].removeProperty('checked');
				ownership[0].setProperty('disabled', 'disabled');
			} else {  //allow ONLY HOUSE for all others (just Hamptons for now)
				ownership.removeProperty('disabled'); 
			}
			ownership = null;
			
			//building age
			var buildingAge = $("advanced_search").getElements('input[name^=buildingAge]');  
			if (region_id.contains('1') && region_id.length == 1){
				buildingAge.removeProperty('disabled');
			} else {
				buildingAge.setProperty('disabled', 'disabled');
			}
			buildingAge = null;
			
			//building access
			var access = $("advanced_search").getElements('input[name^=access]');  
			if (region_id.contains('1') && region_id.length == 1){
				access.removeProperty('disabled');
			} else {
				access.setProperty('disabled', 'disabled');
			}
			access = null;
			
			//service levels
			var serviceLevel = $("advanced_search").getElements('input[name^=serviceLevel]');  
			if (region_id.contains('1') && region_id.length == 1){
				serviceLevel.removeProperty('disabled');
			} else {
				serviceLevel.setProperty('disabled', 'disabled');
			}
			serviceLevel = null;
			
			
			//set google map center
			if (App.map.mapCreated) { //make sure map is created
				App.advSearch.setGoogleMapCenter();
				App.map.moveMap(App.map.mapCenter.point, App.map.mapCenter.zoom);
			}
			
			listingTermsChangeAction();
		};
		App.advSearch.frmRegion.addEvent("click", regionChangeAction);
		regionChangeAction();
		//App.advSearch.frmRegion.fireEvent('click');
		
		
		
		
		//======================= toggle gray text for form items
		App.txtToggle.keyword = new textToggler("ads_keywordsmall", { text: "Web ID, Address or ZIP", onClass: "normal", offClass: "gray" });
		//App.txtToggle.minPrice = new textToggler("ads_min_price", { text: "Min", onClass: "normal", offClass: "gray" });
		//App.txtToggle.maxPrice = new textToggler("ads_max_price", { text: "Max", onClass: "normal", offClass: "gray" });
		
		//=================== Advanced search submit event
		frmSearch.addEvent("submit",  function(event){
			//var e = new Event(event); e.stop(); //stop the default action
			
			//set the form data into a cookie for reload and browser history
			//App.advSearch.searchCookie = Cookie.write('searchCookie', this.toQueryString(), {"duration": 0, path: "/" });
			App.advSearch.searchCookie = App.cookie.write('searchCookie', this.toQueryString(), 0);
			//alert(Cookie.read('searchCookie'));
			
			//convert cookie data to JS object data
			App.advSearch.searchString = new urlDecoder(Cookie.read('searchCookie'));
			//alert(App.advSearch.searchString.items)
			
			//cover the form with alpha panel
			$("result_panels").showLoading();
			
			//set the AJAX send parameters
			this.set('send', {
				//what to do once submit action is completed
				onComplete: function(response) { 
					//******** HANDLE "POST" SUBMISSION RESPONSE *********
					App.advSearch.json = JSON.decode(response);
					App.advSearch.populateResultPage();
					
					
					$("result_panels").hideLoading();	//uncover the form panel
					//******* END HANDLING POST DATA RESPONSE ********
				}
			});
			//Send the form data - with delay to show fake load time
			this.send();
			
			//alert("sent");
		});
		
		//send the request for data to the server
		if (App.advSearch.searchString.items){
			App.advSearch.sendAjaxSearchRequest(null, {pageNo: App.advSearch.searchString.items.pageNo, startingRecord: 1, endingRecord: App.advSearch.totalPerPage });
		} else {
			App.advSearch.sendAjaxSearchRequest(null, {pageNo: 1, startingRecord: 1, endingRecord: App.advSearch.totalPerPage });
		}
		
		//garbage collection
		frmSearch = null;
	}
	
});




//******************************************
//*********** LOCAL FUNCTIONS **************
//******************************************
App.advSearch.handleGoogleMap = function(){

	//============ create markers ==============
	App.map.clearMarkers(App.map.map);
	//GUnload();
	//App.map.map.clearOverlays();
	var totalRecords = 0;
	if (App.advSearch.totalRecords){ 
		$each(App.advSearch.json, function(rootVals, rootItem){	
			if (rootItem == "properties"){ 
				//rootVals.reverse();
				$each(rootVals, function(details, properties){					//loop through each properties '0,1,2,...'
					if (details.property_status.toInt() < 11){
						totalRecords++;
						App.map.addMarkers(App.map.map, details, true);
					}
				});
			}
		});
	}
	$("map_total_records").set("html", "Found <span class='bold'>" + totalRecords + "</span> listings");
	//============ draw polygons =============
	
	/*
	var chkRegions = $("advanced_search").getElements('input[name^=region]'), regions = [];
	chkRegions.each(function(item, i){
		if (item.checked){
			regions.push(item.value);
		}
	});
	regions.each(function(item, i){
		App.map.createPolygon({city: "New York City", region: item});
		
	});
	*/
	App.advSearch.json = null;
}
App.advSearch.setGoogleMapCenter = function(){
	if (App.advSearch.region_id.length == 1){ //just one region selected
		if (App.advSearch.region_id[0] == 1){
			App.map.mapCenter = App.advSearch.regions.Manhattan;
		} else if (App.advSearch.region_id[0] == 2){
			App.map.mapCenter = App.advSearch.regions.Hamptons;
		} else if (App.advSearch.region_id[0] == 3){
			App.map.mapCenter = App.advSearch.regions.Westchester;
		}
	} else if (App.advSearch.region_id.length == 3){
		App.map.mapCenter = App.advSearch.regions.Manhattan_Hamptons_Westchester;
	} else if (App.advSearch.region_id.length == 2){
		if (App.advSearch.region_id.contains('1') && App.advSearch.region_id.contains('2')){
			App.map.mapCenter = App.advSearch.regions.Manhattan_Hamptons;
		} else if (App.advSearch.region_id.contains('1') && App.advSearch.region_id.contains('3')){
			App.map.mapCenter = App.advSearch.regions.Manhattan_Westchester;
		} else if (App.advSearch.region_id.contains('2') && App.advSearch.region_id.contains('3')){
			App.map.mapCenter = App.advSearch.regions.Hamptons_Westchester;
		}
	}
}

App.advSearch.preLoadSnippets = function(){
	App.advSearch.requestSnippet = new Request({
		url: "/assets/snippets/listings.php", 
		method: "get",
		autoCancel: true,
		onSuccess: function(responseText, responseXML){
			App.advSearch.listingSnippet = responseText;
			App.advSearch.requestSnippet = null;  //garbage collection
		}
	});
	App.advSearch.requestSnippet.send();
}

//============ handle search requests
App.advSearch.sendAjaxSearchRequest = function(event, obj){
	if (event) { var e = new Event(event); 
		
		//========= do nothing when certain keys are pressed
		//48 - 57 - numbers
		//65-90 - the characters
		//16,17,18 - shift, control, alt
		var i = 0, invalidKeys = [];
		invalidKeys[i] = 16; i++; invalidKeys[i] = 17; i++; invalidKeys[i] = 18; i++;
		//37, 38, 39, 40 - arrows
		invalidKeys[i] = 37; i++; invalidKeys[i] = 38; i++; invalidKeys[i] = 39; i++; invalidKeys[i] = 40; i++; 
		//33 - 36 - the home, pageup, pagedown, end keys
		invalidKeys[i] = 33; i++; invalidKeys[i] = 34; i++; invalidKeys[i] = 35; i++; invalidKeys[i] = 36; i++; 
		//44, 45, 144 - num, print scrn, insert
		invalidKeys[i] = 44; i++; invalidKeys[i] = 45; i++; invalidKeys[i] = 144; i++; 
		//20 - caps lock
		invalidKeys[i] = 20; i++; 
		
		
		if(invalidKeys.contains(e.code)){ return;  }
	}
	
	//reset google info window
	if (App.map.mapCreated){ 
		App.map.infoWindow.hide();
	}
	//obj.pageNo = page number
	//obj.startingRec = starting record
	//obj.endingRec = ending records
	App.advSearch.setPageinationStats(obj);
	
	//TODO  - DELETE THIS LATER WHEN THRE ARE WESTCHESTER PROPERTIES
	var miami = $("frm_region_4");
	var searchReults = $("search_result_container").getElement("div.tabbedPanel");
	var propsComingSoonPanel = $("search_result_container").getElement("div.props_coming_soon");
	var propsComingSoon = true;
	if (miami.checked && propsComingSoon){
		searchReults.setStyle("display", "none");
		propsComingSoonPanel.setStyle("display", "block");
		return;
	} else {
		searchReults.setStyle("display", "block");
		propsComingSoonPanel.setStyle("display", "none");
	}
	
	//========= send the request to the POST/GET file
	frmSearch = $("advanced_search");
	frmSearch.fireEvent("submit");
	frmSearch = null;
}

//function is called BEFORE sending DATA request
App.advSearch.setPageinationStats = function(obj){
	//obj.pageNo = [age number
	//obj.startingRec = starting record
	//obj.endingRec = ending records
	
	var el = $("advanced_search");
	el.pageNo.value = obj.pageNo;
	el.startingRecord.value = obj.startingRecord;
	el.endingRecord.value = obj.endingRecord;
	el = null;  //garbage collection
}

//function is called AFTER sending DATA request
App.advSearch.updatePagination = function(){
	var frmSearch = $("advanced_search"),
		elCurrPage = $$( $("currPageTop"), $("currPageBottom") ),
		elTotalpPage = $$( $("totalPageTop"), $("totalPageBottom") ),
		elTotalRecords = $$( $("totalRecordsTop"), $("totalRecordsBottom") ),
		i = 0, val = null;
	
	//========== handle page number and total records - UPDATE THE SEARCH FORM
	//set total records and total page numbers
	frmSearch.totalRecords.value = App.advSearch.totalRecords;
	frmSearch.totalPages.value = App.advSearch.totalPages;
	
	if (App.advSearch.totalRecords == 0){
		var currPage = 0;
		App.advSearch.frmPageNext.setProperty("disabled", true);
		App.advSearch.frmPageNext.addClass("disabled");
	} else {
		var currPage = frmSearch.pageNo.value;
	}
	
	//============== handle page numbering
	elCurrPage.set("html", currPage); elCurrPage = null;  //garbage collection
	elTotalpPage.set("html", App.advSearch.totalPages); elTotalpPage = null;  //garbage collection
	elTotalRecords.set("html",  App.advSearch.totalRecords + " matches. "); elTotalRecords = null;
	
	//========== enable/disable pagination buttons
	if (App.advSearch.totalPages == 1){
		App.advSearch.frmPagePrevious.setProperty("disabled", true);
		App.advSearch.frmPagePrevious.addClass("disabled");
		App.advSearch.frmPageNext.setProperty("disabled", true);
		App.advSearch.frmPageNext.addClass("disabled");
	} 
	if (App.advSearch.totalPages ==  frmSearch.pageNo.value){
		App.advSearch.frmPageNext.setProperty("disabled", true);
		App.advSearch.frmPageNext.addClass("disabled");
	} 
	if (frmSearch.pageNo.value == 1){
		App.advSearch.frmPagePrevious.setProperty("disabled", true);
		App.advSearch.frmPagePrevious.addClass("disabled");
	} 
	if (App.advSearch.totalPages > 1 && frmSearch.pageNo.value < App.advSearch.totalPages){
		App.advSearch.frmPageNext.setProperty("disabled", false);
		App.advSearch.frmPageNext.removeClass("disabled");
	}
	if (App.advSearch.totalPages > 1 && frmSearch.pageNo.value > 1){
		App.advSearch.frmPagePrevious.setProperty("disabled", false);
		App.advSearch.frmPagePrevious.removeClass("disabled");
	}
	
	frmSearch = null; //garbage collection
}

App.advSearch.populateResultPage = function(){
	var container = $("listing_container"), i = 0, snippets = [], str = "", css_toggle = "";
		
	App.advSearch.totalRecords = 0;
	App.advSearch.totalPages = 0;
	
	App.advSearch.totalRecords = App.advSearch.json.total;
	App.advSearch.totalPages = App.advSearch.json.pageCount; 
	App.advSearch.itemCount = App.advSearch.json.currentItemCount;
	
	//create google map
	if (App.advSearch.resultTabs.selectedTab == 1){
		App.advSearch.handleGoogleMap();
	} else {
	
		if (App.advSearch.totalRecords){ //if records are returned
			//=========== populate the LIST/MAP with result
			$each(App.advSearch.json.properties, function(details, properties){						//loop through root records - 'total' and 'properties'
	
				//loop through each properties '0,1,2,...'
				//"thumbnail", "fullAddress", "listingID", "address", "address_unit", "city", "state", "zip", "auction_start_date", 
				//"neighborhood", "total_rooms", "beds", "baths", "sqft", "auction_starting_price", "property_type", "openHouses", "saved"
				
				if (css_toggle == ""){
					css_toggle = " container_light";
				} else {
					css_toggle = "";
				}
				
				snippets[i] = new Element("div", { "class": "listing_container" + css_toggle });
				str = App.advSearch.listingSnippet;
				
				var labelClass = "left";
				if (details.property_status == 11 || details.property_status == 12 || details.property_status == 14 || details.property_status == 15){  labelClass = "left left_sold"; }
				
				//===== address and photo
				str = str.str_replace("##ID##", details.listingID);
				str = str.str_replace("##ADDRESS##", details.address + 
								  ", " + details.city + 
								  ", " + details.state + 
								  ", " + details.zip 
								  );
				str = str.str_replace("##IMG##", details.thumbnail);
				
				if (details.listing_terms == 'rental'){
					str = str.str_replace("##RENTAL_ICON_THUMBNAIL##", 'thumbnail_rental');
					str = str.str_replace("##RENTAL_ICON_CLASS##", 'visible');
				} else {
					str = str.str_replace("##RENTAL_ICON_THUMBNAIL##", '');
					str = str.str_replace("##RENTAL_ICON_CLASS##", 'invisible');
				}
				var isDollarEvent = details.dollar_event;
				if (isDollarEvent) isDollarEvent = isDollarEvent.toInt();
				//alert($type(isDollarEvent))
				if (isDollarEvent && details.property_status == 9){ 
					//str = str.str_replace("##DOLLAR_ICON_THUMBNAIL##", 'thumbnail_dollar_event');
					//str = str.str_replace("##DOLLAR_ICON_CLASS##", 'visible');
					str = str.str_replace("<!--##DOLLAR_EVENT##-->", "<a href='/properties/overview.php?id=" + details.listingID + "' class='dollar_event'></a>");
					str = str.str_replace("##DOLLAR_ICON_THUMBNAIL##", '');
					str = str.str_replace("##DOLLAR_ICON_CLASS##", 'invisible');
				} else {
					str = str.str_replace("##DOLLAR_ICON_THUMBNAIL##", '');
					str = str.str_replace("##DOLLAR_ICON_CLASS##", 'invisible');
				}
				
				//set the address class based on status
				if (details.property_status == 11 || details.property_status == 12 || details.property_status == 14 || details.property_status == 15){ 
					str = str.str_replace("##ADDRESS_CLASS##", "sold");
				} else {
					str = str.str_replace("##ADDRESS_CLASS##", "");
				}
				
				//=========== auction notice - property tag
				if (details.property_status == 10){ 
					str = str.str_replace("<!--##ON_AUCTION##-->", "<div class='on_auction'></div>");
				}
				if (details.property_status == 11){ 
					if (details.outcome_status == 1){
						str = str.str_replace("<!--##ON_AUCTION##-->", "<div class='pending'></div>");
					} else {
						str = str.str_replace("<!--##ON_AUCTION##-->", "<div class='auction_closed'></div>");
					}
				} else if (details.property_status == 12){ 
					str = str.str_replace("<!--##ON_AUCTION##-->", "<div class='auction_closed'></div>");
					//str = str.str_replace("<!--##ON_AUCTION##-->", "<div class='sold'></div>");
				} else if (details.property_status == 14){ 
					str = str.str_replace("<!--##ON_AUCTION##-->", "<div class='auction_closed'></div>");
					//str = str.str_replace("<!--##ON_AUCTION##-->", "<div class='closed'></div>");
				}
				
				//======== main details
				//str = str.str_replace("##NEIGHBORHOOD##", details.neighborhood);
				str = str.str_replace("<!--##WEB_ID##-->", "<label class='" + labelClass + "'>Web ID:</label>" + details.listingID + "<br />");
				str = str.str_replace("<!--##REGION##-->", "<label class='region " + labelClass + " bold'>" + details.region[0].region + "</label><br />");
				
				//str = str.str_replace("<!--##LISTING_TYPE##-->", "<label class='" + labelClass + "'>Listing Type:</label>" + details.listing_type + "<br />");
				
				//residential vs. commercial
				str = str.str_replace("<!--##PROPERTY_TYPE##-->", "<label class='" + labelClass + "'>Property Type:</label>" + details.property_type + ((details.listing_terms == 'rental')? ' (' + details.ownership + ')' : '') + "<br />");
				if (details.listing_terms == 'rental'){
					str = str.str_replace("<!--##LISTING_TERMS##-->", "<label class='" + labelClass + "'>Listing Type:</label><span class='emphasized'>" + details.listing_terms.toUpperCase() + "</span><br />");
					str = str.str_replace("<!--##RENTAL_PERIOD##-->", "<label class='" + labelClass + "'>Rental Period:</label>" + details.rental_period + "<br />");
				}
				
				if (details.property_status < 11){
					if (details.property_type == "Residential"){
						str = str.str_replace("<!--##SPACE##-->", 
											  "<label class='" + labelClass + "'>Sq. Footage:</label>" + details.sqft + "<br />" + 
											  "<label class='" + labelClass + "'>Beds &amp; Baths:</label>" + details.beds + " / " + details.baths + "<br />" );
					
					} else {
						if (details.building_sqft){
							str = str.str_replace("<!--##SPACE##-->", "<label class='" + labelClass + "'>Building SF:</label>" + details.building_sqft + "<br />");
						}
						if (details.residential_units != null && details.commercial_units != null){
							str = str.str_replace("<!--##NO_UNITS##-->", "<label class='" + labelClass + "'>No. of Units:</label>" + (details.residential_units.toInt() + details.commercial_units.toInt()) + "<br />");
						}
					}
				}
				
				//show prices
				var closing_bid = details.closing_bid;
				(closing_bid) ? closing_bid = (closing_bid+"").toCurrency() : closing_bid = "N/A";
				
				//rental prices
				if (details.listing_terms == 'rental'){
					//str = str.str_replace("<!--##ORIGINAL_PRICE##-->", "<label class='" + labelClass + "'>Asking Rent:</label>" + (details.rent_amount+"").toCurrency() + "<br />");
					str = str.str_replace("<!--##ORIGINAL_PRICE##-->", "");
					if (details.property_status < 11){
						str = str.str_replace("<!--##STARTING_BID##-->", "<label class='" + labelClass + "'>Starting Bid:</label>" + (details.auction_starting_price+"").toCurrency() + ((details.auction_method == 'reverse') ? " (Bid for Less)" : "") + "<br />");
					} else {
						str = str.str_replace("<!--##STARTING_BID##-->", "<label class='" + labelClass + "'>Owner Asks:</label>" + (details.auction_starting_price+"").toCurrency() + "<br /><label class='" + labelClass + "'>Closing Bid:</label>" + closing_bid + "<br />");
					}
				}
				
				//auction vs. sale
				if (details.listing_type != "Sale"){
					str = str.str_replace("<!--##ORIGINAL_PRICE##-->", "<label class='" + labelClass + "'>Original Price:</label>" + (details.original_price+"").toCurrency() + "<br />");
					if (details.property_status < 11){
						str = str.str_replace("<!--##STARTING_BID##-->", "<label class='" + labelClass + "'>Starting Bid:</label>" + (details.auction_starting_price+"").toCurrency() + ((details.auction_method == 'reverse') ? " (Bid for Less)" : "") + "<br />");
					} else {
						str = str.str_replace("<!--##STARTING_BID##-->", "<label class='" + labelClass + "'>Starting Bid:</label>" + (details.auction_starting_price+"").toCurrency() + "<br /><label class='" + labelClass + "'>Closing Bid:</label>" + closing_bid + "<br />");
					}
				} else {
					str = str.str_replace("<!--##SALE_PRICE##-->", "<label class='" + labelClass + "'>Sale Price:</label>" + (details.sale_price+"").toCurrency() + "<br />");
				}
				
				
				//======== buttons ====
				
				//save listing buttons
				//alert(user_id + " " + details.owner_id.toInt() + (user_id != details.owner_id.toInt()));
				if (user_id != details.owner_id.toInt()){
					if (!details.saved){
						if (details.property_status < 11){
							strHtml = '<div class="button">' + 
											'<a class="link save" href="/properties/property_post.php?saveListing=true&listingID=' + details.listingID +'">Add as Favorite</a>' + 
									   '</div>';
							str = str.str_replace("<!--##SAVE##-->", strHtml);
						}
					}	else {
						str = str.str_replace("<!--##A_FAVORITE##-->", "<a class='link favorite'></a>");
					}
					
					if (details.listing_type == "Auction"){
						//Bid Now
						if (details.property_status == 10 && isUserBroker == false){
							strHtml = '<div class="button">' + 
											'<a class="link bid_now" href="/properties/bidding.php?id=' + details.listingID +'">Bid Now</a>' + 
									   '</div>';
							str = str.str_replace("<!--##BIDDING##-->", strHtml);		
						} else if (details.property_status == 9 && isUserBroker == false){
							strHtml = '<div class="button">' + 
											'<a class="link bid_now" href="/properties/bidding_enrollment.php?id=' + details.listingID +'">Enroll to Bid</a>' + 
									   '</div>';
							str = str.str_replace("<!--##BIDDING##-->", strHtml);		
						}
					}
				} else if (user_id == details.owner_id.toInt() && isUserBroker){
					strHtml = '<div class="button">' + 
								'<a class="link manage" href="/properties/manage_property.php?id=' + details.listingID +'">Manage Listing</a>' + 
							  '</div>';
					str = str.str_replace("<!--##MANAGE##-->", strHtml);
					
					
				}
				
				//view property
				strHtml = '<div class="button">' + 
								'<a class="link view" href="/properties/overview.php?id=' + details.listingID +'">More Details</a>' + 
						   '</div>';
				str = str.str_replace("<!--##VIEW##-->", strHtml);
				
				//email to friend
				strHtml = '<div class="button">' + 
								'<a class="link email_friend" href="/properties/email_friend.php?id=' + details.listingID + '">Email to Friend</a>' + 
						   '</div>';
				str = str.str_replace("<!--##EMAIL##-->", strHtml);
				
				//contact agent
				if (details.listing_type == "Sale"){
					strHtml = '<div class="button">' + 
									'<a class="link contact_agent" href="/properties/contact_agent.php?id=' + details.listingID + '">Contact Agent</a>' + 
							   '</div>';
					str = str.str_replace("<!--##CONTACT_AGENT##-->", strHtml);
				}
				
				//win 100K
				if (details.game_period_id){
					if (details.bet_amount){
						var btn_text = "Update Guess";
					} else {
						var btn_text = "WIN $100K";
					}
					strHtml = '<div class="button">' + 
								'<a class="link win_100K" href="/properties/modal_guessing.php?auctionID=' + details.auctionID + '">' + btn_text + '</a>' + 
						   '</div>';
					str = str.str_replace("<!--##WIN_100K##-->", strHtml);	
				}
				
				//======= auction and open house dates
				if (details.listing_type != "Sale"){
					
					if (details.property_status < 11){
						str = str.str_replace("<!--##AUCTION_DATE##-->", "<label class='left bold'>Bidding Event:</label>" + details.auction_start_date + "<br />");
					} else {
						str = str.str_replace("<!--##AUCTION_DATE##-->", "<label class='left_sold bold'><span class='normal bold'>Bidding Started</span>: " + details.auction_start_date + ", <span class='normal bold'>Bidding Closed</span>: " + details.closing_date + "</label>");
					}
				}
				
				//Open House Dates
				if (details.property_status < 11){ 
					if (details.openHouses){
						var strHtml = "";
						for (oh=0;oh<details.openHouses.length;oh++){
							if (strHtml.length > 0){
								strHtml += "&nbsp;&nbsp;|&nbsp;&nbsp;";
							}
							strHtml += details.openHouses[oh].date + " " + 
									 details.openHouses[oh].start_time + " to " + 
									 details.openHouses[oh].end_time;
						}
						str = str.str_replace("<!--##OPEN_HOUSE_DATES##-->", "<label class='left bold'>Open House:</label>" + strHtml);
					}
				}
				
				//insert the HTML into the snippet code
				snippets[i].set("html", str);
				i++; //i is set to keep track of each new property snippet
			});
			
			//garbage previous display
			tempEl = container.getElements(".listing_container"); 
			if (tempEl){ tempEl.destroy();  }
			tempEl = null;
			
			//create the new display
			container.empty();
			tempEl = $$(snippets); tempEl.injectInside(container); 
			tempEl = null; App.collectGarbage(snippets); 
			
			//========== add the events ==============
			//save listing
			tempEl = container.getElements(".save");
			tempEl.addEvent("click", function(event){
				event.stop();
				var lnk = this;
				this.set("html", "Adding ...");
				var req1 = new Request({
					url: this.href, 
					method: "get",
					autoCancel: true,
					onSuccess: function(responseText, responseXML){
						var json = JSON.decode(responseText);
						App.roar.empty();
						App.roar.alert("Save Favorite", "<span class='" + json.CssClass + "'>" + json.msg + "</span>");
						if (json.CssClass == "success"){	
							var lnk_parent = lnk.getParent();
							lnk.empty();
							lnk.removeProperty("href");
							lnk.removeClass("save");
							lnk.addClass("favorite");
							lnk.inject(lnk.getParent(".button_container"), "top");
							lnk_parent.destroy();
							App.updateFavoriteCount(true);
						} else {
							lnk.set("html", "Add as Favorite");
						}
							
					}
				}).send();
				
			});
			App.storeEvents(tempEl, "click");
			tempEl = null;
			
			//email to friend listing
			tempEl = container.getElements(".email_friend");
			tempEl.addEvent("click", function(event){
				new Event(event).stop();
				App.modal.launch({ width: 730, height: 480, title: "Email Listing to Friend", iframe: true, url: this.href });
			});
			App.storeEvents(tempEl, "click");
			tempEl = null;
			
			//contact broker listing
			tempEl = container.getElements(".contact_agent");
			tempEl.addEvent("click", function(event){
				new Event(event).stop();
				App.modal.launch({ width: 730, height: 410, title: "Contact Agent", iframe: true, url: this.href });
			});
			App.storeEvents(tempEl, "click");
			tempEl = null;
			
			//email to friend listing
			tempEl = container.getElements(".win_100K");
			tempEl.addEvent("click", function(event){
				new Event(event).stop();
				App.modal.launch({ width: 850, height: 480, title: 'Play "Guess 10 for $100,000?"', iframe: true, url: this.href,
						onClose: function(){
							if (top.reload) top.location.href = top.location.href;
							App.modal.onClose = function(){};
						}
					});
			});
			App.storeEvents(tempEl, "click");
			tempEl = null;
			
			
			
			
		} else {
			//============= What happens if there is no result	
		
			container.empty();
			var msg = new Element("div", { "class": "error margin_normal" }).set("html", 'Sorry, no properties found. Try to modify your search choices.')
			msg.inject(container);
			msg = null;
			//App.advSearch.resultTabs.select(App.advSearch.resultTabs.selectedTab);
		
		} //if (App.advSearch.totalRecords){
			
		//========== pagination
		App.advSearch.updatePagination();
			
		container = null; //garbage collection
			
	} //if (App.advSearch.resultTabs.selectedTab == 1){
		
}


App.advSearch.disableFieldsForCommercial = function(bool){
	var beds = $("advanced_search").getElements("input[name^=beds]");	
	var baths = $("advanced_search").getElements("input[name^=baths]");	
	var ownership = $("advanced_search").getElements("input[name^=ownership]");	
	var buildingAge = $("advanced_search").getElements("input[name^=buildingAge]");	
	var access = $("advanced_search").getElements("input[name^=access]");	
	var serviceLevel = $("advanced_search").getElements("input[name^=serviceLevel]");	
	var petPolicy = $("advanced_search").getElements("input[name^=petPolicy]");	
	var ads_washerdryer = $("ads_washerdryer");	
	var ads_outdoor = $("ads_outdoor");	
	var ads_loft = $("ads_loft");	
	
	var els = $$(beds, baths, ownership, buildingAge, access, serviceLevel, petPolicy, ads_washerdryer, ads_outdoor, ads_loft);
	
	if (bool){
		els.setProperty("disabled", "disabled");
		els.removeProperty("checked");
	} else {
		els.removeProperty("disabled");
	}
	
	//garbage collection
	beds = null; 
	baths = null; 
	ownership = null; 
	buildingAge = null;  
	access = null; 
	serviceLevel = null; 
	petPolicy = null; 
	ads_washerdryer = null; 
	ads_outdoor = null; 
	ads_loft = null; 
	els = null;
}

