var maploaded = false;
var Communities = {

	list: new Array(),
		
	id: 'dynamic',
		//the <div> id where Communities are disabled and rewritten
	obj: 'this will be the document element of the id:',
		//the DOM  object associated to the id (for easier access)
	formName: 'amenities',
		//the name of the DOM form element with filter controls
	amenitiesList: new Array(),
		//a numerically indexed normal array of all the possible amenities on the Community Select page
	amenities: new Object(),
	
	amenitiesLanguage: new Array(),
		//an associative array (as an object) where a key is an amenity and its value is true or false, corresponding to which amenities are checked off
	rentSorted: false,
		//the state of rent sorting (false, "ascending", "descending")
	bedroomsSorted: false,
	
	bedroomsDisplaying: 0,
		//the number of bedrooms selected in the filter
	townhomesDisplaying: false,
	
	bathsDisplaying: 10,
	
	maxrentDisplaying: "Any",
		//the maximum rent selected in the filter
	primaryCity: null,
		//if a query string shows a primaryCity it's saved here and transferred to the filter cookie
	currentHighlight: 0,
	tackOriginalId: -1,
	loadedFromQuery: {bedrooms: false, baths: false, maxrent: false, city: false, rentSorted: false, townhomes: false},
	
	add: function(community) {
			//adds a community object to the Communities.list array, and adds its obj, hideCount, hide, and defaultOrder properties
			//takes a community object (from the in-page script)
			//returns nothing
		community.obj = document.getElementById('community_' + (this.list.length+1));
		community.originalId = this.list.length+1;
		community.hideCount = 0;
		community.hide = new Object();
		community.defaultOrder = this.list.length-1;
		community.rentRange = {min: community.rent.min, max: community.rent.max};
		//sort unit list by bedrooms
		//and bedroom chunks by bathrooms
		
		community.Units = community.Units.sort(this.Sort.unitSort);
		var safeMaxBedrooms = 0;
		var safeMaxBaths = 0;
		
		var safeTownhomeMaxBedrooms = 0;
		var safeTownhomeMaxBaths = 0;
		
		for(var c=0;c<community.Units.length;c++) {
			if (community.Units[c].bedrooms > safeMaxBedrooms) safeMaxBedrooms = community.Units[c].bedrooms;
			if (community.Units[c].baths > safeMaxBaths) safeMaxBaths = community.Units[c].baths;
			if (community.Units[c].townhome) {
				if (community.Units[c].bedrooms > safeTownhomeMaxBedrooms) safeTownhomeMaxBedrooms = community.Units[c].bedrooms;
				if (community.Units[c].baths > safeTownhomeMaxBaths) safeTownhomeMaxBaths = community.Units[c].baths;
			}
		}
		community.maxBedrooms = safeMaxBedrooms;
		community.maxBaths = safeMaxBaths * 10;
		
		community.townhomeMaxBedrooms = safeTownhomeMaxBedrooms;
		community.townhomeMaxBaths = safeTownhomeMaxBaths * 10;
		
		community.UnitsRent = new Object();
		community.TownhomesRent = new Object();
		community.hasAnyTownhomes = false;
		var bedroomsWorking = community.maxBedrooms;
		community.UnitsRent["bedrooms_" + bedroomsWorking] = {baths_10: [], baths_15: [], baths_20: [], baths_25: []};
		community.TownhomesRent["bedrooms_" + bedroomsWorking] = {baths_10: [], baths_15: [], baths_20: [], baths_25: []};
		for(var c=0;c<community.Units.length;c++) {
			while(bedroomsWorking != community.Units[c].bedrooms && bedroomsWorking > -1) {
				bedroomsWorking--;
				community.UnitsRent["bedrooms_" + bedroomsWorking] = {baths_10: [], baths_15: [], baths_20: [], baths_25: []};
				community.TownhomesRent["bedrooms_" + bedroomsWorking] = {baths_10: [], baths_15: [], baths_20: [], baths_25: []};
			}
			bathsWorking = community.Units[c].baths*10;
			if (community.Units[c].townhome) {
				community.TownhomesRent["bedrooms_" + bedroomsWorking]["baths_" + bathsWorking].push(community.Units[c].rent);		
				community.hasAnyTownhomes = true;
			}
			community.UnitsRent["bedrooms_" + bedroomsWorking]["baths_" + bathsWorking].push(community.Units[c].rent);
		}
		while(bedroomsWorking > 0) {
			bedroomsWorking--;
			community.UnitsRent["bedrooms_" + bedroomsWorking] = {baths_10: [], baths_15: [], baths_20: [], baths_25: []};
			community.TownhomesRent["bedrooms_" + bedroomsWorking] = {baths_10: [], baths_15: [], baths_20: [], baths_25: []};
		}
		
		var WorkingUnitsRent = new cloneObject(community.UnitsRent);
		community.WorkingUnitsRent = WorkingUnitsRent;
		var WorkingTownhomesRent = new cloneObject(community.TownhomesRent);
		community.WorkingTownhomesRent = WorkingTownhomesRent;
		
		for(var c=community.maxBedrooms;c>-1;c--) {
			var bedroomsWorkingOn = "bedrooms_" + c;
			var bedroomsPrevious = "bedrooms_" + (c+1);
			for(d=25;d>5;d-=5) {
				var bathsWorkingOn = "baths_" + d;
				var bathsPrevious = "baths_" + (d+5);
				var totalRents = community.WorkingUnitsRent[bedroomsWorkingOn][bathsWorkingOn];
				//all this doubling needs to be optimized
				var totalTownhomesRents = community.WorkingTownhomesRent[bedroomsWorkingOn][bathsWorkingOn];
				
				if (community.WorkingUnitsRent[bedroomsWorkingOn][bathsPrevious]) totalRents = totalRents.concat(community.WorkingUnitsRent[bedroomsWorkingOn][bathsPrevious]).sort(this.Sort.ascending);
				if (community.WorkingTownhomesRent[bedroomsWorkingOn][bathsPrevious]) totalTownhomesRents = totalTownhomesRents.concat(community.WorkingTownhomesRent[bedroomsWorkingOn][bathsPrevious]).sort(this.Sort.ascending);
				
				if (c<community.maxBedrooms && community.WorkingUnitsRent[bedroomsPrevious][bathsWorkingOn]) {				
					totalRents = totalRents.concat(community.WorkingUnitsRent[bedroomsPrevious][bathsWorkingOn]).sort(this.Sort.ascending);
				}
				if (c<community.maxBedrooms && community.WorkingTownhomesRent[bedroomsPrevious][bathsWorkingOn]) {				
					totalTownhomesRents = totalTownhomesRents.concat(community.WorkingTownhomesRent[bedroomsPrevious][bathsWorkingOn]).sort(this.Sort.ascending);
				}
				//reduce some of the repetition
				for (e=0;e<totalRents.length-1;e++) {
					if (totalRents[e+1]==totalRents[e]) totalRents.splice(e,1);
				}
				for (e=0;e<totalTownhomesRents.length-1;e++) {
					if (totalTownhomesRents[e+1]==totalTownhomesRents[e]) totalTownhomesRents.splice(e,1);
				}
				community.WorkingUnitsRent[bedroomsWorkingOn][bathsWorkingOn] = totalRents;
				community.WorkingTownhomesRent[bedroomsWorkingOn][bathsWorkingOn] = totalTownhomesRents;								
			}
		}
		//alert(community.WorkingUnitsRent.bedrooms_3.baths_20);
		//alert(community.WorkingTownhomesRent.bedrooms_3.baths_20);
		community.Rent = community.UnitsRent;
		community.WorkingRent = community.WorkingUnitsRent;
			
		this.list.push(community);
		
		savedBedroomsBathsObject = this.saveBedroomsBathsRanges(this.list.length-1);
		this.list[this.list.length-1].dataDisplaying = this.outputRange(savedBedroomsBathsObject.bedrooms, '', true) + " " + this.outputRange(savedBedroomsBathsObject.baths) + " " + this.outputRange(community.rent, '$');
	},
	
	Sort: {
		unitSort: function(a,b) {
			return (a.bedrooms==b.bedrooms ? (b.baths-a.baths):(b.bedrooms-a.bedrooms));
		},
			//object that holds all custom array.sort functions
		ascending: function(a,b) {
				//used to sort numerically ascending
			return(a-b)
		},
		descending: function(a,b) {
				//used to sort numerically descending
			return(b-a)
		},
		byAmenity: function(a,b) {
				//used to sort any filtered out community after any non-filtered community, and by rent within the two groups
			return ((a.hideCount && !b.hideCount) ? 1 :((b.hideCount && !a.hideCount) ? -1 : Sort.byRent(a,b)));			
		},
		
		byRent: function(a,b) {
				//used to sort by the specified bedroom's rent range
			bedroomsDisplaying = "bedrooms_" + Communities.bedroomsDisplaying;
			bathsDisplaying = "baths_" + Communities.bathsDisplaying;
			
			grayedOutSort = ((Communities.rentSorted == 'ascending') ? Sort.ascending(a.WorkingRent.bedrooms_0.baths_10[0], b.WorkingRent.bedrooms_0.baths_10[0]) :
					((Communities.rentSorted == 'descending') ? Sort.descending(a.WorkingRent.bedrooms_0.baths_10[a.WorkingRent.bedrooms_0.baths_10.length-1], b.WorkingRent.bedrooms_0.baths_10[b.WorkingRent.bedrooms_0.baths_10.length-1]) :
					Sort.ascending(a.defaultOrder, b.defaultOrder)));
					
			
			if (a.hideCount && b.hideCount) return grayedOutSort;
				
			minRent = {a: a.rentRange.min,
						b: b.rentRange.min};
			maxRent = {a: a.rentRange.max,
						b: b.rentRange.max};	

			nonGrayedOutSort = ((Communities.rentSorted == 'ascending') ? Sort.ascending(minRent.a, minRent.b) :
					((Communities.rentSorted == 'descending') ? Sort.descending(maxRent.a, maxRent.b) :
					Sort.ascending(a.defaultOrder, b.defaultOrder)));
			
			return nonGrayedOutSort;
		}
	},	
	
	sortByRent: function() {
			//sets Communities.rentSorted, runs all the sorting
			//returns nothing
		this.rentSorted = (!this.rentSorted ? 'ascending' :
			((this.rentSorted=='ascending') ? 'descending' : false));
		this.list = this.list.sort(this.Sort.byAmenity);
		this.redraw();
		//setting class to show
		document.getElementById('rent-sort-btn').className = (this.rentSorted ? this.rentSorted : "not-sorted");
	},
	
	filterByAmenities: function(clickedAmenity, dontRedraw) {
			//sets Communities.amenities, filters grayed and non-grayed communities, and runs all the sorting
			//takes which amenity was clicked (uses DOM to get value)
			//returns nothing
		this.amenities[clickedAmenity] = document[this.formName][clickedAmenity].checked;
		if (document[this.formName][clickedAmenity].checked) {
			for (var c=0;c<this.list.length;c++) {
				if (!this.list[c].amenities[clickedAmenity]) {
					this.hideManage(c, clickedAmenity, true);
				}
			}
		}
		else {
			for (var c=0;c<this.list.length;c++) {
				this.hideManage(c, clickedAmenity, false);
			}
		}
		
		this.list = this.list.sort(this.Sort.byAmenity);
		if (!dontRedraw) this.redraw();
	},
	
	filterByBedrooms: function(data, dontRedraw) {
			//sets Communities.bedroomsDisplaying, filters communities that do not fit bedrooms selection, also rechecks maxrent qualification based on new # bedrooms
			//takes the value of the bedrooms dropdown
			//returns nothing
			
		this.bedroomsDisplaying = parseInt(data);
		data = parseInt(data);
		
		for (var c=0;c<this.list.length;c++) {
			maxBedrooms = this.list[c].maxBedrooms;
			if (this.townhomesDisplaying) maxBedrooms = this.list[c].townhomeMaxBedrooms;
			if (data == 0) this.hideManage(c, "bedrooms", false);
			else {
				if (data > maxBedrooms) this.hideManage(c, "bedrooms", true);
				else this.hideManage(c, "bedrooms", false);
			}
			this.hideOrShowByMaxrent(c);
		}
		
		this.list = this.list.sort(this.Sort.byAmenity);
		if (!dontRedraw) this.redraw();
	},
	
	filterByBaths: function(data, dontRedraw) {
			//half baths come in as 15 and 25
		this.bathsDisplaying = parseInt(data);	
		data = parseInt(data);		

		
		for (var c=0;c<this.list.length;c++) {
			maxBaths = this.list[c].maxBaths;
			if (this.townhomesDisplaying) maxBaths = this.list[c].townhomeMaxBaths;
			if (data == 10) this.hideManage(c, "baths", false);
			else {
				if (data > maxBaths) this.hideManage(c, "baths", true);
				else this.hideManage(c, "baths", false);
			}
			this.hideOrShowByMaxrent(c);
		}
		
		this.list = this.list.sort(this.Sort.byAmenity);
		if (!dontRedraw) this.redraw();
	},
	
	filterByTownhomes: function(dontRedraw) {
		var data = document[this.formName].townhomes.checked;
		this.townhomesDisplaying = data;
		for(var c=0;c<this.list.length;c++) {
			if (data) {
				if (this.list[c].hasAnyTownhomes) {
					this.list[c].Rent = this.list[c].TownhomesRent;
					this.list[c].WorkingRent = this.list[c].WorkingTownhomesRent;
				}
				else this.hideManage(c, "townhome", true);
			
				if (this.bedroomsDisplaying == 0) this.hideManage(c, "bedrooms", false);
				else {
					if (this.bedroomsDisplaying > this.list[c].townhomeMaxBedrooms) this.hideManage(c, "bedrooms", true);
					else this.hideManage(c, "bedrooms", false);
				}				
				if (this.bathsDisplaying == 10) this.hideManage(c, "baths", false);
				else {
					if (this.bathsDisplaying > this.list[c].townhomeMaxBaths) this.hideManage(c, "baths", true);
					else this.hideManage(c, "baths", false);
				}
			}
			else {
				this.list[c].Rent = this.list[c].UnitsRent;
				this.list[c].WorkingRent = this.list[c].WorkingUnitsRent;
				this.hideManage(c, "townhome", false);
				
				if (this.bedroomsDisplaying == 0) this.hideManage(c, "bedrooms", false);
				else {
					if (this.bedroomsDisplaying > this.list[c].maxBedrooms) this.hideManage(c, "bedrooms", true);
					else this.hideManage(c, "bedrooms", false);
				}				
				if (this.bathsDisplaying == 10) this.hideManage(c, "baths", false);
				else {
					if (this.bathsDisplaying > this.list[c].maxBaths) this.hideManage(c, "baths", true);
					else this.hideManage(c, "baths", false);
				}
			}
			this.hideOrShowByMaxrent(c);
		}		
			
		this.list = this.list.sort(this.Sort.byAmenity);
		if (!dontRedraw) this.redraw();
	},
	
	filterByMaxrent: function(data, dontRedraw) {
			//sets Communities.maxrentDisplaying, filters communities that don't fit maxRent selection based on # bedrooms selected
			//takes value from maxrent dropdown
			//returns nothing
		if (data =="Any") this.maxrentDisplaying = data;
		else this.maxrentDisplaying = parseInt(data);
		for (var c=0;c<this.list.length;c++) {
			this.hideOrShowByMaxrent(c);
		}		
		this.list = this.list.sort(this.Sort.byAmenity);
		if (!dontRedraw) this.redraw();
	},
	
	hideOrShowByMaxrent: function(listIndex) {
		var rentRange = this.getRentRange(listIndex);
		if (this.maxrentDisplaying == "Any") {
			this.hideManage(listIndex, "maxrent", false);
			if (this.list[listIndex].hideCount<1) this.list[listIndex].rentRange = {min: rentRange.min, max: rentRange.max};
		}
		else {
			if (rentRange.min > this.maxrentDisplaying) this.hideManage(listIndex, "maxrent", true);
			else {
				this.hideManage(listIndex, "maxrent", false);
				this.saveRentRange(listIndex, rentRange);
			}
		}
	},
	
	saveBedroomsBathsRanges: function(listIndex) {		
		//check each bed_bath combo for a Rent entry - meaning a place exists
		//if place exists, add that # of baths to the baths range
		var bathsRange = new Array();
		var bedroomsRange = new Array();
		for (var c=10;c<30;c+=5) {			
			if (c == this.list[listIndex].maxBaths) bathsStopChecking = c;
		}
		
		for(var c=this.bedroomsDisplaying;c<=this.list[listIndex].maxBedrooms;c++) {
			bedroomsChecking = "bedrooms_" + c;		
			for(var d=this.bathsDisplaying;d<=bathsStopChecking;d+=5) {
				bathsChecking = "baths_" + d;
				//if there's a rent at this bed bath, add bath to baths range
				if (this.list[listIndex].Rent[bedroomsChecking][bathsChecking].length) {
					var e=0;
					while(this.list[listIndex].Rent[bedroomsChecking][bathsChecking][e]>this.maxrentDisplaying && e<this.list[listIndex].Rent[bedroomsChecking][bathsChecking].length) e++;
					if (e<this.list[listIndex].Rent[bedroomsChecking][bathsChecking].length) {
						bathsRange.push(d);
						bedroomsRange.push(c);
					}
				}				
			}
		}
		bedroomsRange = bedroomsRange.sort();
		bathsRange = bathsRange.sort();
		//this.list[listIndex].bathsRange = {min: bathsRange[0]/10, max: bathsRange[bathsRange.length-1]/10};
		//this.list[listIndex].bedroomsRange = {min: bedroomsRange[0], max: bedroomsRange[bedroomsRange.length-1]};
		return {baths: {min: bathsRange[0]/10, max: bathsRange[bathsRange.length-1]/10},
			bedrooms: {min: bedroomsRange[0], max: bedroomsRange[bedroomsRange.length-1]}}
	},
	
	outputRange: function(rangeObject, leadingChar, zeroAsStudio) {
		if (!leadingChar) leadingChar = '';		
		if (rangeObject.min == rangeObject.max) {
			if (zeroAsStudio && (rangeObject.min == 0)) rangeObject.min = "Studio";
			return (leadingChar + rangeObject.min.toString());
		}
		if (zeroAsStudio && (rangeObject.min == 0)) rangeObject.min = "Studio";
		return (leadingChar + (rangeObject.min) + " - " + leadingChar + rangeObject.max)
	},
	
	getRentRange: function(listIndex) {
		bedroomsDisplaying = "bedrooms_" + this.bedroomsDisplaying;
		bathsDisplaying = "baths_" + this.bathsDisplaying;		
		if (typeof this.list[listIndex].WorkingRent[bedroomsDisplaying]=='object') {
			if (this.list[listIndex].WorkingRent[bedroomsDisplaying][bathsDisplaying].length > 0) {
				var min = this.list[listIndex].WorkingRent[bedroomsDisplaying][bathsDisplaying][0];
				var max = this.list[listIndex].WorkingRent[bedroomsDisplaying][bathsDisplaying][this.list[listIndex].WorkingRent[bedroomsDisplaying][bathsDisplaying].length-1];		
				return {min: min, max: max, asArray: this.list[listIndex].WorkingRent[bedroomsDisplaying][bathsDisplaying]};
			}
		}
		return {min: 0, max: 0, asArray: [0]}
	},
	
	saveRentRange: function(listIndex, rentRange) {
		if (rentRange.max <= this.maxrentDisplaying) this.list[listIndex].rentRange = rentRange;
		else {
			var c=rentRange.asArray.length-1;
			while(rentRange.asArray[c]>this.maxrentDisplaying) c--;
			this.list[listIndex].rentRange = {min: rentRange.min, max: rentRange.asArray[c]};
		}
	},
	
	hideManage: function(listIndex, hideName, becomeHidden) {
			//changes Communities.list's community css classes, incriments hideCount and sets hide Object
			//listIndex =  index of a community in Communities.list, hideName = amenity working with, becomeHidden is boolean
			//returns nothing
		if (becomeHidden) {
			if (!this.list[listIndex].hide[hideName]) this.list[listIndex].hideCount ++;
			this.list[listIndex].hide[hideName] = true;
			this.list[listIndex].obj.className = "deactivated";
		}
		else {
			if (this.list[listIndex].hide[hideName]) {
				this.list[listIndex].hide[hideName] = null;
				this.list[listIndex].hideCount --;
				if (!this.list[listIndex].hideCount) {
					this.list[listIndex].obj.className = "";
				}
			}
		}
	},
	
	highlight: function(elementOriginalId) {
		try {
			if (maploaded) {
				if (this.tackOriginalId != -1) tackmouseout(this.tackOriginalId);
				tackmouseover(elementOriginalId);
				this.tackOriginalId = elementOriginalId;
			}
		}
		catch (err) {
		}
		this.list[this.currentHighlight].obj.className = this.list[this.currentHighlight].obj.className.split('highlighted')[0];
		for(var c=0;c<this.list.length;c++) {
			if (this.list[c].originalId == elementOriginalId) {
				if (this.list[c].obj.className.split('highlighted').length<2) this.list[c].obj.className += " highlighted";
				this.currentHighlight = c;
			}
		}
	},
	
	redraw: function() {
			//typically called after a sort, removes all DOM elements in the DOM's Communities.obj element and redraws them (in a new order)
			//returns nothing		
		
		Printout.countShowing = 0;
		Printout.bedrooms = this.bedroomsDisplaying;
		Printout.baths = this.bathsDisplaying/10;
		Printout.maxrent = this.maxrentDisplaying;
		Printout.townhomes = this.townhomesDisplaying;
		Printout.amenities = new Array();
		for(var c=0;c<this.amenitiesList.length;c++) {
			if (this.amenities[this.amenitiesList[c]]) Printout.amenities.push(this.amenitiesLanguage[c]);
		}
		
		for (var c=0;c<this.list.length;c++) {
			savedBedroomsBathsObject = this.saveBedroomsBathsRanges(c);
			this.list[c].bathsRange = savedBedroomsBathsObject.baths;
			this.list[c].bedroomsRange = savedBedroomsBathsObject.bedrooms;	
			
			var rentRangeElements = getElementsByClass("rent-range", this.list[c].obj);
			var bathsRangeElements = getElementsByClass("baths-range", this.list[c].obj);
			var bedroomsRangeElements = getElementsByClass("bedrooms-range", this.list[c].obj);
			var rentRangeDynamicElements = getElementsByClass("rent-range-dynamic", this.list[c].obj);
			var bathsRangeDynamicElements = getElementsByClass("baths-range-dynamic", this.list[c].obj);
			var bedroomsRangeDynamicElements = getElementsByClass("bedrooms-range-dynamic", this.list[c].obj);
			
			if (this.list[c].hideCount==0) {
				Printout.countShowing++;
				rentRange = this.outputRange(this.list[c].rentRange, '$');
				bathsRange = this.outputRange(this.list[c].bathsRange);
				bedroomsRange = this.outputRange(this.list[c].bedroomsRange, '', true);
				
				if (rentRangeDynamicElements[0].firstChild) rentRangeDynamicElements[0].removeChild(rentRangeDynamicElements[0].firstChild);
				rentRangeDynamicElements[0].appendChild(document.createTextNode(rentRange));
				if (bathsRangeDynamicElements[0].firstChild) bathsRangeDynamicElements[0].removeChild(bathsRangeDynamicElements[0].firstChild);
				bathsRangeDynamicElements[0].appendChild(document.createTextNode(bathsRange));			
				if (bedroomsRangeDynamicElements[0].firstChild) bedroomsRangeDynamicElements[0].removeChild(bedroomsRangeDynamicElements[0].firstChild);
				bedroomsRangeDynamicElements[0].appendChild(document.createTextNode(bedroomsRange));
			}
			
			if (this.list[c].hideCount > 0 || this.list[c].dataDisplaying == bedroomsRange + " " + bathsRange + " " + rentRange) {
				rentRangeDynamicElements[0].style.display = "none";
				bathsRangeDynamicElements[0].style.display = "none";
				bedroomsRangeDynamicElements[0].style.display = "none";
				rentRangeElements[0].style.fontSize = "14px";
				bathsRangeElements[0].style.fontSize = "14px";
				bedroomsRangeElements[0].style.fontSize = "14px";
				rentRangeElements[0].style.color = "#333";
				bathsRangeElements[0].style.color = "#333";
				bedroomsRangeElements[0].style.color = "#333";
			}
			else {
				rentRangeDynamicElements[0].style.display = "block";
				bathsRangeDynamicElements[0].style.display = "block";
				bedroomsRangeDynamicElements[0].style.display = "block";
				rentRangeElements[0].style.fontSize = "12px";
				bathsRangeElements[0].style.fontSize = "12px";
				bedroomsRangeElements[0].style.fontSize = "12px";
				rentRangeElements[0].style.color = "#888";
				bathsRangeElements[0].style.color = "#888";
				bedroomsRangeElements[0].style.color = "#888";					
			}
			var rowClass = (c/2 == Math.round(c/2) ? "c-odd" : "c-even");
			if (this.list[c].obj.className.substring(0,11) == "deactivated") this.list[c].obj.className = "deactivated " + rowClass;
			else this.list[c].obj.className = rowClass;
			//tempObj.appendChild(copyObj);
		}
		
		//while (this.obj.hasChildNodes()) {
		//	this.obj.removeChild(this.obj.firstChild);
		//}
		for(var c=0;c<this.list.length;c++) {
			this.obj.appendChild(this.list[c].obj);
		}
		
		
		lineElement = document.getElementById('selector-description');
		while (lineElement.hasChildNodes()) {
			lineElement.removeChild(lineElement.firstChild);
		}
		lineElement.appendChild(Printout.write());		
		if (Printout.countShowing < Printout.countTotal) {
			var resetLink = Dom.create({tag: "a", href: "javascript: Communities.showAll()", text: "Show all " + Printout.countTotal});
			lineElement.appendChild(resetLink);
		}		
	},
		
	finalize: function(id) {
			//clean-up after in-page script has added all communities to Communities.list
			//returns nothing
		this.id = id;
		this.obj = document.getElementById(Communities.id);
		this.totalAmenities();
		if (Dom) {
			//removes in-page script that added communities to Communities
			var scriptElements = this.obj.getElementsByTagName('script');
			while (scriptElements.length) {	
				Dom.remove(scriptElements[0]);
			}
		}
		Printout.initialize();
		this.loadQueryFilter();
		Communities.setFilter(this.CookieFilter.load());
		this.loadedFromQuery = {};
		if (EventManager) EventManager.add(window, "unload", Communities.CookieFilter.save);
	},
	
	totalAmenities: function(formName) {
			//coordinates the amenities checkboxes on the page with Communities.amenities and Communities.amenitiesList
			//takes the DOM form name
			//returns nothing
		var formName = (formName == null) ? this.formName : formName;
		this.formName = formName;
		var codeObjs = document[formName].getElementsByTagName('code');
		
		for(var c=0;c<codeObjs.length;c++) {
			var codeId = codeObjs[c].id;
			this.amenities[codeId] = false;					
			this.amenitiesList.push(codeId.substr(5));
			this.amenitiesLanguage.push(codeObjs[c].firstChild.nodeValue);
		}
	},
	
	loadQueryFilter: function() {
		var url = window.location.toString();
		if (url.indexOf('=') == -1) return false;
		
		var queryString = url.substring(url.indexOf('?')+1);
		var queries = queryString.split('&');
		var queryObject = new Object();
		for(var c=0;c<queries.length;c++) {
			var pair = queries[c].split('=');
			queryObject[pair[0]] = pair[1];					
		}
		this.setFilter(queryObject, true);
		return true;
	},
	
	CookieFilter: {
			//controls saving and loading filter state on page load and unload
			
		save: function() {
				//compiles filter state into text string and writes cookie to current folder path
				//returns nothing
			if (CookieCutter) {
				var pageUrl = window.location.toString();
				var cookiePath = pageUrl.substring(pageUrl.indexOf(".com") + 4);
				cookiePath = cookiePath.split('/');
				cookiePath.pop();
				cookiePath = cookiePath.join('/') + "/";                
				var filterCookie = "bedrooms=" + Communities.bedroomsDisplaying +
									",baths=" + Communities.bathsDisplaying +
									",maxrent=" + Communities.maxrentDisplaying +
									",townhomes=" + Communities.townhomesDisplaying +
									",rentSorted=" + Communities.rentSorted +
									",bedroomsSorted=" + Communities.bedroomsSorted;
				if (Communities.primaryCity) filterCookie += ",city=" + Communities.primaryCity;
				for (var c=0;c<Communities.amenitiesList.length;c++) {
					if (Communities.amenities[Communities.amenitiesList[c]]) {
						filterCookie = filterCookie + "," + Communities.amenitiesList[c] + "=true";
					}
				}
				CookieCutter.create("filter", filterCookie, 1, cookiePath);
			}
		},
		
		load: function() {
				//loads filtering state cookie, runs all sorting functions, sets forms on page
				//returns nothing
			if (CookieCutter) {
				var filterCookie = CookieCutter.read("filter", true);				
				if (filterCookie) return filterCookie
			}
		}
	},
	
	showAll: function() {
		var filterObject = {
			bedrooms: "0",
			baths: 10,
			maxrent: "Any",
			townhomes: false,
			amenities: "0",
			townhome: false,
			rentSorted: this.rentSorted
		}
		this.setFilter(filterObject);
	},
	
	setFilter: function(filterObject, fromQuery) {
		if (!filterObject) return false;
		
		if (fromQuery || !this.loadedFromQuery.rentSorted) {
			this.rentSorted = ((filterObject.rentSorted == "false" || !filterObject.rentSorted) ? false
								: filterObject.rentSorted);
			document.getElementById('rent-sort-btn').className = (this.rentSorted ? this.rentSorted : "");			
			if (fromQuery) this.loadedFromQuery.rentSorted = true;
		}
		if ((fromQuery || !this.loadedFromQuery.city) && filterObject.city) {
			this.setCityAsOrder(filterObject.city);
			if (fromQuery) this.loadedFromQuery.city = true;
		}
				
		for(var c=0;c<this.amenitiesList.length;c++) {
			var amenity = this.amenitiesList[c];
			if (filterObject[amenity]) {
				//if (!this.loadedFromQuery['103bees'] && !filterObject['103bees']) {
					document[Communities.formName][amenity].checked=true;
					this.filterByAmenities(amenity,true);
				//}
			}
			else {
				document[Communities.formName][amenity].checked=false;
				this.filterByAmenities(amenity,true);
			}
		}
		//if (fromQuery && filterObject['103bees']) this.loadedFromQuery['103bees'] = true;
		
		if ((fromQuery || !this.loadedFromQuery.townhomes) && filterObject.townhomes=="true") {
			document[Communities.formName].townhomes.checked=true;
			this.filterByTownhomes(true);
			if (fromQuery) this.loadedFromQuery.townhomes = true;
		}
		else if (fromQuery || !this.loadedFromQuery.townhomes) {
			document[Communities.formName].townhomes.checked=false;
			this.filterByTownhomes(true);
		}
		if ((fromQuery || !this.loadedFromQuery.bedrooms) && filterObject.bedrooms) {			
			this.filterByBedrooms(filterObject.bedrooms,true);
			//set forms
			var selectBedrooms = document[Communities.formName]['select_bedrooms'];			
			for(var c=0;c<selectBedrooms.length;c++) {
				if (selectBedrooms.options[c].value == filterObject.bedrooms) {
					document[Communities.formName]['select_bedrooms'].selectedIndex = c;
				}
			}
			if (fromQuery) this.loadedFromQuery.bedrooms = true;
		}
		if ((fromQuery || !this.loadedFromQuery.baths) && filterObject.baths) {
			this.filterByBaths(filterObject.baths,true);
			//set forms
			var selectBaths = document[Communities.formName]['select_baths'];
			for(var c=0;c<selectBaths.length;c++) {
				if (selectBaths.options[c].value == filterObject.baths) {
					document[Communities.formName]['select_baths'].selectedIndex = c;
				}
			}
			if (fromQuery) this.loadedFromQuery.baths = true;
		}
		if ((fromQuery || !this.loadedFromQuery.maxrent) && filterObject.maxrent) {
			this.filterByMaxrent(filterObject.maxrent,true);
			//set forms
			var selectMaxrent = document[Communities.formName]['select_maxrent'];
			for(var c=0;c<selectMaxrent.length;c++) {
				if (selectMaxrent.options[c].value == filterObject.maxrent) {
					document[Communities.formName]['select_maxrent'].selectedIndex = c;
				}
			}
			if (fromQuery) this.loadedFromQuery.maxrent = true;
		}
		//this.redraw() //taken out by doug 20090522
	},
	
	setCityAsOrder: function(primaryCity) {		
		this.primaryCity = primaryCity;
		if (primaryCity!="default") this.reorderByCity(primaryCity);		
	},
	
	reorderByCity: function(primaryCity) {
		for(var c=0;c<this.list.length;c++) {
			if (this.list[c].city.toLowerCase() == primaryCity.toLowerCase() ||
				escape(this.list[c].city.toLowerCase()) == primaryCity.toLowerCase() ||
				this.list[c].city.toLowerCase().replace(/[^a-z]+/g,'') == primaryCity.toLowerCase().replace(/[^a-z]+/g,''))
				{
				this.list[c].defaultOrder = c;
			}
			else this.list[c].defaultOrder = 100+c;
		}
		this.list = this.list.sort(this.Sort.byAmenity);
		this.redraw();
	}
}
var Sort = Communities.Sort;

var Printout = {
	countShowing: 0,
	countTotal: 0,
	city: "",
	state: "",
	bedrooms: 0,
	townhomes: false,
	baths: 1,
	maxrent: "Any",
	amenities: new Array(),
	phrase: {
		countShowing: "",
		countTotal: "",
		allBoth: "both ",
		location: "",
		withHave: "have",
		bedrooms: "",
		baths: "",
		units: " apartments",
		maxrent: "",
		feature: "feature",
		amenities: ""
	},
	
	initialize: function() {
		this.countShowing = Communities.list.length;
		this.countTotal = Communities.list.length;
		this.phrase.countTotal = this.countTotal + " ";
		if (this.countTotal!=2) this.phrase.allBoth = "all " + this.countTotal + " ";
	},
	
	write: function() {
		if (this.townhomes) this.phrase.units = " townhomes";
		else this.phrase.units = " apartments";
		
		if (this.countShowing == this.countTotal) {
			this.phrase.countShowing = this.phrase.allBoth;
			this.phrase.countTotal = "";
		}
		else {
			if (this.countShowing==0) {
				if (this.countTotal==2) this.phrase.countShowing = "that neither of the ";
				else this.phrase.countShowing = "that none of the ";
			}
			
			else this.phrase.countShowing = this.countShowing + " out of the ";
			this.phrase.countTotal = this.countTotal + " ";
		}
		
		if (this.countShowing==1 || this.countShowing==0) {
			this.phrase.withHave = " has";
			this.phrase.feature = "features";
		}
		else {
			this.phrase.withHave = " have";
			this.phrase.feature = "feature";
		}		
		
		this.phrase.location = " in " + this.city;// + ", " + this.state;
		
		var orBetter = "";
		var bedroomsComma = "";
		var andAmenities = " and ";
		
		if (this.bedrooms == 0) this.phrase.bedrooms = "";
		else {
			this.phrase.bedrooms = " " + this.bedrooms + " bedroom";
			bedroomsComma = ",";
			orBetter = " or better,";
		}
		
		if (this.baths == 1) this.phrase.baths = "";
		else {
			//if (this.baths != Math.round(this.baths)) change to &frac12;
			this.phrase.baths = bedroomsComma + " " + this.baths + " bath";
			orBetter = " or better,";
		}
		
		if (this.maxrent == "Any") {
			this.phrase.maxrent = "";
			if (!orBetter.length) {
				if (!this.townhomes) {
					this.phrase.units = "";
					this.phrase.withHave = "";
					andAmenities = " ";
				}											
			}
		}
		else {
			this.phrase.maxrent = " under the price of $" + this.maxrent + " per month,";		
		}
		
		this.phrase.amenities = "";
		if (this.amenities.length) {
			if (this.amenities.length==1) {
				var amenitiesPlural = "amenity";
				var amenitiesList = Dom.create({tag: 'strong', text: this.amenities[0]});
			}
			else {
				var amenitiesPlural = "amenities";
				var lastAmenity = this.amenities.pop();
				if (this.amenities.length==1) {
					var amenitiesList = Dom.create({tag: 'span'});
					amenitiesList.appendChild(Dom.create({tag: 'strong', text: this.amenities[0]}));
					amenitiesList.appendChild(document.createTextNode(" and "));
					amenitiesList.appendChild(Dom.create({tag: 'strong', text: lastAmenity}));
					//this.amenities[0] + " and " + lastAmenity;
				}
				else {
					var amenitiesList = Dom.create({tag: 'span'});
					for(var c=0;c<this.amenities.length;c++) {
						amenitiesList.appendChild(Dom.create({tag: 'strong', text: this.amenities[c]}));
						amenitiesList.appendChild(document.createTextNode(", "));
					}
					//var amenitiesList = this.amenities.join(", ") + ", and " + lastAmenity;
					amenitiesList.appendChild(document.createTextNode("and "));
					amenitiesList.appendChild(Dom.create({tag: 'strong', text: lastAmenity}));
				}
			}
			this.phrase.amenities = andAmenities + this.phrase.feature +" the " + amenitiesPlural + ": " + amenitiesList;
			this.phrase.amenities = Dom.create({tag: 'span'});
			this.phrase.amenities.appendChild(document.createTextNode(andAmenities + this.phrase.feature +" the " + amenitiesPlural + ": "));
			this.phrase.amenities.appendChild(amenitiesList);
			//this.phrase.amenities.appendChild(Dom.create({tag: 'strong', text: amenitiesList}));
		}
		else {
			if (!this.phrase.maxrent.length) orBetter = orBetter.substr(0,10);
			else this.phrase.maxrent = this.phrase.maxrent.substr(0,this.phrase.maxrent.length-1);
		}
		
		/*var output = "Showing " + this.phrase.countShowing + this.phrase.countTotal + "Communities" + this.phrase.location +
				this.phrase.withHave + this.phrase.bedrooms + this.phrase.baths + this.phrase.units + orBetter + this.phrase.maxrent + 
				this.phrase.amenities + ". ";*/
		
		var output = Dom.create({tag: 'span'});
		output.appendChild(document.createTextNode("Showing "));
		output.appendChild(Dom.create({tag: 'strong', text: (this.phrase.countShowing + this.phrase.countTotal + "Apartment Communities")}));
		output.appendChild(document.createTextNode(
				this.phrase.location +
				this.phrase.withHave +
				this.phrase.bedrooms +
				this.phrase.baths +
				this.phrase.units + orBetter +
				this.phrase.maxrent));
		if (!this.phrase.amenities == "") output.appendChild(this.phrase.amenities);
		output.appendChild(document.createTextNode(". "));
		
		var returnNode = output;//= document.createTextNode(output);
		return returnNode;
	}
}

var Floorplans = {
	list: new Array(),
	add: function(floorplan) {
		floorplan.hide = false;
		floorplan.obj = document.getElementById('floorplan_' + (this.list.length+1));
		floorplan.unitRents = floorplan.unitRents.sort(Sort.ascending);
		floorplan.rentRange = {min: floorplan.unitRents[0], max: floorplan.unitRents[floorplan.unitRents.length-1]};
		this.list.push(floorplan);
	},
	finalize: function() {
		this.setFilter(Communities.CookieFilter.load());
	},
	setFilter: function(filterObject) {
		setDeactivatedRows = new Array();
		allAreDeactivated = true;
		if (!filterObject) return;
		var maxrent = parseInt(filterObject.maxrent)
		for(var c=0;c<this.list.length;c++) {
			if (this.list[c].bedrooms < parseInt(filterObject.bedrooms) ||
				this.list[c].baths < parseInt(filterObject.baths) ||
				(!this.list[c].townhomes && filterObject.townhomes=="true") ||
				this.list[c].unitRents[0] > maxrent)
				{
					setDeactivatedRows.push(c);
			}
			else allAreDeactivated = false;
			
			/*if (this.list[c].unitRents[0] <= maxrent &&	this.list[c].unitRents[this.list[c].unitRents.length-1] > maxrent) {
				//change range
				var d=0;
				while(this.list[c].unitRents[d] <= maxrent) d++;
				this.list[c].rentRange.max=this.list[c].unitRents[d-1];
				
				rentRange = Communities.outputRange(this.list[c].rentRange);
				var rentRangeElements = getElementsByClass("rent-range-dynamic", this.list[c].obj);
				if (rentRangeElements[0].firstChild) rentRangeElements[0].removeChild(rentRangeElements[0].firstChild);
				rentRangeElements[0].appendChild(document.createTextNode(rentRange));
			}*/
		}
		if (!allAreDeactivated && setDeactivatedRows.length>0) {
			for(var c=0;c<setDeactivatedRows.length;c++) {
				this.list[setDeactivatedRows[c]].hide = true;
				this.list[setDeactivatedRows[c]].obj.className = this.list[setDeactivatedRows[c]].obj.className + " deactivated";
			}
			var theadObj = document.getElementById('dynamic').parentNode.getElementsByTagName('thead')[0];
			var theadTrCurrent = theadObj.getElementsByTagName('tr')[0];
			theadTrCurrent.className = "remove-border";
			
			var trObj = document.createElement('tr');
			trObj.className = "show-all";
			var thObj = Dom.create({tag: 'th', text: 'Highlighting floorplans that match your bed, bath, and max rent criteria. '});
			thObj.colSpan = 6;
			thObj.appendChild(Dom.create({tag: 'a', href: 'javascript: Floorplans.showAll()', text: 'Show All'}));
			trObj.appendChild(thObj);
			//theadObj.insertBefore(trObj, theadTrCurrent);
			this.newTrObj = theadObj.appendChild(trObj);
		}
	},
	showAll: function() {
		for(var c=0;c<this.list.length;c++) {
			this.list[c].obj.className = this.list[c].obj.className.split('deactivated')[0];
		}
		this.newTrObj.parentNode.getElementsByTagName('tr')[0].className = "";
		Dom.remove(this.newTrObj);
	}
}