/**********************************************************************************************
								MRC COMMANDS
LAST UPDATE:	26/JUN/2009
AUTHOR:			JORGE A. RODRIGUEZ HERNANDEZ
***********************************************************************************************/
var flagAyuda=false;
var idHelp="help";
var idTooltip="tooltip";
var arrIds= new Array( );
var historial=new Array();
var discardImpresion=true;

var locc=null;
var conn=null;
var flagMapReady=false;

/***				***/
function cargarEnMapa(arrCommands){
	locc.mapletRemoteControl( 
		new Map24.WebServices.Message.mapletRemoteControlRequest({
	       	MapletRemoteControlRequest: new Map24.WebServices.MapletRemoteControlRequest({ Map24MRC: new Map24.WebServices.Map24MRC({ Commands: arrCommands})  })    	  		}),function(){/*alert("ok");*/},	  onError,		  onTimeout
	);
	historial.push(arrCommands);
}

function cargarEnMapa2(arrCommands){
	conn.mapletRemoteControl( 
		new Map24.WebServices.Message.mapletRemoteControlRequest({
	       	MapletRemoteControlRequest: new Map24.WebServices.MapletRemoteControlRequest({ Map24MRC: new Map24.WebServices.Map24MRC({ Commands: arrCommands})  })    	  		})
	); 
	historial.push(arrCommands);
}

/***		REALIZAR ACERCAMIENTO EN UN DETERMINADO PTO (LON, LAT)		***/
function zoom(lon,lat,zoomin){	
	if(zoomin==null) var zoomtmp=1000;
	else var zoomtmp=zoomin;
	Map24.MapApplication.center( {Longitude: lon, Latitude: lat, MinimumWidth: zoomtmp  } );		
}

/***				***/
function showEnMapa(ids, op, Load ){
	if(op) var ctrl="ENABLE";
	else var ctrl="DISABLE";
	var commandS= new Map24.WebServices.XMLCommandWrapper ({ ControlMapObject: new Map24.WebServices.ControlMapObject({ Control: ctrl, MapObjectIDs: ids	})	});
	if(Load)	cargarEnMapa( [commandS] );
	else		return	commandS;
}

/***				***/
function showLayers(arrIds,op, map24){
	if(op) cmd="ENABLE";    
	else cmd="DISABLE";	
	command=[new Map24.WebServices.XMLCommandWrapper ({ ControlLayer: new Map24.WebServices.ControlLayer({Control: cmd, LayerIDs: arrIds, Map24Layers: map24 }) })];	
	cargarEnMapa2(command);
}

/***				***/
function removeEnMapa(ids, Load){
	var commandR=new Map24.WebServices.XMLCommandWrapper ({ RemoveMapObject : new Map24.WebServices.RemoveMapObject({ MapObjectIDs: ids	})	});
	if(Load)	cargarEnMapa( [commandR] );
	else		return	commandR;
}

/***				***/
function removeGroup(idGroup){
	var arrTmp= arrIds[idGroup];	
	removeEnMapa( [idTooltip], true);	
	for(var n=0; n<arrTmp.length; n++)
		removeEnMapa( [arrTmp[n]], true);		
	arrIds[idGroup]=new Array();
}

/***				***/
function addComponent(component, Load){
	var commandA=new Map24.WebServices.XMLCommandWrapper ({ ControlComponent: new Map24.WebServices.ControlComponent({ Control: "SHOW", Component: component	})	});
	if(Load)	cargarEnMapa( [commandA] );
	else		return	commandA;
}

/***				***/
function component(component, show, Load){
	if(show) var ctr="SHOW";
	else	 var ctr="HIDE";
	var commandA=new Map24.WebServices.XMLCommandWrapper ({ ControlComponent: new Map24.WebServices.ControlComponent({ Control: show, Component: component	})	});
	if(Load)	cargarEnMapa( [commandA] );
	else		return	commandA;
}

/***	Activar un componente del mapa (Botones predefinidos)			***/
function startComponent(component){
	var command=new Map24.WebServices.XMLCommandWrapper ({ ControlComponent: new Map24.WebServices.ControlComponent({ Control:"SHOW",Properties: [ new Map24.WebServices.Property({	Key:"triggerAction", Value:component})] })	});	
	cargarEnMapa( [command] );
}


/***	ARREGLAR			***/
function vistaSatelital(vista){
	var commandA=new Map24.WebServices.XMLCommandWrapper ({ ControlComponent: new Map24.WebServices.ControlComponent({ 
						Control: "SHOW", Component: "TILES",
						Properties:[ new Map24.WebServices.Property({Key: "setstate", Value: vista})]	//MAP, SATELLITE, HIBRYD		
				})	});
	cargarEnMapa( [commandA] );
}

/***				***/
function centrar( op, info, zoom, Load){
	if(op==1)
		var commandC=new Map24.WebServices.XMLCommandWrapper ({
					SetMapView: new Map24.WebServices.SetMapView ({ 
						ClippingWidth: new Map24.WebServices.SetMapViewClippingWidth({ MinimumWidth: zoom }) ,
						Coordinates: [ new Map24.WebServices.Coordinate({ Longitude: info.longitude,	Latitude: info.latitude }) ]		  
					})
				});
	else
		var commandC=new Map24.WebServices.XMLCommandWrapper ({
						SetMapView: new Map24.WebServices.SetMapView ({ 
						ClippingWidth: new Map24.WebServices.SetMapViewClippingWidth({ MinimumWidth: zoom  }),	
						MapObjectIDs: [info.id]
					})
				});
	if(Load)	cargarEnMapa2( [commandC] );
	else		return	commandC;
}

/***				***/
function centrarGrupo(arrInfo){
	var mx=0;
	var my=0;
	var Mx=0;
	var My=0;		

	for(var i=0; i<arrInfo.length;i++){
		var info=arrInfo[i];
		if(i==0){  Mx=mx=info.longitude;  My=my=info.latitude;		}
		else{
			if( info.longitude>Mx){ Mx=info.longitude; }	if( info.latitude>My){ My=info.latitude; }				
			if( info.longitude<mx){ mx=info.longitude; }	if( info.latitude<my){ my=info.latitude; }
		}
	}
	var arrCmdsGral=new Array();
	arrCmdsGral.push( setVistaMapa(mx,My,Mx,my,false) );
	arrCmdsGral.push( zoomOut(false) );
	cargarEnMapa2( arrCmdsGral );
} 

/***				***/
function setVistaMapa(lon1,lat1,lon2,lat2, Load){
	var commandV=new Map24.WebServices.XMLCommandWrapper ({
		SetMapView: new Map24.WebServices.SetMapView ({ 
			Coordinates: [ 
				new Map24.WebServices.Coordinate({ Longitude: lon1,	Latitude: lat1 }),
				new Map24.WebServices.Coordinate({ Longitude: lon2,	Latitude: lat2 })
			]		  
		})
	})	
	if(Load)	cargarEnMapa2( [commandV] );
	else		return	commandV;
}

/***				***/
function zoomOut( Load ){
	var commandZ=new Map24.WebServices.XMLCommandWrapper ({			
		ModifyMapView: new Map24.WebServices.ModifyMapView ({ 		
			Control: "ZOOMOUT"
		})
	})

	if(Load)	cargarEnMapa( [commandZ] );
	else		return	commandZ;
}
/***				***/
var minVisibilidadHObj=0;
var maxVisibilidadHObj=100000;

function crearHtmlObj(info,tooltip,Load){
	if(tooltip) var idObj=idTooltip;
	else		var idObj=info.id;
	var commandH=new Map24.WebServices.XMLCommandWrapper ({
				DeclareMap24HTMLObject: new Map24.WebServices.DeclareMap24HTMLObject({
					MapObjectID: idObj, HTML: info.contenido,		Discard: discardImpresion, 
					Coordinate: new Map24.WebServices.Coordinate({	Longitude: info.longitude,	Latitude: info.latitude	}),
					Customize: new Map24.WebServices.MapObjectCustomSettings({Properties:[ new Map24.WebServices.Property({Key: "STAY_IN_VIEW", Value: "1"})	]	}),
					Orientation: new Map24.WebServices.MapObjectOrientation({ 
									Horizontal: orientacionH,	Vertical: orientacionV, HOffset: separacionH, VOffset: separacionV	
								})
				})		
			});
	if(Load)	cargarEnMapa( [commandH, showEnMapa( [idObj],true,false )] );
	else		return	commandH;
}

function crearHtmlObjAv(info,tooltip,Load){
	
	var idObj=(tooltip)?idTooltip : info.idS;
	var sepH=(info.sH==null)?separacionH : info.sH;
	var sepV=(info.sV==null)?separacionV : info.sV;
	
	var orH=(info.oH==null)?orientacionH : info.oH;
	var orV=(info.oV==null)?orientacionV : info.oV;

	var commandH=new Map24.WebServices.XMLCommandWrapper ({
				DeclareMap24HTMLObject: new Map24.WebServices.DeclareMap24HTMLObject({
					MapObjectID: idObj, HTML: info.sucursal,		Discard: discardImpresion, 
					Coordinate: new Map24.WebServices.Coordinate({	Longitude: info.longitude,	Latitude: info.latitude	}),
					Customize: new Map24.WebServices.MapObjectCustomSettings({Properties:[ new Map24.WebServices.Property({Key: "STAY_IN_VIEW", Value: "1"})	]	}),
					Orientation: new Map24.WebServices.MapObjectOrientation({ 
									Horizontal: orH,	Vertical: orV, HOffset: sepH, VOffset: sepV	
								})					
				})		
			});
	if(Load)	cargarEnMapa( [commandH, showEnMapa( [idObj],true,false )] );
	else		return	commandH;
}

/***				***/
function crearHtmlObj_C(info,Load){
	var commandHC=new Map24.WebServices.XMLCommandWrapper ({
				DeclareMap24HTMLObject: new Map24.WebServices.DeclareMap24HTMLObject({
					MapObjectID: info.id, HTML: info.contenido,		Discard: discardImpresion, 
					CanvasReferencePoint: new Map24.WebServices.CanvasReferencePoint({HPercentage: info.vh,	VPercentage: info.vp	}),
					Orientation: new Map24.WebServices.MapObjectOrientation({ Horizontal: "right",	Vertical: "bottom", HOffset: 0, VOffset: 0	})
				})		
			});
	if(Load)	cargarEnMapa( [commandHC, showEnMapa( [info.id],true,false )] );
	else		return	commandHC;
}

/***				***/
function crearOvalo(info,Load)
{
	var commandR=new Map24.WebServices.XMLCommandWrapper({
		DeclareMap24Oval: new Map24.WebServices.DeclareMap24Oval({
			MapObjectID: info.id,	Width: info.width,	Height: info.height,
			Center: new Map24.WebServices.Coordinate({	Longitude: info.longitude,	Latitude: info.latitude	}),					
			FillPaintRules:[new Map24.WebServices.PaintRuleFILL({MaxMPP:1000,DrawPhase: 'ROADS'})],//Reglas para el relleno del óvalo
			BorderColor:new Map24.WebServices.Color({ red:info.r, green:info.g, blue: info.b, alpha:info.a }), //Color de borde del óvalo
			FillColor: new Map24.WebServices.Color({ red:info.r, green:info.g, blue: info.b, alpha:info.a  })//Color de rrelleno del óvalo
		})
	});
	if(Load)	cargarEnMapa( [commandR, showEnMapa( [info.id],true,false )] );
	else		return	commandR;
}

/***				***/
var minVisibilidadLoc=0;
var maxVisibilidadLoc=100000;

function  crearLocation(info, Load){
 	var command;	
	if(info.descripcion!=null) 	var desc=info.descripcion;
	else 						var desc="";
	if( isNaN(info.simbolo) ){
		var commandL=new Map24.WebServices.XMLCommandWrapper ({
			DeclareMap24Location: new Map24.WebServices.DeclareMap24Location({
				MapObjectID: info.id,	LogoURL: info.simbolo,	Description: desc,	Discard: discardImpresion, MinMPP: minVisibilidadLoc, MaxMPP: maxVisibilidadLoc,
				Coordinate: new Map24.WebServices.Coordinate({	Longitude: info.longitude,	Latitude: info.latitude	})			
			})		
		});	
	}
	else{
		var commandL=new Map24.WebServices.XMLCommandWrapper ({
			DeclareMap24Location: new Map24.WebServices.DeclareMap24Location({
				MapObjectID: info.id,	SymbolID: info.simbolo,	Description: desc,	Discard: discardImpresion, 	MinMPP: minVisibilidadLoc, MaxMPP: maxVisibilidadLoc,	
				Coordinate: new Map24.WebServices.Coordinate({	Longitude: info.longitude,	Latitude: info.latitude	})			
			})		
		});			
	}
	
	if(Load)	cargarEnMapa( [commandL, showEnMapa( [info.id],true,false ) ] );
	else		return commandL;
}

function  crearLocationAv(info, Load){
 	var command;	
	if(info.descripcion!=null) 	var desc=info.descripcion;
	else 						var desc="";
	if( isNaN(info.simbolo) ){
		var commandL=new Map24.WebServices.XMLCommandWrapper ({
			DeclareMap24Location: new Map24.WebServices.DeclareMap24Location({
				MapObjectID: info.id,	LogoURL: info.simbolo,	Description: desc,	Discard: discardImpresion, MinMPP: minVisibilidadLoc, MaxMPP: maxVisibilidadLoc,
				Coordinate: new Map24.WebServices.Coordinate({	Longitude: info.longitude,	Latitude: info.latitude	}),
				Events: [	
						 new Map24.WebServices.MapObjectEvent({	ID: info.evento,
							Commands: [	
								new Map24.WebServices.XMLCommandWrapper({ Surf:	new Map24.WebServices.Surf({ URL:"javascript:"+info.funcion,TargetFrame:"_self"}) })  
							]
						 })
					 ]					
			})		
		});	
	}
	else{
		var commandL=new Map24.WebServices.XMLCommandWrapper ({
			DeclareMap24Location: new Map24.WebServices.DeclareMap24Location({
				MapObjectID: info.id,	SymbolID: info.simbolo,	Description: desc,	Discard: discardImpresion, 	MinMPP: minVisibilidadLoc, MaxMPP: maxVisibilidadLoc,	
				Coordinate: new Map24.WebServices.Coordinate({	Longitude: info.longitude,	Latitude: info.latitude	})			
			})		
		});			
	}
	
	if(Load)	cargarEnMapa( [commandL, showEnMapa( [info.id],true,false ) ] );
	else		return commandL;
}

/***				***/
function  crearTooltipLocation(info,Load){
//	if(info.contenido==null)	info.contenido=obtenerContenido(info);	
	if(info.contenido==null)	obtenerContenido(info);	
	if(info.descripcion==null) 	info.descripcion="";
	var evento=(info.evento==null)?"OnMouseOver": info.evento;
	if( isNaN(info.simbolo) ){
		var commandT=new Map24.WebServices.XMLCommandWrapper ({
			DeclareMap24Location: new Map24.WebServices.DeclareMap24Location({
				MapObjectID: info.id,	LogoURL: info.simbolo,	Description: info.descripcion, Discard: discardImpresion, MinMPP: minVisibilidadLoc, MaxMPP: maxVisibilidadLoc, Coordinate: new Map24.WebServices.Coordinate({	Longitude: info.longitude,	Latitude: info.latitude	}),
				Events: [	new Map24.WebServices.MapObjectEvent({	ID: evento, //OnMouseOut OnMouseDown OnMouseUp OnClick OnDblClic
								Commands: [	crearHtmlObj(info,true,false),	 showEnMapa( [idTooltip],true,false )    ]
							})
						 ]	
			})		
		});	
	}
	else{
		var commandT=new Map24.WebServices.XMLCommandWrapper ({
			DeclareMap24Location: new Map24.WebServices.DeclareMap24Location({
				MapObjectID: info.id,	SymbolID: info.simbolo,	Description: info.descripcion, Discard: discardImpresion, MinMPP: minVisibilidadLoc, MaxMPP: maxVisibilidadLoc, Coordinate: new Map24.WebServices.Coordinate({	Longitude: info.longitude,	Latitude: info.latitude	}),
				Events: [	new Map24.WebServices.MapObjectEvent({	ID: evento, //OnMouseOut OnMouseDown OnMouseUp OnClick OnDblClic
								Commands: [	crearHtmlObj(info,true,false),	 showEnMapa( [idTooltip],true,false )    ]
							})
						 ]	
			})		
		});			
	}
	if(Load)	cargarEnMapa( [commandT, showEnMapa( [info.id],true,false ) ] );
	else		return commandT;
}



/***				***/
function crearGrupo(nombre, ids,Load){
	var commandG= new Map24.WebServices.XMLCommandWrapper ({
		DeclareMapObjectGroup: new Map24.WebServices.DeclareMapObjectGroup ({	MapObjectGroupID: nombre,	MapObjectIDs: ids	})		
	})
	
	if(Load)	cargarEnMapa( [commandG, showEnMapa([nombre],true,false ) ] );
	else 		return	commandG;
}

/***				***/
function  addGroup(info){	
	var arrTmp=arrIds[ info.arreglo ];
	arrTmp.push( info.id );
	arrIds[ info.arreglo ]= arrTmp ;
	return crearGrupo( info.arreglo, arrTmp, false );	
}
	
/***				***/
function  addGroupLocation(info,tipo){	
	var commands= new Array();	
	if(tipo==1)		commands.push( crearLocation(info,false) );					
	else{
		commands.push( crearTooltipLocation(info,false) );				
		commands.push( showTooltip( info,false) );
	}
	commands.push( addGroup(info) );		
	cargarEnMapa(commands);	
	if(tipo==1){ 	showEnMapa( [info.id],true,true );
	//alert(info.id);
	}
	else			showEnMapa( [info.id,idTooltip],true,true );
	
}

/***				***/
function  addGroupLocation_n(info,tipo){	
	var commands= new Array();	
	if(tipo==1)		commands.push( crearLocation(info,false) );					
	else{
		commands.push( crearTooltipLocation(info,false) );				
		commands.push( showTooltip( info,false) );
	}
	addGroup(info);
	
	if(tipo==1) 	commands.push( showEnMapa( arrIds[info.arreglo],true,false ) );
	else{			commands.push( showEnMapa( arrIds[info.arreglo],true,false ) );
					commands.push( showEnMapa( [idTooltip],true,false ) );
	}
	cargarEnMapa(commands);
}

/***				***/
function crearLocationsGroup( arrInfo, tipo, show, center, showTool ){	
	var commandsG = new Array();
	var arrTmp=arrIds[ arrInfo[0].arreglo ];	
	
	if(showTool ==null) var showT=false;
	else	var showT=showTool;
	
	for(var i=0; i< arrInfo.length;i++){
		if(tipo==1)		commandsG.push( crearLocation(arrInfo[i],false) );					
		else			commandsG.push( crearTooltipLocation(arrInfo[i],false) );
		arrTmp.push( arrInfo[i].id );
	}
	arrIds[ arrInfo[0].arreglo ]= arrTmp ;
	commandsG.push( crearGrupo( arrInfo[0].arreglo, arrTmp) );
	
	if(tipo!=1 && showT){
		commandsG.push( showTooltip( arrInfo[0],false) );
		arrTmp.push(idTooltip);			
	}
	cargarEnMapa(commandsG);
	
	if(show)	showEnMapa( arrTmp,true,true );
	if(center)	centrar( 2, arrInfo[0],1000,true ); 
}

/***				***/
function removeElement( grupo, pos ){
	removeEnMapa( [grupo+pos],true  );
	showEnMapa([idTooltip], false , true );
	var arrTmp=arrIds[grupo];
	arrTmp[pos]=null;		
}


/***				***/
function showTooltip(info, Load){
	if(info.contenido==null)	info.contenido=obtenerContenido(info);	
	var command = crearHtmlObj(info,true,false);
	if(Load)	cargarEnMapa([	command,	showEnMapa( [idTooltip],true )	]);
	else		return command;
}

/***				***/
function borrarGrupo(gpo){
	if(arrIds[gpo].length>0){
		removeEnMapa( [gpo], true );
		arrIds[gpo]=new Array();
	}
}

function showAyuda(contenido){
	if(!flagAyuda){
		crearHtmlObj_C({vp:0, vh:0, id:idHelp, contenido:contenido },true );
		flagAyuda=true;
		actividad=10;
		//logRegister(actividad);
	}
	else{
		showEnMapa( [idHelp],false,true);
		flagAyuda=false;
	}	
}

/**********************************************************************************************
						OBTENER IMAGEN DEL MAPA
***********************************************************************************************/
function getImage(sesion){
		var url_ws="http://maptp17.map24.com/map24/webservices1.5?mid=***&sid="	+sesion;
		var cmd='<img src="'+url_ws +'&cgi=Map24RenderEngine&action=renderMapImage&view=Map24Applet&iw=600&ih=400"/>';
		return cmd;
}


/**********************************************************************************************
						METODOS PARA EJERCICIOS REVERSE GEOCODE
							(TERMINAR DE ARREGLAR)
***********************************************************************************************/
var gpoMan="manual";
var arrPtos= new Array();
arrIds[gpoMan]=new Array();

///***	 		 	***/  
//function reverseGeocode(lon, lat,grupo){
//    var geocoder = new Map24.GeocoderServiceStub();
//	geocoder.reverseGeocode({ Longitude: lon, Latitude: lat, Grupo: grupo, CallbackFunction: printResult});
//	actividad=3;
//	//logRegister(actividad);
//}  
//
///***	 ESTANDARIZAR PARA QUE SEA GENERICO		 	***/  
//function printResult( location ){	
//	var p=location.getCountry();
//	var e=location.getState();
//	if( p == "MX" && e!=null) {
//		var dir=estandarizarDireccion( location, this.Longitude, this.Latitude,symbolReverseG, this.Grupo );		
//		if(this.Grupo==gpoMan){
//			arrPtos.push(dir);		
//			addGroupLocation(dir,2);
//		}
//		else{
//			resReverseGeocode(dir);
//		}
//	}
//}
//
///***	 		 	***/  
//function estandarizarDireccion( location, lon , lat, symbol, grupo ){	
//	return { arreglo: grupo ,longitude: lon, latitude: lat, cp: location.getZip(), estado: location.getState(), calle: location.getStreet(), colonia: location.getDistrict(), pais: location.getCountry(), interes: location.getName(), municipio: location.getCity(), simbolo: symbol,posicion: arrPtos.length, id: grupo+arrPtos.length } ;
//}
//{ arreglo,longitude, latitude, cp, estado, calle, colonia, pais, interes, municipio, simbolo,posicion, id} 

function reverseGeocode(lon, lat){
	conn.reverseGeocodeAddresses( new Map24.WebServices.Message.reverseGeocodeAddressesRequest( {
				ReverseGeocodeAddressesRequest: new Map24.WebServices.ReverseGeocodeAddressesRequest({
					Coordinates: [ new Map24.WebServices.Coordinate({	Longitude: lon,	Latitude: lat	})  ]
				})
			  }) ,onSuccesReverseGeocodeAddresses,  onError, onTimeout	);
}  

function onSuccesReverseGeocodeAddresses(){
	var rqst=this.RequestMsg.getProperty("ReverseGeocodeAddressesRequest");
	var cor=rqst.getProperty("Coordinates");

	var response = this.Response.getProperty("GeocodeAddressesResponse");
	var alternativas = response.getProperty("GeocodedAddresses");
	var arrDir=alternativas[0].getProperty("Alternatives");
	var dir=estandarizarDireccion( arrDir[0],symbolReverseG, cor[0].getProperty("Longitude"), cor[0].getProperty("Latitude"),symbolReverseG);		
	resReverseGeocode(dir);
}

function estandarizarDireccion( location, symbol, lon, lat){	
	if( location.getProperty("HouseNo")!="" )
		var calle=location.getProperty("Street")+ " #" +location.getProperty("HouseNo");
	else
		var calle=location.getProperty("Street");

	return { longitude: lon, latitude: lat, cp: location.getProperty("ZIP"), estado: location.getProperty("State"), calle: calle, colonia: location.getProperty("District"), pais: location.getProperty("Country"), municipio: location.getProperty("City"), simbolo: symbol } ;
}

/****************************************************************************************************/
var opRes=null;
var arrResp2=new Array( new Array(), new Array() );
var gpoBusO="origenes";
var gpoBusD="destinos";
arrIds[gpoBusO]=new Array();
arrIds[gpoBusD]=new Array();

var resultados=null;

/***		BUSQUEDA DE UNA DIRECCION CON EL WEBSERVICE SEARCHFREE		***/
function buscarDir(arrDir){	
	if( (arrDir[0]==null || arrDir[0]=="") && (arrDir[1]!=null || arrDir[1]!="") ) var inicio=1; 
	else	var inicio =0;
	resultados=0;
	
	for(var n=0; n< arrDir.length; n++){
		if(arrDir[n]!=null && arrDir[n]!=""){
			resultados++;
			arrResp2[n]=new Array();
			var mapFreeSearch= new Map24.WebServices.MapSearchFreeRequest({ SearchText: arrDir[n],	MaxNoOfAlternatives: 99 });
			if(searchOnlyMX){
				mapFreeSearch.Properties= [new Map24.WebServices.Property({ Key: 'Ctry', Value: 'mx'})];				
			}
			conn.searchFree(new Map24.WebServices.Message.searchFreeRequest({ MapSearchFreeRequest: mapFreeSearch }), onSuccessSearchFreeTest, onError, onTimeout );
		}
	}
	opRes = inicio-1;
}

function onSuccessSearchFreeTest(){
	opRes++;
	var response = this.Response.getProperty("MapSearchResponse");
    var alternatives = response.getProperty("Alternatives");
	if((alternatives!= null)&&(alternatives.length>0)){
		for( var i=0; i<alternatives.length; i++ ){			
			var currentResults = new Object();				
			for(var j=0; j<12; j++){
				currentResults[j] ="";				
			}
			currentResults[0] = alternatives[i].getProperty("Coordinate").getProperty("Longitude");
			currentResults[1] = alternatives[i].getProperty("Coordinate").getProperty("Latitude");				
			var propsMajor = alternatives[i].getProperty("PropertiesMajor");
			for(zhl = 0; zhl< propsMajor.length; zhl++){
				if(propsMajor[zhl].getProperty("Key") == "Zip"){currentResults[2] = propsMajor[zhl].getProperty("Value");};
        		if(propsMajor[zhl].getProperty("Key") == "Cty"){currentResults[3] = propsMajor[zhl].getProperty("Value");};
				if(propsMajor[zhl].getProperty("Key") == "Sta"){currentResults[4] = propsMajor[zhl].getProperty("Value");};
				if(propsMajor[zhl].getProperty("Key") == "Street"){currentResults[5] = propsMajor[zhl].getProperty("Value");};
				if(propsMajor[zhl].getProperty("Key") == "District"){currentResults[6] = propsMajor[zhl].getProperty("Value");};
				if(propsMajor[zhl].getProperty("Key") == "Ctry"){currentResults[7] = propsMajor[zhl].getProperty("Value");};
				if(propsMajor[zhl].getProperty("Key") == "Name"){currentResults[8] = propsMajor[zhl].getProperty("Value");};		
				if(propsMajor[zhl].getProperty("Key") == "City"){currentResults[9] = propsMajor[zhl].getProperty("Value");};		  
			}	
			currentResults[10] = alternatives[i].getProperty("Hierarchy");
			var propsMinor = alternatives[i].getProperty("PropertiesMinor");
			var arrTmp2=new Array();
			for(zhl = 0; zhl< propsMinor.length; zhl++){
				arrTmp2[ propsMinor[zhl].getProperty("Key")]= propsMinor[zhl].getProperty("Value");
			}						
			currentResults[11]=arrTmp2;
			validarResultadoTest(currentResults,opRes);			
      	}			
	}	
	
	if(resultados==1){
		resBuscarDir(arrResp2);		
	}
	else{
		if(opRes==1){
			resBuscarDir(arrResp2);
		}
	}
}

/***		VALIDACION DE LA INFORMACION QUE REGRESA EL WEBSERVICE		***/
function validarResultadoTest(currentResults,op){
	if(searchOnlyMX){
		if( currentResults[7] == "MX" && arrResp2[op].length<numeroResultados && validarEstado(currentResults) ){	
			var sTmp= (isNaN(symbolBusqueda))? symbolBusqueda.replace("{num}",arrResp2[op].length+1) : symbolBusqueda + arrResp2[op].length;
			estandarizarLocacionTest(currentResults,op, sTmp)
		}
	}
	else{
		if( arrResp2[op].length<numeroResultados && validarEstado(currentResults) ){	
			var sTmp= (isNaN(symbolBusqueda))? symbolBusqueda.replace("{num}",arrResp2[op].length+1) : symbolBusqueda + arrResp2[op].length;
			estandarizarLocacionTest(currentResults,op, sTmp)
		}		
	}
}

/***		CONVERTIR RESPUESTA DE BUSQUEDA EN UN ARREGLO ASOCITIVO			***/
function estandarizarLocacionTest(currentResults,op,symbol){	
	if (op==0)	var nombre=gpoBusO;	
	else 		var nombre=gpoBusD;
	var arrTmp=arrResp2[op]
	if(currentResults[11].Type==7){
		arrTmp.push( {arreglo: nombre, posicion: arrResp2[op].length, simbolo: symbol, id: nombre+arrResp2[op].length, longitude:currentResults[0], latitude: currentResults[1], cp: currentResults[2], cty: currentResults[3], estado: currentResults[4], calle: currentResults[5], colonia: currentResults[6], pais:currentResults[7], interes: currentResults[8], municipio: currentResults[9], hierarchy: currentResults[10], layerId:currentResults[11].LAYER_ID, typePOI: currentResults[11].PoiThemeID, telefono: currentResults[11].PHONE, categortia: currentResults[11].NT_FACILITY });
	}
	else{
		arrTmp.push( {arreglo: nombre, posicion: arrResp2[op].length, simbolo: symbol, id: nombre+arrResp2[op].length, longitude:currentResults[0], latitude: currentResults[1], cp: currentResults[2], cty: currentResults[3], estado: currentResults[4], calle: currentResults[5], colonia: currentResults[6], pais:currentResults[7], interes: currentResults[8], municipio: currentResults[9], hierarchy: currentResults[10]  });
	}
}

/**********************************************************************************************
									METODOS PARA BUSQUEDAS
***********************************************************************************************/
var numeroResultados=10;
var arrResp=null;
var gpoBus="busqueda";
arrIds[gpoBus]=new Array();
var searchOnlyMX=true;

/***		BUSQUEDA DE UNA DIRECCION CON EL WEBSERVICE SEARCHFREE		***/
function buscarDireccion(direccion){
	borrarGrupo(gpoBus);
	arrResp=new Array();
	
   	var mapFreeSearch= new Map24.WebServices.MapSearchFreeRequest({ SearchText: direccion,	MaxNoOfAlternatives: 200 });
	if(searchOnlyMX){
		mapFreeSearch.Properties= [new Map24.WebServices.Property({ Key: 'Ctry', Value: 'mx'})];
	}		
	conn.searchFree(new Map24.WebServices.Message.searchFreeRequest({ MapSearchFreeRequest: mapFreeSearch }), onSuccessSearchFree, onError, onTimeout );
}

/***				***/
function onSuccessSearchFree(){
	var response = this.Response.getProperty("MapSearchResponse");
    var alternatives = response.getProperty("Alternatives");
    if((alternatives!= null)&&(alternatives.length>0)){
		for( var i=0; i<alternatives.length; i++ ){			
			var currentResults = new Object();				
			for(var j=0; j<12; j++)
				currentResults[j] ="";				
			currentResults[0] = alternatives[i].getProperty("Coordinate").getProperty("Longitude");
			currentResults[1] = alternatives[i].getProperty("Coordinate").getProperty("Latitude");				
			var propsMajor = alternatives[i].getProperty("PropertiesMajor");
			for(zhl = 0; zhl< propsMajor.length; zhl++){
				if(propsMajor[zhl].getProperty("Key") == "Zip"){currentResults[2] = propsMajor[zhl].getProperty("Value");};
        		if(propsMajor[zhl].getProperty("Key") == "Cty"){currentResults[3] = propsMajor[zhl].getProperty("Value");};
				if(propsMajor[zhl].getProperty("Key") == "Sta"){currentResults[4] = propsMajor[zhl].getProperty("Value");};
				if(propsMajor[zhl].getProperty("Key") == "Street"){currentResults[5] = propsMajor[zhl].getProperty("Value");};
				if(propsMajor[zhl].getProperty("Key") == "District"){currentResults[6] = propsMajor[zhl].getProperty("Value");};
				if(propsMajor[zhl].getProperty("Key") == "Ctry"){currentResults[7] = propsMajor[zhl].getProperty("Value");};
				if(propsMajor[zhl].getProperty("Key") == "Name"){currentResults[8] = propsMajor[zhl].getProperty("Value");};		
				if(propsMajor[zhl].getProperty("Key") == "City"){currentResults[9] = propsMajor[zhl].getProperty("Value");};		  
			}	
			currentResults[10] = alternatives[i].getProperty("Hierarchy");
			var propsMinor = alternatives[i].getProperty("PropertiesMinor");
			var arrTmp2=new Array();
			for(zhl = 0; zhl< propsMinor.length; zhl++){
				arrTmp2[ propsMinor[zhl].getProperty("Key")]= propsMinor[zhl].getProperty("Value");
			}						
			currentResults[11]=arrTmp2;
			validarResultado(currentResults);			
      	}
	}
	resBuscarDireccion(arrResp);
}

/***		VALIDACION DE LA INFORMACION QUE REGRESA EL WEBSERVICE		***/
function validarResultado(currentResults){
	if(searchOnlyMX){
		if( currentResults[7] == "MX" && arrResp.length<numeroResultados && validarEstado(currentResults) ){	
			var sTmp= (isNaN(symbolBusqueda))? symbolBusqueda.replace("{num}",arrResp.length+1) : symbolBusqueda + arrResp.length;
			estandarizarLocacion(currentResults,sTmp);
		}
	}
	else{
		if( arrResp.length<numeroResultados && validarEstado(currentResults) ){	
			var sTmp= (isNaN(symbolBusqueda))? symbolBusqueda.replace("{num}",arrResp.length+1) : symbolBusqueda + arrResp.length;
			estandarizarLocacion(currentResults,sTmp);
		}
	}
}

var arrValEdos=new Array();
function validarEstado(currentResults){
	if(arrValEdos.length>0){
		for(var i in arrValEdos){
			if(currentResults[4].toLowerCase() ==arrValEdos[i].toLowerCase()){
				return true;
			}
		}
		return false;
	}
	else{
		return true;
	}
}

/***		CONVERTIR RESPUESTA DE BUSQUEDA EN UN ARREGLO ASOCITIVO			***/
function estandarizarLocacion(currentResults,symbol){	
	if(currentResults[11].Type==7){
		arrResp.push( {arreglo: gpoBus, posicion: arrResp.length, simbolo: symbol, id: gpoBus+arrResp.length, longitude:currentResults[0], latitude: currentResults[1],  cp: currentResults[2], cty: currentResults[3], estado: currentResults[4], calle: currentResults[5], colonia: currentResults[6], pais:currentResults[7], interes: currentResults[8], municipio: currentResults[9], hierarchy: currentResults[10], layerId:currentResults[11].LAYER_ID, typePOI: currentResults[11].PoiThemeID, telefono: currentResults[11].PHONE, categortia: currentResults[11].NT_FACILITY});																																																																																																					
	}
	else{
		arrResp.push( {arreglo: gpoBus, posicion: arrResp.length, simbolo: symbol, id: gpoBus+arrResp.length, longitude:currentResults[0], latitude: currentResults[1],  cp: currentResults[2], cty: currentResults[3], estado: currentResults[4], calle: currentResults[5], colonia: currentResults[6], pais:currentResults[7], interes: currentResults[8], municipio: currentResults[9], hierarchy: currentResults[10]});																																																																																																					
	}
}

/**********************************************************************************************
									METODOS PARA RUTEO									
***********************************************************************************************/
var gpoRut="ruta";
arrIds[gpoRut]=new Array();
var arrRuta=new Array(null,null);

var routeID=null;
var router=null;
var modo="Shortest";//var modo="Faster";

var symbolD=6;
var symbolO=8;
var symbolI=7;

var colorRoute="#008050";
var alfaRoute=160;
var flagStart=false;
var zoomVuelo=5000;
var flagAutoShow=true;
var flagRemovePto=true;
var flagLoading=false;
var flagTooltipRuta=false;

/***		METODO PARA ESTABLECER ORIGEN O DESTINO		***/
function agregarPto(arrDir,indicador){	
	showEnMapa( [idTooltip],false,true );	
	var symbol="";
	var pto="";//cambiar a pto
	var flagOK;
	if(indicador==0){	pto=(idiomaMap=="es")? "origen": "start";			symbol=symbolO;	}	
	else 			{	pto=(idiomaMap=="es")? "destino": "destination";	symbol=symbolD;	}	
	var mensaje=(idiomaMap=="es")? "Ya existe el punto "+ pto+", desea remplazarlo?": "Replace "+pto+" point?";
	
	flagOK=validarPto(arrDir,indicador);		
	if( flagOK ){		
		if(arrRuta[indicador]!= null ){
			if( confirm( mensaje ) ){
				if(flagLoading && indicador==0){	loading_ruta(true);		}
				borrarElemento(indicador);
			}
			else	return false;
		}		
		else
			if(flagLoading && indicador==0){	loading_ruta(true);		}

		if(flagRemovePto)
			showEnMapa([arrDir.id],false,true);
		
		if(flagTooltipRuta){
			arrRuta[indicador]={arreglo: gpoRut, posicion: indicador, id: gpoRut+indicador, simbolo: symbol, longitude: arrDir.longitude, latitude: arrDir.latitude, contenido: arrDir.contenido};					
			addGroupLocation(arrRuta[indicador], 2);
		}
		else{
			arrRuta[indicador]={arreglo: gpoRut, posicion: indicador, id: gpoRut+indicador, simbolo: symbol, longitude: arrDir.longitude, latitude: arrDir.latitude};		
			addGroupLocation(arrRuta[indicador],1);
		}
		
		if(arrRuta[0]!=null && arrRuta[1]!=null ){
			borrarLineaRuta();
			if( flagAutoShow )	calcularRuta();
		}			
	}
	else{	
		alert("Origen y destino no pueden ser el mismo punto!!");
		return false;
	}
}

function ruteo(arrInfo){	
	if(arrInfo.length>0){
		arrRuta=new Array();
		var ult, cont=0;
		for( var n in arrInfo){
			if(cont==0){
				arrRuta[cont]={arreglo: gpoRut, posicion: cont, id: gpoRut+cont, longitude: arrInfo[n].longitude, latitude: arrInfo[n].latitude, simbolo: symbolO};		
			}
			else{
				var sTmp= (isNaN(symbolI))? symbolI.replace("{num}", cont) : symbolI + cont;
				arrRuta[cont]={arreglo: gpoRut,posicion: cont,id: gpoRut+cont,longitude: arrInfo[n].longitude,latitude: arrInfo[n].latitude,simbolo: sTmp};						
				ult=n;
			}		
			cont++;
		}
		arrRuta[ult].simbolo=symbolD;

		crearLocationsGroup( arrRuta, 1 , true , false);
		centrarGrupo(arrInfo);
		
		if( flagAutoShow ){
			borrarLineaRuta();
			calcularRuta();
		}
	}
	else{
		alert("arreglo con menos de 2 ptos");
	}
}

//Esta función solo aplica para la página de vedirecto - bicentenario
function ruteoCte(arrInfo){	
	if(arrInfo.length>0){
		arrRuta=new Array();
		var ult, cont=0;
		for( var n in arrInfo){
			arrRuta[cont]={arreglo: gpoRut,posicion: cont,id: gpoRut+cont,longitude: arrInfo[n].longitude,latitude: arrInfo[n].latitude/*,simbolo: symbol*/};
			cont++;
		}		
		if( flagAutoShow ){
			flagShowToolbarInf=false;
			borrarLineaRuta();
			calcularRuta();			
		}
		arrRuta=new Array(null,null);
		arrIds[gpoRut]=new Array();

	}
	else{
		alert("arreglo con menos de 2 ptos");
	}
}

/*** 	WEB SERVICE DE MAP24 PARA CALCULAR LA RUTA***/
var idiomaMap="es";
function calcularRuta(){
	var inicio;
	var fin;
	var intermedios=new Array();	
	
	if(arrRuta[0] != null && arrRuta[1] != null ){	
		for(var i=0; i < arrRuta.length; i++){
			var arreglo=arrRuta[i];
			if( i==0)	inicio= returnCoordenada(arreglo.longitude,arreglo.latitude);
			else{
				if( i== arrRuta.length-1 )	fin= returnCoordenada(arreglo.longitude,arreglo.latitude);
				else intermedios.push( returnCoordenada(arreglo.longitude,arreglo.latitude) );
			}
		}
				
		conn.calculateRoute( new Map24.WebServices.Message.calculateRouteRequest ({
			CalculateRouteRequest: new Map24.WebServices.CalculateRouteRequest({
				DescriptionLanguage: idiomaMap,	CalculationMode: modo,	Destination: fin,	Start: inicio,
				ViaPoints: intermedios
				//Properties:[ new Map24.WebServices.Property({Key: "RespondRouteSegmentProperties", Value: true})]
				})
			} ),onSuccessCalculateRoute,
			onError,
			onTimeout
		);
		if(modo=="Faster") 	actividad=4;
		else 				actividad=5;
		//falta log
	}
	else	alert("Ruta incompleta");
}

function onSuccessCalculateRoute(){
	var response = this.Response.getProperty("CalculateRouteResponse");
	var route ="";
	route = response.getProperty("Route");
	var routeId = route.getProperty("RouteID");
	displayRoute(route);
}

/***		METODO PARA MOSTRAR LA LINEA DE LA RUTA EN EL MAPA		***/
var flagShowFlightRoute=true;
var flagShowToolbarInf=true;
function displayRoute( route ){
	router = new Map24.RoutingServiceStub();
	routeID = route.getProperty("RouteID");
	router.showRoute ({	RouteId: routeID, Color: [colorRoute,alfaRoute] });   
	
	if( flagShowFlightRoute )
		Map24.MapApplication.displayHelicopterFlight({	RouteId: routeID,	FlightZoom: zoomVuelo, start: flagStart });
	
/*	if( !flagShowToolbarInf )
	showToolbarInferior(false);*/
	
	descripcionRuta(route);
}

function iniFlight(){
	if(routeID!=null)	Map24.MapApplication.displayHelicopterFlight({	RouteId: routeID,	FlightZoom: zoomVuelo, start: true });
	else				alert("No existe ruta");
}

/***		CONVERTIR UNA LONGITUD Y LATITUD EN COORDENADA		***/
function returnCoordenada(lon,lat){
	var coord = new Map24.WebServices.CoordinateAndAddress({	
					Coordinate:	new Map24.WebServices.Coordinate({		 
										Latitude: lat, 
										Longitude: lon   
								})
					});
	return coord;
}

/***		VALIDAR QUE ORIGEN Y DESTINO NO SEAN IGUALES		***/
function validarPto(arrDir,indicador){
	var aux=(indicador-1)*-1;
	if(arrRuta[aux]!=null){
		if( arrRuta[aux].longitude == arrDir.longitude && arrRuta[aux].latitude && arrDir.latitude){
			return false;					
		}
	}
	return true;
}

/***		OCULTAR LINEA DEL RECORRIDO DE LA RUTA		***/
function borrarLineaRuta(){
	if(router!=null && routeID!=null){
		//router.hideRoute( {RouteId: routeID} );
		router.removeRoute( {RouteId: routeID} );
		router=null;
		routeID=null;
	}	
	Map24.MapApplication.controlComponent({    Control:"HIDE",Component:"M3DROUTE"   	});
    Map24.MapApplication.controlComponent({    Control:"HIDE",Component:"SHOWM3DROUTE"  });
	Map24.MapApplication.controlComponent({    Control:"HIDE",Component:"M3D"		   	});    
    Map24.MapApplication.controlComponent({    Control:"HIDE",Component:"SHOWM3D"		});	
	
	//showToolbarInferior(false);
}

function showToolbarInferior(op){
	var cond=(op)? "SHOW" : "HIDE";
	Map24.MapApplication.controlComponent({    Control:cond,Component:"M3DROUTE"   	});
    Map24.MapApplication.controlComponent({    Control:cond,Component:"SHOWM3DROUTE"  });
	Map24.MapApplication.controlComponent({    Control:cond,Component:"M3D"		   	});    
    Map24.MapApplication.controlComponent({    Control:cond,Component:"SHOWM3D"		});	
}
/***		BORRAR LOS PUNTOS DE LA RUTA		***/
function borrarPtosRuta(){
		removeGroup(gpoRut);
		arrRuta=new Array(null,null);
		arrIds[gpoRut]=new Array();
}

/***		BORRAR UN DETERMINADO PUNTO DE LA RUTA		***/
function borrarElemento(pos){
	if(arrRuta[pos]!=null){			
		removeElement( gpoRut, pos );
		arrRuta[pos]=null;
	}
}

var arrDescr=null;
function descripcionRuta(rutaID){
	arrDescr= new Array();
	var segments = rutaID.getProperty("Segments");	

	for(var i = 0 ; i < segments.length; i++){
		var desc={tipo:null, numTipo:null, sentido:null, numSentido:null, texto:null, longitude:null, latitude:null, via:null};
		desc.tipo = segments[i].getProperty("StreetClass");		
//		desc.numTipo= segments[i].getProperty("Properties").getProperty("StreetTypeAsInt");		
		desc.sentido = segments[i].getProperty("Direction").getProperty("Hint");
		desc.numSentido = segments[i].getProperty("Direction").getProperty("Value");
		var arrD=new Array();
		var arrC=new Array();
		var description = segments[i].getProperty("Descriptions");		
		desc.texto=description[0].getProperty("Text").replace(/(\[|\[\/)[0-9A-Z_]+\]/g, '' );
		desc.latitude=description[0].getProperty("Coordinate").getProperty("Latitude");
		desc.longitude=description[0].getProperty("Coordinate").getProperty("Longitude");
		desc.via=segments[i].getProperty("Via");
		arrDescr.push(desc);
	}		
	resCalcularRuta(arrDescr);
}

/*** INTERCAMBIA ENTRE PUNTO ORIGEN Y PUNTO DESTINO ***/
function intercambiarRuta(){
	borrarLineaRuta();
	if(arrRuta[0]!=null)	removeElement( "ruta", 0 );	
	if(arrRuta[1]!=null)	removeElement( "ruta", 1 );		
	arrIds[gpoRut]=new Array();

	var locOr=arrRuta[0];
	arrRuta[0]=arrRuta[1];
	arrRuta[1]=locOr;

	if(arrRuta[1]!=null){
		arrRuta[1].posicion=1;
		arrRuta[1].simbolo=symbolD;	
		arrRuta[1].id=arrRuta[1].arreglo+arrRuta[1].posicion;
		crearLocation(arrRuta[1],true);
		arrIds[gpoRut].push(arrRuta[1].id);
	}
	if(arrRuta[0]!=null){
		arrRuta[0].posicion=0;
		arrRuta[0].simbolo=symbolO;	
		arrRuta[0].id=arrRuta[0].arreglo+arrRuta[0].posicion;
		crearLocation(arrRuta[0],true);
		arrIds[gpoRut].push(arrRuta[0].id);
	}
}

function crearLinea(info,Load){
	var commandR= new Map24.WebServices.XMLCommandWrapper({
		DeclareMap24Polyline: new Map24.WebServices.DeclareMap24Polyline({
			MapObjectID: info.id, Discard:discardImpresion,
			Coordinates: new Map24.WebServices.CoordinatesArray ({ Longitudes: info.longitudes, Latitudes: info.latitudes }),				
			Color:new Map24.WebServices.Color({red: info.r, green: info.g, blue: info.b, alpha: info.a})
		})
	 });
	if(Load){ cargarEnMapa( [commandR, showEnMapa( [info.id],true,false )] );	}
	else{	return	commandR;	}
}