var autosuggest = null;

PTRFPlaceSearchBox = function(node, tabNode, tabTypes) {
	this.eventTypes = new Object();
	this.eventTypes.submit = 'submit';
	this.eventTypes.response = 'response';
	this.eventTypes.dd_initialized = 'dd_initialized';

	this.eventManager = new _eventManager();
	for (var ev in this.eventTypes)
		this.eventManager.registerEventID(ev);

	this.type = null;
	this.defaultType = null;

	this.textbox = document.createElement("input");
	this.textbox.type = "text";
	this.textbox.style.width = "100%";
	this.textbox.style.height = "100%";

	//this.textboxState = document.createElement("input");
	//this.textboxState.type = "text";
	//this.textboxState.style.width = "20%";
	//this.textboxState.style.height = "100%";
	//this.textboxState.style.display = "none";
	//this.textboxState.style.marginRight = "10px";

	var usStates = document.createElement('select');
	usStates.id = 'states'; 
	usStates.name = 'states';
	usStates.style.display = "none";
	usStates.style.width = "30%";
	//usStates.style.height = "50%";
	usStates.style.marginRight = "10px";

	this.addState = function(stateName, fips, abbrev) {		
		var o = document.createElement('option');
		o.value = fips;
		o.title = abbrev
		o.innerHTML = stateName;
		if (stateName == "Pennsylvania") o.selected = true;
		usStates.appendChild(o);
	}

	 this.addState("Alabama", '01', 'AL');
	 this.addState("Alaska", '02', 'AK');
	 //this.addState("American Samoa", 60, 'AS');
	 this.addState("Arizona", '04', 'AZ');
	 this.addState("Arkansas", '05', 'AR');
	 this.addState("California", '06', 'CA');
	 this.addState("Colorado", '08', 'CO');
	 //this.addState("Commonwealth of the Northern Mariana Isla", 69, 'MP');
	 this.addState("Connecticut", '09', 'CT');
	 this.addState("Delaware", 10, 'DE');
	 this.addState("District of Columbia", 11, 'DC');
	 this.addState("Florida", 12, 'FL');
	 this.addState("Georgia", 13, 'GA');
	 //this.addState("Guam", 66, 'GU');
	 this.addState("Hawaii", 15, 'HI');
	 this.addState("Idaho", 16, 'ID');
	 this.addState("Illinois", 17, 'IL');
	 this.addState("Indiana", 18, 'IN');
	 this.addState("Iowa", 19, 'IA');
	 this.addState("Kansas", 20, 'KS');
	 this.addState("Kentucky", 21, 'KY');
	 this.addState("Louisiana", 22, 'LA');
	 this.addState("Maine", 23, 'ME');
	 this.addState("Maryland", 24, 'MD');
	 this.addState("Massachusetts", 25, 'MA');
	 this.addState("Michigan", 26, 'MI');
	 this.addState("Minnesota", 27, 'MN');
	 this.addState("Mississippi", 28, 'MS');
	 this.addState("Missouri", 29, 'MO');
	 this.addState("Montana", 30, 'MT');
	 this.addState("Nebraska", 31, 'NE');
	 this.addState("Nevada", 32, 'NV');
	 this.addState("New Hampshire", 33, 'NH');
	 this.addState("New Jersey", 34, 'NJ');
	 this.addState("New Mexico", 35, 'NM');
	 this.addState("New York", 36, 'NY');
	 this.addState("North Carolina", 37, 'NC');
	 this.addState("North Dakota", 38, 'ND');
	 this.addState("Ohio", 39, 'OH');
	 this.addState("Oklahoma", 40, 'OK');
	 this.addState("Oregon", 41, 'OR');
	 this.addState("Pennsylvania", 42, 'PA');
	 //this.addState("Puerto Rico", 72, 'PR');
	 this.addState("Rhode Island", 44, 'RI');
	 this.addState("South Carolina", 45, 'SC');
	 this.addState("South Dakota", 46, 'SD');
	 this.addState("Tennessee", 47, 'TN');
	 this.addState("Texas", 48, 'TX');
	 this.addState("Utah", 49, 'UT');
	 this.addState("Vermont", 50, 'VT');
	 //this.addState("Virgin Islands of the United States", 78, 'VI');
	 this.addState("Virginia", 51, 'VA');
	 this.addState("Washington", 53, 'WA');
	 this.addState("West Virginia", 54, 'WV');
	 this.addState("Wisconsin", 55, 'WI');
	 this.addState("Wyoming", 56, 'WY');

	this.textboxState = usStates;

	this.textboxCounty = document.createElement("input");
	this.textboxCounty.type = "text";
	this.textboxCounty.style.width = "41%";
	this.textboxCounty.style.height = "100%";
	this.textboxCounty.style.display = "none";
	this.textboxCounty.style.marginRight = "10px";

	this.textboxCong = document.createElement('select');
	this.textboxCong.style.display = "none";
	this.textboxCong.style.width = "66%";
	//this.textboxCong.style.height = "50%";
	this.textboxCong.style.marginRight = "10px";
	this.textboxCong.state = "";

	this.textboxStateDistOpts = document.createElement('select');
	this.textboxStateDistOpts.style.paddingLeft = "0px";
	this.textboxStateDistOpts.style.display = "none";
	this.textboxStateDistOpts.style.width = "27%";
	//this.textboxStateDistOpts.style.height = "50%";
	this.textboxStateDistOpts.style.marginRight = "10px";
	var option = document.createElement('option');
	option.innerHTML = "Upper House Districts";
	option.value = PPlaceType.SLD_UPPER.id;
	this.textboxStateDistOpts.appendChild(option);
	var option = document.createElement('option');
	option.innerHTML = "Lower House Districts";
	option.value = PPlaceType.SLD_LOWER.id;
	this.textboxStateDistOpts.appendChild(option);
	var box = this;
	PEvent.addListener(this.textboxStateDistOpts, 'change', function() {
		if (this.value == PPlaceType.SLD_UPPER.id)
			box.setType(PPlaceType.SLD_UPPER);
		else if (this.value == PPlaceType.SLD_LOWER.id)
			box.setType(PPlaceType.SLD_LOWER);
	});

	this.textboxStateDist = document.createElement('select');
	this.textboxStateDist.style.paddingLeft = "0px";
	this.textboxStateDist.style.display = "none";
	this.textboxStateDist.style.width = "38%";
	//this.textboxStateDist.style.height = "50%";
	this.textboxStateDist.style.marginRight = "10px";
	this.textboxStateDist.state = "";
	this.textboxStateDist.stateDistType = "";

	this.textboxCBSA = document.createElement('select');
	this.textboxCBSA.style.paddingLeft = "0px";
	this.textboxCBSA.style.display = "none";
	this.textboxCBSA.style.width = "66%";
	this.textboxCBSA.style.marginRight = "10px";
	this.textboxCBSA.state = "";
		
	var box=this;
	// capture enter key for all textboxes
	this.textboxArr = [this.textbox,this.textboxCBSA,this.textboxStateDist,this.textboxStateDistOpts,this.textboxCong,this.textboxCounty,this.textboxState];
	for (var i=0; i<this.textboxArr.length; i++) {
		PEvent.addListener(this.textboxArr[i], 'keydown', function(e) {
			e = (e)?e:((event)?event:null);
			if (e && e.keyCode == 13)
				box.submit();
		});
	}

	var geocoder = new PClientGeocoder();
	PEvent.addListener(this.textboxState, 'change', function(e) {
		this.style.color = '#7a7a7a';
		if (box.type[0] == PPlaceType.CENSUSTRACT)
			box.textboxCounty.focus();
		else if (box.type[0] == PPlaceType.CONGRESSIONAL)
			box.populateCongressional();
		else if (box.type[0] == PPlaceType.SLD_UPPER || box.type[0] == PPlaceType.SLD_LOWER)
			box.populateStateDistricts();
		else if (box.type[0] == PPlaceType.CBSA_07)
			box.populateCBSA07();
	});
	
	PEvent.addListener(this.textboxCong, 'change', function() {
		this.style.color = '#7a7a7a';
	});

	node.appendChild(this.textboxState);
	node.appendChild(this.textboxCong);
	node.appendChild(this.textboxStateDistOpts);
	node.appendChild(this.textboxStateDist);
	node.appendChild(this.textboxCounty);
	node.appendChild(this.textboxCBSA);
	node.appendChild(this.textbox);

	// applies a focus event for the textboxes that helps keep track of which value to display
	this.setFocusEvents();
	this.setUp();

	if (tabNode)
		this.addSearchTabs(tabNode, tabTypes);
}

PTRFPlaceSearchBox.prototype.addSearchTabs = function(tabNode, tabTypes) {
	this.tabTypes = tabTypes;
	this.tabs = [];
	var box = this;
	for (var i=0; i<tabTypes.length; i++) {
		var tab = document.createElement('a');
		tab.href = "javascript:void(0)";
		var b = document.createElement('b');
		tab.appendChild(b);
		tab.tabType = tabTypes[i];
		tab.tabNum = i;
		if (tabTypes[i] == 'Default') {
			b.innerHTML = "Search the Map";
			tab.className = "highlightTab";
			PEvent.addListener(tab, 'click', function() {
				box.setType();
				box.selectTab(this.tabNum);
				box.setSearchValue();
				for (var i=0; i<box.textboxArr.length; i++) {
					if (box.textboxArr[i].style.display == "inline") {
						// give focus to the textbox if default value isn't still set.
						// this is so enter key will work when the tab is selected
						if (box.textbox.value.search("Enter Address") != 0)
							box.textboxArr[i].focus();
						break;
					}
				}
			});
		}
		else {
			if (tabTypes[i] == PPlaceType.SLD_UPPER)
				b.innerHTML = "State District";
			else if (tabTypes[i] == PPlaceType.CBSA_07)
				b.innerHTML = "Metro";
			else
				b.innerHTML = tabTypes[i].getName();

			tab.className = "searchboxTabs";
			PEvent.addListener(tab, 'click', function() {
				box.setType(this.tabType);
				box.selectTab(this.tabNum);
				box.setSearchValue(this.tabType);
				for (var i=0; i<box.textboxArr.length; i++) {
					if (box.textboxArr[i].style.display == "inline") {
						if (this.tabType == PPlaceType.CENSUSTRACT || this.tabType == PPlaceType.SCHOOL) {
							if (box.textbox.value != 'e.g., "Philadelphia City School District"' && box.textbox.value != 'e.g., "401104"')
								box.textboxArr[i].focus();
						}
						else
							box.textboxArr[i].focus();
						break;
					}
				}
			});
		}
		this.tabs.push(tab);
		tabNode.appendChild(tab);
	}
}

PTRFPlaceSearchBox.prototype.selectTab = function(tabNum) {
	for (var i=0; i<this.tabs.length; i++) {
		if (i == tabNum)
			this.tabs[i].className = "highlightTab";
		else if (this.tabs[i].disabled == true)
			this.tabs[i].className = "searchboxTabs searchboxDisableTab";
		else
			this.tabs[i].className = "searchboxTabs";
	}
}

PTRFPlaceSearchBox.prototype.getTab = function(tabNum) {
	return this.tabs[tabNum];
}

PTRFPlaceSearchBox.prototype.getTabs = function() {
	return this.tabs;
}

PTRFPlaceSearchBox.prototype.disableTab = function(tabNum) {
	var tab = this.tabs[tabNum];
	tab.disabled = true;
	tab.className += " searchboxDisableTab";
	PEvent.clearInstanceListeners(tab);
}

PTRFPlaceSearchBox.prototype.enableTab = function(tabNum) {
	var tab = this.tabs[tabNum];
	tab.disabled = false;
	tab.className = "searchboxTabs";
	var box = this;
	PEvent.addListener(tab, 'click', function() {
		box.setType(box.tabTypes[tabNum]);
		box.selectTab(tabNum);
		box.setSearchValue(box.tabTypes[tabNum]);
	});
}

PTRFPlaceSearchBox.prototype.setSearchValue = function(tabType) {
	var search = this;
 	if (!tabType) {
		search.textbox.id = "as_searchthemap";
		if( autosuggest != null ) {
		autosuggest["as_searchthemap"] = new AutoSuggest( 
			"as_searchthemap",
			{
				script:"ajax/as_searchthemap.jsp?",
				varname:"input",
				json:true,
				minchars:3,
                                callback: function (obj) {
                                        PPlaceLoader.load([obj.gbid], function(places) { addMarkerWindow( createPlacesDiv(places), places[0] ); });
                                }
			}
		);
		}

 		if (search.searchthemap && search.searchthemap.search("Enter Address") != 0) {
 			search.textbox.style.color = "#7a7a7a";
 			search.textbox.value = search.searchthemap;
 			search.tab = "searchthemap";
 		}
 		else {
 			search.textbox.style.color = "#fff";
 			search.textbox.value = 'Enter Address, City, County, State, or Zip';
 			search.tab = "searchthemap"
 		}
 	}
 	else if (tabType == PPlaceType.CONGRESSIONAL) {
 		if (search.congressional) {
	 		search.textbox.style.color = "#7a7a7a";
	 		search.tab = "congressional";
	 	}
	 	else {
 			search.textbox.style.color = "#fff";
 			search.tab = "congressional";
 		}
 	}
 	else if (tabType == PPlaceType.SCHOOL) {
		// Autosuggest 2.0
		search.textbox.id = "as_school";
		if( autosuggest != null ) {
		autosuggest["as_school"] = new AutoSuggest( 
			"as_school",
			{
				script:"ajax/as_school.jsp?",
				varname:"input",
				json:true,
				minchars:3,
				callback: function (obj) {/*  affect dom here */},
				beforeCallback: function (input) {
					this.putTmpParam( 'sgbid', jQuery("#states")[0].value );
					return true;
				},
                                callback: function (obj) {
                                        // PPlaceLoader.load([obj.gbid], function(places) { addMarkerWindow( createPlacesDiv(places), places[0] ); });
                                }
			}
		);
		}

 		if (search.school && search.school.search("e.g.,") !=0) {
 			search.textbox.style.color = "#7a7a7a";
			search.textbox.value = search.school;
			search.tab = "school";
		}
		else {
 			search.textbox.style.color = "#fff";
 			search.textbox.value = 'e.g., "Philadelphia City School District"';
 			search.tab = "school";
 		}
 	}
 	else if (tabType == PPlaceType.CENSUSTRACT) {
		
		// Autosuggest 2.0
		search.textbox.id = "as_census";
		if( autosuggest != null ) {
		autosuggest["as_county"] = new AutoSuggest( 
			"as_county", 
			{
				script:"ajax/as_county.jsp?",
				varname:"input",
				json:true,
				minchars:3,
				shownoresults:true,
				beforeAjaxRequest : function (input) {
					autosuggest["as_census"].cgbid = null;
	                                this.putTmpParam( 'sgbid', jQuery("#states").attr("value") );
        	                        return true;
                	        },
				callback : function (obj) {
					autosuggest["as_census"].cgbid = obj.gbid;
				}
			}
		);
		
		autosuggest["as_census"] = new AutoSuggest( 
			"as_census",
			{
				script:"ajax/as_census.jsp?",
				varname:"input",
				json:true,
				callback: function (obj) {/*  affect dom here */},
				shownoresults:true, 
				minchars:2,
				shownoresults:true,
				beforeAjaxRequest : function (input) {
					if( this.cgbid ) {  
						this.putTmpParam( 'cgbid', this.cgbid );
						return true;
					} else if( autosuggest["as_county"] && autosuggest["as_county"].aSuggestions.length > 0 ) {
						this.putTmpParam( 'cgbid', autosuggest["as_county"].aSuggestions[0].gbid );
						return true;
					} else  {
						alert( "Please select a county first" );
						jQuery("input#as_county").focus();
						return false;
					}
                                },
	                        callback : function (obj) {
                                        PPlaceLoader.load([obj.gbid], function(places) { addMarkerWindow( createPlacesDiv(places), places[0] ); });
                                }
			}
		);
		}

 		if (search.census && search.census.search("e.g.,") != 0) {
 			search.textbox.style.color = "#7a7a7a";
			search.textbox.value = search.census;
			search.tab = "census"
		}
		else {
			search.textbox.style.color = "#fff";
			search.textbox.value = 'e.g., "401104"';
 			search.tab = "census"
 		}
 	}
 	else if (tabType == PPlaceType.SLD_UPPER) {
 		if (search.statedistricts)
	 		search.textbox.style.color = "#7a7a7a";
	 	else
 			search.textbox.style.color = "#fff";
		search.tab = "statedistricts";
 	}
 	else if (tabType == PPlaceType.CBSA_07) {
 		if (search.cbsa)
	 		search.textbox.style.color = "#7a7a7a";
	 	else
 			search.textbox.style.color = "#fff";
		search.tab = "cbsa";
 	}
 }

PTRFPlaceSearchBox.prototype.setFocusEvents = function() {
	var search = this;
	PEvent.addListener(search.textbox, 'focus', function() {
		this.style.color = '#7a7a7a';
		if (this.wasClicked == true) return;
		this.wasClicked = true;
		if (!search.tab)
		search.tab = "searchthemap";
		this.value = "";	
	});
	PEvent.addListener(search.textboxState, 'focus', function() {
		if (this.wasClicked == true) return;
		this.wasClicked = true;
		search.tab = "census";
	});
	PEvent.addListener(search.textboxCong, 'focus', function() {
		if (this.wasClicked == true) return;
		this.wasClicked = true;
		search.tab = "congressional";
	});
	PEvent.addListener(search.textboxStateDistOpts, 'focus', function() {
		if (this.wasClicked == true) return;
		this.wasClicked = true;
		search.tab = "statedistricts";
	});
	PEvent.addListener(search.textboxStateDist, 'focus', function() {
		if (this.wasClicked == true) return;
		this.wasClicked = true;
		search.tab = "statedistricts";
	});
	PEvent.addListener(search.textboxCBSA, 'focus', function() {
		if (this.wasClicked == true) return;
		this.wasClicked = true;
		search.tab = "cbsa";
	});
	// focus event that clears textbox if value is the default value
 	PEvent.addListener(search.textbox, 'focus', function() {
		var s = search.textbox.value;
		search.textbox.style.color = "#7a7a7a";
		if (s == 'Enter Address, City, County, State, or Zip') {
			search.tab = "searchthemap";
			this.value = "";
		}
		else if (s == 'e.g., "Philadelphia City School District"') {
			search.tab = "school";
			this.value = "";	
		}
		else if (s == 'e.g., "401104"') { 
			search.tab = "census";
			this.value = "";
		}
	});
	// focus event that clears textbox if value is the default value
	PEvent.addListener(search.textboxCounty, 'focus', function() {
		search.textboxCounty.style.color = "#7a7a7a";
		var c = search.textboxCounty.value;
		if (c == 'Enter County') {
			search.tab = "census";
			if (this.wasClicked == true ) {
				return;
			}
			this.value = "";
		}
		this.wasClicked = true;
	});
}

PTRFPlaceSearchBox.prototype.reset = function() {
	this.setType(null);
	this.selectTab(0);
	this.setSearchValue(null);

	// Set the default values for textboxes
	search.census = 'e.g., "401104"';
	search.school = 'e.g., "Philadelphia City School District"';
	search.searchthemap  = 'Enter Address, City, County, State, or Zip';
	search.textbox.value = search.searchthemap;
	search.textboxCounty.value = 'Enter County';
	search.textboxCounty.wasClicked = "";
}

PTRFPlaceSearchBox.prototype.setUp = function() {
	this.textbox.className = "searchbox";
	this.textbox.value = 'Enter Address, City, County, State, or Zip';
	this.textboxState.className = "searchbox";
	this.textboxCounty.className = "searchbox";
	this.textboxCounty.id = "as_county";
	this.textboxCounty.name = "as_county";
	this.textboxCounty.value = 'Enter County';
	this.textboxCong.className = "searchbox";
	this.textboxStateDistOpts.className = "searchbox";
	this.textboxStateDist.className = "searchbox";
	this.textboxCBSA.className = "searchbox";
}

PTRFPlaceSearchBox.prototype.addListener = function(eventId, func) {
	this.eventManager.registerForEvent(eventId, [], func);
}

PTRFPlaceSearchBox.prototype.setDefaultTypes = function(types) {
	this.defaultType = types;
}

PTRFPlaceSearchBox.prototype.getSearchString = function() {
	return this.textbox.value;
}

PTRFPlaceSearchBox.prototype.setTypes = function(types) {
	if (types) {
		this.type = types;
	}
	else
		this.type = this.defaultType;
}	

PTRFPlaceSearchBox.prototype.setType = function(type) {
	if (type)
		this.type = [type];
	else
		this.type = this.defaultType;

	// toggle input boxes
	if (type && type == PPlaceType.CENSUSTRACT) {
		this.textboxCong.style.display = "none";
		this.textboxState.style.display = "inline";
		this.textboxState.style.paddingLeft = "0px";
		this.textboxCounty.style.display = "inline";
		this.textboxStateDistOpts.style.display = "none";
		this.textboxStateDist.style.display = "none";
		this.textbox.style.display = "inline";	
		this.textbox.style.width = "20%";
		this.textboxCBSA.style.display = "none";
	} 
	else if (type && type == PPlaceType.CONGRESSIONAL) {
		this.textboxState.style.display = "inline";
		this.textboxState.style.paddingLeft = "0px";
		this.textboxCounty.style.display = "none";
		this.textbox.style.display = "none";
		this.textboxStateDistOpts.style.display = "none";
		this.textboxStateDist.style.display = "none";
		this.textboxCong.style.display = "inline";
		this.textboxCBSA.style.display = "none";
		this.populateCongressional();
	} 
	else if (type && type == PPlaceType.SCHOOL) {
		this.textboxCong.style.display = "none";
		this.textboxState.style.display = "inline";
		this.textboxState.style.paddingLeft = "0px";
		this.textboxCounty.style.display = "none";
		this.textboxStateDistOpts.style.display = "none";
		this.textboxStateDist.style.display = "none";
		this.textbox.style.display = "inline";	
		this.textbox.style.width = "64%";
		this.textboxCBSA.style.display = "none";
	}
	else if (type && (type == PPlaceType.SLD_UPPER || type == PPlaceType.SLD_LOWER)) {
		this.textboxState.style.display = "inline";
		this.textboxState.style.paddingLeft = "0px";
		this.textboxCounty.style.display = "none";
		this.textbox.style.display = "none";
		this.textboxCong.style.display = "none";
		this.textboxStateDistOpts.style.display = "inline";
		this.textboxStateDist.style.display = "inline";
		this.textboxCBSA.style.display = "none";
		this.populateStateDistricts();
	} 
	else if (type && type == PPlaceType.CBSA_07) {
		this.textboxState.style.display = "inline";
		this.textboxState.style.paddingLeft = "0px";
		this.textboxCounty.style.display = "none";
		this.textbox.style.display = "none";
		this.textboxCong.style.display = "none";
		this.textboxStateDistOpts.style.display = "none";
		this.textboxStateDist.style.display = "none";
		this.textboxCBSA.style.display = "inline";
		this.populateCBSA07();
	} 
	else {
		this.textboxState.style.display = "none";
		this.textboxState.style.paddingLeft = "0px";
		this.textboxCounty.style.display = "none";
		this.textbox.style.display = "inline";
		this.textbox.style.width = "100%";
		this.textboxCong.style.display = "none";
		this.textboxStateDistOpts.style.display = "none";
		this.textboxStateDist.style.display = "none";
		this.textboxCBSA.style.display = "none";
	}
}

PTRFPlaceSearchBox.prototype.populateDropDowns = function(placetypes, elem) {
	var geocoder = new PClientGeocoder();
	var d = this.textboxState;
	var stateText = d.options[d.selectedIndex].innerHTML;
	var stateId = d.options[d.selectedIndex].value;

	if (stateId != elem.state || (elem.stateDistType && placetypes[0] != elem.stateDistType)) {
		// clear dropdown
		while(elem.hasChildNodes())
			elem.removeChild(elem.firstChild);
		// find districts and populate dropdown
		var box = this;
		if (placetypes[0] == PPlaceType.CBSA_07) {
			// because some cbsa places overlap different states it needs to check places within the state
			geocoder.getPlace(stateText, function(stateplaces) {

				// Kluge to add a cbsa to drop down for DC since technically DC doesn't contain a cbsa but a cbsa contains DC
				// REMOVE this when db is fixed and the cbsa is returned as being contained by DC
				if (stateplaces[0].label == "District of Columbia") {
					var cdoption = document.createElement('option');
					// place id and label
					cdoption.value = 616030;
					cdoption.text = "Washington-Arlington-Alexandria, DC-VA-MD-WV Metropolitan Statistical Area";
					try {
						elem.add(cdoption,null);
					}
					catch (ex) {
						elem.add(cdoption);
					}
					return;
				}

				var state = stateplaces[0];
				// check so Arkansas isn't used instead of Kansas and make sure place is in US
				if (stateplaces.length > 1) {
					for (var j=0; j<stateplaces.length; j++) {
						if (stateplaces[j].getLabel() == stateText && stateplaces[j].country == "United States")
							state = stateplaces[j];
					}
				}
				state.getPlacesWithin(placetypes[0], function(places) {
					for (var i=0; i<places.length; i++) {
						var cdoption = document.createElement('option');
						cdoption.value = places[i].id;
						cdoption.text = places[i].getLabel().replace(stateText + " ", "");
						try {
							elem.add(cdoption,null);
						}
						catch (ex) {
							elem.add(cdoption);
						}
					}
					box.eventManager.triggerEvent('dd_initialized', places);
				}, 5, 200, PPlaceOrder.LABEL);
			}, 200, "geo_boundary_identifier", [PPlaceType.STATE]);
		}
		else {
			geocoder.getPlace(stateText, function(places) {
				for (var i=0; i<places.length; i++) {
					// Kluge: Currently places are populated based on the state string, so Arkansas places are appearing in Kanas dropdown
					// TODO: Use getPlacesWithin instead of getPlace, but need to get the state pplace object first
					if (stateText == "Kansas" && places[i].getState() == "AR")
						continue;
					var cdoption = document.createElement('option');
					cdoption.value = places[i].id;
					cdoption.text = places[i].getLabel().replace(stateText + " ", "");
					try {
						elem.add(cdoption,null);
					}
					catch (ex) {
						elem.add(cdoption);
					}
				}
				// need to hard code 3 state house districts since PA has 203 in it and 200 is the max
				if (stateText == "Pennsylvania" && placetypes[0] == PPlaceType.SLD_LOWER) {
					var allplaces = places;
					PPlaceLoader.load([1884717, 1884718, 1884711], function(places) {
						for (var i=0; i<places.length; i++) {
							var cdoption = document.createElement('option');
							cdoption.value = places[i].id;
							cdoption.text = places[i].getLabel().replace(stateText + " ", "");
							try {
								elem.add(cdoption,null);
							}
							catch (ex) {
								elem.add(cdoption);
							}
							allplaces.push(places[i]);
						}
						box.eventManager.triggerEvent('dd_initialized', allplaces);
					});
				}						
				else
					box.eventManager.triggerEvent('dd_initialized', places);
			}, 200, "geo_boundary_identifier", placetypes);
		}

		// keep track of state value to avoid reloading
		elem.state = stateId;
		// keep track of state district type(upper or lower)
		if (elem.stateDistType || elem.stateDistType == "") {
			elem.stateDistType = placetypes[0];
		}
	}
}

PTRFPlaceSearchBox.prototype.populateCongressional = function() {
	this.populateDropDowns(this.type, this.textboxCong);
}
PTRFPlaceSearchBox.prototype.populateStateDistricts = function() {
	this.populateDropDowns(this.type, this.textboxStateDist, this.stateDistState, this.stateDistType);
}
PTRFPlaceSearchBox.prototype.populateCBSA07 = function() {
	this.populateDropDowns(this.type, this.textboxCBSA, this.cbsaState);
}

PTRFPlaceSearchBox.prototype.cleanString = function(s) {
	if (s.search("e.g.,") == 0) {			
		return '';
	} else {
		return s.replace(/^\s+|\s+$/g,"");
	}
}

PTRFPlaceSearchBox.prototype.submit = function() {
	var geocoder = new PClientGeocoder();
	this.eventManager.triggerEvent('submit');
	var box = this;
	var text = this.getSearchString();
	var type = this.type;
	if (text.search("e.g.,") == 0) {
		 text = text.replace(/e.g., "/,"");
		 text = text.replace(/"/,"");
	}

	// explicit lat/lng
	var matches = /^(-?\d+(\.\d+)?),(-?\d+(\.\d+)?)$/.exec( text );
	if( matches ) {
		var lat = parseFloat(matches[1]);
		var lng = parseFloat(matches[3]);
		var address = new PAddress(lat+','+lng,lng,lat);
		box.eventManager.triggerEvent('response',address);
	}
	// find census tracts
	else if (this.type && this.type[0] == PPlaceType.CENSUSTRACT) {
		var d = this.textboxState;
		var stateText = d.options[d.selectedIndex].value;
		var countyText = this.textboxCounty.value;
		if (countyText.search("e.g.,") == 0) {
			countyText = countyText.replace(/e.g., "/,"");
			countyText = countyText.replace(/"/,"");
		}

		if (this.cleanString(countyText) == '') {
			alert('Please enter County name.');
			return;
		}

		if (this.cleanString(text) != "") {
			var f = function(places) {
				if (places.length > 0)
					box.eventManager.triggerEvent('response', places);
				else {
					var alerter = new PAlerter();
					var pos = getAlertPosition(parseInt(alerter.box.style.width));
					var content = "Location \"<b>" + d.options[d.selectedIndex].innerHTML + ", " + countyText + ", " + text + "</b>\" not found. For help finding the census tract:  <a class='pagelinks' href='" + PEnvironment.blogUrl + "/?p=213' target='_blank'>click here</a>";
					alerter.popup(content,pos[0],pos[1],"OK");
				}

			};

			var path = ['states', 'fips', stateText, 'counties', 'names', countyText, 'censustracts', 'numbers', text];
			path = path.join('/');
                        PPlaceLoader.loadByPath(path, f, {ord:'geo_boundary_identifier asc'});
		}
	// get congressional district
	} else if (this.type && this.type[0] == PPlaceType.CONGRESSIONAL) {
		var d = this.textboxCong;
		var congid = d.options[d.selectedIndex].value;
		PPlaceLoader.load([congid], function(places) {
			box.eventManager.triggerEvent('response', places);
		});
	// find school district
	} else if (this.type && this.type[0] == PPlaceType.SCHOOL) {
		var d = this.textboxState;
		var stateText = d.options[d.selectedIndex].title;
		text += ', '+ stateText;
		if (this.cleanString(text) == '') {
			alert('Please enter School District name.');
			return;
		}
		if (this.cleanString(text) != "") {
			geocoder.getPlace(text,
				function(places) {
					if (places.length > 0)
						box.eventManager.triggerEvent('response',places);
					else {
						var alerter = new PAlerter();
						var pos = getAlertPosition(parseInt(alerter.box.style.width));
						var content = "Location \"<b>" + search.getSearchString() + "</b>\" not found.";
						alerter.popup(content,pos[0],pos[1],"OK");
					}
					},
					5,
					PPlaceOrder.POPULATION,
					box.type
			);					
		}
	// get upper house districts
	} else if (this.type && (this.type[0] == PPlaceType.SLD_UPPER || this.type[0] == PPlaceType.SLD_LOWER)) {
		var d = this.textboxStateDist;
		var statedistid = d.options[d.selectedIndex].value;
		PPlaceLoader.load([statedistid], function(places) {
			box.eventManager.triggerEvent('response', places);
		});
	// get cbsa
	} else if (this.type && this.type[0] == PPlaceType.CBSA_07) {
		var d = this.textboxCBSA;
		var cbsaid = d.options[d.selectedIndex].value;
		PPlaceLoader.load([cbsaid], function(places) {
			box.eventManager.triggerEvent('response', places);
		});
	// find all other places
	} else {
		var placetypes = null;
		// check for county subdivision text
		if (text.toLowerCase().indexOf(' county subdivision') != -1) {
			text = text.toLowerCase().replace(' county subdivision','');
			placetypes = [PPlaceType.COUNTY_SUBDIVISION];
		} else
			placetypes = box.type;

		if (this.cleanString(text) != "") {
			geocoder.getPlace(text,
				function(places) {
					if (places.length > 0)
						box.eventManager.triggerEvent('response',places);
					else
						geocoder.getLocations(text, function(address) {
							box.eventManager.triggerEvent('response',address);
						});
					},
					5,
					PPlaceOrder.POPULATION,
					placetypes
			);
		}
	}

	if (this.tab == "searchthemap")
		this.searchthemap = this.textbox.value;
	else if (this.tab == "county")
		this.county = this.textbox.value;
	else if (this.tab == "census")
		this.census = this.textbox.value;
	else if (this.tab == "school")
		this.school = this.textbox.value;

}

// Initiates the searchbox with all the tabs and sets the search event
function initSearchBox() {
	var searchTabTypes = [ 'Default', PPlaceType.CENSUSTRACT,
	                       PPlaceType.CONGRESSIONAL, PPlaceType.SCHOOL, PPlaceType.SLD_UPPER,
	                       PPlaceType.CBSA_07 ];
	// search box
	search = new PTRFPlaceSearchBox(document.getElementById("search"), document.getElementById('searchboxtabs'), searchTabTypes);

	// Autosuggest 2.0
	// Since we're sharing search.textbox, we have to instantiate a new instance
	// of autocomplete every time we change search.textbox.id
	search.textbox.id = "as_searchthemap";
	if (autosuggest != null) {
		autosuggest["as_searchthemap"] = new AutoSuggest("as_searchthemap", {
			script :"ajax/as_searchthemap.jsp?",
			varname :"input",
			json :true,
			minchars :3,
			callback : function(obj) {
			PPlaceLoader.load( [ obj.gbid ], function(places) {
				addMarkerWindow(createPlacesDiv(places), places[0]);
			});
		}
		});
	}

	// limit types (e.g. so we don't end up searching for zcta types)
	search.setDefaultTypes( [ PPlaceType.STATE, PPlaceType.COUNTY,
	                          PPlaceType.COUNTY_SUBDIVISION, PPlaceType.CITY, PPlaceType.ZIP ]);
	search.setTypes(null);

	search.addListener('response', function(places) {
		var html = null;

		if (places instanceof PAddress) {
			if (places.wasFound()) {
				session.placeName = '"' + places.addr + '"';
				// TODO: remove old session code
				session2.put('place', places.addr);
				session2.put('lng', places.x);
				session2.put('lat', places.y);

				html = "<div class='infoBubbleText'>" + places.addr + "</div><br />";
				addMarkerWindow(html, new PLatLng(places.y, places.x));
			} else {
				var alerter = new PAlerter();
				var pos = getAlertPosition(parseInt(alerter.box.style.width));
				var content = "Location \"<b>" + places.addr + "</b>\" not found. For help finding your address or city:  <a class='pagelinks' href='" + PEnvironment.blogUrl + "/?p=200' target='_blank'>click here</a>";
				alerter.popup(content, pos[0], pos[1], "OK");
			}
		} else {
			// KLUGE: filter out non US places
			var l = places.length;
			var full = places;
			places = [];
			var p;
			for ( var i = 0; i < l; i++) {
				p = full[i];
				if (p.country == "United States") {
					places.push(p);
				}
			}

			if (places.length == 0) {
				var alerter = new PAlerter();
				var pos = getAlertPosition(parseInt(alerter.box.style.width));
				alerter.popup("Location \"<b>" + search.getSearchString() + "</b>\" not found.", pos[0], pos[1], "OK");
			} else {
				var html = createPlacesDiv(places, search.getSearchString());
				addMarkerWindow(html, places[0]);
				session2.put('p', places[0].id);
			}
		}
	});
}
