/**
* Common Javascript objects & routines
* 
* Mashup copyright Dylan Kuhn 2006.
*/

/**
* XML Service object
*/
function TodmXmlRequest () {
	this.request = GXmlHttp.create();
}

// Create and discard an initial object.
// This forces the prototype object to be created in JavaScript 1.1
new TodmXmlRequest();

TodmXmlRequest.prototype.xml_id = 5;

TodmXmlRequest.prototype.strings = {
	request_failed:'Request Failed'
};

TodmXmlRequest.prototype.messages = [];

TodmXmlRequest.prototype.makeUrl = function (args) {
	var url_arr = ['index.php?id=',this.xml_id];
	for (field in args) {
		url_arr.push('&');
		url_arr.push(field);
		url_arr.push('=');
		url_arr.push(encodeURIComponent(args[field]));
	}
	return url_arr.join('');
}

TodmXmlRequest.prototype.verifyResponse = function () {
	if (this.request.status == 200) {
		var xml_doc = this.request.responseXML;
		if (!xml_doc) {
			throw this.strings.request_failed + ': ' + this.request.responseText + ' for ' + this.url;
		}
		var confirmations = xml_doc.getElementsByTagName('confirmation');
		if (confirmations.length > 0) {
			return true;
		}
		var errors = xml_doc.getElementsByTagName('error');
		if (errors.length == 0) {
			throw this.strings.request_failed + ': ' + this.request.responseText;
		} else {
			throw this.strings.request_failed + ' ' + 
				errors[0].getElementsByTagName('service')[0].firstChild.nodeValue + ': ' +
				errors[0].getElementsByTagName('message')[0].firstChild.nodeValue;
		}
	} else {
		throw this.strings.request_failed + ': Status ' + this.request.status + ' for ' + this.url;
	}
}

TodmXmlRequest.prototype.onFailure = function (msg) {
	this.messages.push(msg);
}

TodmXmlRequest.prototype.onSuccess = function () {
}

TodmXmlRequest.prototype.requestChange = function () {
	if (this.request.readyState == 4) {
		try {
			this.verifyResponse();
			this.onSuccess();
		} catch (msg) {
			this.onFailure(msg);
		}
	}
}

TodmXmlRequest.prototype.execute = function (method,args,async) {
	this.url = this.makeUrl(args);
	this.request.open('GET',this.url,async);
	if (async) {
		var _this = this;
		this.request.onreadystatechange = function () {_this.requestChange()};
		this.request.send(null);
		return true;
	} else {
		this.request.send(null);
		this.verifyResponse();
		return this.request.responseXML;
	}
}

