
// Dodo (August, 31th 2007): I want my Array back!
var PrototypeMaid = {
	object_cupboard: new Object()
	, array_cupboard: new Array()
	, vaccum: function()
	{
		var new_carpet = new Object(); // bought a new dirty carpet.. let's vacuum it.
		
		for(var dust in new_carpet)
		{
			eval("delete Object.prototype." + dust + ";"); 
		}
		new_carpet = new Array(); 
		for(var dust in new_carpet)
		{
			eval("delete Array.prototype." + dust + ";"); 
		}
	}
	
	, party: function()
	{
		for(var stuff in PrototypeMaid.object_cupboard)
		{
			eval("Object.prototype." + stuff + " = PrototypeMaid.object_cupboard." + stuff + ";");
		}
		for(var stuff in PrototypeMaid.array_cupboard)
		{
			eval("Array.prototype." + stuff + " = PrototypeMaid.array_cupboard." + stuff + ";");
		}
	}
};

// PrototypeMaid.vaccum(); // TODO let her have a party afterwards
/*
if(typeof($) == "undefined")
{
	alert("jetzt gehts prototype net!");
	function ForEach(obj)
	{
		this.obj = obj;
	}
	
	ForEach.prototype.each = function(fun)
	{
		for(var key in this.obj)
		{
			var p = {};
			p.key = key;
			p.value = this.obj.key;
			fun(p);
		}
	}
	
	
	function $H(obj)
	{
		alert("warum wird das ausgef�hrt?");
		return(new ForEach(obj));
	}
	
}
*/

function ThesAjax(user_, pw_)
{
  this.user = user_;
  this.pw = pw_;
  this.req = null;
  this.std = true;
  this.req_meth = "POST";
	if (typeof XMLHttpRequest != "undefined")
		this.req = new XMLHttpRequest();
	else if (typeof ActiveXObject != "undefined")
	{
    	this.std = false;
    	var onam = ["Msxml2.XMLHTTP.4.0", "Microsoft.XMLHTTP", "Msxml2.XMLHTTP"];
		for(var ofs = 0; ofs < onam.length; ++ofs)
		{
			try
			{
				this.req = new ActiveXObject(onam[ofs]);
				break;
			} catch (e)	{
				// Object not found try next
			}
		}
	}
	this.serialize = this.serializePhp;
}

ThesAjax.prototype.serializeJs = function(data)
{
  var me = this;
  if(typeof(data) == "undefined" || data == null)
    return(null);
  else if(data.constructor == String)
    return("\"" + data.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g,"\\n") + "\"");
  else if(data.constructor == Number)
    return("" + data);
  else if(data.constructor == Boolean)
    return(data? "true" : "false");
  else if(data.constructor == Date)
    return(data.toString());
  else if(data.constructor == Array)
  {
    var ret = "";
    $H(data).each(function(pair) {
    	var d = me.serializeJs(pair.value);
    	if(d != null)
    		ret += "," + d;
    });
    
    if(ret.length == 0)
      ret = "[";
      //alert(ret);
    return(ret.replace(/^,/, "[") + "]");
  }
  else if(typeof(data) == "object")
  {
    var ret = "{";
    $H(data).each(function(pair) {
       	el = me.serializeJs(pair.value);
    	
    	if(el != null)
        {
      	  if(ret.length > 1)
        	ret += ",";
          ret += pair.key +":"+ el;
        }
    });
       //alert(ret);
    return(ret + "}");
  }
  return(null);
  // ignore function, undefined
}

ThesAjax.prototype.serializePhp = function(data)
{
	var me = this;
  if(typeof(data) == "undefined" || data == null)
    return("N;");
  else if(data.constructor == String)
  {
    var len = data.length;
    len += data.replace(/[\000-\177]/g, "");
    // ...
    return("s:" + len + ":\"" + data + "\";");
  }
  else if(data.constructor == Number)
  {
    return("d:" + data + ";");
  }
  else if(data.constructor == Boolean)
    return(data? "b:1;" : "b:0;");
  else if(data.constructor == Date)
    return(this.serializePhp(data.toString()));
  else if(data.constructor == Array)
  {
    var ret = "a:" + data.length + ":{";
    for(var idx = 0; idx < data.length; idx++) {
    	var val = data[idx]; 
    	var d = me.serializePhp(val);
	      if(d != null)
	        ret += "i:" + idx + ";" + d;
    }
    return(ret + "}");
  }
  else if(typeof(data) == "object")
  {
    var onam = (data.constructor == "Object" || String(data.constructor).match(/function Object/)
    || String(data.constructor).match(/\[function\]/))? "stdClass" : data.constructor;
    var ret = "";
    var acnt = 0;
    //alert($H(data).toJSON());
    $H(data).each(function(pair) {
    	el = me.serializePhp(pair.value);
      	if(el != null)
	      {
	        acnt ++;
	        ret += me.serializePhp(pair.key) + el;
	      }
    });
    return("O:"+onam.length+":\"" + onam + "\":" + acnt + ":{" + ret + "}");
  }
  return(null);
  // ignore function, undefined
}

ThesAjax.prototype.callSync = function(url, data)
{
  var throw_it = null;
  try
  {
		this.req.open(this.req_meth, url, false, this.user, this.pw);
		var s_data = this.serialize(data);
		this.req.send(s_data);

		if(this.req.responseText.substr(0, 6) == "throw ")
		{
			throw_it = this.req.responseText;
		}
		else if(this.req.responseText.substr(0, 50).search(/[ \t\n]*function /) >= 0
		     || this.req.responseText.substr(0, 50).search(/[ \t\n]*var /) >= 0)
		{
			var hd = document.getElementsByTagName('head');
			if(hd == null)
			{
				document.write('<' + 'script type="text/javascript">\n');
				document.write(this.req.responseText);
				document.write('\n<' + '/script>\n');
			}
			else
			{
// document.getElementsByTagName("body")[0].appendChild(document.createElement("pre")).appendChild(document.createTextNode("###script= "+this.req.responseText));
 				eval(this.req.responseText);
// 				var scr = document.createElement('script');
// 				scr = hd[0].appendChild(scr);
// 				scr.setAttribute('type', 'text/javascript');
// 				scr.appendChild(document.createTextNode(this.req.responseText));
			}
			return(null);
		}
		else
		{
			eval("var ret = " + this.req.responseText);
			return(ret);
		}
	} catch(exc) {
		var txt = "FATAL: \n" + Object.toJSON(exc) + "\n" + this.req.responseText;
		txt.replace("\n", "<br/>\n"); 
		var e = document.createElement('div');
	  	e.appendChild(document.createTextNode(txt));
	  	if ($('MdmSearchResult')) {
	  		$('MdmSearchResult').appendChild(e);
	  	} else {
	  		$$('body')[0].appendChild(e);
	  	}
	  	//alert(txt);  
	}
	if(throw_it)
		  eval(throw_it.replace("throw new Error", "alert"));
		  eval(throw_it);
}

ThesAjax.prototype.callAsync = function(call_back, url, data)
{
  try
  {
// 		if(this.std)
// 		  ;
// 		else
		this.call_back = call_back;
		this.req.open(this.req_meth, url, true, this.user, this.pw);
		this.req.onreadystatechange = this.handleResult;
		this.req.send(this.serialize(data));
	} catch(exc) {
	  //alert("FATAL: " + this.serializeJs(exc));
	}
}

ThesAjax.prototype.handleResult = function()
{
   this.call_back(eval(this.req.responseText));
}

var _globalThesAjaxInstance = null;

ThesAjax.globalInstance = function()
{
	if(_globalThesAjaxInstance == null) {
		_globalThesAjaxInstance = new ThesAjax();
	}
	return(_globalThesAjaxInstance);
}
