var MusicPinOrder = {
  duplicate_details: function(event) {
    if (event.target.checked) {
      $('#order_delivery_address_1')[0].value = $('#order_address_1')[0].value;   
      $('#order_delivery_address_2')[0].value = $('#order_address_2')[0].value; 
      $('#order_delivery_city')[0].value = $('#order_city')[0].value; 
      $('#order_delivery_country')[0].selectedIndex = $('#order_country')[0].selectedIndex; 
      $('#order_delivery_address_holder').hide(); 
    } else { 
      $('#order_delivery_address_1')[0].value = ''; 
      $('#order_delivery_address_2')[0].value = ''; 
      $('#order_delivery_city')[0].value = '';
      $('#order_delivery_address_holder').show(); 
    }
  },
  
  replace_form: function(data, textStatus) { 
    $('#order-form-holder').replaceWith(data);
    if ($('#order-form-holder').length > 0) {
      MusicPinOrder.prepare_homepage();
      alert('Sorry, we couldnt complete your request, please check that you have entered all the correct information');
    }
    return false;
  },

  prepare_homepage: function() {
    $.ajaxSetup({
      beforeSend: function(xhr) {
        xhr.setRequestHeader("Accept", "text/javascript");
      }
    });
    
    $('#order_delivery_address_holder').before('<div id="order_delivery"><label>Delivery details the same as primary address?</label> same as above <input type="checkbox" id="duplicate-delivery-details" /></div>');
    $('#duplicate-delivery-details').change(MusicPinOrder.duplicate_details);

    $('#order-form-holder #order-form').submit(function (event) {
      if (! $('#terms_checkbox')[0].checked) {
        alert("Please agree to MusicPin's Terms & Conditions"); 
        return false;
      }

      $.post(event.target.action + '.js', $(this).serialize(), MusicPinOrder.replace_form, 'html');
      return false;
    });
  }
}