﻿/////////////////////////////////////////////////////////////////////////////////////////////////
//
//  Feel free to use this script for your purpose, but please do not modify this header.
//  This script has been created by 
//  
//  Daniele Restelli    (drestelli@lab4.net) 
//  Robert  Hodges      (rhodges@lab4.net) 
//
//  Lab4 Consulting s.r.l. 
//  http://www.lab4.net/
//
//
//
//
// Terms and Conditions
// 
// THIS CODE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER CONTRIBUTORS 
// BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
// AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS CODE, 
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/////////////////////////////////////////////////////////////////////////////////////////////////



function Lab4Map(MapId){
    this.mapObj = document.getElementById(MapId);
    this.map = new GMap2(this.mapObj);
    this.geocoder = null;
    this.zoomLevel = 12 ;
    this.MapId = MapId;
    this.iconData ;
    this.markers = [];
    this.icons = {};
    this.bounds = new GLatLngBounds();
    this.currentWindow = -1;
    this.poiCollection = "";
    this.creaBalloonFunction = null; 
    this.creaItemFunction = null; 
    this.SideBarObj = null;
}

    Lab4Map.prototype.setCenter=function(centerLat, centerLong){
        //centerLat = centerLat.replace(",", ".");
        //centerLong = centerLong.replace(",", ".");
        this.map.setCenter(new GLatLng(centerLat, centerLong), this.zoomLevel);
    }


    Lab4Map.prototype.EnableLargeMapControl=function(){ 
        this.map.addControl(new GLargeMapControl());
    }

    Lab4Map.prototype.EnableOverviewMapControl=function(){
        this.map.addControl(new GOverviewMapControl());
    }
    
    Lab4Map.prototype.load=function() {
        this.map.enableDoubleClickZoom();
        this.geocoder = new GClientGeocoder();
        this.centerMap();
      }

    
    Lab4Map.prototype.getIcon=function(images) {
      var icon = null;
      if (images) {
        if (icons[images[0]]) {
          icon = icons[images[0]];
        } else {
          icon = new GIcon();
          icon.image = "img/" + images[0] + ".png";
          var size = iconData[images[0]];
          icon.iconSize = new GSize(size.width, size.height);
          icon.iconAnchor = new GPoint(size.width >> 1, size.height >> 1);
          icon.shadow = "img/" + images[1] + ".png";
          size = iconData[images[1]];
          icon.shadowSize = new GSize(size.width, size.height);
          icons[images[0]] = icon;
        }
      }
      return icon;
    }

    Lab4Map.prototype.getGeoCodedPoint=function(indirizzo){
          if (geocoder) 
          {
            geocoder.getLocations(indirizzo,
              function(response) 
              {
                    if (!response || response.Status.code != 200) {
                        alert("Attenzione: non e' stato possibile trovare sulla mappa l'indirizzo specificato.");
           	            return null;
	                } else {
                        var place = response.Placemark[0];
	                    var xx = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
	                    alert("funzione " + xx)
	                    return  xx;
                    }
              }
            );
          }
    }

    Lab4Map.prototype.getGeocodedPoint=function(poi, i){
            if (geocoder) {
                geocoder.getLatLng( poi["via"]+" "+poi["citta"] +" "+poi["cap"] +" "+poi["nazione"]  ,
                  function(point)
                  {
                        if (!point) {
                            alert("Attenzione: non e' stato possibile trovare sulla mappa l'indirizzo specificato.");
                        }else{
                            addPoint(point, poi, i);
                             bounds.extend(point); 
                            this.centerMap();
                        }
                  }
                );
          }
    }

    Lab4Map.prototype.setupMarkers=function(poiList) {
        this.poiCollection = poiList;
        var sideBar= document.createElement("span");
        var pois = this.poiCollection[0]["places"];
        for (var i = 0; i < pois.length; i++) {
            var poi = pois[i];
            // patch per IE: la poiCollection è zero-based in IE, mentre non lo è in FF
            if (poi!=null){
                var point = null;
                if(poi["lat"]=="" || poi["long"]==""){
                    this.getGeocodedPoint(poi, i)
                }else{
                    point= new GLatLng(poi["lat"].replace(",","."), poi["long"].replace(",","."));
                    this.addPoint(point, poi, i);
                    this.bounds.extend(point); 
                }
                if(this.SideBarObj){
                    var elemento= document.createElement("div");
                    elemento.id = "indirizzo" + i ;
                    //this.setSideBarOnMouseOver(elemento, i, this.markers);
                    GEvent.addDomListener(elemento, "mouseover", this.newEventPassthru(this.markers[i], name)); 

                    elemento.innerHTML = this.creaItemFunction(i, this.creaBalloonById(i) )
                    sideBar.appendChild(elemento) ;   
                }
            }
        }
        if(this.SideBarObj){
            this.SideBarObj.appendChild(sideBar) ;
        }
        this.centerMap();
    }



/*
    DEPRECATO - NON UTILIZZATO
    Lab4Map.prototype.setSideBarOnMouseOver= function(elemento, i, localMarkers){
            GEvent.addDomListener(elemento, "mouseover", this.newEventPassthru(localMarkers[i], name)); 

            elemento.onmouseover = function(){
                    if(currentPoint!=i){
                        try{
                            alert("aggiungo il listener");
                            //GEvent.trigger(localMarkers[i], "click");
                        }catch(exception){
                            alert(exception.message);
                        }
                        currentPoint = i;
                    }
                }
            return elemento;
            
    }


    Lab4Map.prototype.openBaloon=function(t) {
        if(currentWindow!=t){
            GEvent.trigger(this.markers[t], "click");
            currentWindow=t;
        }
    }
*/


    Lab4Map.prototype.newEventPassthru= function(obj, mapEvent) {  
          return function() {   
                    try{
                        GEvent.trigger(obj, mapEvent);  
                    }catch(Exception){
                       // alert(Exception.message);
                    }
           };  
    }  


    Lab4Map.prototype.setSideBarObj= function(SideBarObjId){
        this.SideBarObj = document.getElementById(SideBarObjId);
    } 


    Lab4Map.prototype.centerMap=function(){
        if (this.zoomLevel==0){
            this.map.setZoom(this.map.getBoundsZoomLevel(this.bounds));
        }else{
            this.map.setZoom(parseInt(this.zoomLevel));
        }
        this.map.setCenter(this.bounds.getCenter());
        this.map.savePosition();
    }

    Lab4Map.prototype.addPoint=function(point, poi, i){
           if(point){
                var html = this.creaBalloonById( i );
                var icon = null;
                var marker = this.cm_createMarker(point, poi["titolo"], icon, html);
                this.map.addOverlay(marker);
                this.markers.push(marker);
                this.bounds.extend(point);
            }    
    }
      
    Lab4Map.prototype.cm_createMarker=function(point, title, icon, html) {
      var markerOpts = {};
      markerOpts = {
        "title": title,
        "clickable": true
        };
      //"icon": icon,
      var newPoint = point;
      var marker = new LabeledMarker(newPoint, markerOpts);
    
      GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(html);
      });
      GEvent.addListener(marker, "infowindowclose", function() {
         this.map.returnToSavedPosition();
      });
      return marker;
    }
    

    Lab4Map.prototype.findLocation=function(titolo, via, cap, citta, provinciasigla, telefono, fax, mail){
          var address = via + " " + cap + " " + citta + " " + provinciasigla ;    
          var bt  = creaBalloon(titolo, via, citta, provinciasigla, telefono, fax, mail)
          geocoder.getLocations(address,     
                function (response) {
                      this.map.clearOverlays();
                      if (!response || response.Status.code != 200) {
                        alert("Sorry, we were unable to geocode that address");
                      } else {
                        place = response.Placemark[0];
                        point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
                        marker = new GMarker(point);
                        this.map.addOverlay(marker);
                        this.map.setCenter(bounds.getCenter());
                        marker.openInfoWindowHtml(bt);
                      }
                }
            
          
          );
    }

	Lab4Map.prototype.creaBalloonById=function(id){
 	    var poi = poiCollection[0]["places"][id] ;
        return this.creaBalloonFunction(poi["titolo"], poi["via"], poi["citta"], poi["provinciasigla"], poi["telefono"], poi["fax"], poi["mail"]);
     } 
