var pic_directory = 'trailpics/';
var map;
var xml;
var _mMapError =0;
var label;

var initial_zoom = 10;

var url;


var entries = [];
var customIcons = [];
var prev_center;
var trail_array_old = new Array();



function showlabel(marker,lbl) {
	label.innerHTML = lbl;
	var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
	var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
	var anchor=marker.getIcon().iconAnchor;
	var width=marker.getIcon().iconSize.width;
	var height=label.clientHeight;
	var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y -anchor.y -height));
	
	pos.apply(label);
	label.style.visibility="visible";
}
  
function WMSCreateMap( name, copyright, baseUrl, layer, minResolution, maxResolution, urlArg )
{
    var tileLayer = new GTileLayer( new GCopyrightCollection( copyright ), minResolution, maxResolution );
    tileLayer.baseUrl = baseUrl;
    tileLayer.layer = layer;
    tileLayer.getTileUrl = WMSGetTileUrl;
    tileLayer.getCopyright = function () { return copyright; };
    var tileLayers = [ tileLayer ];
    return new GMapType( tileLayers, G_SATELLITE_MAP.getProjection(),name, { errorMessage: _mMapError, urlArg: 'o' } );
}

function WMSGetTileUrl( tile, zoom )
{
    var southWestPixel = new GPoint( tile.x * 256, ( tile.y + 1 ) * 256);
    var northEastPixel = new GPoint( ( tile.x + 1 ) * 256, tile.y * 256);
    var southWestCoords =G_NORMAL_MAP.getProjection().fromPixelToLatLng( southWestPixel, zoom );
    var northEastCoords =G_NORMAL_MAP.getProjection().fromPixelToLatLng( northEastPixel, zoom );
    var bbox = southWestCoords.lng() + ',' + southWestCoords.lat() +',' + northEastCoords.lng() + ',' + northEastCoords.lat();
    return this.baseUrl + '?VERSION=1.1.1&REQUEST=GetMap&LAYERS=' +this.layer + '&STYLES=&SRS=EPSG:4326&BBOX=' + bbox +'&WIDTH=256&HEIGHT=256&FORMAT=image/jpeg&BGCOLOR=0xCCCCCC&EXCEPTIONS=INIMAGE';
}

function loadIcons() {
	var icon_directory = 'images/icons/';
	url = "scripts/php/gen_icons.php";
	
	GDownloadUrl(url, function(data) {
	 	var xml = GXml.parse(data);
		
		var icons_xml = xml.documentElement.getElementsByTagName("icon");
		
		for (i = 0; i<icons_xml.length; i++) {
		
			var gicon = new GIcon(); 
			gicon.image = icon_directory + icons_xml[i].getAttribute("image");
			gicon.shadow = icon_directory + icons_xml[i].getAttribute("shadow");
			gicon.iconSize = new GSize(parseInt(icons_xml[i].getAttribute("iconSize_x")), parseInt(icons_xml[i].getAttribute("iconSize_y")));
			gicon.shadowSize = new GSize(parseInt(icons_xml[i].getAttribute("shadowSize_x")), parseInt(icons_xml[i].getAttribute("shadowSize_y")));
			gicon.iconAnchor = new GPoint(parseInt(icons_xml[i].getAttribute("iconAnchor_x")), parseInt(icons_xml[i].getAttribute("iconAnchor_y")));
			gicon.infoWindowAnchor = new GPoint(parseInt(icons_xml[i].getAttribute("infoWindowAnchor_x")), parseInt(icons_xml[i].getAttribute("infoWindowAnchor_y")));
			customIcons[icons_xml[i].getAttribute("id")] = gicon;
		}
	});
	
}


function createMarker(entry){
    var marker = new GMarker(entry.point,customIcons[entry.marker_icon_id]);
    GEvent.addListener(marker, "click", function() {
		
		map.panTo(entry.point);
        document.getElementById("trackus_info").innerHTML=entry.info_html;
        document.getElementById("trackus_thumbnail_excerpt").innerHTML=entry.html;
		set_new_center_to_cookie(entry.id);
        });
    return marker;
}

function createShelterMarker(shelter){
	html = '<div class="current_info_item_label">Name:  </div><div class="current_info_item_value">' + shelter.name + '</div>';
    var marker = new GMarker(shelter.point,customIcons[shelter.marker_icon_id]);
	if(shelter.capacity == 0) {
		shelter_capacity = 'unknown';
	}
	else {
		shelter_capacity = shelter.capacity;
	}
    GEvent.addListener(marker, "click", function() {
		
		map.panTo(shelter.point);
		/*marker.openInfoWindowHtml('<div class="google_info_window"><div class="current_info_item"><div class="current_info_item_label">Name:  </div><div class="current_info_item_value">' + shelter.name + '</div></div><div class="current_info_item"><div class="current_info_item_label">Type:  </div><div class="current_info_item_value">' + shelter.type + '</div></div><div class="current_info_item"><div class="current_info_item_label">Official ?:  </div><div class="current_info_item_value">' + shelter.official + '</div></div><div class="current_info_item"><div class="current_info_item_label">Near AT ?:  </div><div class="current_info_item_value">' + shelter.near_at + '</div></div><div class="current_info_item"><div class="current_info_item_label">Fee ?:  </div><div class="current_info_item_value">' + shelter.fee + '</div></div><div class="current_info_item_label">Capacity:  </div><div class="current_info_item_value">' + shelter_capacity + '</div></div></div>');*/
        //document.getElementById("trackus_info").innerHTML=entry.info_html;
        //document.getElementById("trackus_thumbnail_excerpt").innerHTML=entry.html;
        });
		
	GEvent.addListener(marker,"mouseover", function() {
        showlabel(marker,'<div class="label"><div class="google_info_window"><div class="current_info_item"><div class="current_info_item_label">Name:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div><div class="current_info_item_value">' + shelter.name + '</div></div><div class="current_info_item"><div class="current_info_item_label">Type:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div><div class="current_info_item_value">' + shelter.type + '</div></div><div class="current_info_item"><div class="current_info_item_label">Official ?:&nbsp;</div><div class="current_info_item_value">' + shelter.official + '</div></div><div class="current_info_item"><div class="current_info_item_label">Near AT ?:</div><div class="current_info_item_value">' + shelter.near_at + '</div></div><div class="current_info_item"><div class="current_info_item_label">Fee ?:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div><div class="current_info_item_value">' + shelter.fee + '</div></div><div class="current_info_item_label">Capacity:&nbsp;&nbsp;</div><div class="current_info_item_value">' + shelter_capacity + '</div></div></div></div>');
    });
    GEvent.addListener(marker,"mouseout", function() {
        label.style.visibility="hidden";
    });
    return marker;
}



function setupMap() {
    if (GBrowserIsCompatible()) { 
		loadIcons();
		map = new GMap2(document.getElementById("full_map"));
		map.addControl(new GLargeMapControl());
		map.enableDoubleClickZoom();
		map.addControl(new GMapTypeControl());
		map.addControl(new GOverviewMapControl());
		map.addMapType(G_PHYSICAL_MAP);
		map.addControl(new GScaleControl( ));
		map.setCenter(new GLatLng(39.9097,-97.4707), 4, G_PHYSICAL_MAP);
		document.getElementById("info_lat").innerHTML='Lat:  ' + (39.9097).toFixed(5);
		document.getElementById("info_lng").innerHTML='Lng:  ' + (-97.4707).toFixed(5);
		WMS_TOPO_MAP = WMSCreateMap( 'Topo', 'Imagery by USGS / Web Service by TerraServer', 'http://www.terraserver-usa.com/ogcmap6.ashx', 'DRG',4, 17, 't' );
		WMS_DOQ_MAP = WMSCreateMap( 'DOQ', 'Imagery by USGS / Web Service by TerraServer', 'http://www.terraserver-usa.com/ogcmap6.ashx', 'DOQ',4, 18, 'o' );
		// adds map types to your map
		map.addMapType(WMS_TOPO_MAP);
		map.addMapType(WMS_DOQ_MAP);
		label = document.createElement("div");
		map.getPane(G_MAP_FLOAT_PANE).appendChild(label);
		label.style.visibility="hidden";
		
		var mgr;
		mgr = new GMarkerManager(map);
		var loaded_marker_ids = new Array(0);
		var mgr2;
		mgr2 = new GMarkerManager(map);
		var loaded_shelter_marker_ids = new Array(0);
		
		
		// When map is panned or zoom is changed, clear the polyline, create new polyline for current viewbox and add as overlay
		GEvent.addListener(map, "moveend", function()  {
			if(prev_center != map.getCenter()) {
				var center = map.getCenter();
				document.getElementById("info_lat").innerHTML='Lat:  ' + (center.lat()).toFixed(5);
				document.getElementById("info_lng").innerHTML='Lng:  ' + (center.lng()).toFixed(5);
				var polylineEncoder = new PolylineEncoder();
				var request = GXmlHttp.create();
				var bounds = map.getBounds();
				var swcorner = bounds.getSouthWest();
				var necorner = bounds.getNorthEast();
				var height = necorner.lat()-swcorner.lat();
				var width = swcorner.lng() -necorner.lng();
				var zoomlevel = map.getZoom();
				
				var expansion_fraction = 0.3;
				var expanded_swcorner_lat = swcorner.lat() - (expansion_fraction*height);
				var expanded_necorner_lat = necorner.lat()  + (expansion_fraction*height);
				var expanded_swcorner_lng = swcorner.lng()  + (expansion_fraction*width);
				var expanded_necorner_lng = necorner.lng()  - (expansion_fraction*width);
				
				
				var url = "scripts/php/gen_xml.php?" + "slat=" + expanded_swcorner_lat + "&nlat=" + expanded_necorner_lat + "&wlng=" + expanded_swcorner_lng + "&elng=" + expanded_necorner_lng + "&zoom=" + zoomlevel + "&jour=0&photo=0&trail=1&shelters=1";
				
				request.open("GET", url, true);
				request.onreadystatechange = function() {
					if(request.readyState == 4) {
						var trail_array = new Array();
						var xmlDoc = request.responseXML;
						var trail_xml = xmlDoc.documentElement.getElementsByTagName("trail");
						var trailmap_legend = "";
						if(trail_xml.length != 0) {
							for(var a = 0; a < trail_xml.length; a++) {
								var trail_name = trail_xml[a].getAttribute("name");
								var color = trail_xml[a].getAttribute("color");
								var weight = trail_xml[a].getAttribute("weight");
								var opacity = trail_xml[a].getAttribute("opacity");
								trailmap_legend = trailmap_legend + '<div class="color_block" style="float: left; background: ' + color + '; margin-top: 7px; font-size: 0em; width: 25px; height: 3px;"></div><span class="trail_name" style="padding-left: 10px; width: 100%; height: 100%;">' + trail_name + '</span><div style="float: none"></div>';
								
								//document.getElementById("info_lng").innerHTML='Lng:  ' + (center.lng()).toFixed(5);
								
								//alert(color + "  " + weight + "  " + opacity);
								var trail_points_xml = trail_xml[a].getElementsByTagName("trail_point");
						
						//var trail_points_xml = xmlDoc.documentElement.getElementsByTagName("trail_point");
						if(trail_points_xml.length > 1) {
							var trail_points = new Array(0);
							for (var i = 0; i<trail_points_xml.length; i++) {
								trail_points[i] = new GLatLng(parseFloat(trail_points_xml[i].getAttribute("lat")),parseFloat(trail_points_xml[i].getAttribute("lng")));
							}
							var polyline;
							polyline = polylineEncoder.dpEncodeToGPolyline(trail_points, color, parseFloat(weight), parseFloat(opacity));
							trail_array.push(polyline);
						}
					}
					trailmap_legend = trailmap_legend + '<div style="text-align: center; text-decoration: underline; padding-top: 5px;"><a href="http://www.fivemillionsteps.com">To Our Homepage</a></div><div style="text-align: center; color: red; padding-top: 5px;">No Guarantees on Accuracy!!!</div>';
					document.getElementById("trailmap_legend").innerHTML=trailmap_legend;
				}
							
						var entries_xml = xmlDoc.documentElement.getElementsByTagName("entry");
						var entries = new Array(0);
						if(entries_xml.length != 0) {
							for (i = 0; i<entries_xml.length; i++) {
								entries[i] = new Entry(entries_xml[i]);
								var loaded = false;
								for(j = 0; j<loaded_marker_ids.length; j++) {
									if(entries[i].id == loaded_marker_ids[j]) {
										loaded = true;
									}
									if(entries[i].id > loaded_marker_ids[j]) {
										break;
									}
								}
								if(!loaded) {
									mgr.addMarker(createMarker(entries[i]),entries[i].zoom);
									loaded_marker_ids.push(entries[i].id);
									loaded_marker_ids.sort();
								}
							}
						}
						
						var shelters_xml = xmlDoc.documentElement.getElementsByTagName("shelter");
						var shelters = new Array(0);
						if(shelters_xml.length != 0) {
							//alert(shelters_xml.length);
							for (i = 0; i<shelters_xml.length; i++) {
								shelters[i] = new Shelter(shelters_xml[i]);
								var loaded = false;
								for(j = 0; j<loaded_shelter_marker_ids.length; j++) {
									//alert(shelters[i].id + "   " + loaded_shelter_marker_ids[j]);
									if(shelters[i].id == loaded_shelter_marker_ids[j]) {
										loaded = true;
									}
									if(shelters[i].id > loaded_shelter_marker_ids[j]) {
										break;
									}
								}
								if(!loaded) {
									//alert("not loaded");
									mgr2.addMarker(createShelterMarker(shelters[i]),shelters[i].zoom);
									loaded_shelter_marker_ids.push(shelters[i].id);
									loaded_shelter_marker_ids.sort();
								}
							}
						}
						
						
						for(var i = 0; i < trail_array_old.length; i++) {
							map.removeOverlay(trail_array_old[i]);
						}
						trail_array_old = trail_array;
						if(entries_xml.length != 0) {
							//mgr.refresh();
						}
						if(shelters_xml.length != 0) {
							//mgr2.refresh();
						}
						if(trail_array.length != 0) {
							for(var i = 0; i < trail_array.length; i++) {
								map.addOverlay(trail_array[i]);
								//alert(trail_array[i].getLength());
							}
						}
					}
				}
				request.send(null);
				prevCenter = map.getCenter();
				
			}
	});
	
	GEvent.trigger(map, "moveend");

	
    }
}





