
/*************************************************************
	generic code for processing ajax requests
*************************************************************/
//the number of simultaenous asynchronouse requests we can have
ajaxQueueNum = 20;

//our handlers.  These match the typeid tag in our xml response
registeredHandlers = new Array();
registeredHandlers["emailstatus"] = "writeEmailStatus";
registeredHandlers["searchcobroker"] = "writeCobrokerList";
registeredHandlers["companyselectlist"] = "writeCompanyList";
registeredHandlers["cobrokerinfo"] = "writeCobrokerInfo";
registeredHandlers["egmembers"] = "writeGroupMembers";
registeredHandlers["egcontacts"] = "writeGroupContacts";
registeredHandlers["companyinfo"] = "writeCompanyInfo";
registeredHandlers["searchprospect"] = "writeProspectResults";
registeredHandlers["searchagent"] = "writeAgentResults";
registeredHandlers["listings"] = "writeListings";

//store our requests in here
ajaxRequests = new Array();
ajaxRequests[0] = 0;

//parses xml response and hands it off to the appropriate function if it exists
function parseResponse(req) {

	var respXML = req.responseXML;
	var respTXT = req.responseText;

	var z = 0;

	//determine if there's no xml info available
 	if (!respXML || (respXML && !respXML.hasChildNodes())) {

		//if there's no text either, get out
		if (!respTXT) return false;

		//continue with txt processing
		//return the typeid value 

		//first, find the typeid hidden field
		pos = respTXT.indexOf("name=typeid");
		if (pos==-1) pos = respTXT.indexOf("name='typeid'");
		if (pos==-1) pos = respTXT.indexOf("name=\"typeid\"");
		if (pos==-1) return false;

		//extract the value from the field
		tmp = respTXT.substr(pos);
		valpos = tmp.indexOf("value=") + 6;
		endpos = tmp.indexOf(">");
		diff = endpos - valpos;
		tmp = tmp.substr(valpos,diff);
		elementName = tmp.replace(/[^a-zA-Z 0-9_-]+/g,'');

		//call the handling function
		if (registeredHandlers[elementName]) {
			
			func = eval(registeredHandlers[elementName]);
			func(respTXT);
			return true;

		}

		return false;

	}

	//carry on with xml processing
	var typeElement = respXML.getElementsByTagName("typeid");
	if (!typeElement[0]) return false;

	//get our function name for handling, and hand this off
	var elementName = typeElement[0].firstChild.nodeValue;

	// this is within a loop over all elements
	if (registeredHandlers[elementName]) {

		func = eval(registeredHandlers[elementName]);

		//only pass on an element to our handler function
		for (z=0;z<respXML.childNodes.length;z++) {
			if (respXML.childNodes[z].nodeType==1) {
				func(respXML.childNodes[z]);
				break;
			}
		}

		return true;

	//if there is no handler, return the text
	} else return false;

}

//handles our xml requests for getting data
function loadXMLReq(url,reqMode,noCache) {

	var xmlreq = null;
	var openIndex = 0;

	//default to GET if reqMode is not set
	if (!reqMode) reqMode = "GET";

	//find an opening in our queue to store the request information
	for (i=0;i<ajaxQueueNum;i++) {

		if (ajaxRequests[i] == null) {
			openIndex = i;
			break;
		}

	}

	//our callback function for processing the return from our xml request
	callBackFunc = function xmlHttpChange() {
				
				for (i=0;i<ajaxQueueNum;i++) {

					req = ajaxRequests[i];
					if (req==null) continue;

					if (req.readyState == 4) {

                    				if(req.status == 200) {

							//handle the response and empty this queue entry
							//we empty the queue first because a processing lag
							//seems to cause it to be called again
							ajaxRequests[i] = null; 
							if (!parseResponse(req)) {
								if (req.responseText.length > 0) {
									if (confirm("There was an error loading the page.  Do you wish to see the error text?")) {
										alert(req.responseText);
									}
								}
							}
						}

                			}
				}

			};

	if (window.XMLHttpRequest) {
		ajaxRequests[openIndex] = new XMLHttpRequest();
		ajaxRequests[openIndex].onreadystatechange = callBackFunc;
    		ajaxRequests[openIndex].open(reqMode, url, true);

		//if it's a post, send the proper header
		if (reqMode=="POST") ajaxRequests[openIndex].setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");

		//prevent caching if set
		if (noCache) ajaxRequests[openIndex].setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2005 00:00:00 GMT");

    		ajaxRequests[openIndex].send(null);
  	}
  	else if (window.ActiveXObject) {
    		ajaxRequests[openIndex]=new ActiveXObject("Microsoft.XMLHTTP");
    		if (ajaxRequests[openIndex]) {

			//append a random string to the url to prevent caching in ie if we are loading
			//an xml file directly
			if (url.indexOf(".xml") != '-1') {
				randstr = randomString();
				if (url.indexOf("?") != '-1') url += "&" + randstr;
				else url += "?" + randstr;
			}

      			ajaxRequests[openIndex].onreadystatechange = callBackFunc;
      			ajaxRequests[openIndex].open(reqMode,url,true);

			//if it's a post, send the proper header
			if (reqMode=="POST") ajaxRequests[openIndex].setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");

			//prevent caching if set
			if (noCache) ajaxRequests[openIndex].setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2005 00:00:00 GMT");

			//send headers to prevent ie from caching files that it thinks are static
      			ajaxRequests[openIndex].send();
    		}
  	}

}

//this function posts data from a form to a url
function postAjaxForm(docForm,url,reqMode) {

	query = form2Query(docForm);
	url += "&" + query;

	//just return the string if desired
	if (reqMode=="return") return url;
	else loadXMLReq(url,reqMode);

}


//this function converts a form's data to a query string to be passed to a server
//as a get or post.  The var docForm should be a reference to a <form>
function form2Query(docForm) {

	var strSubmitContent = '';
	var formElem;
	var strLastElemName = '';
	
	for (i = 0; i < docForm.elements.length; i++) {
		
		formElem = docForm.elements[i];

		switch (formElem.type) {

			// Text fields, hidden form elements
			case 'text':
			case 'hidden':
			case 'password':
			case 'textarea':
			case 'select-one':
				strSubmitContent += formElem.name + '=' + escape(formElem.value) + '&'
				break;
				
			// Radio buttons
			case 'radio':
				if (formElem.checked) {
					strSubmitContent += formElem.name + '=' + escape(formElem.value) + '&'
				}
				break;
				
			// Checkboxes
			case 'checkbox':
				if (formElem.checked) {
					strSubmitContent += formElem.name + '=' + escape(formElem.value) + '&';
				}
				break;
				
		}
	}
	
	// Remove trailing separator
	strSubmitContent = strSubmitContent.substr(0, strSubmitContent.length - 1);
	return strSubmitContent;

}


/**********************************************
	parse our xml into an associative array
	takes the top node as a reference
	ex:
	resp = req.responseXML;
	arr = parseXML(resp.firstChild);
**********************************************/

function parseXML(dataNode) {

	//get our objects
	var len = dataNode.childNodes.length;

	var arr = new Array();
	var keyarr = new Array();

	var n=0;
	var i = 0;

	while (dataNode.childNodes[i]) {

		var objNode = dataNode.childNodes[i];

		if (objNode.nodeType==1) {

			var keyname = objNode.nodeName;

			if (objNode.hasChildNodes()) {

				//if the key does not exist in our key array, added it and reset its counter
				if (!keyarr[keyname]) {
					keyarr[keyname] = 0;
					arr[keyname] = new Array();
				}

				n = keyarr[keyname];

				arr[keyname][n] = new Array();

				//store single length nodes here
				if (objNode.childNodes.length==1) arr[keyname] = objNode.firstChild.nodeValue;
				else {

					var c = 0;
					while (objNode.childNodes[c]) {

						var curNode = objNode.childNodes[c];
						var curName = curNode.nodeName;

						//only continue on nodes that are elements
 						if (curNode.nodeType==1) {

							if (document.all) {
								if (curNode.firstChild) {
									//there are nested tags here, get them ( I don't think this is a good check)
									if (curNode.firstChild.nodeType == 1) {
										arr[keyname][n][curName] = parseXML(curNode);
									} else  {
										arr[keyname][n][curName] = curNode.firstChild.nodeValue;
									}
								}
							} else {
								//there are nested tags here, get them ( I don't think this is a good check)
								if (curNode.childNodes.length > 1) {
									arr[keyname][n][curName] = parseXML(curNode);
								} else if (curNode.childNodes.length==1) {
									arr[keyname][n][curName] = curNode.firstChild.nodeValue;
								}
							}
						}

						c++;
					}

				}

				keyarr[keyname]++;

			}

		}

		i++;

	}

	return arr;

}

//set a floatStyle for an object
function setFloat(myvar,floatVal) {

        if (document.all) myvar.style.styleFloat = floatVal;
        else myvar.setAttribute("style","float:" + floatVal);

        return myvar;
}

//set a className value for an object
function setClass(myvar,classVal) {

        if (document.all) myvar.setAttribute("className",classVal);
        else myvar.setAttribute("class",classVal);

        return myvar;
}

//set an onclick event for an object
function setClick(myvar,click) {

        if (document.all) myvar.onclick = new Function(" " + click + " ");
        else myvar.setAttribute("onClick",click);

        return myvar;

}

//create a new form
function createForm(formType,formName,checked) {

	var curform;

	if (checked) formCheck = checked;
	else formCheck = "";

	//just don't ask...
	if (document.all) {
		fStr = "<input type=\"" + formType + "\" name=\"" + formName + "\" " + formCheck + ">";
		curform = document.createElement(fStr);
	}
	else {
		var curform = document.createElement("input");
		curform.setAttribute("name",formName);
		curform.setAttribute("type",formType);
		curform.setAttribute("id",formName);
		if (checked) curform.checked = true;
	}

	return curform;

}

//create a new form
function createSelect(formName,change) {

	var curform;

	//just don't ask...
	if (document.all) {

		if (change) onChange = "onChange=\"" + change + "\"";
		else onChange = "";

		fStr = "<select name=\"" + formName + "\" id=\"" + formName + "\" " + onChange + ">";
		curform = document.createElement(fStr);
	}
	else {
		var curform = document.createElement("select");
		curform.setAttribute("name",formName);
		curform.setAttribute("id",formName);
		if (change) curform.setAttribute("onChange",change);
	}

	return curform;

}

//set an onclick event for an object
function setChange(myvar,click) {

        if (document.all) myvar.onchange = new Function(" " + click + " ");
        else myvar.setAttribute("onChange",click);

        return myvar;

}

//set an onclick event for an object
function setKeyUp(myvar,click) {

        if (document.all) myvar.onkeyup = new Function(" " + click + " ");
        else myvar.setAttribute("onkeyup",click);

        return myvar;

}

function escapeBackslash(str) {

        var arr = str.split("\\");
        var newstr = arr.join("\\\\");

        return newstr;
}


