// custom place type config for legend
PPlaceTypeConfig.PLEGEND = new PPlaceTypeConfig();
PPlaceTypeConfig.PLEGEND.zooms[0] = PPlaceType.STATE;
PPlaceTypeConfig.PLEGEND.zooms[3] = [PPlaceType.COUNTY,PPlaceType.CITY];
PPlaceTypeConfig.PLEGEND.zooms[5] = PPlaceType.SCHOOL;
PPlaceTypeConfig.PLEGEND.zooms[6] = [PPlaceType.ZIP,PPlaceType.ZCTA];
PPlaceTypeConfig.PLEGEND.zooms[7] = PPlaceType.COUNTY_SUBDIVISION;
PPlaceTypeConfig.PLEGEND.zooms[9] = PPlaceType.CENSUSTRACT;
PPlaceTypeConfig.PLEGEND.zooms[12] = PPlaceType.BLOCKGROUP;

/*******************************
**** Class: PTRFOnMapWidget ****
*******************************/
PTRFOnMapWidget = function(map, div, widgetid) {
	var pWidget = this;
	if (map)
		this.map = map;
	else {
		this.map = new Object();
		this.map.kamap = new Object();
		this.map.kamap.server = "http://api.pushpin.com/api/1.1/kamap4p/htdocs/";
	}
	this.id = widgetid;

	// background for widget (default styles)
	this.background = div;

	// widget box (default styles)
	this.box = document.createElement("div");

	// widget heading (default styles)
	this.heading = document.createElement("div");
	this.heading.id = div.id + "_heading";
	this.heading.style.cursor = "pointer";
	this.heading.innerHTML = "<h3>Legend</h3>";

	PEvent.addListener(this.heading, 'click', function() { pWidget.toggleMinMaximize(); });

	// widget heading width
/*	
	var widgetWidth = parseInt(this.background.style.width);
	var totalPadding = parseInt(this.box.style.paddingLeft) + parseInt(this.box.style.paddingRight) +
						parseInt(this.heading.style.paddingLeft) + parseInt(this.heading.style.paddingRight) +
						parseInt(this.box.style.borderLeftWidth) + parseInt(this.box.style.borderRightWidth) +
						parseInt(this.heading.style.borderRightWidth) + parseInt(this.background.style.borderRightWidth);
	this.heading.style.width = (widgetWidth - totalPadding) + "px";
*/
	// widget body (default styles)
	this.body = document.createElement("div");
	this.body.className = "breakdown";		

	// default widget state
//	this.disableDragging();
	this.box.appendChild(this.heading);
	this.background.appendChild(this.box);
	this.box.appendChild(this.body);

//	this.maximize();

	this.listeners = [];

	if (widgetid) {
		if (widgetid == P_WIDGET_LAYER_ID) {
			this.map.widgetLayer = this;
			var mapref = this.map;
			PEvent.addListener(this.map, "zoomend", function() { mapref.refreshWidget(mapref.widgetLayer); });
		}
		else if (this.id == P_WIDGET_OVERLAY_ID)
			this.map.widgetOverlay = this;
		else if (this.id == P_WIDGET_INDICATOR_ID) {
			this.map.widgetIndicator = this; 
			this.map.kamap.widgetIndicator = this;
		}
		this.buildWidget();
	}
}


PTRFOnMapWidget.prototype.buildWidget = function() {
//	this.clearListeners();
	if (this.id == P_WIDGET_INDICATOR_ID) {
		var widgetMap = this.map;
		var widget = this;
		var legend = "";
		if (this.map.getLegend() != null && this.map.getIndicator() != null && this.map.getLegend().getBoundaryType()) {
			var leg = this.map.getLegend();
			var ind = leg.getIndicator();
			var incrementValue = PWebUtil.getBreakIncrement(leg.getBreaks());
			var breaks = leg.getFormattedBreaks(incrementValue);
			var incrementBreaks = leg.getIncrementedBreaks(incrementValue);
			var colors = leg.getColors();
			legend = "<table cellpadding=0 cellspacing=0 border=0>";
			var numbreaks = leg.getNumberOfBreaks();

			// check for no data value
			if (leg.getIndicator().nodata)
				numbreaks += 1;
			
			for (var i=0; i<numbreaks; i++) {
				var breaksString = "";
				if (ind.nodata && i == 0) {
					legend += "<tr><td width=25 style='width: 25px; background-color: #" + colors[i] + "'>&nbsp;</td><td style='background-color:#fff'>&nbsp;</td><td colspan=3 style='color:#ccc;font-style:italic'>Insufficient Data</td></tr>";
					nodata = true;
				} else {
					if (ind.breakid == P_BREAKTYPE_EXACT_VALUE_ID || ind.breakid == P_BREAKTYPE_EXACT_VALUE_CUSTOM_ID)
						breaksString = "<td colspan=3 align='center' style='padding-left: 3px'>" + breaks[i] + "</td>";
					else {
						if ((i == 0 || (i == 1 && nodata))) {
							breaksString = "<td colspan='3' align='center' style='padding-left: 3px'>" + breaks[i+1] + " or less</td>";
						}
						else if (i == numbreaks - 1)
							breaksString = "<td colspan='3' align='center' style='padding-left: 3px'>" + incrementBreaks[i] + " or more </td>";
						else {
							var startbreak;
				               		if (i == 0 || (i == 1 && nodata))
								startbreak = breaks[i];
							else
								startbreak = incrementBreaks[i];
							if (startbreak == breaks[i+1])
								breaksString = "<td align='right' style='padding-left: 3px'>" + startbreak + "</td><td width=20 align='center'></td><td align='right' style='padding-right: 3px'></td>";
							else
								breaksString = "<td align='right' style='padding-left: 3px'>" + startbreak + "</td><td width=20 align='center'>&ndash;</td><td align='right' style='padding-right: 3px'>" + breaks[i+1] + "</td>";
						}
					}
						legend += "<tr><td width=25 style='width: 25px; background-color: #" + colors[i] + "'>&nbsp;</td><td style='background-color:#fff'>&nbsp;</td>" + breaksString +  "</tr>";
				}
				legend += "<tr><td colspan=4><div style='font-size:1px'>&nbsp;</div></td></tr>";
			}
			legend += "</table>";
			legend += "<p class='credits'>";
			legend += "Shaded by " + leg.getBoundaryType().name;
			legend += "<br>";
			if (leg.getIndicator().source != '')
				legend += "<i>Source: " + leg.getIndicator().source + "</i>";
			legend += "</p>";
		} else if (this.map.getIndicator() != null)
			legend += "<span style='font-size:12px;color: #ff0000;'><i>Zoom in further to see this data.</i></span><br>";

		if (!this.indLegend) {
			this.indLegend = document.createElement('div');
			this.body.appendChild(this.indLegend);
		}
		this.indLegend.innerHTML = legend;
	}
}

PTRFOnMapWidget.prototype.toggleMinMaximize = function() {
	if (this.isMaximized()) {
		this.minimize();
	}
	else {
		this.maximize();
	}
}

PTRFOnMapWidget.prototype.maximize = function() {
	if (!this.isMaximized()) {
		this.box.appendChild(this.body);
		
		// ie fix -- otherwise loses all the checked marks
		if (this.layersDiv || this.overlaysDiv)
			this.buildWidget();

		this.isMax = true;
	}
}

PTRFOnMapWidget.prototype.minimize = function() {
	if (this.isMaximized()) {
		this.box.removeChild(this.body);
		this.isMax = false;
	}
}

PTRFOnMapWidget.prototype.isMaximized = function() {
	if (this.isMax)
		return this.isMax;
	else
		return false;
}


function onLoad(place, ind, placetypes, period, highlightPlace, latlng, zoom) {
	var map = new PMap(document.getElementById('mapContainer'));
	// Delays map load
	map.enableLoadDelay();

	map.addControl(new PSmallMapControl());
	map.enableDoubleClickZoom();
	if (place == "united states") {
		map.setCenter(new PLatLng(37.8902, -98.9129), 2);
		if (ind)
			showIndicator(map, ind, period);

		// add params to map link
		var mapLink = document.getElementById('mapLink');
		if (mapLink)
			mapLink.href = "/map?i=" + ind;
	}
	else if (latlng && zoom) {
		map.setCenter(new PLatLng(latlng[0],latlng[1]), zoom);
		if (ind)
			showIndicator(map, ind, period);
	}
	else {
		centerPlace(place, map, ind, placetypes, period, highlightPlace);
	}

	// Turns off map load delay
	if (!ind)
		map.disableLoadDelay();
}

function centerPlace(place, map, ind, placetypes, period, highlightPlace) {
	if (!placetypes)
		var placetypes = [PPlaceType.CITY];
	var geocoder = new PClientGeocoder();
	// Find place and zoom to bounds
	if (geocoder && place.replace(/^\s+|\s+$/g,"") != "") {
		geocoder.getPlace(
			place,
			function(places) {
				if (places.length == 0)
					alert("Place \"" + place + "\" not found");
				else {
					// Add marker and open info window
					map.setCenterBounds(places[0].getBounds());
				}
				if (ind)
					showIndicator(map, ind, period);

				// add params to map link
				var mapLink = document.getElementById('mapLink');
				if (mapLink)
					mapLink.href = "/map?p=" + places[0].id + "&i=" + ind;

				if (highlightPlace)
					addPolygons(map, places[0].getVertices()[0]);
			}, 10, null, placetypes
		);
	}
}

function showIndicator(map, ind, period) {
	if (ind == 9627156)
		PColorRamp.DEFAULT = new PColorRamp('trf', [new PColor('5D4770'),new PColor('E6CCE0'),new PColor('FAFAB6')]);
	else
		PColorRamp.DEFAULT = new PColorRamp('trf', [new PColor("FFE6F4"), new PColor("E6CCE0"), new PColor("CCB1CC"), new PColor("B29AB8"), new PColor("9B839B"), new PColor("866F94"), new PColor("725B82"), new PColor("5D4770")]);
	PIndicatorLoader.load([ind], function(inds) {
		if (period)
			inds[0].setPeriod(period);
		map.setIndicator(inds[0]);
		var title = document.getElementById('mapTitle');
		title.innerHTML = inds[0].getFullLabel();
	});
	map.getLegend().setNumberOfBreaks(5);
	map.getLegend().setColorRamp(PColorRamp.DEFAULT);
	var widget = new PTRFOnMapWidget(map, document.getElementById("onmaplegend"), P_WIDGET_INDICATOR_ID);

	// Need to add a zoomend event so double click zooms refresh the widget
	PEvent.addListener(map, 'zoomend', function() {
		map.refreshWidget(widget);
	});

	// show map after indicator is on
	map.disableLoadDelay();
}

function addPolygons(map, vertices) {
	var poly = new PPolyline(vertices);
	map.addOverlay(poly);
}
