/*
 * NHM 'Group Sales Form' Javascript Library
 * Michael P, Jan/2010
 */

_err = "";
_posted = false;

/*
 * init method
 */
window.onload = function() {

  $(function() {
    $("#error-dialog").dialog({
      autoOpen: false,
      bgiframe: true,
      modal: true,
      position: top,
      closeOnEscape: true,
      buttons: { "Ok": function() { $(this).dialog("close"); } }
    });
  });

  $(".step").show();
  
}

/*
 * sets global error message
 */
function setErrMessage(t) {
  _err = t;
}

/*
 * shows the error dialog, using _err
 */
function errDialog() {
  if (_err) { // show message only if we have text for it
    $("#error-dialog-message").html(_err);
    $("#error-dialog").dialog('open');
  }
}

/*
 * resets the form
 */
function resetMe() {
  $("#form-feedback").clearForm();
}

/*
 * submits the form if not error are found
 */
function submitMe() {
  if (checkForm()) {
    if (_posted) return;
    _posted = true;
    var post_data = $("#form-feedback").serialize();
    $.post(
      "/site/feedback-form-post",
      post_data,
      function (data) {
        if (data[0]) {
  				$('.step').fadeOut('fast', function () { $('.thank-you').fadeIn('fast'); } );
          $("#form-feedback").clearForm();
        } else {
          _posted = false;
          t = data[1];
          setErrMessage(t);
          errDialog();
        }
      },
      "json");
  } else {
    errDialog();
  }
}

/*
 * validates the form, used before submit
 */
function checkForm() {
  ok = true;
  $(".error").removeClass("error");
  // first check required fields
  $("#all_fields .required").each( function () {
    if (!checkRequired($(this))) {
      ok = false;
      setErrMessage('Please fill in all the required data.');
    }
  });
  // if all required fields are there, check for email inputs to be valid
  if (ok) {
    $("#all_fields .mail").each( function () {
      if (!checkEmail($(this))) {
        ok = false;
        setErrMessage('The email address you provided is not valid.');
      }
    });
  }
  return ok;
}
