var map = null;
var tileCounty = 0;
var tileZCTA = 0;
var g_AddressPP = null;
var g_rsslayers = new Array();
var g_tileLayerRoot = "http://www.imapdata.com/VE_PABB/";
var g_curLabel = null;

function getDomObject(name) { return document.getElementById(name); }

function CreateMap()
{
	map = new VEMap('myMap');
	var mapoptions = new VEMapOptions();
	mapoptions.EnableBirdseye = false;
	map.onLoadMap = LoadBaseMaps;
	map.LoadMap(new VELatLong(40.994346, -77.627500), 7, VEMapStyle.Road, false, VEMapMode.Mode2D, false, 0, mapoptions);
	map.SetMouseWheelZoomToCenter(false);
	map.AttachEvent("onendzoom", OnEndZoom);	
	map.AttachEvent("onendpan", OnEndPan);	
	map.AttachEvent("onmouseout", InfoBoxFix);	
	map.AttachEvent("onmousedown", InfoBoxFixClick);	
}

function LoadBaseMaps()
{
	MaskMapLoad();
	StateMapLoad();
}

function MaskMapLoad()
{
	var tileSource = new VETileSourceSpecification("Mask", "http://www.imapdata.com/VE_PABB/Mask/%4.png");
	tileSource.NumServers = 1;
	tileSource.Bounds = [new VELatLongRectangle(new VELatLong(45.0890356,-84.3750000),new VELatLong(36.5978891,-73.1250000))];
	tileSource.MinZoomLevel = 5;
	tileSource.MaxZoomLevel = 14;
	tileSource.Opacity = 0.80; 
	tileSource.ZIndex = 50;
	map.AddTileLayer(tileSource, true);
}

function StateMapLoad()
{
	var tileSource = new VETileSourceSpecification("State", "http://www.imapdata.com/VE_PABB/State/%4.png");
	tileSource.NumServers = 1;
	tileSource.Bounds = [new VELatLongRectangle(new VELatLong(45.0890356,-84.3750000),new VELatLong(36.5978891,-73.1250000))];
	tileSource.MinZoomLevel = 5;
	tileSource.MaxZoomLevel = 14;
	tileSource.Opacity = 1.00;        
	tileSource.ZIndex = 100;
	map.AddTileLayer(tileSource, true);
}

function EventMapLoadCounty()
{
	RemoveAddressSearch();
	DeleteLabel();
	if(tileZCTA != 0) {
		RemoveTileLayer("ZCTA");
		tileZCTA = 0;
	} 
	
	if(tileCounty == 0) {
		AddTileLayer("County", "County", 5, 14, 100);
		tileCounty = 1;
	}
	moveToCounty();
}

function EventMapLoadZCTA()
{
	RemoveAddressSearch();			
	DeleteLabel();
	if(tileCounty != 0) {
		RemoveTileLayer("County");
		tileCounty = 0;
	} 
	
	if(tileZCTA == 0) {
		AddTileLayer("ZCTA", "ZCTA", 10, 14, 100);
		tileZCTA = 1;
	}       
	moveToZCTA();
}
		
function moveToCounty()
{ 
	var LatLon = document.getElementById('CountyLocations').value.split(",");
	var lat = LatLon[0];
	var lon = LatLon[1];
	var CountyName = LatLon[2];
	var CountyFIPS = LatLon[3];
	var CountyZoom = LatLon[4];
	var veLatLon = new VELatLong(lat, lon);
	
	if(CountyFIPS == 42) { map.SetCenterAndZoom(veLatLon, 7); }
	else {
		map.SetCenterAndZoom(veLatLon, 10);
	}
		
	tileCounty++;
	AddCountyLabel(veLatLon,CountyName,CountyFIPS);
}

function moveToZCTA() {
    var LatLon = document.getElementById('ZCTALocations').value.split(",");
    var lat = LatLon[0];
    var lon = LatLon[1];
    var ZCTAName = LatLon[2];
    var veLatLon = new VELatLong(lat, lon);

    map.SetCenterAndZoom(veLatLon, 12);
    tileZCTA++;
    AddZCTALabel(veLatLon, ZCTAName);
}

function AddCountyLabel(veLatLon, CountyName, CountyFIPS) {
    g_curLabel = new VEShape(VEShapeType.Pushpin, veLatLon);
    var icon = "<div style='border-style: groove;background-color: #255895;color:white;font-variant: small-caps;font-size:20px;font-weight:bold;font-family:sans-serif;'>&nbsp;" + CountyName + "&nbsp;</div>";

    //Set the icon
    g_curLabel.SetCustomIcon(icon);

    //Set the info box
    //var infobox = "<div style='width: 340px; height: 300px;  background-color:#FFFFFF' id='InfoBox'>";
    //infobox += "<iframe src='http://www.imapdata.com/client/net/pa/pa_bb_providersVE.aspx?Feature_ID=" + CountyFIPS + "&FeatureTitle=" + CountyName + "' name='I1' width='340' height='300' frameborder='0' border='0' style='border:none;'></iframe>";
    //infobox += "</div>"
    var infobox = "<div><b>" + CountyName + "</b></div><br /><div><a href='http://www.imapdata.com/client/net/pa/pa_bb_providersVE.aspx?Feature_ID=" + CountyFIPS + "&FeatureTitle=" + CountyName + "' target='_blank'>List of Broadband Providers</a></div>";
    map.ClearInfoBoxStyles();
    g_curLabel.SetDescription(infobox);
    map.AddShape(g_curLabel);
}

function AddZCTALabel(veLatLon,ZCTAName)
{
	g_curLabel = new VEShape(VEShapeType.Pushpin, veLatLon);
	var icon = "<div style='border-style: groove;background-color: #255895;color:white;font-variant: small-caps;font-size:20px;font-weight:bold;font-family:sans-serif;'>&nbsp;" + ZCTAName + "&nbsp;</div>";
		
	//Set the icon
	g_curLabel.SetCustomIcon(icon);
	
	//Set the info box
//	var infobox = "<div style='border:1px solid #808080;position: absolute; left: 2px; top: 4px; width: 340px; height: 300px;  background-color:#FFFFFF' id='InfoBox'>"
//				+"<iframe src='http://www.imapdata.com/client/net/pa/pa_bb_providersVE.aspx?Feature_ID=" + ZCTAName + "&FeatureTitle=" + ZCTAName + "&nbsp' name='I1' width='340' height='300' style='border:none;'></iframe>"
//				+"</div>"
	var infobox = "<div><b>" + ZCTAName + "</b></div><br /><div><a href='http://www.imapdata.com/client/net/pa/pa_bb_providersVE.aspx?Feature_ID=" + ZCTAName + "&FeatureTitle=" + ZCTAName + "' target='_blank'>List of Broadband Providers</a></div>";

	map.ClearInfoBoxStyles();
	g_curLabel.SetDescription(infobox);
	
	//Add the shape the the map
	map.AddShape(g_curLabel);
}

function DeleteLabel()
{
	if(g_curLabel != null) {
		map.DeleteShape(g_curLabel);
		g_curLabel = null;
	}
}
	
function OnEndZoom(e)
{
	var zoom = map.GetZoomLevel();
	if(zoom>=14){
		map.SetZoomLevel(14);
		return;		
	}
	ResetDynamicRSSLayers();
}

function OnEndPan(e)
{
	ResetDynamicRSSLayers();
}
		
function InfoBoxFixClick(PAevent) 
{
	var id = PAevent.elementID;
	if (id != null) {
		var shape = document.getElementById(id);
		if (shape.className == "VEAPI_Pushpin")
			return true;
	}
}

function InfoBoxFix(PAevent)
 {
	var id = PAevent.elementID;
	if (id != null){
		var shape = document.getElementById(id);
		if (shape.className == "VEAPI_Pushpin")
			return true;
	}
}

function ToggleRSSLayer(checkbox, data) {
    if (checkbox.checked) {
        if (data.minZoom != -1 && data.minZoom >= map.GetZoomLevel()) {
            checkbox.checked = false;
            alert("You must zoom closer in order for this layer to work!");
        }
        else {
            AddRSSLayer(checkbox.id, data);
        }
    }
    else
        RemoveRSSLayer(checkbox.id);
}

function AddRSSLayer(name, data)
{
	var rssLayer = new VEShapeLayer();
	rssLayer.Hide();
	g_rsslayers.push({ layerName: name, layer: rssLayer, params: data });

	if(data.isDynamic){
		ResetDynamicRSSLayers();
		return;
	}
	
	var layerSpec = new VEShapeSourceSpecification(VEDataType.GeoRSS, "GeoRSS/" + data.url, rssLayer);
	map.ImportShapeLayerData(
		layerSpec, 
		function(addedRssLayer){
			var numShapes = addedRssLayer.GetShapeCount();
			for(var i=0; i < numShapes; ++i) {
				var shape = addedRssLayer.GetShapeByIndex(i);
				shape.SetCustomIcon(shape.IconId);
			}
			addedRssLayer.Show();
		}, 
		false
	);
}

function RemoveRSSLayer(name) 
{
	for(var i = 0; i < g_rsslayers.length; i++){
		if(g_rsslayers[i].layerName==name){
			var layer = g_rsslayers[i].layer;
			map.DeleteShapeLayer(layer);
			g_rsslayers.splice(i, 1);
		}
	}
}

function ResetDynamicRSSLayers(){
	for(var i = 0; i < g_rsslayers.length; i++){
		var layerInfo = g_rsslayers[i];
		if(layerInfo != null && layerInfo != undefined){
			if(layerInfo.params.isDynamic==true){
				
				layerInfo.layer.Hide();
				layerInfo.layer.DeleteAllShapes();
				//map.DeleteShapeLayer(layerInfo.layer);
				
				var curZoom = map.GetZoomLevel();
				if(layerInfo.params.minZoom != -1 && layerInfo.params.minZoom >= curZoom) 
					return;

				var bbox = map.GetMapView();
				var url = "GeoRSS/" + layerInfo.params.url + "?bbox=";
				url += bbox.TopLeftLatLong.Latitude + ",",
				url += bbox.BottomRightLatLong.Longitude + ",";
				url += bbox.BottomRightLatLong.Latitude + ",";
				url += bbox.TopLeftLatLong.Longitude;
				
				var layerSpec = new VEShapeSourceSpecification(VEDataType.GeoRSS, url, layerInfo.layer);
				map.ImportShapeLayerData(
					layerSpec, 
					function(addedRssLayer){
						var numShapes = addedRssLayer.GetShapeCount();
						for(var i=0; i < numShapes; ++i) {
							var shape = addedRssLayer.GetShapeByIndex(i);
							shape.SetCustomIcon(shape.IconId);
						}
						addedRssLayer.Show();
					}, 
					false
				);
				
			}
		}
	}
}


function ToggleTileLayer(checkbox)
{
	if (checkbox.checked) {
		var a = checkbox.value.split(",");
		AddTileLayer(checkbox.id, String(a[0]), Number(a[1]), Number(a[2]), Number(a[3]), Number(a[4]));
	}
	else {
		RemoveTileLayer(checkbox.id);
	}
}

function AddTileLayer(name, srcdirname, minZoom, maxZoom, zIndex, opacity)
{
	var tileSource = new VETileSourceSpecification(name, g_tileLayerRoot+srcdirname+"/%4.png");
	tileSource.NumServers = 1;
	tileSource.Bounds = [new VELatLongRectangle(new VELatLong(45.0890356,-84.3750000),new VELatLong(36.5978891,-73.1250000))];
	tileSource.MinZoomLevel = minZoom;
	tileSource.MaxZoomLevel = maxZoom;
	tileSource.Opacity = opacity;        
	tileSource.ZIndex = zIndex;
	map.AddTileLayer(tileSource, true);	
}

function RemoveTileLayer(name)
{
	map.DeleteTileLayer(name);
}

function ToggleSearchView(){
	var sel = getDomObject("search_type_sel");
	var id = sel[sel.selectedIndex].value;
	getDomObject("searchview_county").style.display = "none";
	getDomObject("searchview_zip").style.display = "none";
	getDomObject("searchview_address").style.display = "none";
	switch(id){
		case "0":
			getDomObject("searchview_county").style.display = "block";
			break;
		case "1":
			getDomObject("searchview_zip").style.display = "block";
			break;
		case "2":
			getDomObject("searchview_address").style.display = "block";
			break;
	}
}

function SearchByAddress() 
{
	var address = "";
	var street = document.getElementById("address_street").value;
	var city = document.getElementById("address_city").value;
	var zip = document.getElementById("address_zip").value;
	
	if (street.length == 0 && city.length == 0 && zip == 0) {
		alert("Please enter at least one address criteria.");
		return;
	}
	
	address = (street.length == 0 ? "" : street += " ");
	address += (city.length == 0 ? "PA" : city += ", PA");
	address += (zip.length == 0 ? "" : " " + zip);
			
	map.Find(null, address, null, null, 0, 1, null, null, false, false, 
		function(shapeLayer, findResults, places, moreResults, errorMsg){
			
			if (places == null) { 
				alert("The requested address could not be located. Please try again."); 
				return; 
			}

			map.ClearInfoBoxStyles();
			if (g_AddressPP != null) map.DeleteShape(g_AddressPP);
			
			var location = places[0].LatLong;
			g_AddressPP = new VEShape(VEShapeType.Pushpin, location);
			g_AddressPP.SetTitle("<div>" + places[0].Name + "</div><br /><div><a href='AllProviders.pdf' target='_blank'>List of Broadband Providers</a></div>");
			map.AddShape(g_AddressPP);
			map.SetCenterAndZoom(location, 13);
		}
	);
}

function RemoveAddressSearch() {
	if (g_AddressPP != null) {
		map.DeleteShape(g_AddressPP);
		g_AddressPP = null;
	}
}