jQuery.preloadImages = function(){
  for(var i = 0; i<arguments.length; i++)
  {
    jQuery("<img>").attr("src", arguments[i]);
  }
}
$.preloadImages(documentRoot+"imagenes/ajaxBar.gif");

var tipoCoordenada = "";

$(document).ready(function(){
	
	// Generar Tabs
	$(".tab_content").hide();
	$("ul.tabs").each(function(){
		$("#"+$(this).parent().parent().attr("id")+" ul.tabs li:first").addClass("active").show();
		$("#"+$(this).parent().parent().attr("id")+" .tab_content:first").show();					   
	}); 

	$("ul.tabs li").click(function()
       {
		$("#"+$(this).parent().parent().attr("id")+" ul.tabs li").removeClass("active");
		$(this).addClass("active");
		// alert("#"+$(this).parent().parent().attr("id"));
		$("#"+$(this).parent().parent().attr("id")+" .tab_content").hide();

		var activeTab = $(this).find("a").attr("href");
		$(activeTab).fadeIn();
		return false;
	});					   
	
	$(document).pngFix();
	
	// Inicializa el mapa
	$('#mapa').jmap('init', {
		'mapType':'map',
		'mapCenter':[25.6834,-100.3135],
		'mapZoom' : 13,
		'mapControl' : 'large',
		'mapEnableType': true,
		'mapEnableSmoothZoom' : true
	},function(map, element, options){
		GEvent.addListener(map, "click", function(overlay, latlng){
			if(tipoCoordenada!=""){
				if (latlng != null) {
					address = latlng;
					geocoder.getLocations(latlng, function(response){
						if(tipoCoordenada=="Origen"){
							map.clearOverlays();
						}
						if (!response || response.Status.code != 200) {
							alert("Ocurrio un error durante la operaci&oacute;n, por favor intente de nuevo");
						} else {
							place = response.Placemark[0];
							point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
							marker = new GMarker(point);
							map.addOverlay(marker);
							$("#coordenadas").val(place.Point.coordinates[0] + "," + place.Point.coordinates[1])
							marker.openInfoWindowHtml('<p style="width:220px;font-size:10px;"><b>Direcci&oacute;n:</b><br/>' + place.address + '<br/><br/>' + '<table><tr><td><a href="javascript:void(0);" id="marcar'+tipoCoordenada+'Lnk" onclick="fcn'+tipoCoordenada+'();">Marcar como mi '+tipoCoordenada+'?</a></td><td><a href="javascript:void(0);" id="marcar'+tipoCoordenada+'Lnk2" onclick="fcn'+tipoCoordenada+'();"><img src="'+documentRoot+'imagenes/okBtn.png" border="0"></a></td></tr></table>&oacute; puedes hacer click en otra ubicaci&oacute;n.</p>');
						}													   
					});
				}
			}
		});
		geocoder = new GClientGeocoder();
	});
	cargaPermanentes();
	cargaRutaInicial();
	
	// Tips para el buscador
	$('.tipped').ktips();
	
	// Imprime ruta desde links
	$("#rutasTab a.rutas").live("click",function(){
		cerrarAyuda();
		ocultarInfoRutas();
		temp = "rutaDoble("+$(this).attr("rel")+")";
		eval(temp);
		return false;
	});
	// Imprime punto de interes desde links
	$("#puntosTab a.puntoInteres").live("click",function(){
		cerrarAyuda();
		ocultarInfoRutas();
		temp = "mostrarPuntoInteres("+$(this).attr("rel")+")";
		eval(temp);
		return false;
	});
	
	// Inicia Operacion de "Como Llegar"
	$("#rutaDirectaLnk").click(function(){
		fcnCancelar();
		cerrarAyuda();
		//$("#encabezadoPagina").after('<div>1- Selecciona el punto de origen &raquo; 2- Selecciona el punto de destino</div>');
		$("#mapa").jmap("ClearMap");
		tipoCoordenada = "Origen";
		$("#mapa").qtip({
               content: 'Haz click en el mapa para seleccionar tu punto de origen.<br/><a href="javascript:void(0);" onclick="fcnCancelar();">&laquo; Cancelar b&uacute;squeda &raquo;</a>', // Set the tooltip content to the current corner
               position: {
                  corner: {
                     tooltip: 'bottomMiddle', // Use the corner...
                     target: 'topMiddle' // ...and opposite corner
                  }
               },
               show: {
                  when: false, // Don't specify a show event
                  ready: true // Show the tooltip when ready
               },
               hide: false, // Don't specify a hide event
               style: {
                  border: {
                     width: 3
                  },
                  padding: 5, 
                  textAlign: 'center',
                  tip: true, // Give it a speech bubble tip with automatic corner detection
                  name: 'cream' // Style it according to the preset 'cream' style
               }
		});
	}); 
	
	// Inicia Operacion de "Rutas por Punto"
	$("#rutasPorPuntoLnk").click(function(){
		fcnCancelar();
		cerrarAyuda();
		$("#mapa").jmap("ClearMap");
		tipoCoordenada = "Punto";
		$("#mapa").qtip({
               content: 'Haz click en el punto del mapa por donde deseas saber las rutas que pasan.<br/><a href="javascript:void(0);" onclick="fcnCancelar();">&laquo; Cancelar b&uacute;squeda &raquo;</a>', // Set the tooltip content to the current corner
               position: {
                  corner: {
                     tooltip: 'bottomMiddle', // Use the corner...
                     target: 'topMiddle' // ...and opposite corner
                  }
               },
               show: {
                  when: false, // Don't specify a show event
                  ready: true // Show the tooltip when ready
               },
               hide: false, // Don't specify a hide event
               style: {
                  border: {
                     width: 3
                  },
                  padding: 5, 
                  textAlign: 'center',
                  tip: true, // Give it a speech bubble tip with automatic corner detection
                  name: 'cream' // Style it according to the preset 'cream' style
               }
		});
	}); 
	
	// Inicia operacion de busqueda
	$("#form1").submit(function(){
		cerrarAyuda();
		fcnCancelar();
		ocultarInfoRutas();
		$("#rutasTab").html('<div id="resultadosTitulo"><table><tr><td valign="middle"><img src="'+documentRoot+'imagenes/ajaxBar.gif" /></td><td valign="middle">Buscando...</td></tr></table></div>');
		$.post(documentRoot+"ajax/buscarruta",	{ Busqueda: $("#buscar").val()	}, function(data){
			$("#rutasTab").html('<div id="resultadosTitulo">Resultados de la B&uacute;squeda:</div>'+data);
		});
		return false;
	});
	// Guarda Comentario
	$("#comentarBtn").click(function(){
		cerrarAyuda();
		$("#comentarBtn").attr({"disabled":"disabled"}).parent().prepend('<img src="'+documentRoot+'imagenes/ajaxBar.gif" />');
		$.post(documentRoot+"ajax/guardarComentario",	{ Comentario_Nombre: $("#Comentario_Nombre").val(), Comentario_Texto: $("#Comentario_Texto").val() }, function(data){
			$("#contenedorComentarios").prepend(data);
			$("#comentarBtn").removeAttr("disabled").prev().remove();
			$("#Comentario_Nombre, #Comentario_Texto").val('').blur();
		});
	});
	
	// Muestra forma de contacto
	$("#contactoLnk").click(function(){
		cerrarAyuda();
		$("#resultados").html('<div id="resultadosTitulo">Forma de Contacto</div><div id="aviso" style="display:none"><img src="'+documentRoot+'imagenes/ajaxBar.gif" alt="" /> Enviando Correo, por favor espere...</div><table border="0" cellpadding="4" cellspacing="0"><tr><td><label for="Nombre">Nombre:</label><br /><input type="text" name="Nombre" id="Nombre" style="width:260px;" /></td></tr><tr><td><label for="CorreoElectronico">Correo Electr&oacute;nico:</label><br /><input type="text" name="CorreoElectronico" id="CorreoElectronico" style="width:260px;"/></td></tr><tr><td><label for="Comentarios">Comentarios:</label><br /><textarea name="Comentarios" id="Comentarios" rows="5" cols="" style="width:260px;"></textarea></td></tr><tr><td><label for="button"></label><input type="submit" name="button" id="button" value="Contacto!" style="width:260px;"/></td></tr></table><p id="avisoP" style="text-align:center;"></p>');					 
		$("#button").click(function(){
			$("#button").attr({"disabled":"disabled"});
			$("#aviso").slideDown("slow");
			$.post(documentRoot+"ajax/enviarCorreo",	{ Nombre: $("#Nombre").val(), CorreoElectronico: $("#CorreoElectronico").val(), Comentarios:$("#Comentarios").val() }, function(data){
				$("#aviso").slideUp("slow",function(){$("#avisoP").html(data)});
				$("#button").removeAttr("disabled");
				$("#Nombre, #CorreoElectronico, #Telefono, #Comentarios").val('');
			});
		});
	});
	
	// Muestra todas las rutas
	$("#defaultRutas").click(function(){
		$("#buscar").val("");
		$("#form1").submit();
		$("li#rutasLi").click();
		$("#buscar").blur();
	});
	
	// Muestra todos los puntos de interes
	$("#defaultPuntos").click(function(){
		fcnCancelar();
		cerrarAyuda();
		ocultarInfoRutas();
		$("li#puntosLi").click();
		$("#resultados").html('<div id="resultadosTitulo"><table><tr><td valign="middle"><img src="'+documentRoot+'imagenes/ajaxBar.gif" /></td><td valign="middle">Buscando...</td></tr></table></div>');
		$.post(documentRoot+"ajax/obtenerPuntosDeInteres",	{}, function(data){
			$("#resultados").html('<div id="resultadosTitulo">Puntos de Inter&eacute;s &oacute; Referencia:</div>'+data);
		});
		return false;
	});
	
	// Muestra las Instrucciones
	$("#instruccionesLnk").click(function(){
		if($("#instruccionesLnk").attr("rel")==0){
			if($("#rutaDirectaLnk").data("qtip")){
				$("#rutaDirectaLnk").qtip("destroy");
			}
			if($("#mostrarTodasLnk").data("qtip")){
				$("#mostrarTodasLnk").qtip("destroy");
			}
			$("#instruccionesLnk").attr("rel",1)
			// ###1
			$("#instruccionesLnk").qtip({
				   content: 'Para cerrar la ayuda haz click de nuevo en <strong>&laquo;Instrucciones&raquo;</strong>.',
					position: {corner: {
						tooltip: 'leftMiddle',
						target: 'rightMiddle'
					}
				},show: {when: false,ready: true},hide: false,style: {border: {width: 3},padding: 5, textAlign: 'center',tip: true,name: 'dark'}
			});
			// ###2
			$("#menuCompartir").qtip({
				   content: 'Comparte este sitio en tus redes sociales como facebook, myspace, digg, delicious y twitter.',
					position: {corner: {
						tooltip: 'topLeft',
						target: 'bottomMiddle'
					}
				},show: {when: false,ready: true},hide: false,style: {border: {width: 3},padding: 5, textAlign: 'center',tip: true,name: 'dark'}
			});
			
			// ###3
			$("#rutaDirectaLnk").qtip({
				   content: 'Haz click en <strong>&laquo;Como Llegar&raquo;</strong> para seleccionar tu origen y destino y el sistema te ofrezca la(s) ruta(s) que te llevan.',
					position: {corner: {
						tooltip: 'bottomLeft',
						target: 'topMiddle'
					}
				},show: {when: false,ready: true},hide: false,style: {border: {width: 3},padding: 5, textAlign: 'center',tip: true,name: 'dark'}
			});
			// ###4
			$("#rutasPorPuntoLnk").qtip({
				   content: 'Haz click en <strong>&laquo;Rutas por Punto&raquo;</strong> para ver que rutas pasan por un punto que elijas.',
					position: {corner: {
						ttooltip: 'topLeft',
						target: 'bottomMiddle'
					}
				},show: {when: false,ready: true},hide: false,style: {border: {width: 3},padding: 5, textAlign: 'center',tip: true,name: 'dark'}
			});
			// ###4.1
			$("#mostrarTodasLnk").qtip({
				   content: 'Haz click en <strong>&laquo;Rutas&raquo;</strong> para cargar de el listado de todas las rutas urbanas.',
					position: {corner: {
						tooltip: 'bottomRight',
						target: 'topMiddle'
					}
				},show: {when: false,ready: true},hide: false,style: {border: {width: 3},padding: 5, textAlign: 'center',tip: true,name: 'dark'}
			});
			// ###5
			$("#search").qtip({
				   content: 'Aquí puedes Buscar las rutas por numero &oacute; palabra clave. Puedes dejar el campo vacio para cargar el listado completo.',
					position: {corner: {
						tooltip: 'topMiddle',
						target: 'bottomMiddle'
					}
				},show: {when: false,ready: true},hide: false,style: {border: {width: 3},padding: 5, textAlign: 'center',tip: true,name: 'dark'}
			});
			// ###6
			$("#resultados").qtip({
				   content: 'Aquí aparecen los resultados de las busquedas y operaciones.',
					position: {corner: {
						tooltip: 'topMiddle',
						target: 'bottomMiddle'
					}
				},show: {when: false,ready: true},hide: false,style: {border: {width: 3},padding: 5, textAlign: 'center',tip: true,name: 'dark'}
			});
		}else{
			cerrarAyuda();
		}
	});
	
});

////////////////////////////////////
// ######### Funciones ########## //
////////////////////////////////////

function cerrarAyuda(){
	$("#instruccionesLnk").attr("rel",0);
	$("#instruccionesLnk,#menuCompartir,#rutaDirectaLnk,#mostrarTodasLnk,#search,#resultados,#rutasPorPuntoLnk").each(function(){
		if($(this).data("qtip")){
			$(this).qtip("destroy");
		}																								  
	});
}
function rutaDesdeClick(rutaId){
	$.post(documentRoot+"index.php/ajax/obtenerRuta/",{rutaId:rutaId}, function(data){
		var temp = 'mostrarmapa('+data+')';
		eval(temp);
		cargaPermanentes();

	});
}

function marcapi(lat,long,titulo,texto,telefono,web){
	if(web!=''){
	   sitioweb = '<a href="'+web+'" target="_blank" title="'+titulo+" - "+texto+'">Sitio Web</a>';
	} else {
	   sitioweb = '&nbsp;';
	}
	var Icon = new GIcon();
      Icon.image = documentRoot+"imagenes/markers/marker_rutadirecta.png";
      Icon.iconSize = new GSize(32, 50);
      Icon.iconAnchor = new GPoint(14, 50);
      Icon.infoWindowAnchor = new GPoint(14, 0);
      Icon.transparent = documentRoot+"imagenes/markers/marker_rutadirecta.png";
	$('#mapa').jmap('AddMarker', {
		'pointLatLng': [lat, long],
		'pointHTML': '<table width="230" border="0" cellspacing="0" cellpadding="2"><tr><td colspan="3"><strong>'+titulo+'</strong></td></tr><tr><td colspan="3" style="border-bottom:solid 1px #DDD">'+texto+'</td></tr><tr><td width="16" valign="middle"><img src="'+documentRoot+'imagenes/telicon.jpg" /></td><td valign="middle">'+telefono+'</td><td align="right" valign="middle">'+sitioweb+'</td></tr></table>',
		'pointIcon' : Icon
	});
}

function mostrarmapa(puntos,clat,clong,id,nombrelargo,tipo,longitud,href,color,cleanMap){
	if(color == "undefined"){
		color ="#ff0000";
	}
	if(cleanMap == "undefined"){
		cleanMap =true;
	}
	if($("#Punto").val() != "" && $("#Punto").val() != "undefined" ){
		puntoLatLong =$("#Punto").val().split(",");
		clat = puntoLatLong[1];
		clong = puntoLatLong[0];
	} else {

}
	mostrarInfoRutas(id,nombrelargo,tipo,longitud,color,cleanMap,href);
	
	$('#mapa').jmap('AddPolylineFromEncoded', {
		'polylinePoints': puntos,
		'polylineStrokeColor': color,
		'polylineStrokeWidth': 5,
		'polylineStrokeOpacity': .6,
		'mapCenter': [clat, clong],
		'polylineLevels': ' ',
		'polylineZoomFactor': 3,
		'polylineNumLevels': 3,
		'polylineZoom': 13,
		'cleanMap':cleanMap
	});
}
function mostrarPuntoInteres(id){
	
	$.post(documentRoot+"ajax/obtenerPuntoInteres",{puntoId:id}, function(data){
		//
		var temp = 'mostrarpuntoenmapa('+data+')';
		eval(temp);
	});
	
}
function rutaDoble(id1,id2){
	ocultarInfoRutas();
	$.post(documentRoot+"ajax/obtenerRuta",{rutaId:id1}, function(data){
		var temp = 'mostrarmapa('+data+',"#FF0000",true)';
		eval(temp);
		$.post(documentRoot+"ajax/obtenerFlechas",{rutaId:id1}, function(data){
			eval(data);
		});
		if(id2!=0 && id2 !='undefined'){
			$.post(documentRoot+"ajax/obtenerRuta",{rutaId:id2}, function(data){
				var temp = 'mostrarmapa('+data+',"#00FF00",false)';
				eval(temp);
				$.post(documentRoot+"ajax/obtenerFlechas",{rutaId:id2}, function(data){
					eval(data);
				});
			});
			
		}
		var origenLatLong = $("#Origen").val().split(",");
		var destinoLatLong = $("#Destino").val().split(",");
		$('#mapa').jmap('AddMarker', {
			'pointLatLng': [origenLatLong[1], origenLatLong[0]],
			'pointHTML': 'Origen'
		});
		$('#mapa').jmap('AddMarker', {
			'pointLatLng': [destinoLatLong[1], destinoLatLong[0]],
			'pointHTML': 'Destino'
		});
		if($("#Punto").val() != "" && $("#Punto").val() != "undefined" ){
			var puntoLatLong = $("#Punto").val().split(",");
			$('#mapa').jmap('AddMarker', {
				'pointLatLng': [puntoLatLong[1], puntoLatLong[0]],
				'pointHTML': 'Mi Punto'
			});	
		}
		cargaPermanentes();
	});
	
}

// Muestra flecha direccional en el mapa
function mostrarFlecha(lng,lat,img){
	var Icon = new GIcon();
      Icon.image = documentRoot+"imagenes/flecha"+img+".png";
      Icon.iconSize = new GSize(9, 9);
      Icon.iconAnchor = new GPoint(5, 9);
      Icon.infoWindowAnchor = new GPoint(5, 0);
      Icon.transparent = documentRoot+"imagenes/flecha"+img+".png";
	$('#mapa').jmap('AddMarker', {
		'pointLatLng': [lat-.00001, lng],
		'pointIcon': Icon
	});
	
}

function mostrarpuntoenmapa(nombre, lng, lat, descripcion){
	//
	$("#mapa").jmap("ClearMap");
	$('#mapa').jmap('AddMarker', {
		'pointLatLng': [lat, lng],
		'centerMap': true,
		'centerMoveMethod': 'pan',
		'pointHTML': '<p style="width:270px;font-size:10px;"><strong>'+nombre+'</strong><br/>'+descripcion+'</p><p><a href="javascript:void(0);" onclick="queRutasPasanPor();">Ver Rutas que pasan por aqu&iacute; &raquo;</a></p>'
	});
	$("#Punto").val(lng+','+lat);
	
}
function rutaDirecta(){
	$("#rutasTab").html('<div id="resultadosTitulo"><table><tr><td valign="middle"><img src="'+documentRoot+'imagenes/ajaxBar.gif" /></td><td valign="middle">Buscando...</td></tr></table></div>');
	origen = $("#Origen").val().split(",");
	destino = $("#Destino").val().split(",");
	$.get(documentRoot+"ajax/RutaDirecta/"+origen[0]+"/"+origen[1]+"/"+destino[0]+"/"+destino[1],{}, function(data){
		$("#rutasTab").html(data);
	});	
}
function queRutasPasanPor(){
	$("li#rutasLi").click();
	$("#rutasTab").html('<div id="resultadosTitulo"><table><tr><td valign="middle"><img src="'+documentRoot+'imagenes/ajaxBar.gif" /></td><td valign="middle">Buscando...</td></tr></table></div>');
	punto = $("#Punto").val().split(",");
	$.get(documentRoot+"ajax/queRutasPasanPor/"+punto[0]+"/"+punto[1],{}, function(data){
		$("#rutasTab").html(data);
	});	
}

function fcnOrigen(){
		// Guardar coordenadas del origen
		Mapifies.MapObjects.Get($('#mapa')).closeInfoWindow();
		$("#"+tipoCoordenada).val($("#coordenadas").val());
		tipoCoordenada = "Destino";
		if($("#mapa").data("qtip")){
			$("#mapa").qtip("destroy");
		}
		$("#mapa").qtip({
               content: 'Ahora haz click en el mapa para seleccionar tu punto de destino.<br/><a href="javascript:coid(0);" onclick="fcnCancelar();">&laquo; Cancelar b&uacute;squeda &raquo;</a>', // Set the tooltip content to the current corner
               position: {
                  corner: {
                      tooltip: 'bottomMiddle', // Use the corner...
                     target: 'topMiddle' // ...and opposite corner
                  }
               },
               show: {
                  when: false, // Don't specify a show event
                  ready: true // Show the tooltip when ready
               },
               hide: false, // Don't specify a hide event
               style: {
                  border: {
                     width: 3
                  },
                  padding: 5, 
                  textAlign: 'center',
                  tip: true, // Give it a speech bubble tip with automatic corner detection
                  name: 'cream' // Style it according to the preset 'cream' style
               }
		});
}
function fcnDestino(){
		// Guardar coordenadas del destino
		Mapifies.MapObjects.Get($('#mapa')).closeInfoWindow();
		$("#"+tipoCoordenada).val($("#coordenadas").val());
		tipoCoordenada = "";
		if($("#mapa").data("qtip")){
			$("#mapa").qtip("destroy");
		}
		rutaDirecta();
}
function fcnPunto(){
		// Guardar coordenadas del punto
		Mapifies.MapObjects.Get($('#mapa')).closeInfoWindow();
		$("#"+tipoCoordenada).val($("#coordenadas").val());
		tipoCoordenada = "";
		if($("#mapa").data("qtip")){
			$("#mapa").qtip("destroy");
		}
		queRutasPasanPor();
}
function fcnCancelar(){
		// Cancelar Busqueda de ruta directa
		//$("#encabezadoPagina").next().remove();
		Mapifies.MapObjects.Get($('#mapa')).closeInfoWindow();
		$("#Origen, #Destino, #Punto").val('');
		tipoCoordenada = "";

		if($("#mapa").data("qtip")){
			$("#mapa").qtip("destroy");
		}
		$("#mapa").jmap("ClearMap");
		cargaPermanentes();
}
function ocultarInfoRutas(){
	$("#infoRutas").slideUp();
}
function mostrarInfoRutas(id,nombrelargo,tipo,longitud,color,reemplazar,href){
	$("li#informacionLi").click();
	if(reemplazar){
		$("#informacionTab").html('<h2>Informaci&oacute;n de las Rutas Trazadas</h2><div class="infoRutaDiv"><table width="300" border="0" cellspacing="0" cellpadding="2"><tr><td valign="top"><div style="width:7px; height:7px; background-color:'+color+'; display:block; margin:6px 6px 0 0;"></div></td><td><h3>'+nombrelargo+' ('+tipo+')</h3></td></tr><tr><td>&nbsp;</td><td><strong>Tipo de Ruta:</strong> '+tipo+'.<br /><strong>Longitud:</strong> '+longitud+' kms.</td></tr><tr><td>&nbsp;</td><td><strong>Enlace Permanente de la ruta:</strong><br /><textarea onclick="select();" style="width:300px;" name="textarea" id="textarea" rows="2">'+href+'</textarea></td></tr></table></div>').slideDown("slow");
	} else {
		$("#informacionTab").append('<div class="infoRutaDiv"><table width="300" border="0" cellspacing="0" cellpadding="2"><tr><td valign="top"><div style="width:7px; height:7px; background-color:'+color+'; display:block; margin:6px 6px 0 10px;"></div></td><td><h3>'+nombrelargo+' ('+tipo+')</h3></td></tr><tr><td>&nbsp;</td><td><strong>Tipo de Ruta:</strong> '+tipo+'.<br /><strong>Longitud:</strong> '+longitud+' kms.</td></tr><tr><td>&nbsp;</td><td><strong>Enlace Permanente de la ruta:</strong><br /><textarea onclick="select();" style="width:300px;" name="textarea" id="textarea" rows="2">'+href+'</textarea></td></tr></table></div>');
	}
}