/*
** All ajax calls should come here
*/

document.domain="vampirefreaks.com";

/* ##### <CONFIG VARIABLES ##### */
// set this to 1 if you want the debug window to display
var debugLevel  = 1;

// this file should handle all ajax GET/POST requests
var ajaxControllerPHP   = "/serv/ajaxController.php";

/* ##### </CONFIG VARIABLES ##### */

function include(file) {
    var script  = document.createElement('script');
    script.src  = file;
    script.type = 'text/javascript';
    script.defer = true;
    document.getElementsByTagName('head').item(0).appendChild(script);
} // include

function log(message) {
    if( debugLevel == 0 || debugLevel == "" ) return;
    if (!log.window_ || log.window_.closed) {
        var win = window.open("", null, "width=400,height=200," +
                              "scrollbars=yes,resizable=yes,status=no," +
                              "location=no,menubar=no,toolbar=no");
        if (!win) return;
        var doc = win.document;
        doc.write("<html><head><title>Debug Log</title></head>" +
                  "<body></body></html>");
        doc.close();
        log.window_ = win;
    }
    var logLine = log.window_.document.createElement("div");
    logLine.appendChild(log.window_.document.createTextNode(message));
    log.window_.document.body.appendChild(logLine);
}


// ################## <AJAX OBJECT FUNCTIONS>

myAjaxObject = new AjaxObject;          //global AjaxObject, gets re-used throughout code

////////////////////////////////////
//AjaxObject Class
function AjaxObject(){
	this.success = 0;                                 //0 for failure, 1 for success
	this.details = null;
	this.error_code = "";                             //server response error code
	this.message = "";                                //server response message
	this.responseFunction = "";                       //callback function to send results to
	this.ajaxRequest = createXmlHttpRequestObject();  //ajax handle
}


///////////////////////////////////////////////////
//sendRequest function, sends ajax request to server  
//parameters:
//          url:		server url that does db / php work
//          options:	JSON object which should include: callback, parameters and method
//output:
//          server will send output to callbackFunction below
AjaxObject.prototype.sendRequest = function(url, options) {
	var callback	= options['callback'];

	var params		= options['parameters'];
	var paramsArray	= new Array();
	for( var key in params ) {
		var value	= encodeURI( params[key] );
		paramsArray.push(key + "=" + value);
	}
	var parameters	= paramsArray.join("&");

	// ##### <GET HANDLING>
	if (!method){
		method = "GET";
	}
	var method		= options['method'];
	if( method.toLowerCase() == "get") {
		url	+=	"?" + parameters;
	}
	// ##### </GET HANDLING>

	if (this.ajaxRequest){
		this.responseFunction = eval(callback);
		this.ajaxRequest.onreadystatechange = this.callbackFunction; //eval(responseFunction);
		this.ajaxRequest.open(method, url, true);
		if( method.toLowerCase() == "post" ) {
			this.ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			this.ajaxRequest.setRequestHeader("Content-length", parameters.length);
			this.ajaxRequest.setRequestHeader("Connection", "close");
		}
		this.ajaxRequest.send(parameters);
	} else {
		alert("AjaxObject.prototype.sendRequest failed");
		return;
	}
}


///////////////////////////////
//callbackFunction , receives request from server and sends it to the proper callback Function
//     parses results and sends them to "responseFunction" specified in sendRequest function.
AjaxObject.prototype.callbackFunction = function(){

    if (myAjaxObject.ajaxRequest.readyState == 4 && myAjaxObject.ajaxRequest.status == 200 ) {
		var success	= 0;
		var json	= null;
        var responseText = myAjaxObject.ajaxRequest.responseText;
		try {
			json	= eval('(' + responseText + ')');
		}
		catch(err) {
			log(err)
		}

		if( json == null ) {
			//alert("AJAX function failed");
			return;
		} else if( json['isSuccess'] == 1 ) {
			success	= 1;
		} 

		myAjaxObject.error_code	= json['error'];
		myAjaxObject.message	= json['msg'];
		myAjaxObject.success	= success;
		myAjaxObject.details	= eval('(' + json['details'] + ')');
		myAjaxObject.responseFunction();
    }
}


/////////////////////////////////////////////////////////
// creates an XMLHttpRequest instance
function createXmlHttpRequestObject() 
{
	// will store the reference to the XMLHttpRequest object
	var xmlHttp;
	// this should work for all browsers except IE6 and older
	try
	{
		// try to create XMLHttpRequest object
		xmlHttp = new XMLHttpRequest();
	}
	catch(e)
	{
		// assume IE6 or older
		var XmlHttpVersions = new Array(
									"MSXML2.XMLHTTP.6.0",
									"MSXML2.XMLHTTP.5.0",
									"MSXML2.XMLHTTP.4.0",
									"MSXML2.XMLHTTP.3.0",
									"MSXML2.XMLHTTP",
									"Microsoft.XMLHTTP"
		);
		// try every prog id until one works
		for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) 
		{
			try 
			{ 
				// try to create XMLHttpRequest object
				xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
			} 
			catch (e) {}
		}
	}
	// return the created object or display an error message
	if (!xmlHttp)
	{
		//alert("Error creating the XMLHttpRequest object.");
		return;
	}
	else 
	{//alert("successfully created XMLHttp object");
		return xmlHttp;
	}
}




// ################## <AJAX OBJECT FUNCTIONS>

