$(function(){
  var name = $("#customer-name"),
  email = $("#customer-email"),
  emailConfirmation = $('#email-confirmation'),
  phone = $("#customer-phone"),
  shippingAddress = $("#shipping-address"),
  city = $("#city"),
  state = $("#state"),
  zipcode = $("#zipcode"),
  allFields = $([]).add(name).add(email).add(emailConfirmation).add(phone).add(shippingAddress).add(city).add(state).add(zipcode),
  tips = $("#validateTips");

  function updateTips(t) {
    tips.text(t);
  }

  function checkEmailEqual(){
    if(email.val() !== emailConfirmation.val()){
      emailConfirmation.addClass('ui-state-error');
      email.addClass('ui-state-error');
      updateTips("The two email addresses don't match.");
      return false;
    }
    else{
      return true;
    }
  }

  function checkRequired(o, n){
    if($.trim(o.val()).length === 0){
      o.addClass('ui-state-error');
      updateTips(n + ' is required.');
      return false;
    }
    else{
      return true;
    }
  }

  function checkLength(o,n,min,max) {
    if ( o.val().length > max || o.val().length < min ) {
      o.addClass('ui-state-error');
      updateTips("Length of " + n + " must be between "+min+" and "+max+".");
      return false;
    } else {
      return true;
    }
  }

  function checkRegexp(o,regexp,n) {
    if ( !( regexp.test( o.val() ) ) ) {
      o.addClass('ui-state-error');
      updateTips(n);
      return false;
    } else {
      return true;
    }
  }

  $("#dialog tfoot").remove();

  $("#dialog").dialog({
    bgiframe: true,
    autoOpen: false,
    width: 400,
    modal: true,
    buttons: {
      'Send': function() {
        var bValid = true;
        updateTips('');
        allFields.removeClass('ui-state-error');

        bValid = bValid && checkRequired(name,"Name");
        bValid = bValid && checkRequired(email,"Email");
        // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
        bValid = bValid && checkRegexp(email,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"Email is invalid.");
        bValid = bValid && checkEmailEqual();
        bValid = bValid && checkRequired(phone, 'Phone Number');
        bValid = bValid && checkRequired(shippingAddress, 'Shipping Address');
        bValid = bValid && checkRequired(city, 'City');
        bValid = bValid && checkRequired(state, 'State');
        bValid = bValid && checkRequired(zipcode, 'Zip Code');

        if (bValid) {
            
          var formData = {};
            
          allFields.each(function(){
            var jField = $(this);
			formData[jField.attr('name')] = jField.val();
          });

          var dlg = $(this);

          updateTips('Processing your order, please wait ...');
            
          $.post($(this).find('form').attr('action'), formData, function(data){
            if(data.status === 'ok'){
              dlg.dialog('close');

              $('<div title="Order Received">Thank you for your interest in The Shadow Warrior! We are currently working out production issues with the printer. We will send you an email when we are all set and you can complete you order and get the book shipped out to you right away.</div>').
              appendTo(document.body).dialog({
                bgiframe: true,
                autoOpen: false,
                width: 400,
                modal: true,
                buttons: {
                  'Close': function(){
                    $(this).dialog('close').remove();
                    $('#purchase-printed').unbind('click').click(function() {
                      alert('We have received your order.');
                      return false;
                    });
                  }
                }
              }).dialog('open');
            }
            else{
              updateTips(data.message);
            }
          }, 'json');

          return;
        }
      }
    }
  });

  $('#purchase-printed').click(function() {
    $('#dialog').dialog('open');
    return false;
  });
});

