$(document).ready(function(){
  // Banners de la home
  $('#adServerHome').cycle({
    fx: 'fade',
    timeout: 7000,     
    speed: 1000
	});
  
  // Ofertas de home y canales; IE6 no soporta PNG transparente
  if (!($.browser.msie && $.browser.version < 7)) {
    $('.banner_img').css('position', 'relative');
    $('.banner_img a').prepend('<img src="/images/mascara_oferta.png" class="banner_mascara" />');
  }

  // Números de teléfono
  $('#telf-intl').hover(
    function() { $('#popListaPaises').show(); },
    function() { $('#popListaPaises').hide(); }
  );
  
  // Carrusel de hoteles
  if ($('#hoteles_canal').length > 0) {
    $('#hoteles_listado_scroll li').each(function(i) {
      if (i % 9 == 0) {
        $('#hoteles_canal #hoteles_listado').append('<ul></ul>');
      }
      $('#hoteles_canal #hoteles_listado ul:last').append($(this));
    });
    $('#hoteles_listado_scroll').remove();
    $('#hoteles_canal #hoteles_listado').css({'overflow':'visible','overflow-x':'visible','overflow-y':'visible'});
    $('#hoteles_canal #hoteles_listado').carouFredSel({
      direction: 'left',
      items: {
        visible: 1
      },
      scroll: {
        items: 1,
        duration: 5000,
        pauseOnHover: true
      },
      auto: {
        pauseDuration: 3000
      }
    });
  }
  
  // Selección de zona y servicios en listado de hoteles, simulando un combo real
  $('#lZonas').click(function(e) {
    e.stopPropagation();
    $('#lZonas ul').toggle();
  });
  $('#lServicios').click(function(e) {
    e.stopPropagation();
    $('#lServicios ul').toggle();
  });

  // Galerías de imágenes
  $("a[rel^='prettyPhoto']").prettyPhoto({
    show_title: false
  });
  
  // Avanzar y retroceder fotos en las fotos de hoteles
  muestraFoto(0);
  $('#bot_foto_menos').click(function() {
    var foto = (foto_actual <= 0) ? fotos_totales - 1 : foto_actual - 1;
    muestraFoto(foto);
  });
  $('#bot_foto_mas').click(function() {
    var foto = (foto_actual >= fotos_totales-1) ? 0 : foto_actual + 1;
    muestraFoto(foto);
  });
  $('#menu_fotos ul li').click(function() {
    var cat = $(this).attr('id').slice(9);
    var i;
    var foto = 0;
    for (i = 0; i < categorias_fotos.length && i < cat; ++i) {
      foto += categorias_fotos[i];
    }
    muestraFoto(foto);
  });
  
  // Mapas de Google Maps; he intentado utilizar algún plugin de jQuery, pero sin éxito
  if (typeof GBrowserIsCompatible == 'function' && GBrowserIsCompatible()) {
    if (typeof cargar_mapa_hotel == 'function') {
      cargar_mapa_hotel();
    }
    if (typeof cargar_mapa_kml == 'function') {
      cargar_mapa_kml();
    }
  } 

  // Envío de CV
  $('#btnEnviarCV').click(function() {
    $('#trabaja').submit();
  });
  
  // Formulario de reserva. Selección de zona; hay que mostrar los hoteles correspondientes
  $('#areaone').change(function() {
    // Obtener la ubicación seleccionada
    var id_ubicacion = $('#areaone').val();
    // Vacío el combo de hoteles
    $('#codigoHotel').removeOption(/./);
    // Ahora hay que rellenar el combo con los hoteles de la ubicación seleccionada
    for (var i = 0; i < hoteles.length; ++i) {
      if (hoteles[i][0] == id_ubicacion) {
        $('#codigoHotel').addOption(hoteles[i][1],hoteles[i][2]);
      }
    }
    // Si no hay ninguna opción, poner una por defecto
    if ($('#codigoHotel option').length == 0) {
      $('#codigoHotel').addOption(0,SELEC_ZONA);
    }
  });
  
  // Formulario de reservas. Selección de fechas
  $('#en_dia,#en_mesano,#sa_dia,#sa_mesano').change(function(){
    mostrar_noches();
  });
  var idioma = (IDIOMA == 'en') ? 'en-GB' : IDIOMA;
  $.datepicker.setDefaults($.datepicker.regional[idioma]);
  $('.cal_datepicker').datepicker({
    dateFormat: 'dd/mm/yy',
    minDate: 0,
    onSelect: fecha_seleccionada
  });
  $('#img_cal_en').click(function(e) {
    e.stopPropagation();
    $('#cal_sa').hide();
    $('#cal_en').toggle();
  });
  $('#img_cal_sa').click(function(e) {
    e.stopPropagation();
    $('#cal_en').hide();
    $('#cal_sa').toggle();
  });
  $('.cal_datepicker').click(function(e) {
    e.stopPropagation();
  });
  if ($.browser.msie && $.browser.version < 7) {
    // Corrección de bug en IE6: http://www.javascriptjunkie.com/?p=5
    $('.cal_datepicker').prepend('<iframe marginwidth="0" marginheight="0" align="bottom" scrolling="no" frameborder="0" style="position: absolute; width: 100%; height: 100%; z-index: -1; display:block; filter:alpha(opacity=0);"></iframe>')
  }

  
  // Formulario de reserva. Expansión de combos de habitaciones
  $('#numHabitaciones,#adultsRoom1').change(function() {
    var nhabs = parseInt($('#numHabitaciones').val());
    // Mostrar los combos con las habitaciones
    switch (nhabs) {
      case 1:
        $('#txtHab1,#hab1,#hab2,#hab3,#hab4').hide();
        break;
      case 2:
        $('#txtHab1,#hab1').show();
        $('#hab2,#hab3,#hab4').hide();
        break;
      case 3:
        $('#txtHab1,#hab1,#hab2').show();
        $('#hab3,#hab4').hide();
        break;
      case 4:
        $('#txtHab1,#hab1,#hab2,#hab3').show();
        $('#hab4').hide();
        break;
      case 5:
        $('#txtHab1,#hab1,#hab2,#hab3,#hab4').show();
        break;
    }
    for (var i = nhabs + 1; i <= 4; ++i) {
      displayChildren(i,0);
      $('#childrenRoom'+i).selectOptions(0);
    }
  });
  
  // Formulario de reserva. Expansion de combos de edades de niños; no sé muy bien como meterlo bien en un bucle
  $('#childrenRoom1').change(function() {
    displayChildren(1,$(this).val());
  });
  $('#childrenRoom2').change(function() {
    displayChildren(2,$(this).val());
  });
  $('#childrenRoom3').change(function() {
    displayChildren(3,$(this).val());
  });
  $('#childrenRoom4').change(function() {
    displayChildren(4,$(this).val());
  });
  $('#childrenRoom5').change(function() {
    displayChildren(5,$(this).val());
  });
  
  // Formulario de reserva. Submit
  $('#btnBuscar').click(function() {
    // Comprobar que haya un hotel seleccionado
    if ($('#codigoHotel').val() == 0) {
      alert(ERROR_SEL);
      return;
    }
    // Comprobar las fechas
    var en_mesano = $('#en_mesano').val().split('-');
    var en = new Date(en_mesano[1],en_mesano[0],$('#en_dia').val());
    var sa_mesano = $('#sa_mesano').val().split('-');
    var sa = new Date(sa_mesano[1],sa_mesano[0],$('#sa_dia').val());
    if (en > sa) {
      alert(ERROR_FECHA);
      return;
    }
    // Comprobar que las edades estén seleccionadas
    if (!compruebaEdades()) {
      alert(ERROR_EDADES_NINOS);
      return;
    }
    // Si todo ha ido bien, preparar los valores ocultos y enviar el formulario
    setBookingParams();
    $('#searchForm').submit();
  });
  
  // Todo aquello que se ha de cerrar, al hacer click fuera del elemento
  $('body').click(function() {
     $('#lZonas ul,#lServicios ul,#cal_en,#cal_sa').hide();
  });

});

function categoriaFoto(foto) {
  var acum = 0;
  var cat;
  for (cat = 0; cat < categorias_fotos.length; ++cat) {
    acum += categorias_fotos[cat];
    if (foto < acum) {
      break;
    }
  }
  return cat;
}

function muestraFoto(foto) {
  if (foto < 0 || foto >= fotos_totales) {
    return;
  }
  // Ocultar foto actual
  $('#foto' + foto_actual).hide();
  var cat = categoriaFoto(foto_actual);
  $('#categoria' + cat).removeClass('selected_menu_fotos');
  // Mostrar nueva foto
  foto_actual = foto;
  $('#foto' + foto_actual).show();
  cat = categoriaFoto(foto_actual);
  $('#categoria' + cat).addClass('selected_menu_fotos');
}

function mapaHotel(id, lat, lon, zoom) {
  // Mapa con controles
  var map = new GMap2(document.getElementById(id));
  map.addControl(new GSmallMapControl());
  map.addControl(new GMapTypeControl());
  // Centrarlo en el hotel
  var hotel = new GLatLng(lat, lon);
  map.setCenter(hotel, zoom);
  // Marcador en el hotel
  var icon = new GIcon();
  icon.image = '/images/gmarker.png';
  icon.iconSize=new GSize(22,20);
  icon.iconAnchor=new GPoint(11,20);
  icon.infoWindowAnchor=new GPoint(11,0);
  var marker = new GMarker(hotel,icon);
  map.addOverlay(marker);
}

function mapaKML(id, lat, lon, zoom, kml) {
  // Mapa con controles
  var map = new GMap2(document.getElementById(id));
  map.addControl(new GSmallMapControl());
  map.addControl(new GMapTypeControl());
  map.setCenter(new GLatLng(lat, lon), zoom);
  // Cargar el KML correspondiente
  var gx = new GGeoXml(kml);
  map.addOverlay(gx);
}

function displayChildren(habitacion, ninos){
  for (var i = 0; i <= 4; ++i) {
    if (i > ninos) {
      $('#child'+i+'Room'+habitacion).selectOptions(0);
      $('#contEdadChild'+habitacion+''+i).hide();
    }
    else {
      $('#contEdadChild'+habitacion+''+i).show();
    }
  }
  if (ninos == 0) {
    $('#habChildren'+habitacion).hide();
  }
  else {
    $('#habChildren'+habitacion).show();
  }  
}

function compruebaEdades() {
  var nhabs = $('#numHabitaciones').val();
  for (var h = 1; h <= nhabs; ++h) {
    var nchild = $('#childrenRoom'+h).val();
    if (nchild != '') {
      for (var c = 1; c <= nchild; ++c) {
        var age = $('#child'+c+'Room'+h).val();
        if (age == '') {
          return false;
        }
      }
    }
  }
  return true;
}

function fecha_seleccionada(dateText, inst) {
  var fecha = dateText.split('/');
  var id = $(this).attr('id');
  if (id == 'cal_en') {
    $('#en_dia').selectOptions(fecha[0]);
    $('#en_mesano').selectOptions(fecha[1] + '-' + fecha[2]);
  }
  else if (id = 'cal_sa') {
    $('#sa_dia').selectOptions(fecha[0]);
    $('#sa_mesano').selectOptions(fecha[1] + '-' + fecha[2]);
  }
  $(this).hide();
  mostrar_noches();
}

function mostrar_noches() {
  var en_mesano = $('#en_mesano').val().split('-');
  var en = new Date(en_mesano[1],en_mesano[0],$('#en_dia').val());
  var sa_mesano = $('#sa_mesano').val().split('-');
  var sa = new Date(sa_mesano[1],sa_mesano[0],$('#sa_dia').val());
  if (en < sa) {
    var diff = new Date();
    diff.setTime(Math.abs(sa.getTime() - en.getTime()));
    var timediff = diff.getTime();
    var dias = Math.floor(timediff / (1000 * 60 * 60 * 24));
    $('#capanoches').html(dias + ' ' + NOCHES);
    $('#noches').val(dias);
  }
  else {
    $('#capanoches').html('');
    $('#noches').val(0);
  }
}

// Ante la falta de documentación, este código no es el ideal, ni de lejos
function setBookingParams() {
  var entrada = $('#en_dia').val() + "-" + $('#en_mesano').val();
  var spl_entrada	= entrada.split("-");
  var fechaEntrada = new Date(new Number(spl_entrada[2]),new Number(spl_entrada[1])-1,new Number(spl_entrada[0]),0,0,0);
  var sdia = fechaEntrada.getDate();
  var smes = fechaEntrada.getMonth()+1;
  var sanyo = fechaEntrada.getFullYear();
  if (sdia<10) 
    sdia = "0"+sdia;
  if (smes<10) 
    smes="0"+smes;
  $('#dia').val(sdia);
  $('#mes').val(smes);
  $('#anio').val(fechaEntrada.getFullYear());
  
  var en_aux = $('#en_mesano').val();
  en_aux = en_aux.split("-"); 

  $('#booking_dia').val($('#en_dia').val());
  $('#booking_mes').val(en_aux[0]);
  $('#booking_anyo').val(en_aux[1]);
  $('#booking_noches').val($('#noches').val());
  $('#booking_codHotel').val($('#codigoHotel').val());

  $('#dia_en').val($('#en_dia').val());
  $('#mes_en').val(en_aux[0]);
  $('#anyo_en').val(en_aux[1]);
  $('#dia').val($('#en_dia').val());
  $('#mes').val(en_aux[0]);
  $('#anio').val(en_aux[1]);
  $('#date1').val($('#en_dia').val() + '/' + en_aux[0] + '/' + en_aux[1]);

  var sa_aux = $('#sa_mesano').val();
  sa_aux = sa_aux.split("-"); 
  $('#dia_sa').val($('#sa_dia').val());
  $('#mes_sa').val(sa_aux[0]);
  $('#anyo_sa').val(sa_aux[1]);
  $('#date2').val($('#sa_dia').val() + '/' + sa_aux[0] + '/' + sa_aux[1]);
  
  $('#codHotel').val($('#codigoHotel').val());
  $('#idPartner').val('MARCA_' + $('#codigoHotel').val());
}

