$(document).ready(function() {
  $('#field_room_count').change(function() {
    updateRooms();
  });
  updateRooms();
  
  $("#request_form").validationEngine();
});

function updateRooms() {
  var totalRooms = $('#field_room_count').val();
  
  var $roomPlaceholder = $('#space_placeholder');
  $roomPlaceholder.empty();
  var $prototype = $('#fieldset_prototype');
  for (var counter = 1; counter <= totalRooms; counter++) {
    var $clone = $prototype.clone();
    $roomPlaceholder.append($clone);
    $clone.removeAttr('id');
    $clone.find('.space_number').text(counter);
    $.each($clone.find('input, select'), function() {
      $(this).attr('name', 'space[' + counter + ']' + $(this).attr('name'));
      $(this).attr('id', 'space_' + counter + '_' + $(this).attr('name'));
    });
    $clone.find('.proto').removeClass('proto');
    $clone.slideDown();
  }
  
  $('a.description').each(function() {
    var $tip = $(this);
    if (!$tip.hasClass('proto') && !$tip.data('qtipdone')){
      $tip.data('content', $tip.html());
      $tip.html('');
      $tip.removeData('qtip') 
      .qtip({
        content: {
          text: $tip.data('content')
        },
        style: {
          classes: 'ui-tooltip-shadow ui-tooltip-blue'
        }
      });
      $tip.data('qtipdone', true);
    }
  });
}

function changeUnits(selectId, totalRooms) {
  var $select = $('#' + selectId);
  $select.empty();
  for (var counter = 1; counter <= totalRooms; counter++) {
    $select.append($('<option>' + counter + '</option>').attr('value', counter));
  }
  $select.val(totalRooms);
}

(function($){
    if (typeof $.fn.prop !== 'function')
    $.fn.prop = function(name, value){
        if (typeof value === 'undefined') {
            return this.attr(name);
        } else {
            return this.attr(name, value);
        }
    };
})(jQuery);

