﻿function ajax(file){
	this.xmlhttp = null;
	this.argumentArray = new Array();
	this.resetData = function() {
		this.method = "GET";
		this.requestFile = file;
		this.responseStatus = new Array(2);
  	};
	this.resetFunctions = function() {
  		this.onLoading = function() { };
  		this.onLoaded = function() { };
  		this.onInteractive = function() { };
  		this.onCompletion = function() { };
  		this.onError = function() { };
		this.onFail = function() { };
	};
	this.init = function(){
		this.resetFunctions();
		this.resetData();
	}
	this.createAJAX = function() {
		try {
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e1) {
			try {
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) {
				this.xmlhttp = null;
			}
		}

		if (! this.xmlhttp) {
			if (typeof XMLHttpRequest != "undefined") {
				this.xmlhttp = new XMLHttpRequest();
			} else {
				this.failed = true;
			}
		}
	};
	this.setArgument = function(name,value){
		this.argumentArray.push(name + "=" + value);
	};
	this.getQueryString = function(){
		var qs = "";
		for(i=0;i<this.argumentArray.length;i++){
			if(i!=0) qs += "&";
			qs += this.argumentArray[i];
		}
		return qs;
	};
	this.runAjax = function(){
		if (this.xmlhttp) {
			if(this.method == "GET"){
				var finalUrl = this.requestFile + "?" + this.getQueryString() + "&timeStamp=" + new Date().getTime();
				this.xmlhttp.open("GET", finalUrl, true);
				this.xmlhttp.send(null);
			}
			else{
				var totalPostUrl = this.requestFile + "?timeStamp" + new Date().getTime();
				this.xmlhttp.open(this.method, totalPostUrl, true);
				try {
					this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				} catch (e) { }
				this.xmlhttp.send(this.getQueryString());
			}
			var owner = this;
			this.xmlhttp.onreadystatechange = function(){
				switch(owner.xmlhttp.readyState){
					case 1:
						owner.onLoading();
						break;
					case 2:
						owner.onLoaded();
						break;
					case 3:
						owner.onInteractive();
						break;
					case 4:
						owner.response = owner.xmlhttp.responseText;
						owner.responseXML = owner.xmlhttp.responseXML;
						owner.responseStatus[0] = owner.xmlhttp.status;
						owner.responseStatus[1] = owner.xmlhttp.statusText;
						
						if (owner.responseStatus[0] == "200") {
							owner.onCompletion();
						} else {
							owner.onError();
						}
						break;
				}
			}
		}
	};
	this.init();
	this.createAJAX();
}
