﻿
  var gLocsInicio = [];   //Usada para asignar las locations de inicio en "Direcciones"
  var gLocsDestino = []; //Usada para asginar las locations de destinio en "Direcciones"

  
  function goMap24() {
    Map24.loadApi( ["core_api", "wrapper_api"] , map24ApiLoaded );
  }
  
  function map24ApiLoaded(){
    //Map24.MapApplication.setStartMapView( { CenterLongitude: -6114.302962962935, CenterLatitude: 1427.7035593220318, MinimumWidth: 3300000 } ); 
    Map24.MapApplication.setStartMapView( { UpperLeftLongitude:-7046.014814814787, UpperLeftLatitude:1996.675423, LowerRightLongitude:-5111.552592592564, LowerRightLatitude:926.9974576271168 } ); 
    Map24.MapApplication.init( { NodeName: "mapa_telnorm", MapType: gMapType, CustomerLayers: "true" } ); 
    conn = Map24.MapApplication.Map.WebServices.openConnection();
    locConn = Map24.Map._Instances.i8.Local.openConnection();

  }




  //Funcion que geocodifica la direccion ingresada en los textbox
  function Geocodifica(strDireccion,posicion){
    //Create a geocoder stub
    var geocoder = new Map24.GeocoderServiceStub();
    //Geocode the start point of the route
    geocoder.geocode({ 
      SearchText: strDireccion, 
      //Define the name of the callback function that is called when the result is available on the client.
      CallbackFunction: setRoutePoint, 
      Language: "es",
      Country: "mx",
      //Set a parameter that is passed to the callback function. The parameter defines that this is the start point.
      CallbackParameters: {position: posicion}
    });

  }

  /*Callback function that is called when the geocoding result is available.
  The locations parameter contains an array with multiple alternative geocoding results.
  The params parameter passes the value of CallbackParameters that specifies which route 
  end point is returned (start or destination point).  */
  function setRoutePoint(locations, params){
    // Si estas calculando un punto intermedio
   var Asignados;
   //Res_por_loc = []; //inicializa la variable
   if (params.position == "start"){  //inicio
        gLocsInicio=locations;
        }
    else if (params.position == "destination"){  //destino 
        gLocsDestino=locations;
    }
    else if ( params.position.substr(0,10) == "intermedio"){
        var punto = params.position.substr(10,1);   //Numero de intermedio que se esta procesando      
        Res_por_loc[punto - 1] = locations.length;    // Resultados por cada locacion  
        Asignados = gIntermedios.length;
        gblOrden = gblOrden + String(punto) + "," ;     //Crea un string con el orden que fueron procesadas los resultados de cada "Geocodifica()"
        for(i=0; i<locations.length; i++){  //Por cada Direccion Geocodificada (resultado) de la misma direccion
            //vias[punto - 1] = locations[0];   // punto - 1 porque esta en base cero
            locations[i]._Label = parseInt(punto);
            locations[i].setDescription(punto);
            gIntermedios[i + Asignados] = locations[i];      //Asigna todas las locaciones encontradas de una misma direccion
            
            // Reccorre el indice con Asignados porque es el numero de valores asignados en el ciclo anterior
        }
   } 
        //After both the start and the destination addresses are geocoded, this function calls the calculateRoute() function.
        //if( typeof routePoints["start"] != "undefined" && typeof routePoints["destination"] != "undefined")
        //calculateRoute(); 
  }
 
  
  //Calculate the route.
  // Uitliza las variables globales Inicio y Destino para determinar cuales direcciones rutear
  function calculateRoute(Inicio,Destino) {
    router = new Map24.RoutingServiceStub();
    router.calculateRoute({
      //Start: routePoints["start"],
      Start: gLocsInicio[Inicio],
      //Destination: routePoints["destination"],
      Destination: gLocsDestino[Destino],
      ViaPoints: vias,
      DescriptionLanguage: "es",
      CallbackFunction: displayRoute
    });
    //document.getElementById("print").disabled = true;
  }   //calculateRoute
  
  
  //Callback function used to access the calculated route of type Map24.WebServices.Route.
  //This function is called after the client has received the result from the routing service.
  function displayRoute( route ){
  
    //Para agregar los botones de las instrucciones de manejo
    var divContsBtns = "<input type='button' class='Estilo3' id='print' onclick='printRouteDescription()' value='Imprime Ruta' title='Imprime la Ruta Mostrada'/>";
    divContsBtns  += "<input type='button' class='Estilo3' id='button_remove_route' onclick='removeRoute( routeID )' value='Nueva Ruta' title='Elimina la Ruta Actual para Crear una Nueva' />  "; 
    document.getElementById('btnsrouteDescription').innerHTML = divContsBtns;
    
    //Remember the routeId. It is used e.g. to hide the route.
    routeID = route.RouteID;
    router.showRoute( {
      RouteId: routeID,
      Color: ['#00F', 150]
    });
    
    FlightControl("SHOW");
    
    //Access the assumed time needed for traversing the route in hours
    var totalTime = ((route.TotalTime)/(60*60) ).toPrecision(3) * 1;
    var horas = parseInt((route.TotalTime)/(60*60));
    var minutos = (((totalTime - horas)*60)/100).toPrecision(2);
    var minutos = parseInt((minutos * 100));
    //Access the total lenght of the route in kilometers
    var totalLength = (route.TotalLength/1000) 
    //Create table with description of the route
    //var div_content = "Tiempo Total: " + totalTime + " h      " ;     
    var div_content;
    if (minutos < 9)    //agrega el cero si son menos de 10 min
        div_content = "Tiempo Total: " + horas + ":0" + minutos + " min     ";
    else 
        div_content = "Tiempo Total: " + horas + ":" + minutos + " min     ";
    //aparte    
    div_content += "&nbsp Distancia Total: "+ totalLength +" km<br /> ";
    div_content += "<br />";
    
       
    //Iterate through the route segments and output the step-by-step textual description of the route
    for(var i = 0; i < route.Segments.length; i++){
      if( typeof route.Segments[i].Coordinates != "undefined" ) {
        coordinates = route.Segments[i].Coordinates;
       
        //Access the longitudes and latitudes of the route segment's coordinates array
        var longitudes = route.Segments[i].Coordinates.Longitudes.toString().split("|");
        var latitudes = route.Segments[i].Coordinates.Latitudes.toString().split("|");
         
        //Get the longitude and latitude in the center of the route segment. 
        //These values are needed for centering on a route segment.
        var centerLon = longitudes[parseInt(longitudes.length / 2)];
        var centerLat = latitudes[parseInt(latitudes.length / 2)];
      }
      //Obtiene parte de la URL para mostrar el link (imagen) Ir2.gif
      var strPN = window.location.pathname;
      var tmpPN = window.location.pathname.substring(1,window.location.pathname.lenght)  //Quita la primer diagonal "/"
      var intPosDiag = tmpPN.search("/");
      var strPN = strPN.substring(0,intPosDiag+1);
        
      //For each route segment add the route description and the button for centering on a route segment
      for(var j = 0; j < route.Segments[i].Descriptions.length; j++){
      	//The route description contains tags for further evaluation. For example, the [M24_STREET] tag is used 
      	//to denote a street in the description. Add the following line of code to replace these tags by a blank:
        div_content += (i+1) + ". " + route.Segments[i].Descriptions[j].Text.replace(/(\[|\[\/)[0-9A-Z_]+\]/g, '' ) 
        //+ "<img src=\"/Xaqui/img/Ir2.gif\" alt=\" <--- Mostrar Ubicacion\" onclick=\"centerOnSegment("+centerLon+", "+centerLat+");\"/><br>"
        + "<img src=\""+strPN+"/img/Ir2.gif\" alt=\" <--- Mostrar Ubicacion\" onclick=\"centerOnSegment("+centerLon+", "+centerLat+");\"/><br>"
      }
    }
    //document.getElementById('routeDescription').style.display="block";
    //Effect.BlindDown('routeDescription');

    document.getElementById('routeDescription').innerHTML = div_content;  //Aqui despliega la ruta en la pagina
    document.getElementById("button_hide_route").disabled = false;
    document.getElementById("button_remove_route").disabled = false;
    document.getElementById("print").disabled = false;
  }     //displayRoute
  
  
  //This function is called after the user has selected a route segment to center on.
  function centerOnSegment (centerLon, centerLat){
    //Center on the given variable
    Map24.MapApplication.center( { Coordinate:new Map24.Coordinate(centerLon, centerLat), MinimumWidth: 200 } );
  }     //centerOnSegment


    //Muestra u oculta el control de vuelo para rutas, valores posibles del parametro ShowHide: "SHOW"|"HIDE"
    function FlightControl(ShowHide){
    //Show/hide the flight control
    Map24.MapApplication.controlComponent({
      Control:ShowHide,Component:"M3DROUTE"
    });
    //Show/hide the button of the flight control
    Map24.MapApplication.controlComponent({
      Control:ShowHide,Component:"SHOWM3DROUTE"
    });
    //Show/hide the flight control
    Map24.MapApplication.controlComponent({
      Control:ShowHide,Component:"M3D"
    });
    //Show/hide the button of the flight control
    Map24.MapApplication.controlComponent({
      Control:ShowHide,Component:"SHOWM3D"
    });

    
    }


  function center( lon, lat ){
    locConn.mapletRemoteControl( 
      new Map24.WebServices.Message.mapletRemoteControlRequest({
        MapletRemoteControlRequest: new Map24.WebServices.MapletRemoteControlRequest({
          Map24MRC: new Map24.WebServices.Map24MRC({
            Commands: [
              new Map24.WebServices.XMLCommandWrapper({
                SetMapView: new Map24.WebServices.SetMapView({
                  Coordinates: [ 
                    new Map24.WebServices.Coordinate({ 
                      Longitude: lon,  
                      Latitude: lat
                    })
                  ],
                  ClippingWidth: new Map24.WebServices.SetMapViewClippingWidth({
                    MinimumWidth: 400
                  })
                })
              })
            ]
          }) 
        })
      }),
      null,
      onError,
      onTimeout
    );
  }
 
  function addOval( lon, lat, r ){  
    locConn.mapletRemoteControl( 
      new Map24.WebServices.Message.mapletRemoteControlRequest({
        MapletRemoteControlRequest: new Map24.WebServices.MapletRemoteControlRequest({
          Map24MRC: new Map24.WebServices.Map24MRC({
            Commands: [
              new Map24.WebServices.XMLCommandWrapper({
                //You can find a complete overview of all properties under Map24.WebServices.DeclareMap24Oval
                DeclareMap24Oval: new Map24.WebServices.DeclareMap24Oval({
                  MapObjectID: "searchRadius",
                  Center: new Map24.WebServices.Coordinate({
                    Longitude: lon, 
                    Latitude: lat                    
                  }),
                  Width: 2*r,
                  Height: 2*r,
                  FillColor: new Map24.WebServices.Color({red: 255, green: 0, blue: 0, alpha: 100}),
                  BorderColor: new Map24.WebServices.Color({red: 0, green: 0, blue: 0, alpha: 255})
                })
              }),
              new Map24.WebServices.XMLCommandWrapper({
                ControlMapObject: new Map24.WebServices.ControlMapObject({
                  MapObjectIDs: ["searchRadius"],
                  Control: "ENABLE"
                })
              }),
              //Center the map view on the oval.
              new Map24.WebServices.XMLCommandWrapper({
                SetMapView: new Map24.WebServices.SetMapView({
                  MapObjectIDs: ["searchRadius"],
                  ClippingWidth: new Map24.WebServices.SetMapViewClippingWidth({
                    MinimumWidth: 4*r
                  })
                })
              })
            ]
          }) 
        })
      }),
      null,
      onError,
      onTimeout
    );
  }









