jQuery.noConflict();
(function($) {
  $(function() {
    addAnother = function(){
      var count = $('.supplier').size();
      var numGuests = parseInt($('#numGuests').val());

      if (numGuests && count <= numGuests){

        /* Steps here are:
        1. find last fieldset
        2. clone it,
        3. attach event handlers to "Add", "Clear" buttons (they don't get cloned)
        4. empty all values in text boxes (which do get cloned)
        5. and insert cloned nodes at end fieldsets group
        6. remove "Add" button from last fieldset
        7. Finally move footer to bottom of page
        */

        $('.supplier:last').clone().insertAfter('.supplier:last')
        .find('p:last :input:first')
          .click(addAnother)
        .end()
        .find('p:last :input:last')
          .click(delFieldset)
        .end()
        .find('input[@type="text"],textarea')
          .attr('value','')
          .css('background-color','white')
          .attr('readonly','')
        .end()
        .find('p:last :input:last')
          .show()
        .end()

        //.end()

        .find('p:last :input:first')
          .hide()
        .end()
      }

      if(count==numGuests){
        $('.supplier:last')
        .find('p:last :input:first')
        .hide()
        .end();
      }
      return false;
    }

    clearFieldset = function() {
      //alert('clear');
      $('../../p/:text', this).attr('value','');
      return false;
    }

    delFieldset = function() {
      //alert('delete');
      $('../..', this).remove()
      $('.supplier:last p:last :input:first').show();
      return false;
    }

    /* Attach event handlers */
    $('.supplier p:last :input:first').click(addAnother);

    /* To first fieldset, we just want to clear fields
    For all others e.g. gt(0), we want to remove the entire fieldset.
    */
    var numGuests = parseInt($('#numGuests').val());
    if (numGuests > 0){
      $('.supplier').eq(0)
      .find('p:last :input:last')
      .click(clearFieldset)
      .end()
      .end()
      .gt(0).find('p:last :input:last')
      .click(delFieldset)
      .end();
    }
  });
})(jQuery);