$(document).ready(hotelSearchInit);

var childCount = 3;

// IE 6 bug fix
function buildStore(from, to, afterBuild) {

  setTimeout(function() {
    var store = new Array();
    for(var i = from; i <= to; i++) {
      var obj = new Object();
      obj.value = i;
      obj.label = i;
      store.push(obj);
    }
    afterBuild(store);
  }, 100);
}


function updateTotalPaxes() {
  var rooms = parseInt($('#rooms-hidden')[0].value);
  var adults = 0;
  var childs = 0;
  var babys = 0;
  for(var i = 1; i <= rooms; i++) {
      adults += parseInt($('#adults_' + i)[0].value);
      childs += parseInt($('#childs_' + i)[0].value);
      babys += parseInt($('#babys_' + i)[0].value);
  }
  $('#adults-hidden')[0].value = adults;
  $('#childs-hidden')[0].value = childs;
  $('#babys-hidden')[0].value = babys;
}

function hotelSearchInit() {

  function bodyClick(event, ui) {
    var id = event.target.id;
    if(id != 'zone-button')
      $('#zone').autocomplete('close');
    if(id != 'hotel-button')
      $('#hotel').autocomplete('close');
    if(id != 'nights-button')
      $('#nights').autocomplete('close');
    if(id != 'rooms-button')
      $('#rooms').autocomplete('close');

    var roomLines = $('.hotel-search-room-line');
    for(var i = 1; i <= roomLines.length; i++) {
      if(id != 'adults_' + i + '-button')
        $('#adults_' + i).autocomplete('close');
      if(id != 'childs_' + i + '-button')
        $('#childs_' + i).autocomplete('close');
      for(var j = 1; j <= childCount; j++) {
        if(id != 'pax-age_' + i + '_' + j +'-button')
          $('#pax-age_' + i + '_' + j).autocomplete('close');
      }
      if(id != 'babys_' + i + '-button')
        $('#babys_' + i).autocomplete('close');
    }
  }

  $('body').bind('click', function(event, ui) {
    bodyClick(event, ui);
  });

  /* zone & hotel */
  initZones();
  var hotelCode = $('#hotel-hidden')[0].value;
  initHotels(null, hotelCode);

  /* checkin - checkout */
  $('#checkin').datepicker({ dateFormat: 'dd/mm/yy', 
                             minDate: '+0',
                             onSelect: function(dateText, inst) {
      var checkin = $('#checkin').datepicker('getDate');
      var minCheckout = checkin;
      minCheckout.setDate(checkin.getDate() + 1);
      $('#checkout').datepicker('option', 'minDate', minCheckout);

      updateNights();
    } 
  });
  $('#checkin-input img').click(function() {
    $('#checkin').datepicker('show');
  });
  if($('#checkin')[0].value == '')
    $('#checkin').datepicker('setDate', '+1');
  $('#checkout').datepicker({ dateFormat: 'dd/mm/yy', 
                              minDate: '+1', 
                              onSelect: function() {
      updateNights();
    }
  });
  if($('#checkout')[0].value == '')
    $('#checkout').datepicker('setDate', '+2');
  $('#checkout-input img').click(function() {
    $('#checkout').datepicker('show');
  });

  /* nights */

  var nightsLabels = $('#nights-input span');
 
  buildStore(1, 30, function(store) { 
    $('#nights').autocomplete({
      minLength: 0,
      source: store,//['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
      select: function(event, ui) {
        var value = ui.item.value;
        $('#nights-hidden')[0].value = value;
        $('#nights')[0].value = value == 1 ? value + ' ' + $(nightsLabels[0]).text() : value + ' ' + $(nightsLabels[1]).text();

        var checkin = $('#checkin').datepicker('getDate');
        var checkout = checkin;
        checkout.setDate(checkout.getDate() + parseInt(value));
        $('#checkout').datepicker('setDate', checkout);

        return false;
      }
    });
  });
  var nights = $('#nights-hidden')[0].value;
  if(nights == '') {
    nights = 1;
    $('#nights-hidden')[0].value = nights;
  }
  $('#nights')[0].value = nights == 1 ? nights + ' ' + $(nightsLabels[0]).text() : nights + ' ' + $(nightsLabels[1]).text();

  $('#nights-button').click(function(event, ui) {
    $('#nights').autocomplete('search', '');
  });

  /* rooms */

  var roomLabels = $('#rooms-input span');
  buildStore(1, 5, function(store) { 
    $('#rooms').autocomplete({
      minLength: 0,
      source: store,//['1', '2', '3', '4', '5'],
      select: function(event, ui) {
        var count = parseInt(ui.item.value);
        updateRooms(count);

        $('#rooms-hidden')[0].value = count;
        $('#rooms')[0].value = count == 1 ? count + ' ' + $(roomLabels[0]).text() : count + ' ' + $(roomLabels[1]).text();

        return false;
      }
    });
  });
  var rooms = $('#rooms-hidden')[0].value;
  if(rooms == '') {
    rooms = 1;
    $('#rooms-hidden')[0].value = rooms;
  }
  $('#rooms')[0].value = rooms == 1 ? rooms + ' ' + $(roomLabels[0]).text() : rooms + ' ' + $(roomLabels[1]).text();

 
  $('#rooms-button').click(function(event, ui) {
    $('#rooms').autocomplete('search', '');
  });

  /* paxes */
  var roomCount = parseInt(rooms);
  for(var i = 1; i <= roomCount; i++)
    initPaxesLine(i);

  /* search button */
  $('#hotel-search-button-image').click(function(event, ui) {
    var form = document.getElementById('hotel-search');
    form.submit();
  });

  /* promocode */
  $('#hotel-search-promocode-text').click(function() {
	  $('#hotel-search-promocode-input').show();
  });
  
}

function initPaxesLine(index) {

  buildStore(1, 5, function(store) { 
    $('#adults_' + index).autocomplete({
      minLength: 0,
      source: store//['1', '2', '3', '4', '5']
    });
  });
    
  $('#adults_' + index + '-button').click(function(event, ui) {
    $('#adults_' + index).autocomplete('search', '');
  });
 
  buildStore(0, childCount, function(store) { 
    $('#childs_' + index).autocomplete({
      minLength: 0,
      source: store,//['0', '1', '2', '3', '4', '5'],
      select: function(event, ui) {
        var count = parseInt(ui.item.value);
        updateAges(index, count);

        return true;
      }
    });
  });
    
  $('#childs_' + index + '-button').click(function(event, ui) {
    $('#childs_' + index).autocomplete('search', '');
  });

  for(var i = 1; i <= childCount; i++)
    initPaxAge(index, i);

  buildStore(0, 2, function(store) { 
    $('#babys_' + index).autocomplete({
      minLength: 0,
      source: store//['0', '1', '2', '3', '4', '5']
    });
  });

  $('#babys_' + index + '-button').click(function(event, ui) {
    $('#babys_' + index).autocomplete('search', '');
  });

}

function initPaxAge(index, count) {

  buildStore(3, 14, function(store) {
    $('#pax-age_' + index + '_' + count).autocomplete({
      minLength: 0,
      source: store
    });
  });

  $('#pax-age_' + index + '_' + count).bind("autocompleteopen", function(event, ui) {
    $(".ui-autocomplete.ui-menu").width(40);
  });
   
  $('#pax-age_'+ index + '_' + count + '-button').click(function(event, ui) {
    $('#pax-age_' + index + '_' + count).autocomplete('search', '');
  });

}

function updateAges(index, count) {
		
  if(count == 0) {
    $('#pax-ages_' + index).hide();
  } else {
    $('#pax-ages_' + index).show();
    for(var i = 1; i <= childCount; i++) {
      if(i <= count)
        $('#pax-age-input_' + index + '_' + i).show();
      else
        $('#pax-age-input_' + index + '_' + i).hide();
    }
  }
  
}

function updateRooms(count) {

  var roomLines = $('.hotel-search-room-line');
  var content = $('#hotel-search-body1-content')[0];

  if(roomLines.length > count) {

    for(var i = 0; i < roomLines.length; i++) {
      var roomLine = roomLines[i];
      if(i >= count)
        content.removeChild(roomLine);
    }

  } else {

  var roomCount = 0;
  for(var i = 0; i < roomLines.length; i++) {
    var roomLine = roomLines[i];
    roomCount++;
  }

  for(var i = roomCount + 1; i <= count; i++)
    content.appendChild(buildRoomLine(i));
  }
  
}

function buildRoomLine(index) {

  var roomLine = document.createElement('div');
  roomLine.className = 'hotel-search-room-line';

  roomLine.appendChild(buildRoomLineText(index));
  
  roomLine.appendChild(buildRoomLineInputs(index));

  return roomLine;
}

function buildRoomLineText(index) {

  var roomLabels = $('#rooms-input span');
  var lineText = document.createElement('div');
  lineText.className = 'hotel-search-room-line-text';   
  var span = document.createElement('span');
  lineText.appendChild(span);
  span.appendChild(document.createTextNode($(roomLabels[0]).text() + ' ' + index)); 
  var img = document.createElement('img');
  lineText.appendChild(img);
  img.src = '/img/hotel-search-room-sep.png';

  return lineText;
}

function buildRoomLineInputs(index) {

  var lineInputs = document.createElement('div');
  lineInputs.className = 'hotel-search-room-line-inputs';

  lineInputs.appendChild(buildRoomInput($('#adults-input_1 span').text(), 'adults', '2', index));
  lineInputs.appendChild(buildRoomInput($('#childs-input_1 span').text(), 'childs', '0', index));
  lineInputs.appendChild(buildAgesInput($('#pax-ages_1 span').text(), index));

  lineInputs.appendChild(buildRoomInput($('#babys-input_1 span').text(), 'babys', '0', index));

  var separator = document.createElement('div');
  lineInputs.appendChild(separator);
  separator.appendChild(document.createTextNode(' ')); 
  separator.style.clear = 'both';
  separator.style.lineHeight = '1px';
 
  return lineInputs;
}

function buildRoomInput(label, name, value, index) {

  var roomInput = document.createElement('div');   
  if(name == 'adults')
    roomInput.className = 'hotel-search-room-input-first-child';
  else
    roomInput.className = 'hotel-search-room-input';
  var inputText = document.createElement('div');
  inputText.className = 'hotel-search-room-input-text';
  inputText.appendChild(document.createTextNode(label));
  roomInput.appendChild(inputText);
  var paxInput = document.createElement('div');
  paxInput.className = 'pax-input';
  var input = document.createElement('input');
  input.name = name + '_' + index;
  input.value = value;
  input.id = name + '_' + index;
  input.readOnly = true;
  paxInput.appendChild(input);
  var img = document.createElement('img');
  img.src = '/img/black-arrow-down.png';
  img.id = name + '_' + index + '-button';
  paxInput.appendChild(img);
  roomInput.appendChild(paxInput); 

  var source = null;
  if (name == 'adults')
    source = ['1', '2', '3', '4', '5'];
  if (name == 'childs')
    source = ['0', '1', '2', '3', '4', '5'];
  if (name == 'babys')
    source = ['0', '1', '2'];

  $(input).autocomplete({
    minLength: 0,
    source: source,
    select: function(event, ui) {
      if(name == 'childs') {
        var count = parseInt(ui.item.value);
        updateAges(index, count);
      }
      return true;
    }
  });
    
  $(img).click(function(event, ui) {
    $(input).autocomplete('search', '');
  });

  return roomInput;
}

function buildAgesInput(label, index) {

  function initPaxAge(input, button) {

    buildStore(2, 14, function(store) {
      $(input).autocomplete({
        minLength: 0,
        source: store
      });
    });

    $(input).bind("autocompleteopen", function(event, ui) {
      $(".ui-autocomplete.ui-menu").width(40);
    });
   
    $(button).click(function(event, ui) {
      $(input).autocomplete('search', '');
    });

  } 

  var roomInput = document.createElement('div');   
  roomInput.className = 'hotel-search-room-age-input hidden';
  roomInput.id = 'pax-ages_' + index;
  var inputText = document.createElement('div');
  inputText.className = 'hotel-search-room-age-input-text';
  inputText.appendChild(document.createTextNode(label));
  roomInput.appendChild(inputText);

  for(var i = 1; i <= childCount; i++) {

    var paxAgeInput = document.createElement('div');
    paxAgeInput.className = 'pax-age-input';
    paxAgeInput.id = 'pax-age-input_' + index + '_' + i;
    var input = document.createElement('input');
    input.name = 'age_' + index + '_' + i;
    input.value = '3';
    input.id = 'pax-age_' + index + '_' + i;
    input.readOnly = true;
    paxAgeInput.appendChild(input);
    var img = document.createElement('img');
    img.src = '/img/black-arrow-down0.png';
    img.id = 'pax-age_' + index + '_' + i + '-button';
    paxAgeInput.appendChild(img);
    roomInput.appendChild(paxAgeInput); 

    initPaxAge(input, img);
  }

  return roomInput;
}


function initZones() {

  listZones(function(zones) {

    $('#zone').autocomplete({
      minLength: 0,
      source: zones,
      select: function(event, ui) {
        var value = ui.item.value;
        var label = ui.item.label;
        $('#zone-hidden')[0].value = value;
        $('#zone')[0].value = label;

        initHotels(value, null);

        return false;
      }
    });

    var zone = $('#zone-hidden')[0].value;
    if(zone != '') {
      var label = null;
      for(var i = 0; i < zones.length && label == null; i++)
        if(zones[i].value == zone)
          label = zones[i].label;
      $('#zone')[0].value = label;
      initHotels(zone, null);
    }

  });

  $('#zone-button').click(function(event, ui) {
    $('#zone').autocomplete('search', '');
  });

}

function initHotels(zone, hotel) {

  if(zone == '')
    zone = null;

  $('#hotel')[0].value = 'Todos los hoteles';
  $('#hotel-hidden')[0].value = '';

  listHotels(zone, function(hotels) {
          
    $('#hotel').autocomplete({
      minLength: 0,
      source: hotels,
      select: function(event, ui) {
        var value = ui.item.value;
        var label = ui.item.label;
        $('#hotel-hidden')[0].value = value;
        $('#hotel')[0].value = label;

        return false;
      }
    });

    $('#hotel-button').click(function(event, ui) {
      $('#hotel').autocomplete('search', '');
    });

    if(hotel != null && hotel != '') {
      var label = null;
      for(var i = 0; i < hotels.length && label == null; i++)
        if(hotels[i].value == hotel)
          label = hotels[i].label;
      $('#hotel')[0].value = label;
      $('#hotel-hidden')[0].value = hotel;
    }

   });

}

function listZones(afterLoad) {

  $.ajax({
    url: '/list-zones',
    success: function(data) {

      var zones = new Array();
      var noZone = new Object();
      zones.push(noZone);
      noZone.value = '';
      noZone.label = $('#zone-input span').text();
      var zoneList = data.getElementsByTagName('zone');
      for(var i = 0; i < zoneList.length; i++) {
        var zone = new Object();
        zones.push(zone);
        zone['value'] = zoneList[i].getAttribute('id');
        var zoneNameList = zoneList[i].getElementsByTagName('name');
        var name = null;
        for(var j = 0; j < zoneNameList.length && name == null; j++)
          if(zoneNameList[j].getAttribute('lang') == 'es')
            name = zoneNameList[j].firstChild.nodeValue;
        zone['label'] = name;
      }

      afterLoad(zones);      

    }
  });  
}

function listHotels(zoneId, afterLoad) {

  $.ajax({
    url: '/list-hotels',
    success: function(data) {

      var hotels = new Array();
      var noHotel = new Object();
      hotels.push(noHotel);
      noHotel.value = '';
      noHotel.label = $('#hotel-input span').text();
      var hotelList = data.getElementsByTagName('hotel');
      for(var i = 0; i < hotelList.length; i++) {
        var zoneElement = hotelList[i].getElementsByTagName('zone')[0];
        if(zoneId != null && zoneElement.getAttribute('id') != zoneId)
          continue;
        var hotel = new Object();
        hotels.push(hotel);
        hotel['value'] = hotelList[i].getAttribute('id');
        var name = hotelList[i].getElementsByTagName('name')[0].firstChild.nodeValue;
        hotel['label'] = name;
      }

      afterLoad(hotels);      

    }
  }); 

}

function updateNights() {
  
  var checkin = $('#checkin').datepicker('getDate');
  var checkout = $('#checkout').datepicker('getDate');

  var nights = Math.round((checkout.getTime() - checkin.getTime()) / (1000 * 3600 * 24));

  var nightsLabels = $('#nights-input span');
  $('#nights')[0].value = nights == 1 ? nights + ' ' + $(nightsLabels[0]).text() : nights + ' ' + $(nightsLabels[1]).text();
  $('#nights-hidden')[0].value = nights;
}

function showtimetable() {
	if(document.getElementById('flotante').style.visibility == 'visible') {
		document.getElementById('flotante').style.visibility = 'hidden';
	} else {
		document.getElementById('flotante').style.visibility = 'visible';
	}
}


