﻿/* Icons */
var icon_start = "<img src=\"Media/start.png\" width=\"22\" height=\"22\" />";
var icon_end = "<img src=\"Media/end.png\" width=\"22\" height=\"22\" />";
var icon_car = "<img src=\"Media/car.gif\" width=\"16\" height=\"16\" />";
/* Windows */
var gmap_window_start = "<div style='width:250px;vertical-align:middle;text-align:center;'>";
var gmap_window_end = "</div>";

/* Initializing */
var initialRoutes = new Array();
var currentMap;
function loadMap() {
 var mapLoader = new enricofoschi.thirds.maps.virtualearth();
 currentMap = mapLoader.LoadDefaultMap();
}
var tmpPoint = new Object();
function loadMapInit() { 
    for(var i = 0; i < initialRoutes.length; i++) {
        var arrayStartEnd = [new VELatLong(initialRoutes[i].start.y,initialRoutes[i].start.x), new VELatLong(initialRoutes[i].end.y,initialRoutes[i].end.x)];
        newShape = new VEShape(VEShapeType.Polyline,arrayStartEnd);
        newShape.SetDescription("<a href=\"#\" onclick=\"return viewRoute("+initialRoutes[i].id+");\">Visualizza dettagli</a>");
        currentMap.AddShape(newShape);
    }
}
function addRoute(id, startX, startY, endX, endY) {
    var tmpRoute = new Object();
    tmpRoute.id = id;
    tmpRoute.start = new GPoint();
    tmpRoute.start.x = startX;
    tmpRoute.start.y = startY;
    tmpRoute.end = new GPoint();
    tmpRoute.end.x = endX;
    tmpRoute.end.y = endY;
    initialRoutes.push(tmpRoute);
}
/* Parsing */
function getMapCenter(address) {
 currentMap.SetCenter(new VELatLong(address.y,address.x));
 return false;
}

/* Geo Coding */
var current_address = "";
function checkAddress(address,city,callback) {
 var param = new Object();
 param.address = address;
 param.city = city;
 param.action = "check";
 getAjaxResponse(null,"geocode.aspx",param,function(response) {
    callback(response);
 });
}
function canGeocode(callback) {
 getAjaxResponse(null,"geocode.aspx",null,function(response) {
    response = parseInt(response);
    if(response) {
     cannotGeocode(response);
    } else callback(response);
 });
}
function cannotGeocode(error) {
 var str = "Siamo spiacenti, ma al momento non possiamo ricercare le coordinate sulla mappa: ";
 if(error == 1) str += "vi sono troppi utenti che stanno effettuando una ricerca contemporaneamente.\n\nPuoi provare a selezionare il punto direttamente sulla mappa o ritentare tra qualche secondo.";
 else if(error == 2) str += "oggi sono state effettuate troppe richieste al server di geocodifica.\n\nPuoi provare a selezionare il punto direttamente sulla mappa o ritentare a effettuare una richiesta domani.";
 alert(str);
}
var geocoder = new GClientGeocoder();
function updateGeocode(gc_id,address,city,callback) {
    addGeocode(function() {
        geocoder.getLatLng(address+", "+city+", Italia",function(point) {
            var param = new Object();
            param.action = "update";
            param.id = gc_id;
            param.address = address;
            param.city = city;
            if(!point) param.status = "N";
            else {
                param.status = "Y";
                param.x = point.x;
                param.y = point.y;
            }
            getAjaxResponse(null,"geocron.aspx", param);
                if(callback) callback(point);
        });
    });
}
function addGeocode(callback) {
 var param = new Object();
 param.action = "add";
 getAjaxResponse(null,"geocode.aspx",param,callback);
}
function showAddress(address,info_window) {
  geocoder.getLatLng(
    address,
    function(point) {
      if (!point) {
        showError("Siamo spiacenti, ma non siamo riusciti a trovare l'indirizzo selezionato ("+address+")");
      } else {
        current_point = point;
        map.setCenter(point,16);
        map.openInfoWindowHtml(point,info_window);
      }
    }
  );
}
/* Pointing addresses */
var map;
var is_route_search = false;
var route_start;
var route_end;
var current_point;
var start_setted = false;
var end_setted = false;
var marker_start;
var marker_end;
var route_polyline;
var setRouteText = gmap_window_start+"<br /><a href='#' onclick='return setRouteStart()'><img border=\"0\" width=\"22\" height=\"22\" alt=\"Punto di partenza\" src=\"Media/start.gif\" align=\"absmiddle\" /> PARTO DA QUI</a><br /><br /><a href='#' onclick='return setRouteEnd()'><img border=\"0\" width=\"22\" height=\"22\" alt=\"Punto di arrivo\" src=\"Media/end.gif\" align=\"absmiddle\" />  ARRIVO QUI</a><br />"+gmap_window_end;
function searchStartAddress() {
    searchAddress(document.new_route_form.txt_address_start.value,document.new_route_form.txt_city_start.value,true);
}
function searchEndAddress() {
    searchAddress(document.new_route_form.txt_address_end.value,document.new_route_form.txt_city_end.value,false);
}
function searchAddress(address,city,is_start) {

 checkAddress(address,city,function(response) {
  var arStr = response.split("|");
  arStr[0] = parseInt(arStr[0]);
  arStr[1] = parseInt(arStr[1]);
  if(is_start) {
   if(!is_route_search && document.new_route_form.h_from) document.new_route_form.h_from.value = arStr[1];
  } else {
   if(!is_route_search && document.new_route_form.h_to) document.new_route_form.h_to.value = arStr[1];
  }
  switch(arStr[0]) {
    case 0: {
        canGeocode(function(response) {
         updateGeocode(arStr[1],address,city,function(point) {
          current_point = point;
          if(current_point) {
            currentMap.SetCenterAndZoom(new VELatLong(current_point.y, current_point.x),16);
            if(is_start) setRouteStart();
            else setRouteEnd();
          } else alert("Siamo spiacenti, ma non siamo riusciti a trovare l'indirizzo specificato");
         });
        });
    }
    break;
    case 1: {
        current_point = new GLatLng(parseFloat(arStr[3]),parseFloat(arStr[2]));
        currentMap.SetCenterAndZoom(new VELatLong(current_point.y,current_point.x),16);
        if(is_start) setRouteStart();        
        else setRouteEnd();
    }
    break;
    case 2: {
        alert("Siamo spiacenti, ma non riusciamo a trovare l'indirizzo \""+address+", "+city+"\".\n\n Se e' stato scritto correttamente, prova a mettere l'indirizzo di un punto o di una piazza vicino.");
    }
    break;    
  }
 }); 
}

function setRouteStart() {
 if(start_setted) currentMap.DeleteShape(marker_start);
 start_setted = true;
 route_start = current_point;
 if(document.new_route_form) {
    if(document.new_route_form.h_from_x) {
        document.new_route_form.h_from_x.value = current_point.x;
        document.new_route_form.h_from_y.value = current_point.y;
    }
 }
 marker_start = new VEShape(VEShapeType.Pushpin, new VELatLong(current_point.y,current_point.x));
 marker_start.SetCustomIcon(icon_start);
 currentMap.AddShape(marker_start);
 RefreshRouteStatus(); 
 return false;
}
function setRouteEnd() { 
 if(end_setted) currentMap.DeleteShape(marker_end);
 route_end = current_point;
 end_setted = true;
 if(document.new_route_form) {
    if(document.new_route_form.h_to_x) {
        document.new_route_form.h_to_x.value = current_point.x;
        document.new_route_form.h_to_y.value = current_point.y;
    }
 }
 marker_end = new VEShape(VEShapeType.Pushpin, new VELatLong(current_point.y,current_point.x));
 marker_end.SetCustomIcon(icon_end);
 currentMap.AddShape(marker_end);
 RefreshRouteStatus(); 
 return false;
}
function clearRouteStart() {
 start_setted = false;
 route_start = null;  
 if(marker_start) currentMap.DeleteShape(marker_start);
 marker_start = null;
 RefreshRouteStatus();  
 return false;
}
function clearRouteEnd() {
 end_setted = false;
 route_start = null;  
 if(marker_end) currentMap.DeleteShape(marker_end);
 marker_end = null;
 RefreshRouteStatus();  
 return false;
}

var directions = null;
function onGDirectionsLoad() {
    if(route_polyline) map.removeOverlay(route_polyline);    
}

var defaultShape;
function RefreshRouteStatus() {
    var rv_str = "";
    if(start_setted) rv_str = "<a href='#' onclick=\"return getMapCenter(route_start);\"><img border=\"0\" width=\"22\" height=\"22\" alt=\"Punto di partenza\" src=\"Media/start.gif\" align=\"absmiddle\" /> Punto di partenza impostato</a>";
    else rv_str += "<font class='error_font'><img border=\"0\" width=\"22\" height=\"22\" alt=\"Punto di arrivo\" src=\"Media/cancel.gif\" align=\"absmiddle\" /> Punto di partenza non ancora impostato</font>";
    rv_str += "<br />";
    if(end_setted) rv_str += "<a href='#' onclick=\"return getMapCenter(route_end);\"><img border=\"0\" width=\"22\" height=\"22\" alt=\"Punto di arrivo\" src=\"Media/end.gif\" align=\"absmiddle\" /> Punto di arrivo impostato</a>";
    else rv_str += "<font class='error_font'><img border=\"0\" width=\"22\" height=\"22\" alt=\"Punto di arrivo\" src=\"Media/cancel.gif\" align=\"absmiddle\" /> Punto di arrivo non ancora impostato</font>";
    if(document.getElementById("div_route_status")) document.getElementById("div_route_status").innerHTML = rv_str;
    if(start_setted && end_setted) {
        if(defaultShape) currentMap.DeleteShape(defaultShape);
        var arrayStartEnd = [new VELatLong(route_start.y,route_start.x), new VELatLong(route_end.y,route_end.x)];
        defaultShape = new VEShape(VEShapeType.Polyline,arrayStartEnd);
        currentMap.AddShape(defaultShape);
        currentMap.GetDirections(arrayStartEnd);        
    } else {
        if(defaultShape) currentMap.DeleteShape(defaultShape);
        defaultShape = null;
    }        
}