window.getQueryString = function() {
	return location.search;
} 
window.getQueryStringValues = function(queryString) {
	var params = {};
	(queryString||getQueryString()).replace('?','').split('&').each(function(group){
		var pair = group.split('='); 
		params[ pair[0] ] = pair[1] ?pair[1] :true;
	}, this);
	return params;
}
 
window.getQueryStringValue = function(name, queryString) {
	var values = getQueryStringValues(queryString);
	if (values[name]) {
		return values[name];
	} else {
		return false;
	}
} 

window.scrollToElement = function(element) {
	var scroll = new Fx.Scroll(window, {
		wait: false,
		duration: 500,
		offset: {'x': -200, 'y': -50},
		transition: Fx.Transitions.Quad.easeInOut
	});
	scroll.toElement(element);
}

window.scrollToLastClicked = function (table) {
	var cookieName = "LastListingClicked"+escape(window.location.search);
	if (scrollToListing = Cookie.read (cookieName)){
		if (element = table.getElement('#Listing-'+scrollToListing)) {
			Cookie.remove(cookieName);
			element.getElement("a").focus();
		}
	}
}

function clearQueryStringToken (Token, OldLocation, Debug) {
	/*Token - The name of the URL QS Token to modify*/
	/*OldLocation - Location to modify.  If False/Null, will use current location.*/
	if (!OldLocation) {Location = window.location.href} else {Location = OldLocation}
	var TokenPattern = new RegExp ("&" +Token);
	var NewSearchPattern = new RegExp (".*html$")
	var NewToken = (NewSearchPattern.test (Location) ? "?OpenDocument" : "") +"&" +Token;

	if (TokenPattern.test (Location)) {
		Location = Location.replace (TokenPattern, "");
		if (Debug) alert ("Remove Any " +Token +": \n" +Location);
	}
	if (!OldLocation) {window.location = Location} else return Location;
}

function toggleQueryStringItem (Token, Value, OldLocation, NoToggle, Debug) {
	/*Token - The name of the URL QS Token to modify*/
	/*Value - The value associated with the Token*/
	/*OldLocation - Location to modify.  If False/Null, will use current location.*/
	/*NoToggle - If True then Token=Value is set if absent or removed if present.  If False then Token=Value will only be set if absent.*/
	/*Determine if there is currently a scheme or not*/
	if (!OldLocation) {Location = window.location.href} else {Location = OldLocation}
	var TokenPattern = new RegExp ("&" +Token +"=[\.a-zA-Z0-9\+\|%]*");
	var TokenValuePattern = new RegExp ("&" +Token +"=" +Value);
	var NewSearchPattern = new RegExp (".*html$")
	var NewTokenValue = (NewSearchPattern.test (Location) ? "?OpenDocument" : "") +"&" +Token +"=" +Value;
	/* Look for "Scheme=<Scheme>" */
	if ("" == Value) {
		Location = Location.replace (TokenPattern, "");
		if (Debug) alert ("Remove Any " +Token +": \n" +Location);
	}
	else if (!NoToggle && TokenValuePattern.test (Location)) {
		Location = Location.replace (TokenValuePattern, "");
		if (Debug) alert ("Remove " +Token +"=" +Value +": \n" +Location)
	}
	else if (TokenPattern.test (Location)) {
		if (Debug) alert (Location.match (TokenPattern)[0]);
		Location = Location.replace (TokenPattern, NewTokenValue);
		if (Debug) alert ("Replace: \n" +Location);
	}
	else {
		Location += (NewTokenValue);
		if (Debug) alert ("Add " +Token +"=" +Value +": \n" +Location)
	}
	if (!OldLocation) {window.location = Location} else return Location;
}

//	Name - Name of the Cookie
//	Value - Value to toggle (add/delete)
//	Debug - Boolean flag to show debug info or not.
//	Returns the number of items in the cookie after the operation.
function toggleCookie (Name, Value, Checked, Debug) {
	/* Cookie is a mootools object */
	var cookie = Cookie.read (Name);				/* The current value of the cookie*/
//	var SelectCountHTML = document.getElementById("SelectCount");
	var SelectCount=0;// = !SelectCountHTML ? -1 : SelectCountHTML.innerHTML;
	
	if ((null == cookie) || ("" == cookie)) {		/* If the cookie is empty*/
		if (Checked) {
			cookie = Value; SelectCount++;
		} else {alert ('Error: Attempting to remove an unselected listing value')}
	} else {											/* If the cookie is not empty */
		var CookieArray = cookie.split ("|");		/* The current value of the cookie as an array*/
		SelectCount = CookieArray.length;
		var Location = null;							/* The current position of the Value in question, or null if not present*/
		for (Counter = 0; Counter <= CookieArray.length; Counter++) {
			Location = CookieArray[Counter] == Value ? Counter : Location;
		}
		if (Checked) {					/* Add the Value to the coookie*/
			if (null != Location) {}
			else {CookieArray = CookieArray.concat (Value); SelectCount++;}
		} else {										/*Delete the Value from the cookie*/
			if (null == Location) {}
			else {CookieArray.splice (Location, 1); SelectCount--;}
		}
		cookie = CookieArray.join ("|");
	}
//	if (SelectCountHTML) {SelectCountHTML.innerHTML = SelectCount}
//	if (SelectCountHTML) {SelectCountHTML.set ('html', SelectCount)}
	if (Debug) {alert (cookie);}
	/* At some point, check to see if the new cookie is an empty string, and delete it if so.*/
	Cookie.write (Name, cookie, {path:"/"});
	return SelectCount;
}

function toggleListing (ListingID, CommunityID, ListingType, isChecked, Debug) {
	/* Cookie is a mootools object */
	var SelectCount = toggleCookie ("Listings", ListingID, isChecked, Debug);
	var SelectCountExt = toggleCookie ("ListingsExt", ListingID+"/"+CommunityID+"/"+ListingType, isChecked, Debug);
	var ListingsExt = Cookie.read ("ListingsExt");
	if (ListingsExt) ListingsExt = ListingsExt.split("|");	/* The current value array of the cookie*/
	
	var CommunityArray = [];
	var PlanArray = [];
	var SpecArray = [];
	if (ListingsExt) ListingsExt.each (function(ListingExt, index, array){
		if (ListingExt != "") {
			ListingExt = ListingExt.split("/");
			if (ListingExt[2] == "P") {
				if (!PlanArray.contains (ListingExt[0])) PlanArray.push (ListingExt[0]);
			} else {
				if (!SpecArray.contains (ListingExt[0])) SpecArray.push (ListingExt[0]);
			}
			if (!CommunityArray.contains (ListingExt[1])) CommunityArray.push (ListingExt[1]);
		}
	});
	
	$('CommunityCount').set('text', CommunityArray.length); 
	$('CommunityCountLabel').set ('text', CommunityArray.length == 1?'Community':'Communities');
	$('PlanCount').set('text', PlanArray.length);
	$('PlanCountLabel').set ('text', PlanArray.length == 1?'Plan':'Plans');
	$('SpecCount').set('text', SpecArray.length);
	$('SpecCountLabel').set ('text', SpecArray.length == 1?'Home':'Homes');
}

function toggleInventoryListing (CheckBox, Debug) {
	var ListingValues = CheckBox.value.split("/");
	toggleListing (ListingValues[0], ListingValues[1], ListingValues[2], CheckBox.checked, Debug);
}

function clearHomeSearch (Form) {
	Form.Availability.selectedIndex = 0;
	Form.Plan.value = "";
	Form.City.selectedIndex = 0;
	Form.Price.selectedIndex = 0;
	Form.Bedrooms.selectedIndex = 0;
	Form.Bathrooms.selectedIndex = 0;
	Form.Garage.selectedIndex = 0;
	Form.Stories.selectedIndex = 0;
	Form.MasterStory.selectedIndex = 0;
	for (Counter = 0; Counter < Form.LivingAreas.length; Counter++) 
		Form.LivingAreas [Counter].checked = false;
}

function changeMarket (Form) {
	Form.City.selectedIndex = 0;
	newHomeSearch (Form);
}

function newHomeSearch (Form) {
	var Location = window.location.href;
	
	Location = clearQueryStringToken ("Help", Location, false);

	var Availability = (-1 == Form.Availability.selectedIndex) ? "" : Form.Availability.options [Form.Availability.selectedIndex].value;
	Location = toggleQueryStringItem ("Availability", Availability, Location, true, false);

	var Market = Form.Market.value ? Form.Market.value : (-1 == Form.Market.selectedIndex) ? "" : Form.Market.options [Form.Market.selectedIndex].value;
	Location = toggleQueryStringItem ("Market", Market, Location, true, false);

	var City = (-1 == Form.City.selectedIndex) ? "" : Form.City.options [Form.City.selectedIndex].value;
	Location = toggleQueryStringItem ("City", City, Location, true, false);

	var Plan = Form.Plan.value;
	Location = toggleQueryStringItem ("Plan", Plan, Location, true, false);

	// Override if plan specified
	var Price = (-1 == Form.Price.selectedIndex) || (0 == Form.Price.selectedIndex) ? "" : Form.Price.options [Form.Price.selectedIndex].value;
	Location = toggleQueryStringItem ("Price", Price, Location, true, false);

	var Bedrooms = (-1 == Form.Bedrooms.selectedIndex) || (0 == Form.Bedrooms.selectedIndex) || (0 != Plan.length) ? "" : Form.Bedrooms.options [Form.Bedrooms.selectedIndex].value.slice (0, 1);
	Location = toggleQueryStringItem ("Bed", Bedrooms, Location, true, false);

	var Bathrooms = (-1 == Form.Bathrooms.selectedIndex) || (0 == Form.Bathrooms.selectedIndex) || (0 != Plan.length) ? "" : Form.Bathrooms.options [Form.Bathrooms.selectedIndex].value.slice (0, 1);
	Location = toggleQueryStringItem ("Bath", Bathrooms, Location, true, false);

	var Garage = (-1 == Form.Garage.selectedIndex) || (0 == Form.Garage.selectedIndex) || (0 != Plan.length) ? "" : Form.Garage.options [Form.Garage.selectedIndex].value.slice (0, 1);
	Location = toggleQueryStringItem ("Garage", Garage, Location, true, false);

	var Stories = (-1 == Form.Stories.selectedIndex) || (0 != Plan.length) ? "" : Form.Stories.options [Form.Stories.selectedIndex].value.slice (0, 1);
	Location = toggleQueryStringItem ("Stories", Stories, Location, true, false);

	var MasterStory = (-1 == Form.MasterStory.selectedIndex) || (0 != Plan.length) ? "" : Form.MasterStory.options [Form.MasterStory.selectedIndex].value;
	Location = toggleQueryStringItem ("Master", MasterStory, Location, true, false);

	var LivingAreas = new Array ();
	for (Counter = 0; Counter < Form.LivingAreas.length; Counter++) {
		if (Form.LivingAreas [Counter].checked) {
			LivingAreas.push (Form.LivingAreas [Counter].value);
		}
	}

	Location = toggleQueryStringItem ("Areas", (0 == LivingAreas.length) || (0 != Plan.length) ? "" : LivingAreas.join ("|"), Location, true, false)
	// End Override
	
	window.location = Location;
	return Location;
}

try {
window.search = function(searchType, searchCategory){
	var console = $("JSPageConsole");
	var helpText = $("HelpText");
	if (helpText) helpText.setStyle("display", "none");
	$("SearchResults").setStyle("display", "block");
		
	var baseURL = '/servlet/ListingsServer?Open&Response=HTML';
	var baseTokens = new Array();
	var specTokens = new Array();
	var planTokens = new Array();
	
	switch (searchType) {
		case "Help": {
			$("HelpText").setStyle("display", "block");
			$("SearchResults").setStyle("display", "none");
			return;
			break;
		}
		case "Category": {
			specTokens.push (searchCategory +"-Spec");
			planTokens.push (searchCategory +"-Plan");
			break;
		}
		case "Selected": {
			baseTokens.push ("Listing=" +Cookie.read("Listings"));
			specTokens.push("Type=(M|S)");
			planTokens.push("Type=P");
			break;
		}
		case "Custom": {
			var Form = $("SearchForm");
			
			var brand = PageView;
			if (temp=brand.indexOf ('ES') > -1) {
				brand = brand.slice(2);
			}
			baseTokens.push("Brand=" +brand);
			var value;
			value = getQueryStringValue("Market")
			if (value == "") value = Cookie.read("LastRegion");
			if (value != "") baseTokens.push("Market=" +value);
			
			value = window.getQueryStringValue("City");
			if (value != "") baseTokens.push("City=" +value);
						
			value = window.getQueryStringValue("Availability");
			if (value != "") baseTokens.push("Availability=" +value);
						
			value = window.getQueryStringValue("Price");
			if (value != "") baseTokens.push("Price=" +value);
			
			value = window.getQueryStringValue("Bed");
			if (value != "") baseTokens.push("Bed=" +value);
			
			value = window.getQueryStringValue("Bath");
			if (value != "") baseTokens.push("Bath=" +value);
			
			value = window.getQueryStringValue("Garage");
			if (value != "") baseTokens.push("Garage=" +value);
			
			value = window.getQueryStringValue("Stories");
			if (value != "") baseTokens.push("Stories=" +value);
			
			value = window.getQueryStringValue("Master");
			if (value != "") baseTokens.push("Master=" +value);
			
			value = window.getQueryStringValue("Areas");
			if (value != "") baseTokens.push("Areas=" +value);
			
			value = window.getQueryStringValue("Plan");
			if (value != "") baseTokens.push("Plan=" +value);
			

			specTokens.push("Type=(M|S)");
			planTokens.push("Type=P");
			break;
		}
	}

	var specURL = baseURL +"&" +specTokens.concat (baseTokens).join("&");
	var planURL = baseURL +"&" +planTokens.concat (baseTokens).join("&");
		
	var specRequest = new Request.HTML({
		url: specURL, 
		method: 'get',
		update: $('SpecResults'),
		onComplete: function() {
			var errors = new Array ();
			var table = $('SpecResults').getElement('table');
			var listings = table.getElements('.SpecListing');
			
			try {
				var captionText = AllTags.contains ('IsSpanish')?
					'Casas en Construcci\u00F3n: ' +listings.length +' Casas':
					'Homes being built: Found ' +listings.length +' Homes';
				var captionContainer = $('SpecResults-Caption');
				if (captionContainer) captionContainer.set ('text', captionText);
				else table.getElement('caption').set ('text', captionText);
			} catch (err) {errors.push(err)}
			
			try {
				new SortingTable(table, { zebra: false, noSort: [".Selection"], preSort: 2, headerRow: 0 } );
			} catch (err) {errors.push(err)}
			
			try {
				var selectedListingIDs = Cookie.read ('ListingsExt');
				selectedListingIDs = selectedListingIDs ? selectedListingIDs.split ('|') : new Array();
			} catch (err) {errors.push(err)}
			
			try {
				listings.each(function(listing, index){
					// check or uncheck based on the Listings cookie.
					var checkbox = listing.getElement('input');
					checkbox.addEvent ('click', function() {toggleInventoryListing (this);});
					checkbox.checked = selectedListingIDs.contains(checkbox.value);
					// Replace past completion dates with label.
					var dateValueElement = listing.getElement('.Completion .Value');
					var dateLabelElement = listing.getElement('.Completion .Label');
					var dateValueText = dateValueElement.get('text');
					var dateValue = new Date ();
					dateValue.setFullYear (dateValueText.substring(6), dateValueText.substring(0,2)-1, dateValueText.substring(3,5));
					var today = new Date ();
					if (today >dateValue) {
						if (!dateValueElement.hasClass('NoShow')) dateValueElement.addClass('NoShow');
						if (dateLabelElement.hasClass('NoShow')) dateLabelElement.removeClass('NoShow')
//						dateValueElement.setStyle('display', 'none');
//						dateLabelElement.setStyle('display', 'inline');
					}
				});	
			} catch (err) {errors.push(err)}
			
			if (errors[0]){throw errors[0];}
			
			window.scrollToLastClicked(table);

			var virtualTourLinks = table.getElements(".Links a");
			if ((virtualTourLinks.length>0) && Shadowbox) Shadowbox.setup(virtualTourLinks); 
/*			
			if (errors[0]){
				throw errors[0]; 
			} else if (errors.length >0) {
				var markup = "";
				errors.each(function(error, index){
					try {
						markup.concat (markup, "<div>" +error.message +"</div>");
					} catch(err) {
						markup.concat (markup, "<div>error generating error message</div>");
					}
				})
			};
*/
		}
	}).send();

	var planRequest = new Request.HTML({
		url: planURL,
		method: 'get',
		update: $('PlanResults'),
		onComplete: function() {
			var table = $('PlanResults').getElement('table');
			new SortingTable(table, { zebra: false, noSort: [".Selection"], preSort: 3, headerRow: 0 } );
			var selectedListingIDs = Cookie.read ('ListingsExt');
			selectedListingIDs = selectedListingIDs ? selectedListingIDs.split ('|') : new Array();
			var listings = table.getElements('.PlanListing');
			var baseCount = table.getElements('.Base').length;
			var optionCount = table.getElements('.Option').length;

			var captionText = AllTags.contains ('IsSpanish')?
				'Casas listas para construirse: ' +baseCount +' planos' +(optionCount>0 ? ', ' +optionCount +' con opciones <input type="button" class="ButtonBordered" value="Mostrar Opciones" id="HideOptions"/>' : ""):
				'Plans ready to build: Found ' +baseCount +' base plans' +(optionCount>0 ? ', ' +optionCount +' option plans <input type="button" class="ButtonBordered" value="Hide Options" id="HideOptions"/>' : "");
			var captionContainer = $('PlanResults-Caption');
			if (captionContainer) captionContainer.set ('html', captionText);
			else table.getElement('caption').set ('html', captionText);

			listings.each(function(listing, index){
				// check or uncheck based on the Listings cookie.
				var checkbox = listing.getElement('input');
				checkbox.addEvent ('click', function() {toggleInventoryListing (this);});
				checkbox.checked = selectedListingIDs.contains(checkbox.value);
			});
			
			var buttonHideOptions = $("HideOptions");
			if (buttonHideOptions) {
				buttonHideOptions.addEvent( 'mousedown', function(evt){
					this.hidden = !this.hidden;
					table.getElements('.Option').forEach (function(item, index){
						if (!this.defaultDisplay) this.defaultDisplay = item.getStyle("display");
						item.setStyle("display", this.hidden ? "none" : this.defaultDisplay);
					}.bind( this ));
//					alert (this.getText());
					if (AllTags.contains ('IsSpanish')) this.setProperty("value", this.hidden ? "Mostrar Opciones" : "Esconder Opciones");
					else this.setProperty("value", this.hidden ? "+ Show Options" : "- Hide Options");
//					var evt = new Event(evt);
//					this.sort_by_header( evt.target.getText() );
				}.bind( buttonHideOptions ) );
				buttonHideOptions.fireEvent('mousedown');
			}
			window.scrollToLastClicked(table);

			var virtualTourLinks = table.getElements(".Links a");
			if ((virtualTourLinks.length>0) && Shadowbox) Shadowbox.setup(virtualTourLinks);

			var panels = $$('#SearchResults .Panel-Exterior');
			panels.each(function (panel) {
				panel.addEvent ('mouseenter', function (){
					var controls = this.getElements('.Panel-Title-Exterior .ButtonBordered');
					controls.each (function(control){
						var start;
						var end = control.retrieve('highlight:original', control.getStyle('color'));
						end = (end == 'transparent') ? '#fff' : end;
						var tween = control.get('tween');
						tween.start('color', start || '#ffff88', end).chain(function(){
							control.setStyle('color', control.retrieve('highlight:original'));
							tween.callChain();
						}.bind(control));
						return control;
					});
				});
			});
			
		}
	}).send();
}
} catch (err) {errors.push(err)}
			
window.searchInit = function () {
	window.helpText = $("HelpText");
	
	//	See if a category search has been requested (Community, Subdivision, or Plan), and if so, set the category token for the search engine.
	var communityID = window.communityID ? window.communityID : window.getQueryStringValue ("CID");
	var subdivisionID = window.subdivisionID ? window.subdivisionID : window.getQueryStringValue ("SID");
	var planID = window.planID ? window.planID : window.getQueryStringValue ("PID");
	var baseCategory = communityID ? "Category=Community-"+communityID : subdivisionID ? "Category=Subdivision-"+subdivisionID : planID ? "Category=Plan-"+planID+"-"+SiteAbbreviation : false;

//	if (window.getQueryStringValues()["Selected"]) window.search ("Selected");
	if (AllTags.contains ('IsSearchRequest') || AllTags.contains ('IsContact')) window.search ('Selected');
//	else if (window.getQueryStringValues()["Help"]) window.search ("Help");
	else if (baseCategory) window.search ("Category", baseCategory);
	else if (window.getQueryStringValue("Market")||Cookie.read("LastRegion")) window.search("Custom");
}


function validateForm (form) {
	var isValid = true;
	var fields = new Array (form.FirstName, form.LastName);
	var field;
	for (counter=0; counter <fields.length; counter++) {
		field = fields[counter];
		if (!field.value) {isValid = false; field.focus(); /*field.style.OriginalBorderColor = field.getStyle ('border-color'); field.setStyle ('border', "1px solid #CC0001")*/}
//		else if (field.style.OriginalBorderColor) {field.setStyle('border-color', field.style.OriginalBorderColor)}
	}
	if (!isValid) {alert ('Please fill in your name.'); return false;}
	else {
		if (form.Email.value || form.Phone.value) {}
		else if (form.Address.value && form.City.value && form.State.value && form.Zip.value) {}
		else {isValid = false; form.Email.focus()}
	}
	if (!isValid) {alert ('Please provide either an email address, phone number, or address (depending on how you want us to contact you.'); return false;}
	if (form.Email.value) if (!emailCheck (form.Email.value)) {form.Email.focus (); return false;}
	return isValid;
}