/****************************************************************************
 * Class:   Downloader
 * Author:  Rodd
 * Purpose: Create an HTTP downloader object compatible with IE and Mozilla
 * Methods:
 *
 *   startDownload(<URI>, <callback>)
 *         Makes an HTTP request to <URI>
 *         Passes the HTTP response to the function <callback>
 *
 *   getURL(<URI>)
 *         Makes an HTTP request to <URI>
 *         Return the HTTP response
 *
 ****************************************************************************/

function Downloader() {
	var dl;

	if (typeof ActiveXObject == 'function') {
		dl = new ActiveXObject("MSXML2.XMLHTTP");
	}
	else {
		dl = new XMLHttpRequest;
	}

	/*
	 * Public Methods
	 */
	this.startDownload = function(url, callback, forceReload) {
		if(forceReload) {
			var cacheBuster = (new Date()).getTime();
			if(url.indexOf('?') >= 0)
				url += '&' + cacheBuster
			else
				url += '?' + cacheBuster
		}
		try {
			dl.open("GET", url, false);
			dl.send('');
			if(typeof callback == 'function') {
				callback(dl.responseText);
			}
			return true;
		}
		catch(e) {
			return false;
		}
	}

	this.getURL = function(url, forceReload) {
		if(forceReload) {
			var cacheBuster = (new Date()).getTime();
			if(url.indexOf('?') >= 0)
				url += '&' + cacheBuster
			else
				url += '?' + cacheBuster
		}

		try {
			dl.open("GET", url, false);
			dl.send('');
			return dl.responseText;
		}
		catch(e) {
			return null;
		}
	}


	this.postURL = function(url, postdata) {
		if(doPost(url, postdata)) {
			return dl.responseText;
		}
		else {
			return null
		}
	}

	this.postXML = function(url, postdata) {
		if(doPost(url, postdata)) {
			return dl.responseXML;
		}
		else {
			return null;
		}
	}

	this.getXML = function(url, forceReload) {
		if(forceReload) {
			var cacheBuster = (new Date()).getTime();
			if(url.indexOf('?') >= 0)
				url += '&' + cacheBuster
			else
				url += '?' + cacheBuster
		}

		try {
			dl.open("GET", url, false);
			dl.send('');
			return dl.responseXML;
		}
		catch(e) {
			return null;
		}
	}


	/*
	 * Private Methods
	 */
	function doPost (url, postdata) {
		var poststring = '';
		if(typeof postdata == 'object') {
			for(var item in postdata)
				poststring += (poststring.length > 0 ? '&' : '') + encodeURIComponent(item) + '=' + encodeURIComponent(postdata[item]);
		}
		else {
			poststring = postdata;
		}

		try {
			dl.open("POST", url, false);
			dl.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			dl.send(poststring);
			return true;
		}
		catch(e) {
			return false;
		}
	}

}
