//This web site uses one page that has its div "ecocontent" updated through multiple AJAX requests. This was done to allow the client
//maximum flexibility in maintaining and updating the site. They can easily add, update, and remove pages by creating simple html
//fragments that get loaded into the main page. Plus, the form handling on the server is generic. They can add or remove any field
//from any form and the server will still send the data forward.  The meta data is the key for google indexing so this one page 
//AJAX solution is a nice fit. There is no worry that the AJAX pages won't be properly indexed. Will revist if they add a shopping
//cart to the site.  
//File Created by Jim Coffey 02/01/2008

//Needs to be global or multiple mouse clicks will end up stepping on each other based on who completes first.
//Every time the function is called this variable resets which effectively kills any outstanding requests.
var http_request = null; 

//Harcoded value as this site uses one page with a div named "ecocontent" that is the only HTML that updates.
var HTML_ELEMENT_ID_NAME = "ecocontent"; 

//This function is responsible for creating the request, binding the asnychrnonous callback function, and sending the request.
function processXMLRequest(url, parameters) {
  if (window.XMLHttpRequest) { 
    try {
       http_request = new XMLHttpRequest();
       if (http_request.overrideMimeType) {
             http_request.overrideMimeType('text/html');
       }
    }
    catch (e) {}
  } else if (window.ActiveXObject) { // IE
    try {
      http_request = new ActiveXObject("Msxml2.XMLHTTP");
    } 
    catch (e) {
      try {
         http_request = new ActiveXObject("Microsoft.XMLHTTP");
      } 
      catch (e) {}
    }
  }
  if (!http_request) {
    alert('Cannot create XMLHttp object. Make sure to allow ActiveX Objects to run when prompted in Internet Explorer.');
    return false;
  }
  try {
     http_request.onreadystatechange = handleResponse;
     http_request.open("GET", url + parameters, true);
     http_request.send(null);
  }
  catch (e) {
     return false;
  }
  return true;
 }

//Asynchrous callback function for handling the response from our AJAX request.
function handleResponse() {
  if ((null != http_request) && (4 == http_request.readyState)) {
    try {
       if (200 == http_request.status) {
          updateInnerHTML(http_request.responseText);
       } else {
          updateInnerHTML(http_request.responseText); //Do same thing as success for now, but improve error handling later - JC
       }
       } catch (e) {
         //Exception will alert() inside updateInnerHTML function
       }
       finally {
          http_request = null;          
       }
    }  
}

//This code is generic for 4 forms and possibly more. The only requirement on all the forms is that the fields
//checked by this function are not blank
function validateForm(form) {
   var reason = "";
   reason += validateRequiredField(form.first_name);
   reason += validateRequiredField(form.last_name);
   reason += validateRequiredField(form.address);
   reason += validateRequiredField(form.city);
   reason += validateRequiredField(form.state);
   reason += validateRequiredField(form.zipcode);
   reason += validateRequiredField(form.phone);
   reason += validateRequiredField(form.email);
      
   if (reason != "") {
    alert("Some required fields have been left blank:\n\n" + reason);
    return false;
   }
   
   return true;
   
}


//Simple validation to make sure they don't completely miss filling something in a required field. This is still a family business
//so they don't want to be real strict as they usually follow up by phone/email anyway.
function validateRequiredField(fld) {
    var error = "";
 
    if (fld.value.length == 0) {
        fld.style.background = 'Yellow'; 
        error = fld.name + "\n"
        fld.focus(); 
    } else {
        fld.style.background = 'White';
    }
    return error;  
}


//Updates the inner HTML with the value in content. It uses HTML_ELEMENT_ID_NAME defined at the top to determine the 
//DIV ID to update. Simply add a variable instead of using this constant and you can update multiple parts of any page.
function updateInnerHTML(content) {
  try {
     document.getElementById(HTML_ELEMENT_ID_NAME).innerHTML = content;
  }
  catch (e) {
   alert("There was a problem updating the page.\nError is:\n" + e);
  }         
}   

//This function is the starting point for updating the main "ecocontent" div. Optionally, it takes a form for the pages
//that have data submitted to the server. This function should be called directly in the href="" for any of the anchor <a> tags
//To create a new page and menu item, you simply create a new file "div_new.html" and a link to the sidebar on the index.html file.
//<Ex: <a href="javascript:updateContent('content/div_new.html', null);">My Link</a>
function updateContent(url, form) {
   var formattedParameters = "";
   var serverResponse;
   if(null!=form) {
      if(!validateForm(form))
         return false;
      formattedParameters = formatXMLGetRequestParameters(form);
   }
   processXMLRequest(url, formattedParameters);
}

//The AJAX code for get requests is a little simpler then when you are dealing with form posts. This function turns the form 
//variables into one long HTTP Style GET request. The ecoclean forms are simple so this code will be revisited if they decide
//to add more complicated order style forms or credit card info.
function formatXMLGetRequestParameters(form) {
  var formattedParameters = "";
  var elements;
  
  if (null != form) {
     try {
        formattedParameters += "?";
        elements = form.elements;
        for (i=0; i < elements.length; i++) {
           switch (elements[i].type) {
            case 'text':
            case 'select-one':
            case 'hidden':
            case 'textarea':
            if(elements[i].value.length > 0)
               formattedParameters += escape(elements[i].name) + '=' + escape(elements[i].value.replace(/[\n\r\t]/g,' ')) + '&';
            break;
            case 'checkbox':
            case 'radio':
            if(true == elements[i].checked)
               formattedParameters += escape(elements[i].name) + '=' + escape(elements[i].value) + '&';
            break;
            default:
           }
         
        }
   } catch (e) {
    }
  }

  return(formattedParameters);
}