 function reportsOnLoad() {
	var urlParam = PWebUtil.parseQuery();
	PSession.fromURI(urlParam);
	updateSessionLinks();
	
	var urlParams = getUrlParams();
	
	// Determine if a polygon was passed in.
	if(urlParams['bid'] && urlParams['polyid'] && urlParams['pname'] && urlParams['plat'] && urlParams['plng'])
		polyenabled = true;
	
	var pdl = document.getElementById('pdl_img');
	addPNGBackground(pdl, "images/menureports-type-predefined.png");
	var radius = document.getElementById('radius_img');
	addPNGBackground(radius, "images/menureports-type-radius.png");
	var cr = document.getElementById('cr_img');
	addPNGBackground(cr, "images/menureports-type-custom.png");
	var poly = document.getElementById('poly_img');
	// Show a different image for when the polygon option is enabled and disabled.
	if(polyenabled)
		addPNGBackground(poly, "images/menureports-type-poly.png");
	else
		addPNGBackground(poly, "images/menureports-type-poly-grey.png");

	var searchBoxTypes = ['Default', PPlaceType.CENSUSTRACT, PPlaceType.BLOCKGROUP, PPlaceType.CONGRESSIONAL, PPlaceType.SCHOOL, PPlaceType.SLD_UPPER, PPlaceType.CBSA_07];
	// search box
	var options = {noStartOver:true, noSetLocationIcon:true};
	search = new PTRFPlaceSearchBox(document.getElementById("SetLocation"), searchBoxTypes, options);

	search.textbox.className = "searchbox";
	search.textbox.style.color = "#fff";

	var defaulttypes = [PPlaceType.STATE, PPlaceType.COUNTY, PPlaceType.COUNTY_SUBDIVISION, PPlaceType.CITY, PPlaceType.ZIP];
	search.setDefaultTypes(defaulttypes);

	// If a specific report was passed in the URL, select it. If not, select the first one.
	// This is done here rather than adding a "checked" to the HTML so we can call its click event.
	var radios = document.reportform.reportradio;
	if(urlParams['type']) {
		for (var i=0; i<radios.length; i++) {
			if (radios[i].value == urlParams['type']) {
				radios[i].checked = true;
				radios[i].click();
			}
		}
	} else {
		radios[0].checked = true;
		radios[0].click();
	}

	if (urlParams['cpid'])
		showCustomRegion(urlParams);
	else if (urlParams['pid'])
		addPlaceToSearchBox(urlParams);
	else {
		search.textbox.value = 'Enter City, County, State, or Zip';
		search.textboxCounty.value = 'Enter County';
		showWidget('predefined');
		// limit types (e.g. so we don't end up searching for zcta types)
		search.setTypes(null);
	}
	search.textboxState.className = "searchbox";
	search.textboxState.style.color = "#fff";
	search.textboxCounty.className = "searchbox";
	search.textboxCounty.style.color = "#fff";
	search.textboxCong.className = "searchbox";
	search.textboxCong.style.color = "#fff";

	PEvent.addListener(search.textbox, 'focus', function() {
		search.textbox.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() {
		//search.textboxState.style.color = '#7a7a7a';
		if (this.wasClicked == true) return;
		this.wasClicked = true;
		search.tab = "census";
		//this.value = "";	
	});
	PEvent.addListener(search.textboxCong, 'focus', function() {
		//search.textboxCong.style.color = '#7a7a7a';
		if (this.wasClicked == true) return;
		this.wasClicked = true;
		search.tab = "congressional";
		//this.value = "";	
	});

	search.addListener('response', function(places) {
		if(permcode != 0) {
			reportAvailability(permcode);
			return;
		}

		var p = document.getElementById('predefined');
		var c = document.getElementById('custom');
		if (p.className == "areaTypeOptions selected")
			var searchtype = "predefined";
		else
			var searchtype = "custom";

		// Checks for place that was set on map page and then get report was clicked from identify, it uses the id in url instead of geocoding
		if (urlParams['pid'] && search.getReportPlace == search.textbox.value) {
			var types = search.getCurrentType();
			// make sure that the search tab wasn't changed before using the place id in the url
			for (var i=0; i<types.length; i++) {
				if (search.innitialPlace.getType() == types[i]) {
					submitReport(search.innitialPlace);
					return;
				}
			}
		}

		if (places instanceof PAddress) {
			var alerter = new PAlerter();
			if (places.wasFound())
				alerter.popup('Please specify an area, not an address.',null,null,"OK");
			else
				alerter.popup("Location \"<b>" + search.getSearchString() + "</b>\" not found.",null,null,"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();
				alerter.popup("Location \"<b>" + search.getSearchString() + "</b>\" not found.",null,null,"OK");
			} 
			else {	
				submitReport(places[0]);
			}			
		}
	});
	
	rsearch = new PPlaceSearchBox(document.getElementById("radiussearch"));
	rsearch.textbox.className = "searchbox";
	rsearch.textbox.style.color = "#fff";
	if (session2.get('place'))
		rsearch.textbox.value = session2.get('place');
	else
		rsearch.textbox.value = 'e.g., "421 North Boundary Street, Williamsburg, VA 23185"';
	var rs = rsearch.textbox.value;
	PEvent.addListener(rsearch.textbox, 'click', function() {
		if (rsearch.clicked == "true") {return}
		rsearch.clicked = "true";
		rsearch.textbox.style.color = "#7a7a7a";
		if (rs == 'e.g., "421 North Boundary Street, Williamsburg, VA 23185"' || rs == session2.get('place')) {
			this.value = "";	
		}
	});
	
	rsearch.addListener('response', function(places) {
		if(permcode != 0) {
			reportAvailability(permcode);
			return;
		}

		if (places instanceof PAddress) {
			if (places.wasFound()) {
				submitReport(places);
			}
			else {
				var alerter = new PAlerter();
				var content = "Location \"<b>" + places.addr + "</b>\" not found. For help finding your address:  <a class='pagelinks' href='/blog?p=200' target='_blank'>click here</a>";
				alerter.popup(content,null,null,"OK");
			}
		} else {
			var alerter = new PAlerter();
			alerter.popup("Please specify a street address, not an area.",null,null,"OK");
		}
	});
	
	if(polyenabled) {
		// A polygon was passed in.
		$('.polygondisplay').text('Retrieving...');
		
		// Hide the radius and polygon Go buttons until the polygon has been retrieved.
		document.getElementById("radiusGoButton").style.display = "none";
		document.getElementById("polygonGoButton").style.display = "none";
		
		// Display the polygon in the radius tab.
		document.getElementById("radiuspolygon").style.display = "inline";
		
		// Retrieve the polygon.
		new PPolyCreator().polyload(urlParams['bid'], urlParams['pname'], urlParams['plat'], urlParams['plng'], function(places) {
			if(places[0]) {
				// Polygon found. Display its name and the radius and polygon Go buttons.
				$('.polygondisplay').text(decodeURIComponent(urlParams['pname']));
				document.getElementById("polygonGoButton").style.display = "inline";
				document.getElementById("radiusGoButton").style.display = "inline";
				
				// Get the polygon's center point and radius. We do this whenever a polygon is passed
				// in, even if the radius report wasn't selected. This way the user can switch to a
				// radius report for the selected polygon from the Report screen, if they choose to.
				var polyrad = getPolygonRadius(places[0]);
				var value = polyrad.lat + ',' + polyrad.lng;
				$('#radiussearch').children('input').val(value);
				$('#radiussearch').children('input').attr( {
					disabled: true
				});
				polyradius = polyrad.size;
			} else {
				// Polygon not found. Display a message to indicate this.
				$('.polygondisplay').text(decodeURIComponent(urlParams['pname']) + " not found.");
				
				// Clear and disable the radius search.
				$('#radiussearch').children('input').val("Polygon not found.");
				$('#radiussearch').children('input').attr( {
					disabled: true
				});
			}
		});
	}
	else {
		$('#polygon').css('color','#aaa');
		$('#polygon').find('.reporttypelinks').css('color','#aaa');
		$('#poly_img').addClass("disabled");
	}

	if(urlParams['area']) {
		if(urlParams['area'] == 'radius' && ((urlParams['lat'] && urlParams['lng']) || urlParams['location'])) {
			showWidget('radius');
			var value = (urlParams['location']) ? urlParams['location'] : urlParams['lat'] + ',' + urlParams['lng'];
			$('#radiussearch').children('input').val(value);
			$('#radiussearch').children('input').attr( {
				disabled: true
			});
		} else if(urlParams['area'] == 'pradius' && polyenabled) {
			// User wants to generate a radius report based on a polygon.
			showWidget('radius');
		} else if(urlParams['area'] == 'polygon' && polyenabled) {
			// User wants to generate a polygon report.
			showWidget('polygon');
		}
	}
	
	// Create and start the notification service.
	notification = new Notification();
	notification.start();
	
	showExpiryAlertFunction();
}

function showWidget(selected) {
	var predwidget = document.getElementById("predefinedwidget");
	var rwidget = document.getElementById("radiuswidget");
	var custwidget = document.getElementById("customregionwidget");
	var polywidget = document.getElementById("polygonwidget");

	if (selected == "predefined") {
		highlightSelected(1);
		predwidget.style.display = "inline";
		rwidget.style.display = "none";
		custwidget.style.display = "none";
		polywidget.style.display = "none";
	}
	if (selected == "radius") {
		highlightSelected(2);
		predwidget.style.display = "none";
		rwidget.style.display = "inline";
		custwidget.style.display = "none";
		polywidget.style.display = "none";
	}
	if (selected == "custom") {
		highlightSelected(3);
		predwidget.style.display = "inline"; 
		rwidget.style.display = "none";
		custwidget.style.display = "inline";
		polywidget.style.display = "none";
	}
	if (selected == "polygon") {
		if(polyenabled) {
			highlightSelected(4);
			predwidget.style.display = "none";
			rwidget.style.display = "none";
			custwidget.style.display = "none";
			polywidget.style.display = "inline";
		} else {
			var alerter = new PAlerter2();
			alerter.popup("Polygons must be selected from the map to access their available reports.", null, null, "OK");
		}
	}
	// Only re-enable the radius search field if the report page wasn't loaded with a polygon.
	if(!polyenabled) {
		$('#radiussearch').children('input').attr({
			disabled: false
		});
	}
}

function getReportSearchType() {
	var type;
	if (polyradius) {
		type = "pradius";
	} else {
		type = $(".areaTypeOptions.selected").attr("id");
	}

	return type;
}

function submitReport(place) {
	if(permcode != 0) {
		reportAvailability(permcode);
		return;
	}

	submitToNextPage(place);
}

function submitToNextPage(place) {
	var address;
	// address can be the place id, the actual address, or the lat lng from a point or polygon or address
	if (place instanceof PAddress) {
		address = place.addr;
	} else if (place instanceof PPlace) {
		address = place.id;
	} else {
		// for when a lat lng is passed in the url
		address = place;
	}

	var urlParams = getUrlParams();
	var report = getReportSelected();
	// Gets the type of report it is. Meaning predefined, custom, radius, or polygon
	var searchtype = getReportSearchType();

	var state = "";
	// Some search types require a state drop down, these are them
	// So we pass the state abbreviation so we can set the drop down on the following page
	if (search.type[0] == PPlaceType.CONGRESSIONAL || search.type[0] == PPlaceType.CENSUSTRACT || search.type[0] == PPlaceType.BLOCKGROUP || search.type[0] == PPlaceType.SLD_UPPER || search.type[0] == PPlaceType.SLD_LOWER || search.type[0] == PPlaceType.CBSA_07 || search.type[0] == PPlaceType.SCHOOL)
		state = search.getSearchStateAbbr();

	if(searchtype == "radius" || searchtype == "pradius") {
		if(polyradius) {
			// Decode pname before encoding it, as it may only be partially decoded.
			var url = "report_area?type=" + report + "&area=" + searchtype + "&location=" + address + "&radius=" + polyradius + "&bid=" + urlParams['bid'] + "&polyid=" + urlParams['polyid'] + "&pname=" + encodeURIComponent(decodeURIComponent(urlParams['pname'])) + "&plat=" + urlParams['plat'] + "&plng=" + urlParams['plng'];
		} else {
			var url = "report_area?type=" + report + "&area=" + searchtype + "&location=" + address + "&radius=" + "0.5";
		}
	}
	else if (place.getType() == PPlaceType.CONGRESSIONAL || place.getType() == PPlaceType.SLD_UPPER || place.getType() == PPlaceType.SLD_LOWER || place.getType() == PPlaceType.CBSA_07) {
		var typeid = place.getType().id;
		var url = "report_area?type="+report+"&area="+searchtype+"&pid="+address+"&ptype="+typeid+"&pstate="+state;
	}
	else if (place.getType() == PPlaceType.BLOCKGROUP || place.getType() == PPlaceType.CENSUSTRACT) {
		var typeid = place.getType().id;
		var url = "report_area?type=" + report + "&area=" + searchtype + "&pid=" + address + "&ptype=" + typeid + "&pstate=" + state + "&pcounty=" + encodeURIComponent(search.getCountyString()) + "&pct=" + encodeURIComponent(search.getCensusString());
	}
	else if (place.getType() == PPlaceType.SCHOOL) {
		var typeid = place.getType().id;		
		var url = "report_area?type="+report+"&area="+searchtype+"&pid="+address+"&ptype="+typeid+"&pstate="+state;
	}
	else {
		var url = "report_area?type="+report+"&area="+searchtype+"&pid="+address;
	} 

        var matches = /^(-?\d+(\.\d+)?)\s*,\s*(-?\d+(\.\d+))?$/.exec( address );
        if ( matches ) {
    		var lat = parseFloat( matches[1] );
                var lng = parseFloat( matches[3] );
		url += '&lat='+lat+'&lng='+lng;
		var urlParams = getUrlParams();
		if(urlParams['did']) {
			url += '&did=' + urlParams['did'];
		}
		if(urlParams['dldid']) {
			url += '&dldid=' + urlParams['dldid'];
		}
	}
	location = url;
}

function highlightSelected(tab) {
	var pdl = document.getElementById('predefined');
	var radius = document.getElementById('radius');
	var cr = document.getElementById('custom');
	var poly = document.getElementById('polygon');

	if (tab == "1") {
		document.getElementById('widgettitle').innerHTML = "Set Map<br />Location";
		pdl.className = "areaTypeOptions selected";
		radius.className = "areaTypeOptions";
		cr.className = "areaTypeOptions";
		poly.className = "areaTypeOptions";
	}
	if (tab == "2") {
		pdl.className = "areaTypeOptions";
		radius.className = "areaTypeOptions selected";
		cr.className = "areaTypeOptions";
		poly.className = "areaTypeOptions";
	}
	if (tab == "3") {
		document.getElementById('widgettitle').innerHTML = "Specify Location<br />to Draw Custom Region";
		pdl.className = "areaTypeOptions";
		radius.className = "areaTypeOptions";
		cr.className = "areaTypeOptions selected";
		poly.className = "areaTypeOptions";
	}
	if (tab == "4" && polyenabled) {
		document.getElementById('widgettitle').innerHTML = "Selected Polygon";
		pdl.className = "areaTypeOptions";
		radius.className = "areaTypeOptions";
		cr.className = "areaTypeOptions";
		poly.className = "areaTypeOptions selected";
	}
}

function initPrevMaps(prevmaps) {
	var p;
	var placeseen = {};
	var placeids = [];

	var prevmaps_s = session2.get('prevmaps');
	if (!prevmaps_s) return;

	for (var i = 0;i < prevmaps_s.length;i++) {
		if (p = prevmaps_s[i].p) {
			if (!placeseen[p]) placeids.push(p);
			placeseen[p] = 1;
		}
	}

	// no need here?
        var initialplace = new PPlace();
	initialplace.id = 547101;
        initialplace.label = "Rice";

	PPlaceLoader.load(placeids, function(places) {
		var mapstatesobj = new PMapStateList(10, initialplace);
		mapstatesobj.setMap = function(map, index) {
			if (this.list && this.list[index]) {
				submitReport(places[index]);
			}
		};

		var mapstates = [];
		for (var i = 0;i < places.length; i++) {
			var mapstate = new PMapState(null, null, null, null, places[i]);
			mapstates.push(mapstate);
		}

		mapstatesobj.list = mapstates;
		prevmaps.refresh(mapstatesobj);
	});

}

function toggleSavedRegions() {
	var savedregions = document.getElementById("savedregions");
	if (savedregions.style.display == "none")
		savedregions.style.display = "block";
	else
		savedregions.style.display = "none";
}

function selectSavedRegion(cpid, regionName) {
	for (var i=0; i < document.reportform.reportradio.length; i++) {
	   if (document.reportform.reportradio[i].checked) {
	      var report = document.reportform.reportradio[i].value;
	   }
	}

	if (!cpid) {
		var cpid = polycreator.currentpolyplace.id;
		var regionName = polycreator.currentpolyplace.getLabel();
	}
	
	location = "report_generate?type=" + report + "&area=custom&cpid=" + cpid + "&name=" + encodeURIComponent(regionName);
}

function selectPolygon() {
	// Retrieve the polygon details
	var urlParams = getUrlParams();

	for(var i=0; i < document.reportform.reportradio.length; i++) {
		if (document.reportform.reportradio[i].checked) {
			var report = document.reportform.reportradio[i].value;
		}
	}
	
	// Decode pname before encoding it, as it may only be partially decoded.
	location = "report_generate?type=" + report + "&area=polygon&bid=" + urlParams['bid'] + "&polyid=" + urlParams['polyid'] + "&name=" + encodeURIComponent(decodeURIComponent(urlParams['pname'])) + "&plat=" + urlParams['plat'] + "&plng=" + urlParams['plng'];
}

function getPolygonRadius(place) {
	// Used to determine the smallest radius that covers a
	// polygon entirely, rounded up to the next half mile.
	
	// Get the center point of the polygon place.
	var polycenter = place.getCentroid();

	// Loop through all vertices and all points in the polygon and find the one furthest from the center point.
	var farthestDistance = 0;
	var polyverts = place.getVertices();
	for(var i=0; i<polyverts.length; i++) {
		var points = polyverts[i];
		for(var j=0; j<points.length; j++) {
			if(polycenter.distanceFrom(points[j]) > farthestDistance) {
				farthestDistance = polycenter.distanceFrom(points[j]);
			}
		}
	}
	
	// Get the distance of the furthest point in miles and round up to the next half mile.
	var miles = (Math.ceil(farthestDistance / 804.672)) / 2;
	
	// Return an object containing the radius' size in miles (rounded to the
	// ten thousandth), as well as its center point's latitude and longitude.
	var radius = new Object();
	radius.lat = Math.round(polycenter.lat() * 10000) / 10000;
	radius.lng = Math.round(polycenter.lng() * 10000) / 10000;
	radius.size = miles;
	
	return radius;
}

function unavailableAlert(text) {
	var alerter = new PAlerter();
	if(text == null) {
		var text = "This report is not available.";
	}
	alerter.popup(text,null,null,"OK");
}

function reportAvailability(perm, code) {
	// Displays an appropriate alert based on the user and the currently selected report.
	// 0 is used when a user is a subscriber and has access to the report. In that case, do nothing.
	permcode = perm;
	if(code == "brookingslaa") {
		// reportAvailability doesn't normally take the report's code. This was just
		// added as a temporary thing to display a message specific to the Brookings report.
		// This is displayed to all users who don't have access to it (even public).
		unavailableAlert("Not yet available to PolicyMap subscribers.  Stay tuned to our PolicyMap email updates and blog for a release announcement about this report.");
	} else if(permcode == null) {
		// No report was selected. We choose one by default so
		// this shouldn't happen, but just in case.
		unavailableAlert("Please select a report from the list.");
	} else if(permcode == 1) {
		// User is not a subscriber.
		subscribeAlert();
	} else if(permcode == 2) {
		// User is a subscriber, but cannot access this report.
		unavailableAlert();
	} else if(permcode == 3) {
		// Custom report that the subscriber doesn't have access to.
		unavailableAlert("This report is custom and not available.");
	}
}

function addPlaceToSearchBox(urlParams) {
	showWidget('predefined');

	var pid = urlParams['pid'];
	var ptype = urlParams['ptype'];
	var county = urlParams['county'] || urlParams['pcounty'];
	var ct = urlParams['ct'] || urlParams['pct'];

	PPlaceLoader.load([pid], function(places) {
		var place = places[0];
		search.innitialPlace = place;
		var label = place.getLabel();
		var d = search.textboxState;
		for (var i=0; i<d.options.length; i++) {
			if (d.options[i].title == place.state)
				d.options[i].selected = true;
		}
		// Census tract
		if (ptype == "6") {
			if(county) {
				search.textboxCounty.value = county;
			} else {
				place.getPlacesContaining(PPlaceType.COUNTY, function(places) {
					search.textboxCounty.value = places[0].getLabel();
				}, 3);
			}

			search.census = label;
			search.tab = "census";
			search.textboxCensus.value = label;
			search.setType(PPlaceType.CENSUSTRACT);
			search.selectType(1);
		}
		// Block group
		else if (ptype == "15") {
			if(county) {
				search.textboxCounty.value = county;
			} else {
				place.getPlacesContaining(PPlaceType.COUNTY, function(places) {
					search.textboxCounty.value = places[0].getLabel();
				}, 3);
			}
			if(ct) {
				search.textboxCensus.value = ct;
			} else {
				place.getPlacesContaining(PPlaceType.CENSUSTRACT, function(places) {
					search.textboxCensus.value = places[0].getLabel();
				}, 3);
			}

			search.block = label;
			search.tab = "block"
			search.textboxBlock.value = label;
			search.setType(PPlaceType.BLOCKGROUP);
			search.selectType(2);
		}
		// Congressional Districts
		else if (ptype == "23") {
			search.congressional = label;
			search.tab = "congressional";
			search.setType(PPlaceType.CONGRESSIONAL);
			search.selectType(3);
			search.populateCongressional();
			search.addListener('dd_initialized', function(places) {
				var d = search.textboxCong;
				for (var i=0; i<places.length; i++) {
					if (places[i].id == pid)
						d.options[i].selected = true;						
				}
			});
		}
		// School 
		else if (ptype == "42") {
			search.setType(PPlaceType.SCHOOL);
			search.tab = "school";
			search.school = label;
			search.selectType(4);
			search.textbox.blur();
			search.textbox.value = label;
		}
		// CBSA and CBSA07
		else if (ptype == "14" || ptype == "58") {
			search.setType(PPlaceType.CBSA_07);
			search.selectType(6);
			search.populateCBSA07();
			search.addListener('dd_initialized', function(places) {
				var d = search.textboxCBSA;
				for (var i=0; i<places.length; i++) {
					if (places[i].id == pid)
						d.options[i].selected = true;						
				}
			});
		}
		// State districts
		else if (ptype == "48" || ptype == "49") {
			search.setType(PPlaceType.SLD_UPPER);
			search.selectType(5);
			search.populateStateDistricts();
		}
		else {
			if (ptype == "21")
				label += ' County Subdivision';
			if (place.getState() != "null")
				label += ', ' + place.getState();
			search.textbox.value = label;
			search.searchthemap = label;
			search.setTypes(null);
		}
		//when get report is clicked on map page, need to save the label displayed in the searchbox so we can see if it hasn't changed and then 
		//we can use the id passed in the url instead of geocoding the value, this is because it might not display the exact same place on the next page otherwise
		//also takes care of CDBG places so we don't have to add CDBG placetype as a searchtype to searchbox.
		search.getReportPlace = label;
	});
}

function getReportSelected() {
	for (var i=0; i < document.reportform.reportradio.length; i++) {
		if (document.reportform.reportradio[i].checked) {
			var report = document.reportform.reportradio[i].value;
		}
	}
	return report;
}

function showCustomRegion(urlParams) {
	polycreator = new PPolyCreator();
	polycreator.load(urlParams['cpid'], function(places) {
		var box = document.getElementById('customregiontitlebox');
		var title = document.getElementById('customregiontitle');
		box.style.display = "block";
		title.innerHTML = places[0].getLabel();
		polycreator.currentpolyplace = places[0];
	});

	search.setType(null);
	showWidget('custom');
}


