
/**************************************************
Joshua K Roberson - 02-23-2008 - v1
Process AJAX request in background through the GET or POST method.
If POST set, gathers any POST elements to send.
If container 'id' passed, rewrites container with results.
PARAMETERS:
action - file to send reqest to for processing
method - POST or other types which default to GET; OPTIONAL
ths - form object passed using 'this'; OPTIONAL
containerId - unique HTML element id to rewrite response to; OPTIONAL
EXAMPLE USAGE:
<form action="#" method="POST" onsubmit="return myAjax('area/login', 'POST', this, 'login_box');">...</form>
<a href="#" onclick="return myAjax('area/logout', 'GET', '', 'login_box');">logout</a>
**************************************************/
function myAjax(action, method, ths, containerId) {
  var xmlHttp = GetXmlHttpObject(); // Prevents race condition of multiple calls on the same page
  if(xmlHttp != null) { // End execution if browser doesn't support AJAX
    // Craft string of paramaters to send
    var params = '&sid=' + Math.random(); // Concatenate random number to prevent the server from using a cached file
    if(typeof(ths) == 'object') { // Concatenate any form elements
      for(i=0; i<ths.elements.length; i++) {
        if (ths.elements[i].type == "checkbox") {
	  //if (ths.elements[i].checked == true) params += '&' + ths.elements[i].name + '=' + ths.elements[i].value;
          if (ths.elements[i].checked == true) params += '&' + ths.elements[i].name + '=' + myAjaxClean(ths.elements[i].value);
        } else {
	  //params += '&' + ths.elements[i].name + '=' + ths.elements[i].value;
          params += '&' + ths.elements[i].name + '=' + myAjaxClean(ths.elements[i].value);
        }
      }
    }

    //xmlHttp.onreadystatechange = stateChanged;
    xmlHttp.onreadystatechange = function() { stateChanged(xmlHttp); };

    if(method == 'POST') {
      xmlHttp.open('POST', action, true);
      xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=UTF-8;');
      xmlHttp.setRequestHeader('Content-length', params.length);
      xmlHttp.setRequestHeader('Connection', 'close');
      xmlHttp.send( params );
    } else {
      if(action.indexOf('?') == -1) { // Not found, add '?' to 'GET' URL
        var urlAdd = '?';
      } else {
        var urlAdd = '';
      }
      xmlHttp.open('GET', action + urlAdd + params, true);
      xmlHttp.send(null);
    }
  }
  return false;

  // Create XHLHttpRequest object for browser
  function GetXmlHttpObject() {
    var xmlHttp;
    try {
      var xmlHttp = new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
      if(xmlHttp.overrideMimeType) { // Firefox 1.5+ not supported
        xmlHttp.overrideMimeType('text/xml'); // Accomodate some versions of Firefox so works
      }
    } catch (e) {
      try {
        var xmlHttp = new ActiveXObject('Msxml2.XMLHTTP'); // Internet Explorer 6.0+
      } catch (e) {
        try {
          var xmlHttp = new ActiveXObject('Microsoft.XMLHTTP'); // Internet Explorer 5.5+
        } catch (e) {
          var xmlHttp = null;
          alert('Your browser does not support AJAX!');
        }
      }
    }
    return xmlHttp;
  }

  // Process response from server
  function stateChanged(xmlHttp) {
    var msg = '';
    var obj = document.getElementById( containerId );

    if(obj != null) { // Write to element if exists
      xmlHttp.onreadystatechange = function() {
        switch(xmlHttp.readyState) {
          case 4: // Request is complete, get data
            if(xmlHttp.status == 200) { // Request status OK
              var msg = xmlHttp.responseText;
              //alert(msg); // DEBUG...
            } else {
              var msg = 'Error with request.';
            }
            break;
          case 3: // Request is in process
          case 2: // Request has been sent
          case 1: // Request has been set up
            var msg = 'Processing.';
            break;
          case 0: // Error, request not initialized
            var msg = 'Error processing.';
            break;
        }
        obj.innerHTML = msg;
      }
    }
    //else { alert('Object does not exist - ' + containerId); } // DEBUG...
  }
}

/**************************************************
Joshua K Roberson - 02-23-2008 - v1
Loop through arguments and pass values to the AJAX process function.
Can use during the 'onload' body event or the 'onclick' tabed DHTML navigation event, etc.
PARAMETERS:
arguments - events to rewrite container info
EXAMPLE USAGE:
<body onload="myAjaxLoad('loadLogin', 'loadInsiderTrading');">
<a href='#' onclick="myAjaxLoad('most_emailed');">most emailed</a>
**************************************************/
function myAjaxLoad() {
  for(var i=0; i<arguments.length; i++) {
    myAjaxProcess(arguments[i]);
  }
  return false;
}

/**************************************************
Joshua K Roberson - 07-24-2008 - v1
Find and replace special characters within a string to pass it in the POST/GET
PARAMETERS:
str - string to rewrite
**************************************************/
function myAjaxClean(str) {
  str = str.replace(/&/g, "%26");
  str = str.replace(/\+/g, "%2B");
  return str;
}
