/*	romke Ajax Interface - Class stuff
	2006(c) romke Roman Barczyński (romke/na/estrefa.pl)
	$Id: Ajax.js 121 2008-04-19 22:21:38Z romke $
	vim: set ts=4 : */

Ajax = function (aBaseURI, aReferer) {
	var ajax = {
		BaseURI : aBaseURI,
		GETParams : new Array(),
		POSTParams : new Array(),
		Referer : aReferer,
		sendTimeParam : true,

		AddGETParam : function (name, value) {
			this.GETParams.push(name + '=' + encodeURIComponent(value));
		},

		AddPOSTParam : function (name, value) {
			this.POSTParams.push(name + '=' + encodeURIComponent(value));
		},

		TimeParam : function () {
			if (this.sendTimeParam) {
				return '?_pch=' + (new Date().getTime()); /* pch - Prevent Cache Hack */
			} else {
				return '?';
			}
		},

		_Open : function (method) {
			var URIParams = this.GETParams.join('&');

			if (window.XMLHttpRequest) { /* mozilla */
				this.HTTP = new XMLHttpRequest();
			} else if (window.ActiveXObject) { /* ie */
				try { this.HTTP = new ActiveXObject("Msxml2.XMLHTTP"); }
				catch (e) {
					try { this.HTTP = new ActiveXObject("Microsoft.XMLHTTP"); }
					catch (E) { this.HTTP = false; }
				}
			}

			var _self = this;

			this.HTTP.onreadystatechange = function () {
				if (_self.HTTP.readyState == 4) {
					if (_self.HTTP.status != 200) {
						if (_self.onError != null) _self.onError();
						delete _self.HTTP;
					} else {
						if (_self.onSuccess != null) _self.onSuccess();
					}
				}
			}

			if (!this.HTTP) return false;

			this.HTTP.open(method, this.BaseURI + this.TimeParam() + ((URIParams != '') ? '&' + URIParams : ''), true);
			if (this.Referer != '') this.HTTP.setRequestHeader('Referer', this.Referer);

		},

		GET : function () {
			this._Open('GET');
			this.HTTP.send(null);
		},

		POST : function () {
			var POSTParams = this.POSTParams.join('&');
			this._Open('POST');
			this.HTTP.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
			this.HTTP.setRequestHeader('Content-length', POSTParams.length);
			this.HTTP.setRequestHeader('Connection', 'close');
			this.HTTP.send(POSTParams);
		}

	};

	return ajax;
}
