// A status indicator div that can contain information as to whether
// information is being loaded or saved.
var statusIndicator=document.createElement('div');
statusIndicator.id="statusIndicator";

var needSave = true;
var getVS = null;
function saveASPAJAX(formName, save, message){
   if(save === undefined){
      save = true;
   }
   if(message === undefined){
      message = true;
   }
   if(needSave || (!message && getVS == null)){
      var form = gI(formName);
      if(isModified(form) || (!message && getVS == null)){
      var xmlReq = getXmlHttpRequestObject();
      var data = '';
      var eName = '';
      var type = '';
      for( var i=0; i< form.length; i++)
      {
         eName = form.elements[i].name;
         type = form.elements[i].type;

         if( eName && eName != '' && eName != '__EVENTTARGET' && eName != '__EVENTARGUMENT' && type != 'submit' && type != 'clear' && type != 'button' && ((type != 'checkbox' && type != 'radio') || form.elements[i].checked) )
         {
            data = data + escape(eName) + '=' + escape(form.elements[i].value).replace(new RegExp('\\+', 'g'), '%2b');
            if( i != form.elements.length - 1 ) data = data + '&';
         }
      }

         var confirmRet = true; 
         var username = getCookie('UID');
         var loggedIn = username != null && username != '';
         if(save && needSave && __oldAnswers){
            confirmRet = confirm("You have answers saved for an old version, but have made modifications on the new version. Saving these changes will overwrite your answers for the old version. Would you like to save?");
         }
         if(message && confirmRet && loggedIn){
            showMessage('Saving your answers. Please wait.');
         }

         data = "getVariableStringAjax=true&" + (save && needSave && confirmRet ? "doAjaxSave=true&":"") + data;
         xmlReq.open("POST", form.action, !loggedIn);
      xmlReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
         xmlReq.send(data);
         if(typeof(__inputDefaultsSet) == 'function'){
            __inputDefaultsSet();
         }

         if(message && confirmRet && loggedIn){
            hideMessage();
         }

         if(xmlReq.status == 200 && xmlReq.responseText != null){
            getVS = xmlReq.responseText;
   }
   }
   }
   return getVS;
}
function encodeHTML(html) {
   encodedHtml=escape(html);
   return encodedHtml;
}
function isModified(oForm, ignoreVH)
{
   if(ignoreVH === undefined){
      ignoreVH = false;
   }
   if(vh.VS()>0 && !ignoreVH){
      return vh.HC();
   }
   else if(typeof(__inputDefaultsCheck) == 'function'){
      return __inputDefaultsCheck();
   }
   else{
	var el, opt, hasDefault, i = 0, j;
	while (el = oForm.elements[i++]) {
		switch (el.type) {
			case 'text' :
         case 'textarea' :
         case 'hidden' :
            if (!/^\s*$/.test(el.value) && el.value != el.defaultValue) return true;
            break;
         case 'checkbox' :
         case 'radio' :
           	if (el.checked != el.defaultChecked) return true;
           	break;
         case 'select-one' :
         case 'select-multiple' :
           	j = 0, hasDefault = false;
           	while (opt = el.options[j++])
              	if (opt.defaultSelected) hasDefault = true;
           	j = hasDefault ? 0 : 1;
           	while (opt = el.options[j++]) 
             	if (opt.selected != opt.defaultSelected) return true;
           	break;
		}
	}
   }
	return false;
}
/**
 * In Internet Explorer, to create the object using new ActiveXObject("Msxml2.XMLHTTP") 
 * or new ActiveXObject("Microsoft.XMLHTTP")
 * depending on the version of MSXML installed. 
 * In Mozilla and Safari, you use new XMLHttpRequest()
 */
function getXmlHttpRequestObject() {
   if(window.XMLHttpRequest) {
      return new XMLHttpRequest();
   } else if(window.ActiveXObject) {
      return new ActiveXObject("Microsoft.XMLHTTP")
   } else {
      alert("can't make xmlhttprequest");
   }
}
/**
 * xmlData: xml data
 *   <?xml version="1.0" encoding="UTF-8"?>
 *   <request>
 *      <command>save|load</command> 
 *      <SID>SecureID</SID> 
 *      <CID>contractIdentifier</CID>
 *      <saveName>name for this save</saveName>
 *      <section>what sort of info</section>
 *      <other>additional metadata</other>
 *      <html (or data)>
 *         Data to save (make sure it is escaped: you can use encodeHTML())
 *      </html (or data)>
 *   </request>
 * 
 * destinationURL: where to post data to.
 * 
 * statusIndicatorParent: parent of where you want the status indicator to go.
 *   It will be added using insertBefore() and you should dispose of it.
 *
 * statusText: what text you want in the status indicator.
 *
 * callbackFunc: what function needs to be called when the request is
 *   answered. The parameters are the request object followed by the status
 *   indicator object.
 *
 *   If passed in as null (false), it will initiate a synchronous httprequest
 */
function httpRequest(xmlData,destinationURL,statusIndicatorParent,statusText,callbackFunc,usePost) {
   if(SID!=false) {
      statusIndicator.innerHTML=statusText;
      if(statusIndicatorParent)
         statusIndicatorParent.insertBefore(statusIndicator,statusIndicatorParent.firstChild);
      var req = getXmlHttpRequestObject();
      // only required if last open param is missing or true
      if(callbackFunc!=false)
         req.onreadystatechange = function() { httpRequestCallback(req,callbackFunc);}
		if(destinationURL) {
	      req.open("POST",destinationURL,callbackFunc!=false);
   	   //POST variables to php code only
      	if(typeof(usePost)=='undefined' || usePost) {req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');}
      	req.send(xmlData);
		}
		// If no destinationURL provided, log an error.
		// October 6, 2011 - Chris Poirier
		else {
			var date = new Date();
			var userData = '(SID="'+SID+'"';
			if(IP) userData += ', IP='+IP;
			userData += ')';
			var postData = 'log_file='+escape('ajaxURL.err')+'&logged_data='+escape('['+date.toGMTString()+'] '+userData+' Destination URL empty in /common/scripts/ajax2.0.js.');
			httpRequest(postData, '/log_service.php', null, '', _donothing, true);
		}
   } else {
      alert("There was a problem reading your user ID. Please go to our contact page and notify technical support.");
   }
}
function _donothing() {}
function checkSaveBlank() {}
function httpRequestCallback(req,callbackFunc) {
   if(req && req.readyState==4) {
      if(req && req.status==200) {
         callbackFunc(req,statusIndicator,true);
      } else {
	//alert("There was a problem transfering information ("+req.status+": "+req.statusText+")");
         callbackFunc(req,statusIndicator,false);
      }
   }
}
function str2XML(str) {
   var xml;
   if(window.ActiveXObject) {
      xml = new ActiveXObject("MSXML2.DOMDocument");
      xml.loadXML(str);
      xml.setProperty("SelectionLanguage","XPath");
   } else {
      xml = (new DOMParser).parseFromString(str, "text/xml");
   }
   return xml;
}
function FormToString(formID){
   str = ''

   var myForm = getForm(formID);
   var el = myForm.elements;
   
   for (var elems=0; elems < myForm.length;elems++) {
      if (el[elems].name != ""){
         str += escape(el[elems].name) + '=';
         if ( el[elems].type == "checkbox") {
            str += el[elems].checked;
         }
         else if( el[elems].type == "radio") {
            var radiogroup = el[el[elems].name];
            for (var j=0; j<radiogroup.length; ++j) {
               if(radiogroup[j].checked) {
                 str += radiogroup[j].value;
               }
            }
            elems = elems + radiogroup.length - 1;
         } else {
             str += escape(el[elems].value);
         }
         str += '&';
      }
   }
   return str;
}

