/* mAjax (c) 2010 Martin van der Werff - martin (at) vanderwerff (dot) org */

var majax_main_inst = null;

var majax_event_inst = null;

var majax_session = null;

var majax_error_callback = null;

var majax_active = false;

function majax_start(url_m, url_e, session, error_callback)
{
	majax_session = session;
	if( error_callback == undefined )
	{
		majax_error_callback = null;
	}
	else
	{
		majax_error_callback = error_callback;
	}
	majax_active = true;
	majax_main_inst = new majax_m(url_m, 1);
	majax_event_inst = new majax_e(url_e, 1);
}

function majax_event(event, id)
{
	majax_event_inst.ajax_request(event, id);
}

function majax_delayed_request()
{
	majax_main_inst.ajax_request();
}

function majax_timeout()
{
	majax_main_inst.majax_debug("mAjax protocol timeout");
	majax_main_inst.majax_error();
}

function majax_e(url, debug)
{
	this.ajax_connection = null;

	this.start = function() 
	{
		this.ajax_connection = new majax_c(this);
  	}

	this.ajax_request = function(event, id)
	{
		if( majax_active )
		{
			this.ajax_connection.reset();
			this.ajax_connection.requestFile = url;
			this.ajax_connection.setVar("e", event);
			this.ajax_connection.setVar("i", id);
			this.ajax_connection.setVar("s", majax_session);
			this.ajax_connection.method = 'GET';
			this.ajax_connection.runAJAX();
		}
	}

	this.start();
}

function majax_m(url, debug)
{
	this.ajax_connection = null;

	this.start = function() 
	{
		this.ajax_connection = new majax_c(this);
		this.ajax_pageversion = 0;
		this.time_next_request = 0;

		this.majax_debug("mAjax loaded");
		this.ajax_request();
  	}

	this.majax_error = function()
	{
		majax_active = false;
		var e = document.getElementById('majax_error');
		if( e != null )
		{ 
			e.style.display = "block";
		}
		if( majax_error_callback != null )
		{ 
			majax_error_callback();
		}
	}

	this.majax_debug = function(msg)
	{
		if( debug )
		{
			var e = document.getElementById('majax_debug');
			if( e != null )
			{ 
				e.innerHTML = msg;
			}
			try
			{
				console.log(msg);
			}
			catch(ex)
			{
			}
		}
	}

	this.ajax_request = function()
	{
		if( majax_active )
		{
			this.ajax_connection.reset();
			this.ajax_connection.requestFile = url;
			this.ajax_connection.setVar("v", this.ajax_pageversion);
			this.ajax_connection.setVar("s", majax_session);
			this.ajax_connection.method = 'GET';
			this.ajax_connection.onCompletion = function(parent) 
			{
				var lines = parent.ajax_connection.response.split("\n");
	
				var count = 0;
	
				var i;
	
				for( i = 0; i < lines.length; ++i )
				{
					var line = lines[i].replace(/^\s+|\s+$/g, '');
	
					if( line.length > 0 )
					{
						++count;
						
						if( count == 1 )
						{
							if( line != "mAjax/1.0" )
							{
								parent.majax_debug("mAjax protocol error");
								parent.majax_error();
								return;
							}
						}
						else if( count == 2 )
						{
							parent.ajax_pageversion = line;
							if( debug )
							{
								e = document.getElementById('majax_version');
								if( e != null )
									{ 
									e.innerHTML = parent.ajax_pageversion;
								}
							}
						}
						else if( count == 3 )
						{
							parent.time_next_request = line;
						}
						else
						{
							try
							{
								parent.majax_process(line);
							}
							catch( ex )
							{
							}
						}
					}
				}
	
				if( count < 3 )
				{
					parent.majax_debug("empty response");
					parent.majax_error();
				}
				else if( parent.time_next_request == 0 )
				{
					parent.ajax_request();
				}
				else if( parent.time_next_request > 0 )
				{
					setTimeout("majax_delayed_request();", parent.time_next_request);
				}
				else
				{
					parent.majax_debug("done");
				}
			};
			this.ajax_connection.onError = function(parent) 
			{
				parent.majax_debug("mAjax error"); 
				parent.majax_error(); 
			}
			this.ajax_connection.onFail = function(parent) 
			{
				parent.majax_debug("mAjax failure"); 
				parent.majax_error(); 
			}
			this.ajax_connection.runAJAX();
		}
	}

	this.majax_process = function(line)
	{
		var oper = line.charAt(0);
		var id = 'none';
		var content = 'none';

		if( line.length > 1 )
		{
			var seppos = line.indexOf(' ');

			if( seppos > 0 )
			{
				id = line.substring(1, seppos);
				content = line.substring(seppos + 1);
			}
			else
			{
				id = line.substring(1);
			}
		}

		if( debug )
		{
			this.majax_debug("[" + oper + "][" + id + "][" + content + "]");
		}

/*
	e	force error
	l	change location (redirect)
	s	change session id
	r	replace innerhtml content
	x	clear innerhtml content
	c	change class
	d	remove element
	a	append element
	q	quit / done
 */
		if( oper == 'e' )
		{
			this.majax_debug("mAjax forced error"); 
			this.majax_error(); 
		}
		else if( oper == 'l' )
		{
			majax_active = false; 
			window.location = content; 
		}
		else if( oper == 's' )
		{
			majax_session = content; 
		}
		else if( oper == 'q' )
		{
			majax_active = false; 
			this.majax_debug("mAjax done"); 
		}
		else
		{
			var e = document.getElementById(id);
			if( e != null )
			{ 
				if( oper == 'r' )
				{
					e.innerHTML = content;
				}
				else if( oper == 'x' )
				{
					e.innerHTML = "";
				}
				else if( oper == 'c' )
				{
					e.className = content;
				}
				else if( oper == 'd' )
				{
					e.parentNode.removeChild(e);
				}
				else if( oper == 'a' ) // div id class
				{
					var params = content.split(' ');

					if( params.length > 1 )
					{
						var el = document.createElement(params[0]);
						el.id = params[1];
						if( params.length > 2 )
						{
							var i, className = "";

							for( i = 2; i < params.length; ++i )
							{
								if( i == 2 )
								{
									className = params[2];
								}
								else
								{
									className += " " + params[i];
								}
							}

							el.className = className;
						}
						e.appendChild(el);
					}
				}
			}
		}
	}

	this.start();
}

function majax_c(parent, file) {

	this.xmlhttp = null;
	this.timeout = null;

	this.resetData = function() {
		this.method = "POST";
  		this.queryStringSeparator = "?";
		this.argumentSeparator = "&";
		this.URLString = "";
		this.encodeURIString = true;
  		this.execute = false;
  		this.element = null;
		this.elementObj = null;
		this.requestFile = file;
		this.vars = new Object();
		this.responseStatus = new Array(2);
		if( self.timeout )
		{
			clearTimeout(self.timeout);
		}
		this.timeout = null;
  	};

	this.resetFunctions = function() {
  		this.onLoading = function(parent) { };
  		this.onLoaded = function(parent) { };
  		this.onInteractive = function(parent) { };
  		this.onCompletion = function(parent) { };
  		this.onError = function(parent) { };
		this.onFail = function(parent) { };
	};

	this.reset = 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.setVar = function(name, value){
		this.vars[name] = Array(value, false);
	};

	this.encVar = function(name, value, returnvars) {
		if (true == returnvars) {
			return Array(encodeURIComponent(name), encodeURIComponent(value));
		} else {
			this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
		}
	}

	this.processURLString = function(string, encode) {
		encoded = encodeURIComponent(this.argumentSeparator);
		regexp = new RegExp(this.argumentSeparator + "|" + encoded);
		varArray = string.split(regexp);
		for (i = 0; i < varArray.length; i++){
			urlVars = varArray[i].split("=");
			if (true == encode){
				this.encVar(urlVars[0], urlVars[1]);
			} else {
				this.setVar(urlVars[0], urlVars[1]);
			}
		}
	}

	this.createURLString = function(urlstring) {
		if (this.encodeURIString && this.URLString.length) {
			this.processURLString(this.URLString, true);
		}

		if (urlstring) {
			if (this.URLString.length) {
				this.URLString += this.argumentSeparator + urlstring;
			} else {
				this.URLString = urlstring;
			}
		}

		// prevents caching of URLString
		this.setVar("rndval", new Date().getTime());

		urlstringtemp = new Array();
		for (key in this.vars) {
			if (false == this.vars[key][1] && true == this.encodeURIString) {
				encoded = this.encVar(key, this.vars[key][0], true);
				delete this.vars[key];
				this.vars[encoded[0]] = Array(encoded[1], true);
				key = encoded[0];
			}

			urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
		}
		if (urlstring){
			this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
		} else {
			this.URLString += urlstringtemp.join(this.argumentSeparator);
		}
	}

	this.runResponse = function() {
		eval(this.response);
	}

	this.runAJAX = function(urlstring) {
		if (this.failed) {
			this.onFail(parent);
		} else {
			this.createURLString(urlstring);
			if (this.element) {
				this.elementObj = document.getElementById(this.element);
			}
			if (this.xmlhttp) {
				var self = this;

				this.timeout = setTimeout("majax_timeout()", 20000);

				if (this.method == "GET") {
					totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
					this.xmlhttp.open(this.method, totalurlstring, true);
				} else {
					this.xmlhttp.open(this.method, this.requestFile, true);
					try {
						this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
					} catch (e) { }
				}

				this.xmlhttp.onreadystatechange = function() {
					switch (self.xmlhttp.readyState) {
						case 1:
							self.onLoading(parent);
							break;
						case 2:
							self.onLoaded(parent);
							break;
						case 3:
							self.onInteractive(parent);
							break;
						case 4:
							if( self.timeout )
							{
								clearTimeout(self.timeout);
							}
							self.response = self.xmlhttp.responseText;
							self.responseXML = self.xmlhttp.responseXML;
							self.responseStatus[0] = self.xmlhttp.status;
							try
							{
								self.responseStatus[1] = self.xmlhttp.statusText;
							}
							catch (e)
							{
								self.responseStatus[1] = "exception";
							}
							if (self.execute) {
								self.runResponse();
							}

							if (self.elementObj) {
								elemNodeName = self.elementObj.nodeName;
								elemNodeName.toLowerCase();
								if (elemNodeName == "input"
								|| elemNodeName == "select"
								|| elemNodeName == "option"
								|| elemNodeName == "textarea") {
									self.elementObj.value = self.response;
								} else {
									self.elementObj.innerHTML = self.response;
								}
							}
							if (self.responseStatus[0] == "200") {
								self.onCompletion(parent);
							} else {
								self.onError(parent);
							}

							self.URLString = "";
							break;
					}
				};

				this.xmlhttp.send(this.URLString);
			}
		}
	};

	this.reset();
	this.createAJAX();
}

