/*

File: contact.js
Purpose: To submit a contact form for validation and to clear the form of input.
Author: Ryan Brady <ryan@dhkfinancial.com>
Last modified: January 2007
Requirements:
  - process.ajax.php
  - cssjs.js (to help with CSS classes via JavaScript)
  - sarissa.js (to help with the Ajax work and cross-browser support)
  - util-functions.js (for making the code easier and cleaner)
Comments:
  - Thanks to the tutorial at <http://yourhtmlsource.com/javascript/ajax.html> for help
Known-issues:

*/



//==============================================================================
// Submit form to a server-side script for validation and handle what comes back
//==============================================================================

addEvent(window, "load", init, false);

function init() {
  if (!Sarissa || !document.getElementsByTagName) {
    return;
  }
  var formElements = document.getElementsByTagName("form");
  for (var i = 0; i < formElements.length; i++) {
    if (formElements[i].className.match(/\bajax\b/)) {
      addEvent(formElements[i], "submit", processForm, false);
    }
  }
}

function processForm(e) {

  //----------------------------------------------------------------------------
  // Set things up
  //----------------------------------------------------------------------------

  // Cancel the submission and figure-out which form was submitted (helpful with multiple forms)
  knackerEvent(e);
  var emailAddress = "info@dhkfinancial.com";
  var target = window.event ? window.event.srcElement : e ? e.target : null;    // target is the same as form#feedback here, but not always
  if (!target) {
    return;
  }
  var formContainer = document.getElementById("form_container");
  var feedbackForm = document.getElementById("feedback");
  var parent = formContainer.parentNode;                                        // To be used in creating the status message

  // Disable the inputs for submission
  for (var i = 0; i < feedbackForm.length; i++) {
    feedbackForm.elements[i].disabled = true;
  }

  // Display the working/loading indicator image                                // Use feedbackForm instead of target in case the form is submitted with the Enter key
  if (document.getElementById("status")) {
    var statusP = document.getElementById("status");
    statusP.parentNode.removeChild(statusP);
  }
  var statusP = document.createElement("p");
  var statusText = document.createTextNode("Processing\u2026");                 // Horizontal ellipsis = U+2026
  statusP.setAttribute("id", "status");
  cssjs("add", statusP, "processing");
  statusP.appendChild(statusText);
  parent.insertBefore(statusP, formContainer);

/*
  var processingIMG = document.createElement("img");
  processingIMG.src = "images/grass.background.png";
  processingIMG.setAttribute("id", "processing");
  processingIMG.setAttribute("alt", "Processing form submission");
  processingIMG.setAttribute("title", "Processing form submission");
  parent.insertBefore(processingIMG, target);
*/

  // The request: How and where the information is being sent
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.open("POST", "/includes/contact_form/process.ajax.php", true);


  //----------------------------------------------------------------------------
  // Callback function
  //----------------------------------------------------------------------------
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4) {

      // Callback code: Do this when a response comes back
      if (xmlhttp.status == 200) {

        // Count the number of input fields and check the validation response for each one
        var fields = xmlhttp.responseXML.getElementsByTagName("field");
        for (var i = 0; i < fields.length; i++) {

          var flag = xmlhttp.responseXML.getElementsByTagName("flag")[i].firstChild.data;          // Whether or not the <data> passed validation
          var label = xmlhttp.responseXML.getElementsByTagName("label")[i].firstChild.data;        // The <label> that the <data> is under (in case a single <label> is used for more than one <field>)
          label = document.getElementById(label + "_label");                                       // Make it match it's HTML id (done here instead of responseXML for easier changes)

          // Apply styles to the <li> that contains the <label> and control(s)
          if (flag == 0) {
            cssjs("add", label.parentNode, "error");
          }
          if (flag == 1) {
            if (cssjs("check", label.parentNode, "error") == true) {
              cssjs("remove", label.parentNode, "error");
            }
          }

        } // Loop over i

        // Check to see if the whole form is OK to send
        var send = xmlhttp.responseXML.getElementsByTagName("send")[0].firstChild.data;
        if (send == 1) {
          // Validation is passed ----------------------------------------------

          // Remove the error-indicator if necessary - - - - - - - - - - - - - -
          for (var j = 0; j < target.length; j++) {                             // It's possible for the variables, "fields" and, "target" to be different

            if (cssjs("check", label.parentNode, "error") == true) {
              cssjs("remove", label.parentNode, "error");
            }

            cssjs("add", feedbackForm, "sent");
            feedbackForm.elements[j].disabled = true;

          }

          // Display a confirmation message - - - - - - - - - - - - - - - - - - 
          // Remove the error message if it is there and them re-create <p id="status">
          if (document.getElementById("status")) {
            var statusP = document.getElementById("status");
            statusP.parentNode.removeChild(statusP);
          }
          var statusP = document.createElement("p");
          statusP.setAttribute("id", "status");
          cssjs("add", statusP, "screen_only");

          // See if the email was successfully sent or not - - - - - - - - - - -
          var sendSuccess = xmlhttp.responseXML.getElementsByTagName("success")[0].firstChild.data;
          if (sendSuccess == 1) {

            var statusText = document.createTextNode("Thank you!");
            cssjs("add", statusP, "success");
            statusP.appendChild(statusText);                                    // Make the inside of <p id="status">

          } else {

            var statusText1 = document.createTextNode("We\u2019re sorry, but there was an error sending the message. Please ");  // Right-quote/apostrophe = U+2019
            var statusText2 = document.createTextNode(" us directly.");

            var emailA = document.createElement("a");
            emailA.setAttribute("href", "mailto:" + emailAddress);
            var emailText = document.createTextNode("e-mail");
            emailA.appendChild(emailText);

            cssjs("add", statusP, "error");
            statusP.appendChild(statusText1);
            statusP.appendChild(emailA);
            statusP.appendChild(statusText2);

          }

          parent.insertBefore(statusP, formContainer);                          // Insert <p id="status"> before <form id="feedback">


          // Remove the buttons and Cc option - - - - - - - - - - - - - - - - - 

          // Buttons are selected individually instead of their container because the container is needed keep the floated form elements from running off the page
          var formSide = document.getElementById("form_side");
          var submitButton = document.getElementById("submit");
          //var clearButton = document.getElementById("clear");

          formSide.parentNode.removeChild(formSide);
          submitButton.parentNode.removeChild(submitButton);
          //clearButton.parentNode.removeChild(clearButton);

        } else {
          // Validation not passed (flags are already set above) ---------------

          // Enable the inputs for editting
          for (var k = 0; k < target.length; k++) {
            feedbackForm.elements[k].disabled = false;
          }

          // Make <p id="status"> if it hasn't been made already
          if (document.getElementById("status")) {
            var statusP = document.getElementById("status");
            statusP.parentNode.removeChild(statusP);
          }

          var statusP = document.createElement("p");
          statusP.setAttribute("id", "status");
          cssjs("add", statusP, "fix");
          var statusText1 = document.createTextNode("Please fix ");
          var statusText2 = document.createTextNode(" and try again.");

          // For <span class="error">
          var errorSpan = document.createElement("span");
          var errorText = document.createTextNode("errors");
          //errorSpan.setAttribute("class", "error");
          cssjs("add", errorSpan, "error");                                     // For IE (the above setAttribute() won't work)
          cssjs("add", statusP, "screen_only");
          errorSpan.appendChild(errorText);

          // Make the inside of <p id="status">
          statusP.appendChild(statusText1);
          statusP.appendChild(errorSpan);
          statusP.appendChild(statusText2);

          // Insert <p id="status"> before <div id="form_container">
          parent.insertBefore(statusP, formContainer);

        }

      } else {

        // Submit server-side-style (without Ajax)
        //target.submit();

      }
    }
  }


  //----------------------------------------------------------------------------
  // Send the POST request as name-value pairs
  //----------------------------------------------------------------------------

  // Construct the name-value string to send
  posts  = "name=" + feedbackForm.elements["name"].value;
  posts += "&org=" + feedbackForm.elements["org"].value;
  posts += "&adr1=" + feedbackForm.elements["adr1"].value;
  posts += "&adr2=" + feedbackForm.elements["adr2"].value;
  posts += "&city=" + feedbackForm.elements["city"].value;
  posts += "&state=" + feedbackForm.elements["state"].value;
  posts += "&zip=" + feedbackForm.elements["zip"].value;
  posts += "&phone=" + feedbackForm.elements["phone"].value;
  posts += "&fax=" + feedbackForm.elements["fax"].value;
  posts += "&email=" + feedbackForm.elements["email"].value;
  posts += "&subject=" + feedbackForm.elements["subject"].value;
  posts += "&message=" + feedbackForm.elements["message"].value;
  if (feedbackForm.elements["cc"].checked == true) {
    posts += "&cc=" + feedbackForm.elements["cc"].value;
  }

  xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xmlhttp.send(posts);


}



//==============================================================================
// *** not used/needed *** Submit the form when the Enter key is pressed
//==============================================================================
function ifEnterKey(e) {

  var key = e.which;
  if (key == 13) {
    processForm(e);
  } else {
    return true;
  }

}



//==============================================================================
// Clear form with the "Clear" button
//==============================================================================
/*function clearFeedback() {

  var feedback = document.getElementById("feedback");
  for (var i = 0; i < feedback.length; i++) {

    // Clear input and make available
    feedback.elements[i].disabled = false;                                                         // Because the Ajax part seems to keep it disabled after submission (even after refresh) unless the page is navigated away and then back
    if (feedback.elements[i].type == "text" || feedback.elements[i].type == "textarea") {          // Because of things like the buttons with "fixed" values
      feedback.elements[i].value = "";
    }
    if (feedback.elements[i].type == "checkbox") {
      feedback.elements[i].checked = false;
    }

    // Remove any previously-place error-indicators
    if (document.getElementById(feedback.elements[i].id + "_label")) {
      var label = document.getElementById(feedback.elements[i].id + "_label");  // One <label> may be used for more than one <input>
      if (cssjs("check", label.parentNode, "error") == true) {
        cssjs("remove", label.parentNode, "error");
      }
    }

  }

  // Remove <p id="status"> if it is there
  if (document.getElementById("status")) {
    var statusP = document.getElementById("status");
    statusP.parentNode.removeChild(statusP);
  }

  document.getElementById("name").focus();

}*/



//==============================================================================
// Show/Hide extra fields
//==============================================================================
function toggleMore() {

  var optionsControl = document.getElementById("more");
  var hideableFields = getElementsByClass("extra");
  var userFields = document.getElementById("user_info");
  var messageFields = document.getElementById("message_info");

  switch (optionsControl.value) {

    case "+":
      for (var i = 0; i < hideableFields.length; i++) {
        hideableFields[i].style.display = "block";
      }
      userFields.style.height = "12em";
      optionsControl.value = "\u2212";                                          // Minus sign = U+2212
			optionsControl.title = "Show fewer fields";
      if (navigator.appName == "Microsoft Internet Explorer") {
        messageFields.style.marginTop = "1.5em";
      }
      break;

    case "\u2212":
      for (var i = 0; i < hideableFields.length; i++) {
        hideableFields[i].style.display = "none";
      }
      userFields.style.height = "1.5em";
      optionsControl.value = "+";
			optionsControl.title = "Show more fields";
      if (navigator.appName == "Microsoft Internet Explorer") {
        messageFields.style.marginTop = "0";
				userFields.style.height = "auto";
      }
      break;

  }

}

