$(function(){
   $(document).on('click', '.multifield_add', function(){
       var self = $(this);
       var el = self.parents('.control-group').children().first().clone();
       el.val('');
       self.parents('.controls').append('<div class="control-group"></div>');
       self.parents('.controls').find('.control-group:last').append(el).append('<button data-name="' + self.attr('data-name') + '" class="multifield_remove"><i class="icon-remove"></i></button>');
       
       return false;
   }); 
   
   $(document).on('click', '.multifield_remove', function(){
       $(this).parent().remove();
       
       return false;
   });
   
   $(document).on('click', 'input[type="submit"]', function(){
       $('.multifield').each(function(){
           var self = $(this);
           var data = [];
           var disabledEl = ($('[name="' + self.attr('name') + '"]:not([type=hidden]').length !== 0 ) ? false : true;
           $('[name="' + self.attr('name') + '"]:not([type=hidden]').each(function(){
               var curEl = $(this);
               if (curEl.val() !== '') {
                   data.push(curEl.val());
               }
               curEl.removeAttr('name');
           });
           if (!disabledEl) {
               self.val($.isEmptyObject(data) ? null : JSON.stringify(data));
           } 
       });
   });
});