/* This code is under the open source BSD license. See included license.txt */
/* Code that handles the XMLHttp object. */

/* Some things I want todo:
   * Forms (submit_form("form_name"))
   * More to come when I think of them...
   * If you think of anything, tell me!
   */

/* Gets a fresh XMLHttp object ready for use! */
function init_object() {
	/* This code was takken from http://jibbering.com/2002/4/httprequest.html */	
	var xmlhttp=false;
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	// JScript gives us Conditional compilation, we can cope with old IE versions.
	// and security blocked creation of the objects.
	 try {
	  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	 } catch (e) {
	  try {
	   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	  } catch (E) {
	   xmlhttp = false;
	  }
	 }
	@end @*/
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
		try {
			xmlhttp = new XMLHttpRequest();
		} catch (e) {
			xmlhttp=false;
		}
	}
	if (!xmlhttp && window.createRequest) {
		try {
			xmlhttp = window.createRequest();
		} catch (e) {
			xmlhttp=false;
		}
	}
	return xmlhttp;
}

/* Performs a simple get on url, then executes f with the return value.
   Good for simple stuff.
 */
function get_simple(url,f){
	var response = "";
	request = init_object();
	request.open("GET",url,true);
	request.onreadystatechange = function(){
		if (request.readyState == 4){
			response = request.responseText;
			delete request;
			eval(f);
		}
	}
	request.send(null); // Send a null to let the server know we're done.
}

/* Submits form and runs result.  Pretty simple.  Only supports GET for now though.  POST Comming. */
function submit_form(form,result){
	if (form.method == "post"){
		alert("Sorry, sumitting POST forms does not work yet...");
		return false;
	}
	var count = 0;
	var get_vars = "";
	url = form.action;
	for (count = 0; count < form.elements.length; ++count){
		if (form.elements.item(count).name) // Only submit the element if it has a name
			get_vars = get_vars + (get_vars ? '&' : '?') + form.elements.item(count).name + "=" + escape(form.elements.item(count).value);
	}
	get_simple(url+get_vars, result);
	return false;
}

/* Some functions that make coding in JavaScript just a little less painfull. */

/* First tries to get an element by ID, then by name */
function element(id){
	if (elm = document.getElementById(id))
		return elm;
	else
		return document.getElementsByName(id)[0];
}

/* Returns the value of element. */
function val(elm){
	return element(elm).value;
}

/* Sets the innerHTML of an element. */
function setHTML(elm, html){
	element(elm).innerHTML = html;
}

	

