var map = null;
var default_zoom = 14;
var bounds = null;
var arrowIcon = null;
var gdir = null;
var cpoints=[];
var npoints=0;
var places=[];
var icon=null;
var box_directions;
var polydirection = null;
var image_dir = '/++resource++geo.images/'
var spinner = new Image();
spinner.src=image_dir+"spinner.gif";


var om = null;

    function clearmessage() {
        om.Clear();
    }
    function showmessage() {
        om = new OverlayMessage(document.getElementById('geobox'));      
        om.Set('<img src="'+spinner.src+'" style="margin-top:40%;" width="16" height="16"/>');
    }     
    function setCoordinates(pos){
        showmessage();
        if (places[pos]) {
            var lat = places[pos].Point.coordinates[1];
            var lng = places[pos].Point.coordinates[0];
            var point = new GLatLng(lat,lng);
            var address = places[pos].address;
            if (cpoints.length!=npoints) {
                var marker = createMarker(point,getIconType(cpoints.length-1,cpoints), address);
                map.removeOverlay(cpoints.splice(0,1,marker)[0]);
            }
            else{
                var marker = createMarker(point,getIconType(cpoints.length-1,cpoints), address);
                cpoints.splice(0,0,marker);
            }
            bounds=null;
            bounds = new GLatLngBounds();
            for (var i=0;i<cpoints.length;i++){
                map.removeOverlay(cpoints[i]) 
                bounds.extend(cpoints[i].getPoint());
                var newicon=getIconType(i,cpoints);
                var oldmarker = cpoints[i];
                cpoints[i]=createMarker(oldmarker.getPoint(),newicon, oldmarker.getTitle());
                map.addOverlay(cpoints[i]);
            }
            if (cpoints.length>1){
                map.setZoom(map.getBoundsZoomLevel(bounds));
                map.setCenter(bounds.getCenter());
            }else{
                map.setCenter(marker.getPoint(),default_zoom);
            } 
            drawDirections(true);
            window.setTimeout(clearmessage, 3000)
        } 
    }

    function createMarker(point,icon,title) {
       var m = new GMarker(point, {title:title,icon:icon})
       bounds.extend(point);
       return m;
    }

    function drawDirections(street){
      if (polydirection) map.removeOverlay(polydirection);
      GEvent.addListener(gdir, "load", function() {
      polydirection = gdir.getPolyline();
      map.addOverlay(polydirection);
      });
      if (cpoints.length<=1) return;
      var a = cpoints[0].getTitle() + "@" +cpoints[0].getPoint().toUrlValue(6);
      var b = cpoints[cpoints.length-1].getTitle() + "@" +cpoints[cpoints.length-1].getPoint().toUrlValue(6);
      for (var i=cpoints.length-1; i>0; i--) {
          b = cpoints[i].getTitle() + "@" +cpoints[i].getPoint().toUrlValue(6) +" to: "+b;
      }
      var a = "from: "+a + " to: " + b;
      if (street==true)
          $(box_directions).show("slow");
      gdir.load(a, {getPolyline:true});
    }
   
    function getIconType(index,list){
      if (index==0)
          return G_START_ICON;
      if (index>=(list.length-1))
          return G_END_ICON;
      return G_PAUSE_ICON;
    }

function viewLocation(){
  if (GBrowserIsCompatible()) {
// ====== This function displays the tooltip ======
// it can be called from an icon mousover or a side_bar mouseover
    bounds = new GLatLngBounds();
    map = new GMap2(document.getElementById("geobox"));
    var geocoder = null;
    icon = new GIcon();
    box_directions = document.getElementById("directions");
    icon.shadow = image_dir+"map_shadow.png";
    icon.iconSize = new GSize(24, 38);
    icon.shadowSize = new GSize(37, 34);
    icon.iconAnchor = new GPoint(9, 34);
    icon.infoWindowAnchor = new GPoint(9, 2);
    gdir=new GDirections(null, box_directions);
    function activateSeach(){
	if ($('#searchAddress')) {
                geocoder = new GClientGeocoder(new GGeocodeCache());
		$('#searchbutton').bind('click', function() { doSearch();return false; });
		$('#addressText').bind('focus', function() { if (!is_searching) this.value = ''; });
		var s = $('#search-results');
		s.hide();
		is_searching = false;
	}
    }

    function doSearch() {
	if (is_searching) return false;
	a = $('#addressText');
	if (a.value == '') return false;
	is_searching = true;
        b = $('#searchbutton');
        b.val('Loading');
        b.attr('disabled',true);
	var s = $('#search-results');
        $(box_directions).hide("slow");
        $('#georemovedirections').bind('click',loadMap);
        $('#georemovedirections').show();
        s.hide("slow",function(){geocoder.getLocations(a.val(), doSearchResponse);});
        //s.html('');
        
    }

    function doSearchResponse(response) {
        result="<h4>Risultati ricerca</h4><ul>"
        if (!response || response.Status.code != 200) {
          alert("Siamo spiacenti, l'indirizzo inserito non ha nessuna corrispondenza");
        } else {
          places = response.Placemark;
          dest_url=cpoints[cpoints.length-1].getTitle() + '@' +cpoints[cpoints.length-1].getPoint().toUrlValue(6);
          for (var i=0;i<places.length;i++){
              //result+='<li><a href="javascript:void(0)" onclick="setCoordinates('+i+')">'+places[i].address+'</a></li>'
              start_url=places[i].address+'@'+ places[i].Point.coordinates[1]+','+places[i].Point.coordinates[0];
              //percorso_url='./@@geolocation_detail.html?light=1&amp;point_start_lat='+places[i].Point.coordinates[0]+'&amp;point_start_lng='+places[i].Point.coordinates[1]+'&amp;point_start_addr='+places[i].address+'&amp;point_end_lat='+places[i].Point.coordinates[0]+'&amp;point_start_lng='+places[i].Point.coordinates[1]+'&amp;point_start_addr='+places[i].address
              percorso_url=String.replace(encodeURI('http://maps.google.it/maps?f=d&hl=it&om=1&amp;saddr='+start_url + '&amp;daddr='+dest_url),"'",'%27');
              result+='<li><a href="javascript:void(0)" onclick="return GB_showFullScreen(\'Persorso\',\''+percorso_url+'\')">'+places[i].address+'</a></li>'
          }     
          result+='</ul>'
        }
        var s = $('#search-results');
	s.html(result);
        s.show("slow", resetForm);
    }

    function resetForm() {
        s = $('#searchbutton');
        s.val('Cerca');
        s.attr('disabled',false);
        is_searching = false;
    }
 
    function loadMap(){
        showmessage();
	var request = GXmlHttp.create();
        if (polydirection) map.removeOverlay(polydirection);
        for (var i=0;i<cpoints.length;i++)
            map.removeOverlay(cpoints[i]); 
        cpoints=[];
        bounds=null;
        bounds = new GLatLngBounds();
        var default_lat = 42.661232;
        var default_lng = 13.698578;
        $('#georemovedirections').hide();
        $('#search-results').hide();
        $(box_directions).hide("slow");
        if (typeof(prefix_path)=="undefined") prefix_path="";
	request.open("GET", prefix_path+"geolocation.xml", true);
	request.onreadystatechange = function() {
	   if (request.readyState == 4) {
		var xmlDoc = GXml.parse(request.responseText);
		// obtain the array of markers and loop through it
		var setting = xmlDoc.documentElement;
		var markers = xmlDoc.documentElement.getElementsByTagName("marker");
		default_zoom = setting.getAttribute('mapzoom');
		map.setCenter(new GLatLng(default_lat, default_lng), default_zoom);
		map.addControl(new GSmallMapControl());
		map.setMapType(eval(String(setting.getAttribute('maptype')))); 
		for (var i = 0; i < markers.length; i++) {
		    // obtain the attribues of each marker
		    var lat = default_lat = parseFloat(markers[i].getAttribute("lat"));
		    var lng = default_lng = parseFloat(markers[i].getAttribute("lng"));
		    var point = new GLatLng(lat,lng);
		    var label = markers[i].getAttribute("label");
	
		    var marker = createMarker(point,getIconType(i,markers),label);
		    cpoints.push(marker);
		    map.addOverlay(marker);
		};
		
		map.setZoom(markers.length>1?map.getBoundsZoomLevel(bounds):parseInt(default_zoom));
		map.setCenter(bounds.getCenter());
		if (parseInt(setting.getAttribute('directions'))){
		    drawDirections();
		};
                npoints=cpoints.length;
                cpoints.reverse();
                window.setTimeout(clearmessage, 3000);
	   };
	};
	request.send(null);
  };
  loadMap();
  activateSeach();
  }
  else {window.alert("Google maps aren't compatible with current Browser.");};
};

registerPloneFunction(viewLocation);
registerEventListener(window, 'unload', GUnload);

