// Muestra o oculta un elemento dependiendo del valor de "valor"
function mostrar( nombreElemento, valor )
{
	var elemento = document.getElementById(nombreElemento);
 	if ( valor ) {
 		elemento.style.visibility = 'visible';
 		elemento.style.display = 'inline';
 	}else{
 		elemento.style.visibility = 'hidden';
 		elemento.style.display = 'none'; 
 	}
 	return true;
}

// Añade marcador a favoritos
function favoritos(url, titulo)
{
	if ((navigator.appName=="Microsoft Internet Explorer") && (parseInt(navigator.appVersion)>=4)) {
		window.external.AddFavorite(url,titulo);
	} else {
		if (navigator.appName == "Netscape")
      window.sidebar.addPanel(titulo,url,'');
	}
}

// Funcion para establecer los valores de la reserva
function onclickReservar( hotel, regimen, habitacion )
{
	document.forms[0].codigoRegimenSeleccionado.value=regimen;
	document.forms[0].codigoTipoHabitacionSeleccionado.value=habitacion;
	document.forms[0].codigoHotelSeleccionado.value=hotel;
}

// Funcion para establecer los valores de una búsqueda automática a través de un enlace de oferta.
// El formato de fecha esperado es dd/mm/yyyy
function onclickOferta( nombreForm, codigoHotel, nombreHotel, fechaInicio, anticipar, anticipacion, estanciaMinima )
{
  var form = $(nombreForm);
  var fecha = fechaInicio.split(/\W+/);
  var minimo = (isNotBlank(estanciaMinima) && (estanciaMinima != "0"))? parseInt(estanciaMinima) : 2;
  var anticipacion = (isNotBlank(anticipacion) && (anticipacion != "0"))? parseInt(anticipacion) : 1;
  var fechaIni = (anticipar)? new ShDate(new Date(fecha[2], parseInt(fecha[1])-1, parseInt(fecha[0]) + anticipacion)) :
                              new ShDate(new Date(fecha[2], parseInt(fecha[1])-1, parseInt(fecha[0])));
  var fechaFin = new ShDate(new Date(fechaIni.date.getFullYear(), fechaIni.date.getMonth(), fechaIni.date.getDate() + minimo));
  
  form.lugar.value = nombreHotel;
  form.codigoHotelSeleccionado.value = codigoHotel;
  form.fechaEntrada.value = fechaFormatoCorto(fechaIni);
  form.numDias.value = minimo;
  form.fechaSalida.value = fechaFormatoCorto(fechaFin);
}

// Pone el foco en el campo indicado
function ponerFoco ( nombre ) 
{
	var campo = document.getElementsByName (nombre)[0];
	if ( campo )
		campo.focus();
	return true;
}

function onLoadMapa ( idDivHotel, idDivMap, idContenedorMapa, latitud, longitud, manejadorError )
{
  var gMap;
  var toolTip = ($(idDivHotel))?  $(idDivHotel).innerHTML : "";
  if (manejadorError)
    gMap = new DiiGMap(idDivMap, { 'manejadorError': manejadorError });
  else
    gMap = new DiiGMap(idDivMap);

  gMap.map.enableScrollWheelZoom();
  gMap.mostrarPunto({ lat: latitud, long: longitud }, toolTip);
  return gMap;
}

function onLoadMapaDireccion ( idDivHotel, idDivMap, idContenedorMapa, direccion, codPostal, poblacionCiudad, manejadorError )
{
	var gMap;

	if (manejadorError)
	  gMap = new DiiGMap(idDivMap, { 'manejadorError': manejadorError });
	else
	  gMap = new DiiGMap(idDivMap);

	gMap.map.enableScrollWheelZoom();
	gMap.mostrarPuntoCallBack(direccion, codPostal, poblacionCiudad, $(idDivHotel).innerHTML);
	return gMap;
} 

function imprimirElemento ( idContenedor )
{
  var ficha = $(idContenedor);
  var ventana = window.open(' ', 'popimpr');
  ventana.document.write( ficha.innerHTML );
  ventana.document.close();
  ventana.print( );
  ventana.close();
} 

function aleatorio ( maxValor )
{
    var ranNum= Math.floor( Math.random() * (maxValor +1) );
    return ranNum;
}

function cargarEditorHTML(){
	tinyMCE.init({
    	mode : "textareas",
    	theme : "advanced",
    	language: "es",
    	plugins : "table,save,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,zoom,flash,searchreplace,print,contextmenu,fullscreen",
    	theme_advanced_buttons1_add_before : "save,separator",
    	theme_advanced_buttons1_add : "fontselect,fontsizeselect",
    	theme_advanced_buttons2_add : "separator,insertdate,inserttime,preview,zoom,separator,forecolor,backcolor",
    	theme_advanced_buttons2_add_before: "cut,copy,paste,separator,search,replace,separator",
    	theme_advanced_buttons3_add_before : "tablecontrols,separator",
    	theme_advanced_buttons3_add : "emotions,iespell,flash,advhr,separator,print,separator,fullscreen",
    	theme_advanced_toolbar_location : "top",
    	theme_advanced_toolbar_align : "left",
    	theme_advanced_path_location : "bottom",
    	plugin_insertdate_dateFormat : "%d-%m-%Y",
    	plugin_insertdate_timeFormat : "%H:%M:%S",
    	extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]",
    	external_link_list_url : "example_data/example_link_list.js",
    	external_image_list_url : "example_data/example_image_list.js",
    	flash_external_list_url : "example_data/example_flash_list.js",
		  spellchecker_languages : "+Spanish=es"
    });
}

function onDivOver ( idDiv )
{
	var div = document.getElementById(idDiv);
    div.style.backgroundColor = 'white';
	div.style.color = '#e18000';
}
	
function onDivNoOver ( idDiv )
{
	var div = document.getElementById(idDiv);
    div.style.backgroundColor = '#ffeab9';
	div.style.color = '#B75B0B';
}

function onChangeCheck ( check, campo )
{
    if ( check.checked )
        campo.value = check.getAttribute('value');
    else
        campo.value = check.getAttribute('onNoValue');
}

function controlInputsObligatorios() {
	$$('input.obligatorio').invoke ('observe', 'blur', 
	  function (event) {
		  var elemento = Event.element(event);
		  (Object.isUndefined(elemento.value) || (elemento.value == ""))?
		      elemento.addClassName('inputsObligatorioVacio') :
			    elemento.removeClassName('inputsObligatorioVacio');
	  }).invoke ('writeAttribute', 'title', "Campo obligatorio");
}

function isNotBlank(valor)
{
  return (valor != null) && (valor.constructor == String) && (valor != "");
}

/* Funciones de la lista de reservas seleccionadas */
/* ATENCIÓN: Las llamadas Ajax GET son agresivamente cacheadas en IE,
 *          la solución es utilizar llamadas tipo POST */
function conmutarDetalle(span, seccion)
{
  if (seccion.visible())
  {
    Effect.SlideUp(seccion.id, { queue: 'end', scaleContent: false, duration: 0.2 });
    span.removeClassName('desplegado');
    span.addClassName('plegado');
  }
  else
  {
    Effect.SlideDown(seccion.id, { queue: 'end', scaleContent: false, duration: 0.2 });
    span.removeClassName('plegado');
    span.addClassName('desplegado');
  }
}

function notificadoresListaReservas(mostrar, listaObjetos)
{
  var lista = $A(listaObjetos).compact();
  var func = (mostrar)? 'startWaiting' : 'stopWaiting';
  lista.invoke(func);
}

/** llamadas de interacción con la Lista de Reservas **/
function cargarListaReservas() {
  var url = 'buscador.html';
  var pars = 'evento=cargarListaReservas';
  var myAjax = new Ajax.Updater(
    { success: 'idListaSeleccionados' }, 
    url, 
    {
      method: 'post', 
      parameters: pars,
      onCreate: function() { notificadoresListaReservas(true, [$('idListaSeleccionados')]); },
      onComplete: function() { notificadoresListaReservas(false, [$('idListaSeleccionados')]); }
    });
}

function seleccionarReserva(codigo, habitacion, tarifa) {
    var url = 'buscador.html';
    var pars = 'evento=seleccionarReserva&codigoHotelSeleccionado=' + codigo + '&indiceHabitacion=' + habitacion + '&indiceTarifa=' + tarifa;
    var idFilaHotel = 'fila' + codigo;

    var myAjax = new Ajax.Updater(
      { success: 'idListaSeleccionados' },
      url,
      {
        method: 'post', 
        parameters: pars,
        onCreate: function() { notificadoresListaReservas(true, [$('idListaSeleccionados'), $(idFilaHotel)]); },
        onComplete: function() { notificadoresListaReservas(false, [$('idListaSeleccionados'), $(idFilaHotel)]); }
      });
}

function descartarReserva(codigo) {
  var url = 'buscador.html';
  var pars = 'evento=deseleccionarReserva&codigoHotelSeleccionado=' + codigo;
  var myAjax = new Ajax.Updater(
    { success: 'idListaSeleccionados' },
    url, 
    {
      method: 'post', 
      parameters: pars,
      onCreate: function(){ notificadoresListaReservas(true, [$('idListaSeleccionados')]); },
      onComplete: function(){ notificadoresListaReservas(false, [$('idListaSeleccionados')]); }
    });
}

function actualizarEstado(codigo) {
    var url = 'buscador.html';
    var pars = 'evento=conmutarDespliegue&codigoHotelSeleccionado=' + codigo;
    var myAjax = new Ajax.Request(
      url, 
      {
        method: 'post', 
        parameters: pars
      });
}

/**
 * Genera una petición de mapa estático de google en caso de error en la foto de un hotel.
 * Si el hotel no posee datos de geolocalización no se realiza petición.
 * @param latitud latitud del punto
 * @param lng     longitud
 * @param clave   clave API GMap
 * @param opciones parámetros opcionales:
 *        { tipoMapa : tipo de mapa, p.d. hybrid (@see http://code.google.com/intl/es-ES/apis/maps/documentation/staticmaps/#MapTypes),
 *          ancho    : ancho de la imagen solicitada, p.d. 150px,
 *          alto     : alto de la imagen solicitada, p.d. 110px,
 *          formato  : formato de imagen, p.d. png32 (@see http://code.google.com/intl/es-ES/apis/maps/documentation/staticmaps/#ImageFormats),
 *          hl       : lenguaje de las leyendas del mapa, p.d. es_ES,
 *          zoom     : nivel de acercamiento, p.d. 16,
 *          tipoMarca: tamaño del marcador, p.d. tiny (@see http://code.google.com/intl/es-ES/apis/maps/documentation/staticmaps/#Markers),
 *          imgError : imagen a mostrar en caso de error
 *        }
 * @return URL de petición de mapa estático
 */
function getGoogleStaticMap(lat, lng, clave, opciones)
{
  var opcs = Object.extend({ tipoMapa : "hybrid",
                             ancho    : "150",
                             alto     : "110",
                             formato  : "png32",
                             htl      : "es_ES",
                             zoom     : 16,
                             tipoMarca: "tiny",
                             imgError : "images/vacio.jpg"
                           }, opciones);

  if (Object.isNumber(lat) && Object.isNumber(lng) && isNotBlank(clave) && (lat != 0) && (lng != 0))
  {
    var url = "http://maps.google.com/staticmap?sensor=false";
    url += "&markers=" + lat + "," + lng;
    url += "&size=" + opcs.ancho + "x" + opcs.alto;
    url += "&maptype=" + opcs.tipoMapa;
    url += "&format=" + opcs.formato;
    url += "&zoom=" + opcs.zoom;
    url += "&key=" + clave;
    return url;
  }
  else
    return opcs.imgError;
}

/**
 * Construye la ruta para cargar la ayuda dependiendo del contexto.
 * Detecta si se trata de un contexto de aplicación (desarrollo) o un contexto raíz y carga la
 * página de ayuda correspondiente.
 */
function ayuda()
{
  var toc = new Hash({ "gestionHoteles.gestion"          : "node1", 
                       "gestionOfertas.gestion"          : "node2",
                       "gestionModelosNewsLetter.gestion": "node3",
                       "gestionReservas.gestion"         : "node4",
                       "gestionPagos.gestion"            : "node5",
                       "gestionLiquidaciones.gestion"    : "node6",
                       "gestionAdministradores.gestion"  : "node7",
                       "gestionColaboradores.gestion"    : "node7",
                       "gestionAfiliados.gestion"        : "node7",
                       "gestionClientes.gestion"         : "node8",
                       "gestionIndice.gestion"           : "node9",
                       "gestionDatosPersonales.gestion"  : "node10",
                       "gestionCambiarClave.gestion"     : "node10",
                       "datosPersonales.coop"            : "node11",
                       "cambiarClave.coop"               : "node11",
                       "liquidacionesPendientes.coop"    : "node12",
                       "liquidacionesRealizadas.coop"    : "node12",
                       "datosPersonales.usr"             : "node13",
                       "cambiarClave.usr"                : "node13",
                       "reservas.usr"                    : "node14"});
  
  var esRaiz = window.location.pathname.search(/\/[^\/]*\/[^\/]*\/([^\/]*\..*)?/) == -1;
  var host = window.location.pathname.replace(/([^\/]*\/)([^\/]*\/)?([^\/]*)\..*/, "$1");
  var nodo   = toc.get(window.location.pathname.replace(/.*\/([^\/]*\..*)/, "$1"));
  var pagina = host + "ayuda/@.htm".replace("@", nodo);
  var ventana = new lightwindow();

  ventana.activateWindow({ href:   pagina,
                           title:  document.title + " - Ayuda",
                           author: "Hotelmecum &copy; Copyright 2009",
                           height: 600,
                           width:  950
                         });
}
