//Variables
tolerance = 0.017;
costo = '(length)';
and_where_query_grafo = 'AND scale=5000';
join_query_grafo = '';
directed = 'false';
debug = false;
english = false;
units = 1;


respRuta = new Array();

MENSAJE_PUNTO_INICIO	= "<b>Punto de Inicio</b><br>Haga click en la ubicación desde donde desea partir. Haga click en aceptar cuando esté de acuerdo.";
MENSAJE_PUNTO_FINAL	= "<b>Punto de Llegada</b><br>Haga click en la ubicación a la que desea llegar. Haga click en aceptar cuando esté de acuerdo.";

MESSAGEBOX_BACKCOLOR 	= "#FFFCCC";
MESSAGEBOX_FONTCOLOR 	= "#000000";
MESSAGEBOX_FONTFAMILY	= "Verdana, Arial, Helvetica, sans-serif";
MESSAGEBOX_FONTSIZE 		= 10;

MESSAGEBOX_BUTTONS_BACKCOLOR 	= "#FFFFFF";
MESSAGEBOX_BUTTONS_FONTCOLOR 	= "#000000";
MESSAGEBOX_BUTTONS_FONTFAMILY = "Verdana, Arial, Helvetica, sans-serif";
MESSAGEBOX_BUTTONS_FONTSIZE 	= 10;

RutLib = function(){};

RutLib.str = new Object();
function initializeAll()
{
	
		initialize();
		var imgInicio = jQuery("#imgInicio");
		var imgFinal = jQuery("#imgFinal");

		imgInicio.onload = filterAlpha;
		imgFinal.onload = filterAlpha;
		
		imgInicio.src = "media/ico/srouting/inicio.gif";
		imgFinal.src = "media/ico/srouting/final.gif";
	
	
	
}

function routing()
{
	this.start = null;
	this.end = null;
}


function PlaceStartPoint( routingObj )
{
	parent.MapLibs.DeactivateZoomRectangle();
	SEvent.RemoveListener(routingObj.mapClick);
	routingObj.mapClick = null;
	routingObj.mapClick = SEvent.AddListener(mapObj, "OnMapClick", StartPointPutIconOnMap);	
//	document.getElementById("divMap").style.cursor = "pointer";
}


function StartPointPutIconOnMap(point)
{		
	routingObj.start = point;
	
	if(routingObj.mapClick != null)
	{
		document.getElementById("StartLat").value = point.Y;
		document.getElementById("StartLong").value = point.X;
	}
	var dir_img = 'media/ico/srouting/inicio.gif';	
	var icon = new SIcon(point, new SSize(20, 34), dir_img, true);

	mapObj.removeIconsOnLayer("StartPointLayer");
	mapObj.addIcon(icon, "StartPointLayer");

	SEvent.RemoveListener(routingObj.mapClick);
	routingObj.mapClick = null;
}


function PlaceEndPoint()
{	
	parent.MapLibs.DeactivateZoomRectangle();
	SEvent.RemoveListener(routingObj.mapClick);
	routingObj.mapClick = null;	
	routingObj.mapClick = SEvent.AddListener(mapObj, "OnMapClick", EndPointPutIconOnMap);
}

function EndPointPutIconOnMap(point)
{	
	routingObj.end = point;
	
	if(routingObj.mapClick != null)
	{
		document.getElementById("EndLat").value = point.Y;
		document.getElementById("EndLong").value = point.X;
	}
	var dir_img = 'media/ico/srouting/final.gif';
	var icon = new SIcon(point, new SSize(20, 34), dir_img, true);
	
	mapObj.removeIconsOnLayer("EndPointLayer");
	mapObj.addIcon(icon, "EndPointLayer");

	SEvent.RemoveListener(routingObj.mapClick);
	routingObj.mapClick = null;
}

function esReal(cadena) {
	var real = /^\-?\d{1,}$|^\-?\d*\.\d{1,}$/;
	return real.test(cadena);
}

function StartLatLongChange()
{
	var StartLat = document.getElementById("StartLat");
	var StartLong = document.getElementById("StartLong");
	
	if( StartLat.value != "" && esReal(StartLat.value) 
		 && StartLong.value != "" && esReal(StartLong.value) )
	{		
		StartPointPutIconOnMap(new SGeoPoint(parseFloat(StartLong.value), parseFloat(StartLat.value)));
	}
	
}

function EndLatLongChange()
{
	var EndLat = document.getElementById("EndLat");
	var EndLong = document.getElementById("EndLong");
	
	if( EndLat.value != "" && esReal(EndLat.value) 
		 && EndLong.value != "" && esReal(EndLong.value) )
	{
		EndPointPutIconOnMap(new SGeoPoint(parseFloat(EndLong.value), parseFloat(EndLat.value)));
	}
}

function OpcionesLanguajeChange(value)
{
	if (value == 1)
	{
		english = false;
	}
	else
	{
		english = true;
	}
}

function OpcionesBusquedaChange( tipo )
{
	var OpcionesText= document.getElementById("opcionesText");
	switch(tipo)
	{
		case '1':	//Pedestre: Ruta Más Corta
			directed = 'false';
			costo = '(length)';
			and_where_query_grafo = '';
			join_query_grafo = '';
			OpcionesText.innerHTML = RutLib.str.cas1;
			break;
		case '2':	//Pedestre: Ruta Corta por Vías Principales
			directed = 'false';
			costo = '(length*codefunctionalroadclass*111000)';
			and_where_query_grafo = '';
			join_query_grafo = '';
			OpcionesText.innerHTML = RutLib.str.cas2;
			break;
		case '3':	//Vehículo: Ruta Más Corta
			directed = 'true';
			costo = '(length*111000)';
			and_where_query_grafo = '';
			join_query_grafo = '';
			OpcionesText.innerHTML = RutLib.str.cas3;
			break;
		case '4':	//Vehículo: Ruta Corta por Vías Principales
			directed = 'true';
			costo = '(length*codefunctionalroadclass*111000)';
			and_where_query_grafo = '';
			join_query_grafo = '';
			OpcionesText.innerHTML = RutLib.str.cas4;
			break;
		case '5':	//Vehículo: Ruta Velocidad Máxima
			directed = 'true';
			costo = '1/speedlimit';
			and_where_query_grafo = 'AND speedlimit<>0';
			join_query_grafo = '';
			OpcionesText.innerHTML = RutLib.str.cas5;
			break;
		case '6':	//Vehículo: Ruta Menor Tiempo
			directed = 'true';
			costo = 'length/speedlimit';
			and_where_query_grafo = 'AND speedlimit<>0';
			join_query_grafo = '';
			OpcionesText.innerHTML = RutLib.str.cas6;
			break;	
		case '7':	//Ruta Corta en Vehículo Forzando Vías Principales
			directed = 'true';
			costo = '(length*POWER(codefunctionalroadclass,10)*111000)';
			and_where_query_grafo = '';
			join_query_grafo = '';
			OpcionesText.innerHTML = RutLib.str.cas7;
			break;
		case '8':	//Ruta Más Corta entre Ciudades en Venezuela
			directed = 'false';
			costo = 'length';
			and_where_query_grafo = '';
			join_query_grafo = '';
			OpcionesText.innerHTML = RutLib.str.cas8;
			document.getElementById("ubica_mapa").selectedIndex = 4;
			UbicacionMapaChange('Venezuela');
			break;
		case '9':	//Ruta Más Corta entre Ciudades por Autopistas
			directed = 'false';
			costo = '(length*POWER(codefunctionalroadclass,10)*111000)';
			and_where_query_grafo = '';
			join_query_grafo = '';
			OpcionesText.innerHTML = RutLib.str.cas9;
			document.getElementById("ubica_mapa").selectedIndex = 4;
			UbicacionMapaChange('Venezuela');
			break;
	}
}

function directedChange()
{
	if (directed == 'false')
	{
		directed = 'true';
	}
	else if (directed == 'true')
	{
		directed = 'false';
	}
}

function OpcionesUnidadesChange(value)
{
	units = value;
}

function BuscarRuta(texto)
{	
	if ( routingObj.start != null && routingObj.end != null )
	{					
		if(texto)
		{
			routeBox = new SGeoBox(routingObj.start.X,routingObj.start.Y,routingObj.end.X,routingObj.end.Y);
			mapObj.ZoomToBox(routeBox, 1, 19);
			var complemento = "inix="+routingObj.start.X+"&iniy="+routingObj.start.Y+"&finx="+routingObj.end.X+"&finy="+routingObj.end.Y+'&costo='+costo+'&dirigido='+directed+'&grafo='+join_query_grafo+'&tipo=layer'+'&';
			//mapObj.RemoveDynamicLayer('ruta');
			var layerRuta = mapObj.AddDynamicLayer("ruta");
			layerRuta.setParserFeatures("","",URL_PG_ROUTING+"?"+complemento);
			layerRuta.setOpacity(100);
			//layerRuta.setCache(false);
			layerRuta.update();
		}
		
		SEvent.RemoveListener(routingObj.mapClick);
		routingObj.mapClick = null;
	}
	else
	{
		if ( routingObj.start == null && routingObj.end == null )
		{
			alert("Marque el punto de Inicio y de Llegada para la ruta deseada");
		}
		else
		{
			if (routingObj.start == null)
			{
				alert("Marque el punto de Inicio de la ruta deseada");
			}
			if (routingObj.end == null)
			{
				alert("Marque el punto de Llegada de la ruta deseada");
			}
		}
	}
}

function TraerTexto()
{	
//	Busqueda._param = {pix:routingObj.start.X,piy:routingObj.start.Y,pfx:routingObj.end.X,pfy:routingObj.end.Y,c:costo,awq:and_where_query_grafo,jq:join_query_grafo,d:directed,e:english,u:units,debug:debug};
//	//Busqueda._param = "pix="+routingObj.start.X+"&piy="+routingObj.start.Y+"&pfx="+routingObj.end.X+"&pfy="+routingObj.end.Y+"&c="+costo+"&awq="+and_where_query_grafo+"&jq="+join_query_grafo+"&d="+directed+"&e="+english+"&u="+units+"&debug="+debug;
//	Busqueda._url = "srouting/ruta.php";
//	alert(Busqueda._contenido);
	return false;
	//var para_texto = "inix="+routingObj.start.X+"&iniy="+routingObj.start.Y+"&finx="+routingObj.end.X+"&finy="+routingObj.end.Y+"&costo="+costo+"&grafo="+and_where_query_grafo+"&jg="+join_query_grafo+"&dirigido="+directed+"&e="+english+"&u="+units+"&debug="+debug+'&tipo=sentidos';
//	var para_texto = "pix="+routingObj.start.X+"&piy="+routingObj.start.Y+"&pfx="+routingObj.end.X+"&pfy="+routingObj.end.Y+"&c="+costo+"&awq="+and_where_query_grafo+"&jq="+join_query_grafo+"&d="+directed+"&e="+english+"&u="+units+"&debug="+debug+'&tipo=sentidos';
//	var http = new SHttpRequest();	// se crea object ajax.	
//	http.Open("srouting/ruta.php");	// se hace el llamado a la pagina que me traera los datos al div.
//	http.Send(para_texto, function MyHandler(){	// variable enviada para hacer consulta en la otra pag.
//		if (http.request.readyState==4)
//		{
//			 alert(http.request.responseText);
//		}
//	});
}

function ActualizarStatus()
{
	//document.getElementById("textOutput").innerHTML = "&nbsp;";
}

function Limpiar()
{
	mapObj.removeIconsOnLayer("StartPointLayer");
	mapObj.removeIconsOnLayer("EndPointLayer");
	mapObj.removeIconsOnLayer("RouteMarkerLayer");
	mapObj.RemoveDynamicLayer("ruta");
	document.getElementById("div_busqueda").innerHTML = "&nbsp;";
	Busqueda._lista.find(".bottom_ico3").click();
	Busqueda._cargar = null;
	Busqueda._mostrando = null;
	Busqueda._tipoBusqueda = null;
	Busqueda._contenido = null;
	Busqueda._data = null;
	Busqueda._rutasFunction = null;
	routingObj.start = null;
	routingObj.end = null;
}

function filterAlpha()
{
	if (this.runtimeStyle&&/\.png$/.test(this.src.toLowerCase()))
	{
		if (this.runtimeStyle.filter=="")
		{
			this.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + this.src + "',sizingMethod='scale')";
			this.src = "media/blank.gif";
		}
	}
}

function GetExtend()
{
	//var TextOutput = document.getElementById("textOutput");
	//TextOutput.innerHTML = mapObj.GetMapExtend().ToString();
}

function MapMouseOverEvent( point )
{
	//var TextOutput = document.getElementById("textCoords");
	//TextOutput.innerHTML = point.ToString();
}

function UbicacionMapaChange( nombre )
{
	switch (nombre) 
	{
   	case 'Caracas':
   		mapObj.ZoomAndGoTo(new SGeoPoint( -66.885623931884765, 10.4752922058105465 ),13 );
   		break;
		case 'Valencia':
			mapObj.ZoomAndGoTo(new SGeoPoint( -67.99301147460938, 10.19565582275390 ),13 );
			break;
		case 'Maracaibo':
			mapObj.ZoomAndGoTo(new SGeoPoint( -71.64630889892578, 10.6402587890625 ),13 );
			break;
		case 'Toronto': 
			mapObj.ZoomAndGoTo(new SGeoPoint( -79.43807780742645, 43.63768994808197 ),10 );
			break;
		case 'Venezuela': 
			mapObj.ZoomAndGoTo(new SGeoPoint(-65.7861328125, 6.943359375),7);
			break;
   }
}

function debugChange()
{
	if(document.getElementById("chkDebug").checked)
	{
		debug = true;
		SmapDebug("ROUTE", true);
	}
	else
	{
		debug = false;
		SmapDebug("ROUTE", false);
	}
}

function ShowSegmentOnMap( x, y )
{
	if(typeof(objCallOut)!= "undefined" && objCallOut && objCallOut.close)
		objCallOut.close();
	var point = new SGeoPoint(x,y);
	var icon = new SIcon(point, new SSize(20, 20), 'media/ico/srouting/pin.gif', true);
	
	mapObj.ZoomAndGoTo(point, mapObj.GetLevel());
	
	mapObj.removeIconsOnLayer("RouteMarkerLayer");
	mapObj.addIcon(icon, "RouteMarkerLayer");
	
	SEvent.AddListener(icon, 'onclick', function(){
		ShowWindow(x, y)
	});
}

function AgregarMiniLayer()
{
	var routeBox = new SGeoBox(routingObj.start.X,routingObj.start.Y,routingObj.end.X,routingObj.end.Y);
	var complemento = "inix="+routingObj.start.X+"&iniy="+routingObj.start.Y+"&finx="+routingObj.end.X+"&finy="+routingObj.end.Y+'&costo='+costo+'&dirigido='+directed+'&grafo='+join_query_grafo+'&tipo=layer'+'&';
	MiniMapObj.RemoveDynamicLayer('miniRuta');
	var MiniRuta = MiniMapObj.AddDynamicLayer("miniRuta");
	MiniRuta.setParserFeatures("","",URL_PG_ROUTING+"?"+complemento);
	MiniRuta.setOpacity(100);
	MiniRuta.update();
}

function AgregarMiniIcono(x, y)
{
	var point = new SGeoPoint(x,y);
	var icon = new SIcon(point, new SSize(20, 20), 'media/ico/srouting/pin.gif', true);
	MiniMapObj.removeIconsOnLayer("MiniRouteMarkerLayer");
	MiniMapObj.addIcon(icon, "MiniRouteMarkerLayer");
}