// form validation scripts

t_e_s_t_i_n_g = false;

var formValidator = null;

function sendData() {
  // disable the submit button to prevent multiple submissions

  $('#submit').attr({'disabled' : 'disabled', 'value' : 'Sending...'});

  showResponse('Procesing ... Please Wait');

  var now = new Date();

  var parms = 'name=' + $('#name').val() + '&'
            + 'email=' + $('#email').val() + '&'
            + 'subject=' + $('#subject').val() + '&'
            + 'comments=' + $('#comments').val() + '&'
            + 'localtime=' + now.format('F j, Y g:i A') + '&'
            + 'securitycode=' + $('#securitycode').val();

  args = {
    url:      'pages/feedbackprocessor.php',
    type:     'POST',
    datatype: 'json',
    data:     parms,
    cache:    false,
    success:  processResults,
    error:    handleError
  }

  $.ajax(args);

return false;
}

function processResults(data) {
  if (!data) {
    showFormError("No response data returned from AJAX request.");
    return;
  }

  if (!data.status) {
    showFormError(data);
    return;
  }

  if (data.status.toLowerCase() == 'success') {
    showResponse(makeText(data.messages), true);
    // remove the buttons to be safe
    $('#submit').hide();
    $('#reset').hide();
  } else {
    showFormError(makeText(data.messages));
    // re-enable the submit button
    $('#submit').val('Send').removeAttr('disabled');
  }
}

function handleError(xhr, textStatus, errorThrown) {
  // safest and easiest approach seems to be to get the error info from the XMLHttpRequest object

  if (xhr.status == '404')
    data = 'Unable to load the page to process the data on the server.'
  else
    data  = 'AJAX Error ' + xhr.status + ':&nbsp;&nbsp;"' + xhr.statusText + '"';

  showFormError(data);
}

function showResponse(data, showClose) {
  // process the "optional" parameter
  if (showClose === undefined)
    showClose = false;

  var resp = $('#responsearea');

  resp.html(data)

  if (showClose) {
    var closeButton = '<div id="closer">Close</div>';
    resp.prepend(closeButton);
    var closer = $('#closer');
    closer.css({'color' : '#FFFFFF',
                 'font-weight' : 'bold',
                 'font-style' : 'italic',
                 'cursor' : 'pointer',
                 'width' : '60px',
                 'position' : 'relative',
                 'left' : '85%',
                 'top' : '5%'
              });
    closer.bind("click", hideResponse);
  }

  resp.show();
}

function hideResponse() {
  $('#responsearea').hide();
}

function showFormError(message) {
  $('#responsearea').hide();

  showError("Processing Error", message);
}

function makeText(messages) {
  var text = '';

  jQuery.each(messages, function() {
    text += this + '<br />';
  });

  return text;
}

function showDialog(titleText, messageText) {
  doDialog(titleText, messageText, false);
}

function showError(titleText, messageText) {
  doDialog(titleText, messageText, true);
}

function doDialog(titleText, messageText, errorPopupType) {
  // this approach does not need a DIV sction pre-defined in the HTML document
  var dlg = $("<div></div>").html(messageText).dialog({
    autoOpen: false,
    resizable: false,
    width: 360,
    height:  240,
    modal: true,
    title: titleText,
    buttons: {
      Ok: function() {
        $(this).dialog('close');
      }
    },
    open: function () {
      if (errorPopupType) {
        $(this).parents(".ui-dialog:first").find(".ui-dialog-titlebar").addClass("ui-state-error");
      }
    }
  });

  dlg.dialog('open');

  return false;
}

function resetForm() {
  if (formValidator != null)
    formValidator.resetForm();

  $('#responsearea').hide();

  // re-enable the submit button just to be sure

  $('#submit').val('Send').removeAttr('disabled');

  if (t_e_s_t_i_n_g) {
    // insert some test data to make things easier
    $('#name').val('George P. Burdell, IV');
    $('#email').val('geo@noway.net');
    $('#subject').val('Feedback - Contact Testing');
    $('#comments').val('Blah, blah, blah ...');
    $('#securitycode').val('abc42');
    $('#securitycode').focus();
  }
}

function init() {
  $('#reset').click(function(evt) {
    resetForm();
    return false;
  });

  $('#name').focus();

  if (t_e_s_t_i_n_g) {
    // insert some test data
    resetForm();
  }

  $.validator.messages.required = "";

  formValidator = $("#feedbackform").validate({
    errorLabelContainer: 'div.warningbox',
    submitHandler: sendData
  });
}

