var $j = jQuery.noConflict();
var flag_hotel_full = true;
var emailCampo, suggestion, email;

$j(document).ready(function() {

  //habilitamos a consulta de hotelfull
  flag_hotel_full = true;
  isHotelFull();
  setInterval("isHotelFull()",500);

  $j('#book_country_code').change(function(){
    if( $j(this).val() == 1)
      $j('#fieldset_state').show();
    else {
      $j('#fieldset_state').hide();
      $j('#book_state').val('')
    }
  });
  $j('#book_country_code').trigger('change');

  //mensagem para agente de viagem
  $j('#btn_travel').click(function() {
    $j('#mensagemAgenteViagens').toggle();
    if( $j(this).text() == 'aqui' )
      $j(this).html('ocultar');
    else
      $j(this).html('aqui');
  });

  // Eventos Analytics
  $j('#book_name').blur(function() {
    if($j(this).val() != '')
      _gaq.push(['_trackPageview', '/reserva/campo/nome_cliente']);
  });

  $j('#book_last_name').blur(function() {
    if($j(this).val() != '')
      _gaq.push(['_trackPageview', '/reserva/campo/sobrenome_cliente']);
  });

  $j('#book_email').blur(function() {
    getEmailSuggestion($j(this).val());

    if($j('#book_email').val() != '')
      _gaq.push(['_trackPageview', '/reserva/campo/email1']);
  });

  $j('#book_confirmation_email').blur(function() {
    if($j('#book_confirmation_email').val() != '')
      _gaq.push(['_trackPageview', '/reserva/campo/email2']);
  });

  $j('#book_country_code').blur( function(){
    if($j(this).val() != '')
    _gaq.push(['_trackPageview', '/reserva/campo/country_code']);
  });

  $j('#book_state').blur( function(){
    if($j(this).val() != '')
    _gaq.push(['_trackPageview', '/reserva/campo/state']);
  });

  $j('#book_city').blur( function(){
    if($j(this).val() != '')
    _gaq.push(['_trackPageview', '/reserva/campo/city']);
  });

  $j('#book_phone').blur( function(){
    if($j(this).val() != '')
    _gaq.push(['_trackPageview', '/reserva/campo/phone']);
  });

  $j('#book_check_in').blur( function(){
    if($j(this).val() != '')
    _gaq.push(['_trackPageview', 'reserva/campo/data_entrada']);
  });

  $j('#book_check_out').blur( function(){
    if($j(this).val() != '')
    _gaq.push(['_trackPageview', '/reserva/campo/data_saida']);
  });


  $j('#btn_fixes_suggestion').click(function() {
    changeEmailField();
    _gaq.push(['_trackEvent', 'Sugestão de Email', 'Corrigir', 'Formulário de reserva']);

  });

  $j('#btn_ignore_suggestion').click(function() {
    sendInfoMessage();
    _gaq.push(['_trackEvent', 'Sugestão de Email', 'Ignorar', 'Formulário de reserva']);
  });

  $j('#form_book').submit(function() {
    isHotelFull();
    enviaForm();
  });

  $j('#a-add-conversation-room').click(function(){
    var room = createRoomElement();
    bindChangeCapacity();
    $j('#form_book fieldset.room tr[id^="block_room_"]:last').effect("highlight", {}, 500);
  });

  $j('.a-remove-conversation-room').click(function(){
    $j(this).parent('td').parent('tr').remove();
  });

  bindChangeCapacity();
  activeChild();

  /*Pré seleciona quarto no form de conversacao a partir de hash da url*/
  var hashes = window.location.hash.slice(1);

  if( hashes )
    selectRoomByHash( hashes );



});

function selectRoomByHash( hashes ){

    // JQuery Unserialize v1.0 by James Campbell
    $j.unserialise = function(Data){
      var Data = Data.split("&");
      var Serialised = new Array();
      Serialised[0] = new Array();
      Serialised[1] = new Array();
      $j.each(Data, function(){
          var Properties = this.split("=");
          //if(Properties[0].search('['))
          Serialised[0].push(Properties[0]);
          Serialised[1].push(Properties[1]);

      });
      return Serialised;
    };

    //serializamos as hashes capturadas
    hashes = $j.unserialise(hashes);

    //passamos por cada hash
    for( var i in hashes[0] ) {

      //se existir a hash quarto E o primeiro select de quartos existir a opção do quarto enviado pela hash
      if( (hashes[0][i] == 'quarto') && ($j('#book_rooms_0_room_id option[value='+hashes[1][i]+']').length) ){
        //pre selecionamos o quarto no primeiro select do form e disparamos o evento change para que seja atualizado o select de capacidade de hospedes
        $j('#book_rooms_0_room_id').val(hashes[1][i]);
        $j('#book_rooms_0_room_id').trigger('change');
      };
    }
}

function bindChangeCapacity(){

  $j('.change-capacity').change(function(){

    //loading do quarto
    var roomNumber = /([0-9]+)/.exec($j(this).attr('id'))[1];
    roomLoading(roomNumber, 'show' );

    var selectCapacity  = $j(this).parent('li').next().find('select.numberGuest');
    var room_id = $j(this).val();

    var capacity = changeRoomCapacity(room_id);
    if(capacity) {

      selectCapacity.children('option').remove();
      for(var i=1; i<=capacity; i++ ) {
        selectCapacity.append('<option value="'+i+'">'+i+'</option>');
      }
      $j(this).prev('input[type=hidden]').val(capacity);

      if( room_id == 0){
        selectCapacity.val( 1 );
      }else{
        selectCapacity.val( capacity );
      }

    }else {
      $j(this).parent('td').parent('tr').remove();
    }

    roomLoading(roomNumber, 'hide' );

  });
}

function activeChild(){

  $j('select.numberChildren').change( function(){
    var nc = $j( this ).val();

    //loading do quarto
    var roomNumber = /([0-9]+)/.exec($j(this).attr('id'))[1];
    roomLoading(roomNumber, 'show' );

    if (nc > 0 ) {
      $j( this ).parent().parent().next().children().show().find('ul').effect("highlight", {}, 300);

      var ulAges = $j( this ).parent().parent().parent().find('ul.children');
      var lioriginal = ulAges.find('li.children_age:first').clone();
      ulAges.find('li.children_age').remove();

      for(var i=0; i<nc; i++ ) {
        var item = lioriginal.clone();
        item.find('select').val(0);

        var ids = /([0-9]+)/.exec(item.find('select').attr('id'));
        var newClass = 'book_rooms_'+ids[1]+'_children_'+i+'_age';
        var newName = 'book[rooms]['+ids[1]+'][children]['+i+'][age]';

        item.find('select').attr('id', newClass );
        item.find('select').attr('class', newClass );
        item.find('select').attr('name', newName );
        item.find('select').prev().attr('for', newClass );

        ulAges.append( item );
      }

    }else{
      $j( this ).parent().parent().next().children().hide();
      // keep just one select when zero
      $j( this ).parent().parent().next().find('ul.children li.children_age:first').nextAll().remove();

    }

    roomLoading(roomNumber, 'hide' )

  });
}

function roomLoading(number, action ){
  var elem = $j('#block_room_'+number+' td > span:first');

  if( action == 'show')
  elem.addClass('formLoadingSign');
  else
  elem.removeClass('formLoadingSign');
}

function showLoading() {
  $j('#loading').css('display','block');
}

function hideLoading() {
  $j('#loading').css('display','none');
}

function enviaForm() {
  showLoading();
  return true;
}

  function isHotelFull() {

    //se já consultamos entao aguardamos alteração das datas para realizar outra consulta
    if(!flag_hotel_full)
      return true;

    var checkin  = $j('#book_check_in').val();
    var checkout = $j('#book_check_out').val();

    //se datas invalidas então desconsideramos a consulta
    if( checkin == 'dd/mm/aaaa' || checkout == 'dd/mm/aaaa' || checkin == '' || checkout == '')
      return true;

    //capturamos qual o id do hotel
    var urlhotel = $j('#form_book').attr('action');
    var e        = /hotel([0-9]+)/;

    if( e.exec(urlhotel)[1] !== null )
      var hotel_id = e.exec(urlhotel)[1];
    else
      return true

    //capturamos qual de qual site é a requisição
    var urlsite  = location.href;
    var eSite    = /(hotel-[a-z-]+)/;

    if( eSite.exec(urlsite) !== null )
      var site   = eSite.exec(urlsite)[1];
    else
      var site   = 'malapronta';

    $j.ajax({
      type: 'POST',
      url: "/webservice.php/ajax/isHotelFull",
      cache: false,
      data: ({hotel_id : hotel_id, checkin: checkin, checkout: checkout, site: site}),
      async: false,
      success: function(response){
        $j('#error_hotel_full_out').html(response);
        flag_hotel_full = false;                                //desabilitamos a consulta de hotelfull

        if( (typeof response === 'undefined') || (!response) || (response == '') )
          return true;

        $j('#error_hotel_full_out').dialog({
          title: 'Hotel lotado no período de '+checkin+' a '+checkout,
          closeOnEscape: true,
          width: 600,
          resizable: false,
          modal : true,
          buttons: {
            'Fechar': function() {
              $j(this).dialog('destroy');
            }
          },
          close: function(ev, ui) {
            $j(this).dialog('destroy');
          }
        });

        return false;
      },
      error: function(response) {                               //ocorreu erro na verificação então deixamos passar
        flag_hotel_full = false;
        return true;
      }
    });
  }

  function getEmailSuggestion(emailCampo) {
    var filtro=/^\S+@\S+\.[a-zA-Z]{2,4}$/;
    if ((email == '')||(email != emailCampo)) {
      email = emailCampo;
      $j.post("/webservice.php/ajax/validateEmail",{ str_email : email},
      function(rs){
        if((rs != "ok") && (filtro.test(rs)) ) {
          try {
            $j('#email_suggestion_value').html(rs);
            suggestion = rs;
            $j('#email_suggestion').show();
          }catch (e){
            alert('Ocorreu um ERRO ao carregar a sugestão de email.\n'+e)
          };
        }else {
          $j('#email_suggestion').hide();
        }
      }
      );
    }
  }

  function sendInfoMessage() {
    var filtro=/^\S+@\S+\.[a-zA-Z]{2,4}$/;
    $j('#email_suggestion').hide();
    if((email != suggestion)&&(suggestion != "")&&(email != "")&&
       (filtro.test(suggestion))&&(filtro.test(email))){
      var url = '/webservice.php/ajax/sendMailSuggestToAdmin';
      $j.post(url,{str_email:email, str_suggestion:suggestion});
    }
  }

  function changeEmailField() {
    var filtro=/^\S+@\S+\.[a-zA-Z]{2,4}$/;
    $j('#email_suggestion').hide();
    $j('#book_email').val(suggestion);
    if((email != suggestion)&&(suggestion != "")&&(email != "")&&
       (filtro.test(suggestion))&&(filtro.test(email))){
      var url = '/webservice.php/ajax/sendMailSuggestAccepted';
      $j.post(url,{str_email:email, str_suggestion:suggestion});
   }
  }

function createRoomElement() {
  var tr_block_room = $j("#tr-btn-add").prev('tr').clone();

  //capturamos qual o numero do bloco clonado para incrementarmos e add o seguinte
  var e             = /block_room_([0-9]+)/;

  if( e.exec(tr_block_room.attr('id'))[1] != null )
    var id_prev_block = parseInt(e.exec(tr_block_room.attr('id'))[1]);
  else
    return false

  var id_next_block = parseInt(id_prev_block);
  id_next_block++;

  //alteramos para os novos ids/names
  tr_block_room.attr('id','block_room_'+id_next_block);
  tr_block_room.find('div.children .'+'block_room_'+id_prev_block).attr('class', 'block_room_'+id_next_block);
  tr_block_room.find('div.children .'+'children_guest_'+id_prev_block).attr('class', 'children_guest_'+id_next_block);
  tr_block_room.find('span:first' ).text('Quarto ' + (id_next_block+1) );
  tr_block_room.insertBefore('#tr-btn-add');

  // replace do id
  $j('#block_room_'+id_next_block+' select.numberGuest' ).each(function(){

    //$j(this).attr('id', $j(this).attr('id' ).replace(/[0-9]+/, id_next_block));
    //$j(this).attr('name',$j(this).attr('name').replace(/[0-9]+/, id_next_block));

    if($j(this).hasClass('change-capacity')) {
      bindChangeCapacity();
      $j(this).trigger('change');
    }

    activeChild()
  });

  // replace do id do quarto dos ids e names
  $j('#block_room_'+id_next_block+' input, #block_room_'+id_next_block+' select' ).each(function(){

    var id_prev   = $j(this).attr('id' );
    var name_prev = $j(this).attr('name');

    $j(this).attr('id', id_prev.replace(/[0-9]+/, id_next_block));
    $j(this).attr('name',name_prev.replace(/[0-9]+/, id_next_block));
  });

  // replace do id do quarto no label
  $j('#block_room_'+id_next_block+' label' ).each(function(){
    $j(this).attr('for', $j(this).attr('for').replace(/[0-9]+/, id_next_block));
  });

  $j('#block_room_'+id_next_block+' .a-remove-conversation-room').bind('click', function(){
    $j(this).parent('td').parent('tr').remove();
  });

  // zera o número de crianças
  $j('#block_room_'+id_next_block+' select.numberChildren ').val(0).trigger('change');

  // define novo quarto como indefinido e marca o número de hóspede 1
  $j('select#book_rooms_'+id_next_block+'_room_id').val(0);
  $j('#block_room_'+id_next_block+' select.numberGuest').val(0);

  $j('#block_room_'+id_next_block+' .a-remove-conversation-room').css('display','block');

  return tr_block_room;
}

function changeRoomCapacity(room) {

  var max = 0;
  $j.ajax({
    type: "POST",
    url: '/webservice.php/ajax/getRoomById',
    async: false,
    data: {room_id: room},
    dataType: "json",
    success: function(response) {
      if(response.error != undefined)
        max = 0;
      else
        max = response.capacity;
    },
    error: function(xmlHttpRequest, status, err) {
      //alert(xmlHttpRequest.statusText + " " + xmlHttpRequest.status + " : " + xmlHttpRequest.responseText);
      temp = 0;
    }

  });

  return max;
}



