
// Check to make sure we haven't already run this script
if (!ajaxJsRunP) {
var ajaxJsRunP = true;
var agt = navigator.userAgent.toLowerCase();
var is_mac = (agt.indexOf("mac") != -1);

var ad_host = "";
var cookie_name = "";

var post_ajax_command = "";
var pre_ajax_command = "";

var ajax_save_history_by_default = true;

var ajax_array = new Array();
var ajax_concurrent = true;
var ajax_debug_p = false;
var ajax_add_from_ajax = true;

var ajax_history_array = new Array();
var ajax_history_current = ajax_history_array.length - 1;
var ajax_history_div = "main"; // the id of the object whose html we should remember

function iframeDoc(iframe) {
  var doc = null;  
  if(iframe.contentDocument)  
    // Firefox, Opera  
    doc = iframe.contentDocument;  
  else if(iframe.contentWindow)  
    // Internet Explorer  
    doc = iframe.contentWindow.document;  
  else if(iframe.document)  
    // Others
    doc = iframe.document;  
  return doc;
}

// Start AJAX history section (still being worked on)
function AJAXHISTORY(refresh_command) {
    if (refresh_command) {
	this.refresh_command = refresh_command;
    } else {
	this.refresh_command = "";
    }
    if (document.getElementById(ajax_history_div)) {
	this.html = document.getElementById(ajax_history_div).innerHTML;
    }
}

function loadAjaxHistory(history_id) {
    if (document.getElementById(ajax_history_div)) {
	if (ajax_history_current != history_id) {
	    ajax_history_current = history_id;
	    var hist = ajax_history_array[history_id];
	    if (hist) {
		document.getElementById(ajax_history_div).innerHTML = hist.html;
		if (hist.refresh_command != "") {
		    hist.refresh_command();
		}
	    }
	}
    }
}

function setAjaxHistory(command) {
    if (document.getElementById(ajax_history_div)) {
	while (ajax_history_array.length > ajax_history_current + 1) {
	    ajax_history_array.pop();
	}
	if (!document.getElementById('ajaxhistory')) {
	    var iframe = document.createElement('iframe');
	    iframe.id = "ajaxhistory";
	    iframe.style.display = 'none';
	    document.body.appendChild(iframe);
	}
	var history_id = ajax_history_array.length;
	ajax_history_current = history_id;
	iframeDoc(document.getElementById('ajaxhistory')).location = "/ajax_history.php?history_id=" + history_id;
	ajax_history_array[history_id] = new AJAXHISTORY(command);
    }
}
// End AJAX history section

/**
 * Create an AJAX object
 * @access public
 **/
function AJAX (url, resultObjectID, message, forcerefresh, vars, checkstate_func, save_history) {
    if (ajax_debug_p == true) {
	setTimeout("throw Error('Enter: AJAX')", 0);
    }
    var req;
    if (window.XMLHttpRequest) {
	req = new XMLHttpRequest();
    } else if (window.ActiveXObject  && !is_mac) {
	req = new window.ActiveXObject("Msxml2.XMLHTTP");
    } else {
	throw Error ("Can not create request Object");
    }
    this.req = req;
    if (save_history == false || save_history == true) {
	this.save_history = save_history;
    } else {
	this.save_history = ajax_save_history_by_default;
    }
    this.resultObjectID = resultObjectID;
    if (resultObjectID && resultObjectID != "") { 
	this.resultObject = document.getElementById(resultObjectID);
    } else {
	this.resultObject;
    }
    if (!this.resultObject && resultObjectID != "") {
	this.rename_counter = 0;
	var ajax_obj = this;
	function resetResultObject() {
	    ajax_obj.rename_counter++;
	    ajax_obj.resultObject = document.getElementById(ajax_obj.resultObjectID);
	    if (!ajax_obj.resultObject) {
		setTimeout(resetResultObject, 0);
	    }
	    if (ajax_obj.rename_counter == 20) {
		alert("Can not find object " + ajax_obj.resultObjectID);
	    }
	}	
	setTimeout(resetResultObject, 100);
    }
    
    this.url = url;
    if (message) {
       this.message = message;
    } else {
	this.message = "";
    }
    this.forcerefresh = forcerefresh;
    this.vars = vars;
    if (checkstate_func) {
	this.checkstate_func = checkstate_func;
    } else {
	this.checkstate_func = "";
    }
    if (ajax_debug_p == true) {
	setTimeout("throw Error('Exit: AJAX')", 0);
    }
    this.ajax_id = ajax_array.length;
    this.orig_height = "";
    this.killed = false;
    ajax_array[ajax_array.length] = this;
}

/**
 * Kill the ajax process
 * @access public
 **/
AJAX.prototype.kill = function() {
    this.killed = true;
    this.req.abort();
}

/**
 * The default checkstate command to use for ajax functions
 * @access private
 **/
AJAX.prototype.defaultcheckstate = function() {
    if (ajax_debug_p == true) {
	setTimeout("throw Error('Enter: defaultcheckstate')", 0);
    }
    if (this.killed) {
	return;
    }
    var ajax_obj = this;
    var ajax_i;
    stats = document.getElementById("output");
    if (ajax_debug_p == true) {
	setTimeout("throw Error('Checkstate: readyState: " + this.req.readyState + "')", 0);
    }
    if (stats) {
	stats.innerHTML = this.req.readyState;
    }
    if (this.req.readyState == 4) {
	if (ajax_debug_p == true) {
	    setTimeout("throw Error('Checkstate: status: " + this.req.status + "')", 0);
	}
	
	if (this.req.status == 500) {
	    var the_error_obj = window.open("", "error",'width=800,height=600,resizable=yes,toolbar=no,location=on,scrollbars=yes,status=yes');	
	    the_error_obj.focus();
	    the_error_obj.moveTo(1,1);
	    the_error_obj.document.write(this.req.responseText);
	    if (ajax_debug_p == true) {
		setTimeout("throw Error('Exit: checkstate')", 0);
	    }
	    return;
	}
	var ua = navigator.userAgent.toLowerCase();
	isIE = ((ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1) && (ua.indexOf("webtv") == -1));
	isSafari = (ua.indexOf("safari") != -1);
	var use_xml = 0;
	if (isSafari) {
	    x = document.createElement('div');
	    x.innerHTML = this.req.responseText;
	
	    var thedocument = x.getElementsByTagName('thedocument');
	    if (thedocument[0]) {
		use_xml = 1;
	    }
	}
	if (this.req.responseXML && this.req.responseXML.documentElement) {
	    var messages = this.req.responseXML.getElementsByTagName('message');
	    document.getElementById('ajaxOutPutMessage').innerHTML="";
	    if (messages.length > 0) {
		document.getElementById('ajaxOutPutMessage').innerHTML = messages[0].firstChild.data;
	    } else {
		document.getElementById('ajaxOutPutMessage').innerHTML="";
	    }
	    if (this.resultObjectID != "") {
		var body = this.req.responseXML.getElementsByTagName('thebody');
		this.resultObject.style.height = this.orig_height;
		this.resultObject.innerHTML = "";
		if (body[0]) {
		    this.resultObject.innerHTML = (body[0].firstChild.data);
		}
	    }
	    var post_ajaxs = this.req.responseXML.getElementsByTagName('post_ajax');
	    var ajax_commands;
	    for (ajax_i= 0; ajax_i < post_ajaxs.length; ajax_i++) {
		ajax_commands = post_ajaxs[ajax_i].firstChild.nodeValue;
		ajax_commands=ajax_commands.replace(/&amp;/g,"\&");
		ajax_commands=ajax_commands.replace(/&lt;/g,"\<");
		ajax_commands=ajax_commands.replace(/&gt;/g,"\>");
		eval(ajax_commands);
	    }
	} else {
	    if (this.resultObjectID != "") {
		this.resultObject.innerHTML = this.req.responseText;
	    }
	    x = document.createElement('div');
	    x.innerHTML = this.req.responseText;
	    if (isIE) {
		var result = this.req.responseText;
		if (result.replace("<script>", "") != result) {
		    result = result.replace(/\n/g, 'RETURNCHARREPLACE');
		    result = result.replace(/\<\/script\>.*?<script>/gim, "OPENSCRIPTCLOSESCRIPT");
		    result = result.replace(/\<\/script\>.*/, "");
		    result = result.replace(/.*\<script\>/, "");
		    result = result.replace(/RETURNCHARREPLACE/g, '\n');
		    var post_ajaxs = result.split(/OPENSCRIPTCLOSESCRIPT/);
		    for (var ajax_i = 0; ajax_i < post_ajaxs.length; ajax_i++) {
			setTimeout(post_ajaxs[ajax_i], 0);
		    }
		}
	    } else {
		var post_ajaxs = x.getElementsByTagName('script');
		//	alert(post_ajaxs.innerHTML);
		for (var ajax_i = 0; ajax_i < post_ajaxs.length; ajax_i++) {
		    //alert(post_ajaxs[ajax_i].innerHTML);
		    setTimeout(post_ajaxs[ajax_i].innerHTML, 0);
		}
	    }
	    if (this.resultObjectID == "" && document.getElementById('ajaxOutPutMessage')) {
		document.getElementById('ajaxOutPutMessage').innerHTML = "";
	    }
	}
	if (post_ajax_command) {
	    eval(post_ajax_command);
	}
	
	setTimeout(this.from_response_javascript, 0);
	if (this.save_history) {
	    function tmp() {
		setAjaxHistory();
	    }
	setTimeout(tmp, 0);	    
	}

    }
    if (ajax_debug_p == true) {
	setTimeout("throw Error('Exit: checkstate')", 0);
    }
};

/**
 * After the checkstate has been run check to see if there is an object
 * with the id of post_ajax.  If there is treat its HTML as javascript to run
 * @access private
 **/
AJAX.prototype.from_response_javascript = function() {
    if (ajax_debug_p == true) {
	setTimeout("throw Error('Enter: from_response_javascript')", 0);
    }
    if (this.killed) {
	return;
    }
    var obj = document.getElementById('post_ajax');
    if (obj) {
	if (obj.innerHTML != "") {
	
	    var commands = obj.innerHTML;
	    commands=commands.replace(/&amp;/g,"\&");
	    commands=commands.replace(/&lt;/g,"\<");
	    commands=commands.replace(/&gt;/g,"\>");
	
	    eval(commands);
	
	    obj.innerHTML = "";
	    obj.id = '';
	    setTimeout(from_response_javascript, 0);
	}
    }
    if (ajax_debug_p == true) {
	setTimeout("throw Error('Exit: from_response_javascript')", 0);
    }
};

/**
 * Commands to run before making an ajax call
 * @access private
 **/
AJAX.prototype.prepost = function() {
    if (ajax_debug_p == true) {
	setTimeout("throw Error('Enter: prepost')", 0);
    }
    if (this.killed) {
	return;
    }
    if (this.message != "") {
	var ajaxOutPutMessage = document.getElementById('ajaxOutPutMessage');
	if (!ajaxOutPutMessage) {
	    ajaxOutPutMessagex = document.createElement('div');
	    ajaxOutPutMessagex.id='ajaxOutPutMessage';
	    ajaxOutPutMessagex.style.position='absolute';
	    ajaxOutPutMessagex.style.top=0;
	    ajaxOutPutMessagex.style.left=0;
	    ajaxOutPutMessagex.style.textAlign="left";
	    ajaxOutPutMessagex.style.filter="alpha(opacity=75)";
	    ajaxOutPutMessagex.style.opacity=.75;
	    ajaxOutPutMessagex.style.background="#FFFFFF";
	    if (this.resultObjectID == "") {
		ajaxOutPutMessagex.innerHTML = this.message;
	    }
	    document.body.insertBefore(ajaxOutPutMessagex, document.body.childNodes[0]);
	} else {
	    if (this.resultObjectID == "") {
		ajaxOutPutMessage.innerHTML = this.message
	    }
	}	
    }
    var change_heights = 0;
    if (change_heights) {
	if (this.resultObjectID != "") {
	    this.orig_height = this.resultObject.style.height;
	}
    }
    if (this.resultObjectID != "" && this.message != "") {
	if (change_heights) {	
	    var top_height_resultObjectID = this.resultObjectID + "_top_height_resultObjectID";
	    var bottom_height_resultObjectID = this.resultObjectID + "_bottom_height_resultObjectID";
	    if (!document.getElementById(top_height_resultObjectID)) {
		this.resultObject.innerHTML = "<div id='" + top_height_resultObjectID + "'></div>" + this.resultObject.innerHTML + "<div id='" + bottom_height_resultObjectID + "'></div>";
		setTimeout('xmlprepost(' + ajax_id + ')', 0);
		if (ajax_debug_p == true) {
		    setTimeout("throw Error('Exit: prepost')", 0);
		}
		return;
	    } else {
		this.resultObject.style.height = findPosY(document.getElementById(bottom_height_resultObjectID)) - findPosY(document.getElementById(top_height_resultObjectID));
	    }	
	}
	
	this.resultObject.innerHTML = this.message;
	if (ajax_debug_p == true) {
	    setTimeout("throw Error('Exit: prepost')", 0);
	}
    }
};

/**
 * The the core of the ajax.  Actually perform the connection to the server.
 * @access private
 **/
AJAX.prototype.engine = function() {
    if (ajax_debug_p == true) {
	setTimeout("throw Error('Enter: engine')", 0);
    }
    if (this.killed) {
	return;
    }

    if (pre_ajax_command) {
	eval(pre_ajax_command);
    }
    if (!ajax_concurrent) {
	if (this.ajax_id > 0) {
	    if (ajax_array[this.ajax_id - 1].req.readyState < 4) {
		var ajax_obj = this;
		function tmp() {
		    ajax_obj.engine();
		}
		setTimeout(tmp, 0);
		if (ajax_debug_p == true) {
		    setTimeout("throw Error('Exit: engine')", 0);
		}
		return;
	    }
	}
    }
    if (this.forcerefresh) {
	document.cookie = cookie_name + "=1; domain=." + ad_host + "; path=/";
    }	
    var ajax_obj = this;
    if (this.checkstate_func == "") {	
	this.req.onreadystatechange=function () {ajax_obj.defaultcheckstate()};
    } else {
	this.req.onreadystatechange=function () {ajax_obj.checkstate_func(ajax_obj.ajax_id)};
    }
    if (!this.vars) {
	if (ajax_add_from_ajax) {
	    if (this.url.search(/\?/) != -1) {
		this.url += "&from_ajax=true";
	    } else {
		this.url += "?from_ajax=true";
	    }
	}
	this.req.open("GET", this.url, true);
    } else {
	if (ajax_add_from_ajax) {
	    this.vars += "&from_ajax=true";
	}
	this.req.open("POST", this.url, true);
	this.req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	this.req.setRequestHeader("Content-length", this.vars.length);
	this.req.setRequestHeader("Connection", "close");
    }
    this.req.send(this.vars);
    if (ajax_debug_p == true) {
	setTimeout("throw Error('Exit: engine')", 0);
    }
    return;
};

/**
 * Convert a form to a cgi string.
 * @access private
 **/
AJAX.prototype.format_form_for_ajax = function(form) {	
    if (ajax_debug_p == true) {
	setTimeout("throw Error('Enter: format_form_for_ajax')", 0);
    }
    if (this.killed) {
	return;
    }
    var str = "";
    for (var i =0 ; i < form.length; i++) {
	if (form[i].name) {
	    if (form[i].type=='checkbox') {
		if (form[i].checked) {
		    str += form[i].name + "=" + escape(form[i].value) + "&";
		} else {
		    str += form[i].name + "=&";
		}
	    } else if (form[i].type=='radio') {
		if (form[i].checked) {
		    str += form[i].name + "=" + escape(form[i].value) + "&";
		}
	    } else {
		str += form[i].name + "=" + escape(form[i].value) + "&";
	    }
	}
    }
    if (ajax_debug_p == true) {
	setTimeout("throw Error('Exit: format_form_for_ajax')", 0);
    }
    return str;
};

/**
 * Convert a form to a cgi string and save it into the AJAX object
 * @access public
 **/
AJAX.prototype.xmlpostform = function(form) {
    if (ajax_debug_p == true) {
	setTimeout("throw Error('Enter: xmlpostform')", 0);
    }
    if (this.killed) {
	return;
    }

    this.vars = this.format_form_for_ajax(form);
    this.url = form.action;
    this.main();
    if (ajax_debug_p == true) {
	setTimeout("throw Error('Exit: xmlpostform')", 0);
    }
    return false;
};

/**
 * Run the AJAX command
 * @access public
 **/
AJAX.prototype.main = function() {    
    if (this.killed) {
	return;
    }
    var ajax_obj = this;
    if (!this.resultObject && this.rename_counter <= 20 && this.resultObjectID != "") {
	function rerun() {
	    ajax_obj.main();
	}
	setTimeout(rerun, 20);
    } else if(this.resultObject || this.resultObjectID == "") {
	this.prepost();
	function tmp() {
	    ajax_obj.engine();
	}
	setTimeout(tmp, 0);
    } else {
	alert("didn't run ajax to connect to " + this.url + " because " + this.resultObjectID + " doesn't exist");
    }

};

/**
 * Removed AJAX objects from ajax_array that have been killed or are finished running
 **/
function clean_ajax() {
    var new_ajax_array = new Array();
    for (var i = 0; i < ajax_array.length; i++) {
	if (ajax_array[i].req.readyState < 4 && !ajax_array[i].killed) {
	    var new_ajax_id = new_ajax_array.length;
	    ajax_array[i].ajax_id = new_ajax_id;
	    new_ajax_array[new_ajax_id] = ajax_array[i];
	}
    }
    ajax_array = new_ajax_array;
}

function findPosY(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
	while (obj.offsetParent) {
	    curtop += obj.offsetTop;
	    obj = obj.offsetParent;
	}
    }
    else if (obj.y)
	curtop += obj.y;
    return curtop;
}

/**
 * Convert a form into an AJAX object and run it.
 **/
function xmlpostform(form, resultObjectID, message, forcerefresh, checkstate_func) {
    if (ajax_debug_p == true) {
	setTimeout("throw Error('Enter: xmlpostform')", 0);
    }
    new AJAX(form.action, resultObjectID, message, forcerefresh, "", checkstate_func).xmlpostform(form);
    if (ajax_debug_p == true) {
	setTimeout("throw Error('Exit: xmlpostform')", 0);
    }
    return false;
}

/**
 * Build the AJAX object and run it.
 **/
function xmlquick (url, resultObjectID) {
    if (ajax_debug_p == true) {
	setTimeout("throw Error('Enter/Exit: xmlquick')", 0);
    }
    new AJAX(url, resultObjectID).main();
    if (ajax_debug_p == true) {
	setTimeout("throw Error('Exit: xmlquick')", 0);
    }
}

/**
 * Build the AJAX object and run it.  (same as xmlquick but sets more parameters)
 **/
function xmlget (url, resultObjectID, message, forcerefresh, checkstate_func) {
    if (ajax_debug_p == true) {
	setTimeout("throw Error('Enter/Exit: xmlget')", 0);
    }
    new AJAX(url, resultObjectID, message, forcerefresh, "", checkstate_func).main();
    if (ajax_debug_p == true) {
	setTimeout("throw Error('Exit: xmlget')", 0);
    }
}

/**
 * Build the AJAX object and run it as a post command.
 **/
function xmlpost (url, resultObjectID, message, forcerefresh, vars, checkstate_func) {
    if (ajax_debug_p == true) {
	setTimeout("throw Error('Enter: xmlpost')", 0);
	setTimeout("throw Error('XMLPOST vars = " + vars + "')", 0);
    }
    new AJAX(url, resultObjectID, message, forcerefresh, vars, checkstate_func).main();

    if (ajax_debug_p == true) {
	setTimeout("throw Error('Exit: xmlpost')", 0);
    }
}

/**
 * Read a cookie in javascript
 **/
function readCookie(name) {
    if (ajax_debug_p == true) {
	setTimeout("throw Error('Enter: readCookie')", 0);
    }
    var ca = document.cookie.split(';');
    var nameEQ = name + "=";
    for(var i=0; i < ca.length; i++) {
	var c = ca[i];
	while (c.charAt(0)==' ') c = c.substring(1, c.length); //delete spaces
	if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    
    if (ajax_debug_p == true) {
	setTimeout("throw Error('Exit: readCookie')", 0);
    }
    return null;
}

/**
 * Trim spaces off a string.
 * (Not needed for the ajax lib but comes in handy.)
 **/
function leftTrim(sString) {
    if (ajax_debug_p == true) {
	setTimeout("throw Error('Enter: leftTrim')", 0);
    }
    while (sString.substring(0,1) == ' ') {
	sString = sString.substring(1, sString.length);
    }
    if (ajax_debug_p == true) {
	setTimeout("throw Error('Exit: leftTrim')", 0);
    }
    return sString;
}

function rightTrim(sString) {
    if (ajax_debug_p == true) {
	setTimeout("throw Error('Enter: rightTrim')", 0);
    }
    while (sString.substring(sString.length-1, sString.length) == ' ') {
	sString = sString.substring(0,sString.length-1);
    }
    if (ajax_debug_p == true) {
	setTimeout("throw Error('Exit: rightTrim')", 0);
    }
    return sString;
}

function trimAll(sString) {
    if (ajax_debug_p == true) {
	setTimeout("throw Error('Enter: TrimAll')", 0);
    }
    while (sString.substring(0,1) == ' ') {
	sString = sString.substring(1, sString.length);
    }
    while (sString.substring(sString.length-1, sString.length) == ' ') {
	sString = sString.substring(0,sString.length-1);
    }
    if (ajax_debug_p == true) {
	setTimeout("throw Error('Exit: TrimAll')", 0);
    }
    return sString;
}

// End of if (!ajaxJsRunP) block
}
