$(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 = 0; 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);
  });

 /* hotel */
  var hotelCode = 75;

  
  /* 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();
	expandForm();
  });

}

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'],
      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 = 0; i < childCount; i++)
    initPaxAge(index, i);

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

  $('#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 = 0; i < childCount; i++) {
      if(i < count)
        $('#pax-age-input_' + index + '_' + i).show();
      else
        $('#pax-age-input_' + index + '_' + i).hide();
    }
  }
  expandForm()
}

function updateRooms(count) {

  var roomFieldset = $('.hotel-search-room-fieldset');
  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));
	//content.appendChild(buildRoomLineFieldset(i));
  }
  expandForm()
}

function buildRoomLineFieldset(index) {

	  var roomFieldset = document.createElement('fieldset');
	  roomFieldset.className = 'hotel-search-room-fieldset';
	  
	  roomFieldset.appendChild(buildRoomLineDiv(index));

	  return roomFieldset;
	}

function buildRoomLine(index) { //Div

  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/rect.png';//'/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($('#offer-js-text_AGE').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/arrow.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'];
  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;
  roomInput.style.margin = '0px 0px 0px 7px';
  roomInput.style.width = '50px';
  roomInput.style.height = 'auto';
  roomInput.style.cssFloat = 'left';
  roomInput.style.display  = 'none';
  
  var inputText = document.createElement('div');
    
  inputText.className = 'hotel-search-room-age-input-text';
  inputText.appendChild(document.createTextNode(label));
  roomInput.appendChild(inputText);

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

    var paxAgeInput = document.createElement('div');
    paxAgeInput.className = 'pax-age-input';
    paxAgeInput.id = 'pax-age-input_' + index + '_' + i;
    paxAgeInput.style.display = 'block';
      var i1 = i + 1;
    var input = document.createElement('input');
    input.name = 'age_' + index + '_' + i1;
    input.value = '3';
    input.id = 'pax-age_' + index + '_' + i;
    input.readOnly = true;
    
    var styleInput = document.createAttribute("style");
    styleInput.value = "border: 0 none; color:#666666; float:left; font-size:90%; height: 16px; margin: 0px; width: 23px;";
    input.setAttributeNode(styleInput);
    
    paxAgeInput.appendChild(input);

    var img = document.createElement('img');
    img.src = '/img/arrow.png';
    img.id = 'pax-age_' + index + '_' + i + '-button';
    paxAgeInput.appendChild(img);
    roomInput.appendChild(paxAgeInput); 

    initPaxAge(input, img);
  }

  return roomInput;
}

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 expandForm(){
    /*if ($("div#formulariLft").height() > $("form#hotel-search").height()) {
       // $("form#hotel-search").height($("div#formulariLft").height())
    }else{*/
        $("div#formulariLft").height($("form#hotel-search").height()+35)
   // }	
}

