/**
 * Handels ajax calls.
 *
 * @copyright	Daniel Lehmann, DreamMedia, Berlin, Germany (www.dreammedia-bny.com)
 * @author		Daniel Lehmann <code@dreammedia-bny.com>
 * @version		1.0
 * @date        09.09.2011
 */


/**
 * The constructor.
 *
 * @param	url		the url of the backend script which handels the call
 */
function Ajax(url) {
	
	this.url = url;
	
}

/**
 * Calls the backend script.
 *
 * If the backend returns an empty string, the callback function will be called with success equals false.
 * If call returns the status 0 (response was empty, not even headers were returned, closed gracefully - TCP FIN, page changed before returned), 
 * the parameter "success" of the callback function will contain the value 0.
 *
 * Returns the success of the call, not of the respons.
 *
 *
 * @param	values		values in the form of an associative array which gets send to the backend script. optional
 * @param	callback	the callback function of the ajax call. it gets to parameters (values:String, success:Boolean/0). optional
 * @param	method		the method of the call ("GET" or "POST"). optional - default is "GET"
 * @param	asyncronous	is the call asyncronous. optional - default is true
 * @return	boolean
 */
Ajax.prototype.call = function (values, callback, method, asyncronous) {	
               
	var request = null;
	
	try {
		request = new XMLHttpRequest();
	} catch (e){
		try {
			request = new ActiveXObject("Msxml2.XMLHTTP")
		} catch (e){
			try {
				request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (failed){
				request = null;
			}
		}  
	}
	
	if (request == null) {
		if (callback) callback(null, false);
		return false;
	}
	
	
	if (typeof values == "undefined") values = new Array();
	if (typeof method == "undefined") method = "GET";
	method = method.toUpperCase();
	if (method != "GET" && method != "POST") method = "GET";
	if (typeof asyncronous == "undefined") asyncronous = true;
	

	var data = "";
	for (var value in values) data += "&"+value+"="+encodeURIComponent(values[value]);
	data = data.substr(1);
	
	
	var url = this.url;
	if (method == "GET") {
		url += "?" + data;
		data = null;
	}
	
	
	var checkData = function () {
		switch(request.readyState) {
			case 4:
				if (request.status != 200) {
					if (request.status == 0) return 0;
					return false;
				} else {    
					if (request.responseText == "") return false;
					else return true;
				}
				break;
			default:
				break;
		}
		return null;	
	}
	
	var onData = function () {
		var success = checkData();
		if (success === null) return;
		if (callback) {
			if (!success) callback(null, success);
			else callback(this.responseText, true);
		}
	}
  
	
	request.open(method, url, asyncronous);
	request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	request.onreadystatechange = onData;
	request.send(data);
	
	
	return true;
	
}
	
