var map;
var gmarkers = new Array();
var moveend;

google.load("maps", "2.x");



// CapitalCitiesCache is a custom cache that extends the standard GeocodeCache.
// We call apply(this) to invoke the parent's class constructor.
function CapitalCitiesCache() {
	GGeocodeCache.apply(this);
}

// Assigns an instance of the parent class as a prototype of the
// child class, to make sure that all methods defined on the parent
// class can be directly invoked on the child class.
CapitalCitiesCache.prototype = new GGeocodeCache();


document.write("<script type='text/javascript' src='/javascript/cities.js'></script>");

// Override the reset method to populate the empty cache with
// information from our array of geocode responses for capitals.
CapitalCitiesCache.prototype.reset = function() {
	GGeocodeCache.prototype.reset.call(this);
	for (var i in cities) {
		this.put(cities[i].name, cities[i]);
	}
}


var baseIcon = new GIcon();
baseIcon.shadow = "/icons12_png/shadow.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);



function mapInit() {
	map = new GMap2(document.getElementById("map"));
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.enableDoubleClickZoom();
	map.enableContinuousZoom();
	enableLiveLoading2();
	geocoder = new GClientGeocoder();
	geocoder.setBaseCountryCode("it");
	geocoder.setCache(new CapitalCitiesCache());
}

function enableLiveLoading() {
	GEvent.addListener(map, "moveend", function() {
		var b = map.getBounds();
		var url = "/xml/stations.php?compact=1" 
			+ "&min_lat="  + b.getSouthWest().lat()
			+ "&min_long=" + b.getSouthWest().lng()
			+ "&max_lat="  + b.getNorthEast().lat()
			+ "&max_long=" + b.getNorthEast().lng();
		// alert(url);
		render(url);
	});
}

function enableLiveLoading2() {
	moveend = GEvent.bind(map, "moveend", this, function() {
		var b = map.getBounds();
		var url = "/xml/stations.php?compact=1" 
			+ "&min_lat="  + b.getSouthWest().lat()
			+ "&min_long=" + b.getSouthWest().lng()
			+ "&max_lat="  + b.getNorthEast().lat()
			+ "&max_long=" + b.getNorthEast().lng();
		// alert(url);
		render(url);
	});
}

function showAddress() {
  var address = document.getElementById("addressTEXT").value;
  geocoder.getLatLng(
    address,
    function(latlng) {
      if (!latlng) {
        alert("Impossibile trovare una corrispondenza per '" + address + "'");
      } else {
        map.setCenter(latlng, 13);
      }
    }
  );
}

function showAddress2() {
  var address = document.getElementById("addressTEXT").value;
  geocoder.getLocations(
    address,
    function(response) {
      if (!response || response.Status.code != 200) {
        alert("Impossibile trovare una corrispondenza per '" + address + "'");
      } else {
        place = response.Placemark[0];
        latlng = new GLatLng(place.Point.coordinates[1],
                             place.Point.coordinates[0]);
        map.setCenter(latlng, 13);
        document.getElementById("addressTEXT").value = place.address;
      }
    }
  );
}

function stationMarker(point, index, company, rank, gpl, metano, prezzo) {
	// Create a lettered icon for this point using our icon class
	var icon = new GIcon(baseIcon);
	var srank = rank <= 3 ? rank : "";
	var sgpl = gpl == "1" ? "_gpl" : "";
	var smetano = metano == "1" ? "_metano" : "";

	// icon.image = "/icons12_png/marker_" + company + ".png";
	// http://www.prezzibenzina.it/livemarker/cached/marker_IN_black1.png
	icon.image = "/livemarker/cached/marker_" + company + "_black" + srank + sgpl + smetano + ".png";

	var marker = new GMarker(point, icon);
	marker.id = index;
	gmarkers[index] = marker;
	var testo = "";
	if (rank != null && rank != '')
		testo += "Il rank di questo distributore &egrave; " + rank;
	if (prezzo != null && prezzo != '')
		testo += "<br> Ultimo prezzo rilevato: " + prezzo;


	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(
			testo
			+ "<br>"
			+ "<br /><a hr"
			+ "ef=\"/distributore.php?&di_id="
			+ index
			+ "\">Visualizza scheda</a>"
			+ "<br>"
			+ "<a hr"
			+ "ef=\"/add_report.php?&di_id="
			+ index
			+ "\">Aggiorna prezzi</a>"
		);
	});
	return marker;
}


function render($url) {
GDownloadUrl($url, function(data) {
	var xml = GXml.parse(data);
	var stations = xml.documentElement.getElementsByTagName("station");
	var tmp = gmarkers.concat();
	for (var i = 0; i < stations.length; i++) {
		var st = stations[i];
		if (gmarkers[st.getAttribute("id")]) {
			tmp[st.getAttribute("id")] = null;
			continue;
		}
		var point = new GLatLng(parseFloat(st.getAttribute("lat")),
				parseFloat(st.getAttribute("lng")));
		
		map.addOverlay(new stationMarker(point, st.getAttribute("id"), st.getAttribute("co"), st.getAttribute("rank"), st.getAttribute("gpl"), st.getAttribute("met"), st.getAttribute("pc")));
	}
	while (tmp.length > 0) {
		var g = tmp.pop();
		if (g) {
			map.removeOverlay(g);
			gmarkers[g.id] = null;
		}
	}
});
}













function skipIt() {

function MyControls() { }
MyControls.prototype = new GControl();

MyControls.prototype.initialize = function(map) {
	var container = document.createElement("div");

	var loadDiv = document.createElement("div");
	this.setButtonStyle_(loadDiv);
	container.appendChild(loadDiv);
	loadDiv.appendChild(document.createTextNode("Carica..."));
	GEvent.addDomListener(loadDiv, "click", function() {
		var b = map.getBounds();
		var url = "/xml/stations.php?compact=1" 
			+ "&min_lat="  + b.getSouthWest().lat()
			+ "&min_long=" + b.getSouthWest().lng()
			+ "&max_lat="  + b.getNorthEast().lat()
			+ "&max_long=" + b.getNorthEast().lng();
		// alert(url);
		render(url);
	});


	// map.getContainer().appendChild(container);
	return container;
}



// By default, the control will appear in the top left corner of the
// map with 7 pixels of padding.
MyControls.prototype.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(7, 14));
}



// Sets the proper CSS for the given button element.
MyControls.prototype.setButtonStyle_ = function(button) {
	button.style.color = "#0000cc";
	button.style.backgroundColor = "white";
	button.style.font = "small Arial";
	button.style.border = "1px solid black";
	button.style.padding = "2px";
	button.style.marginBottom = "3px";
	button.style.textAlign = "center";
	button.style.width = "6em";
	button.style.cursor = "pointer";
}


}






