// Function to perform a function on an input when it is changed/updated.
// Performs the function after X milliseconds after hitting a key, making it
// a lot faster than 'check-every-keypress'.
jQuery.fn.update = function(perform){
    $(this).change(perform);
    $(this).click(perform);
    $(this).blur(perform);
    $(this).focus(perform);
    var input = $(this);
    var t;
    $(this).keyup(function(){
        if (!t)
          t = setTimeout(function(){
              input.each(perform);
              t = undefined;
            },500);
      });
}

$(document).ready(function(){
    $('.delivery').each(function(){
        var delivery = this
        , check = $('<p class="check-fields"><input type="checkbox" value="true">' + 
                   ' Billing is the same as delivery information</p>')
        , checkbox = check.children('input')
        , ds = $('.delivery input')
        , bs = $('.billing input')
        , same = function(){
          for (var i in ds)
            if (bs[i] && ds[i])
              if (bs[i].value != ds[i].value) return false;
          return true;
        }
        , synch = function(){
            if (checkbox[0].checked)
              for (var i in ds)
                if (bs[i] && ds[i])
                  bs[i].value = ds[i].value;
        };
        if (same()) {
          checkbox[0].checked = 'checked';
           $(delivery).next().hide();
        }
        delivery.appendChild(check[0]);
        ds.update(synch);
        checkbox.change(function(){
              synch();
            if (!this.checked) {
              $(delivery).next().fadeIn();
            } else {
              $(delivery).next().fadeOut();
            }
          });
        checkbox.click(function(){$(this).change()});

      });
  });
