Array.prototype.isArray = true;
var imgCarregando       = document.createElement('IMG');
var DV_AjaxCarregando   = document.createElement('DIV');
var DV_BlockScreen	    = document.createElement('DIV');
imgCarregando.src       = COMMONS_PUBLIC + IMGS_HOME + 'carregando.gif';
imgCarregando.border    = 0;

DV_AjaxCarregando.className = 'DV_AjaxCarregando';
DV_BlockScreen.className    = 'DV_BlockScreen';
DV_AjaxCarregando.appendChild( imgCarregando );

function c_Ajax(strUrl) {
	this.projectUrl  = CURRENT_PROJECT_PUBLIC;
	this.url         = strUrl;
	this._simple_req = false;
	this.ajax		 = null;
	this.loadScripts = true;
	this.DOMN = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0",
				 "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP",
				 "Microsoft.XMLHTTP"];
	this._class_name   = null;
	this._obj_temp     = null;

	this.trim = function (str) {
		return str.replace(/^\s*|\s*$/g,"");
	}
				 
	this.print_r = function (objObj, recursive) {
	var strRetorno = "{\n";
			
		if (typeof objObj == 'object') {
			for (x in objObj) {
				if (x == "" || x == null || objObj[x] == undefined || objObj[x] == null || objObj[x] == "______array") continue;
				if (typeof objObj[x] == 'object' && recursive != false) {
					strRetorno += "\n[" +x+ "] => " +this.print_r(objObj[x], recursive)+ "\n";
				} else {			
					strRetorno += "\t["+ x +"] => "+ objObj[x] +"\n";
				}
			}
		} else {
			strRetorno += objObj;
		}
			
			
		strRetorno += "\n}";
				
		return strRetorno;
	}
	
	this.Extends = function (objClassMain, objClassParent) {
		for (x in objClassParent) {
			if (objClassParent[x] == '______array' || x == 'isArray') continue;

			objClassMain[x] = objClassParent[x];
		}
		
		return objClassMain;
	}
	
	this.create = function () {
		try {
		    this.ajax = new XMLHttpRequest();
		} catch (e) {
			for (var i = 0; i < this.DOMN.length; i++) {
				try {
					this.ajax = new ActiveXObject(this.DOMN[i]);
					if (typeof this.ajax == 'object') break;
				} catch (oError) {  }
			}
		}
	}
	
	this.mergeClasses = function (objClass, strClassName) {
		var _NewObj = "_NewObj = {\n";
		var _parent = this;
		var _eval, _temp;
		
		this._class_name = strClassName;
		for (x in objClass) {
			if (objClass[x] == '______array' || x == 'isArray') continue;

			_NewObj += "_" +x+ " : " +this.convertObjs(objClass[x])+ ",\n";
			_NewObj += x+ " : function () { var _args = this.JoinArgs(arguments); _args = (_args == '') ? '' : (', '+_args); \n var _func = \"this.execute('_"+x+"'\"+_args+\" );\"\n eval(_func); },\n";
		}   _NewObj  = _NewObj.substring(0, _NewObj.length-2) + " \n}"; eval(_NewObj);
		
		this.Extends(objClass, _NewObj);
		this.Extends(objClass, this);

		this._obj_temp = objClass;
	}

	this.register = function (strActionPath, objObj) {
		var action = strActionPath.split("/");
		
		this.setUrl('index.php?actionName=' +action[0]+ '.' +action[1]);
		this.mergeClasses((objObj != null ? objObj : eval(action[1])), action[1]);
	}
	
	this.JoinArgs = function (_args) {
	var _return = "";
		for (var x = 0; x < _args.length; x++) {
			if (_args[x] == "" || _args[x] == null || _args[x] == undefined) continue;

			_return += (typeof _args[x] == 'object') ? this.convertObjs(_args[x], true) : this.parserObj(_args[x], true) + ",";
		}   _return  = (_args.length == 1 && typeof _args[0] == 'object') ? _return : _return.substring(0, _return.length-1);
		
		return this.trim(_return);
	}

	this.convertObjs = function (objObj, sending) {
		var retorno = "";
		if (typeof objObj != 'undefined') {
			if (typeof objObj.isArray != 'undefined') {
				retorno = "[";
							
				for (var x = 0; x < objObj.length; x++) {
					if (typeof objObj[x] == 'object') {
						retorno += this.convertObjs(objObj[x], sending) +",";
					} else {						
						retorno += this.parserObj(objObj[x], sending) +",";
					}
				}   retorno = retorno.substring(0, retorno.length -1);
							
				retorno += "]";
			} else if (typeof objObj == 'object') {
				retorno = "{";
							
				for (x in objObj) {
					if (objObj[x] == '______array' || x == 'isArray') continue;	

					if (typeof objObj[x] == 'object') {
						retorno += "\"" +x+ "\":" +this.convertObjs(objObj[x], sending)+ ",";
					} else {						
						retorno += "\"" +x+ "\":" +this.parserObj(objObj[x], sending)+ ",";
					}
				}   retorno = retorno.substring(0, retorno.length -1);
							
				retorno += "}";
			} else {
				retorno = this.parserObj(objObj);
			}
		}
					
		return retorno;
	}
			
	this.parserObj = function (objObj, sending) {
	var _temp, _tmp, _eval, valor;
		if (typeof objObj == 'string') {
			valor = (sending != null && sending == true) ? escape(this.addSlashes(this.addBreak(objObj))) : this.addSlashes(this.addBreak(objObj));
			return '"' +valor+ '"';
		} else {
			return objObj;
		}
	}
			
	this.addSlashes = function (valor) {
		return valor.replace(/\"/g, '\\"');
	}
			
	this.stripSlashes = function (valor) {
		return valor.replace(/\\\"/g, '"');
	}
			
	this.addBreak = function (valor) {
		return valor.replace(/\n/g, '<br />');
	}
	
	this.execute = function () {
		var metodo  = arguments[0];
		var args    = (arguments.length > 2) ? new Array() : "";
		var types	= (arguments.length > 2) ? new Array() : "";
		var strEval = "";
		var Retorno;
		
		if (arguments.length >2) {
			for (var x = 1; x < arguments.length; x++) {
				types.push(((typeof arguments[x] == 'object') ? '1' : '0'));
				args.push(arguments[x]);
			}
		} else {
			args  = arguments[1];
			types = ((typeof arguments[1] == 'object') ? '1' : '0');
		}
		
		if (!this._simple_req)
			this.makeRequest(args, this._class_name, metodo, arguments.length, types);
		else
			this.makeRequest_Simple(args, this._class_name, metodo, arguments.length, types);
	}

	this.AppendJS = function (texto) {
		var Obj, strIni, strFim, ini;
		var IncIni, IncFim, Inc;
		texto = texto.replace(/\&lt;/g, "<");
		texto = texto.replace(/\&gt;/g, ">");

		if (!this.loadScripts) return "";
		
		ini = texto.indexOf('<script', 0);
		while (ini != -1) {
			Obj = document.createElement("SCRIPT");
			
			strIni = texto.indexOf('<script', ini);
			strIni = texto.indexOf('>', strIni);
			strFim = texto.indexOf("</script", strIni);
			
			IncIni = texto.indexOf('src=', ini);
			IncFim = texto.indexOf('>', IncIni);
			Inc    = texto.substring(IncIni+5, IncFim-1);
			
			if (IncIni >= 0) {
				Obj.src  = Inc;
			} else {
				Obj.text = texto.substring(strIni+1, strFim);
			}

			ini = texto.indexOf('<script', strFim);
			document.getElementsByTagName("HEAD")[0].appendChild(Obj);
		}

		if (classObjetos.findObj('errorPageMain')) {
			document.body.innerHTML = document.getElementById('errorPageMain').innerHTML;
			document.title += " - Error Page";
		}
	}
	
	this.makeRequest = function (q, _className, _method, Len, types) {
		var _return = null;
		var _temp   = null;
		var _parent = this;
		var _query  = "";
		var _types  = "";
		var _eval   = "";
		var _res1   = null;
		var _res2   = null;
		var _script = "";
//		var elem    = (document.getElementById('ementoAjaxInput')) ? document.getElementById('ementoAjaxInput') : document.createElement("INPUT");
//		elem.id     = 'ementoAjaxInput';

		this.create();
		
		if (Len >2) {
			for (var i = 0; i < q.length; i++) {
				_query += "query_"+i+"="+(this.convertObjs(q[i]))+"&";
				_types += "_types"+i+"="+this.convertObjs(types[i])+"&";
			}

			_query = _query.substring(0, _query.length-1);
			_types = _types.substring(0, _types.length-1);
		} else {
			_query = "query_0="+(this.convertObjs(q));
			_types = "types_0="+this.convertObjs(types);
		}

		DV_AjaxCarregando.style.display = 'block';
		DV_BlockScreen.style.display    = 'block';
		DV_BlockScreen.style.height     = document.body.scrollHeight + 'px';

		this.ajax.onreadystatechange = function () {  }

		this.ajax.open("post", (this.projectUrl + this.url), false);
		this.ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		this.ajax.setRequestHeader("Connection", "close");
		
//		location = (this.projectUrl + this.url) +"&"+ _query +"&" +_types+ "&class=" +_className+ "&method=" +_method.substring(1,_method.length)+ "&total=" +((Len >2) ? q.length : 1)
//		elem.value = (this.projectUrl + this.url) +"&"+ _query +"&" +_types+ "&class=" +_className+ "&method=" +_method.substring(1,_method.length)+ "&total=" +((Len >2) ? q.length : 1);
//		document.body.appendChild(elem);
		this.ajax.send(_query +"&isAjax=1&" +_types+ "&class=" +_className+ "&method=" +_method.substring(1,_method.length)+ "&total=" +((Len >2) ? q.length : 1) +"&id="+ _REQUEST['id']);

		_eval   = "_return = " +_parent.parserObj(unescape(_parent.ajax.responseText.replace(/\n/g, ' ')))+ ";"; eval(_eval);
		_eval   = "_return = " +unescape(_parent.convertObjs(_return))+ ";"; eval(_eval);
		_script = this.stripSlashes(unescape(_parent.convertObjs(_return))).substring(1);
		_script = _script.substring(0, _script.length - 1);
		this.AppendJS(_script);

		_res1   = _className +"."+ _method +"(" +_return+ ");";
		_res2   = _className +"."+ _method +"(" +_parent.parserObj(_return)+ ");";
		_res3   = "( (!_className ? _className : this._obj_temp) )." + _method +"(" +_return+ ");";
		_res4   = "( (!_className ? _className : this._obj_temp) )." + _method +"(" +_parent.parserObj(_return)+ ");";

		try {
			eval(_res1);
		} catch (e) {
			try {
				eval(_res2);
			} catch (e) {
				try {
					eval(_res3);
				} catch (e) {
					try {
						eval(_res4);
					} catch (e) {}
				}
			}
		}
		
		DV_AjaxCarregando.style.display = 'none';
		DV_BlockScreen.style.display    = 'none';
	}

	this.makeRequest_Simple = function (q, _className, _method, Len, types) {
		var _return = null;
		var _temp   = null;
		var _parent = this;
		var _query  = "";
		var _types  = "";
		var _eval   = "";
		var _res1   = null;
		var _res2   = null;
		var _script = "";

		this.create();

		DV_AjaxCarregando.style.display = 'block';

		this.ajax.open("post", (this.projectUrl + this.url), true);
		this.ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		this.ajax.onreadystatechange = function () {
			if (_parent.ajax.readyState == 4) {	
				if (_parent.ajax.status == 200) {
					_eval   = "_return = " +_parent.parserObj(unescape(_parent.ajax.responseText.replace(/\n/g, ' ')))+ ";"; eval(_eval);
					_eval   = "_return = " +unescape(_parent.convertObjs(_return))+ ";"; eval(_eval);
					_script = _parent.stripSlashes(unescape(_parent.convertObjs(_return))).substring(1);
					_script = _script.substring(0, _script.length - 1);
					_parent.AppendJS(_script);

					_res1   = _className +"."+ _method +"(" +_return+ ");";
					_res2   = _className +"."+ _method +"(" +_parent.parserObj(_return)+ ");";
					_res3   = "( (!_className ? _className : this._obj_temp) )." + _method +"(" +_return+ ");";
					_res4   = "( (!_className ? _className : this._obj_temp) )." + _method +"(" +_parent.parserObj(_return)+ ");";

					try {
						eval(_res1);
					} catch (e) {
						try {
							eval(_res2);
						} catch (e) {
							try {
								eval(_res3);
							} catch (e) {
								try {
									eval(_res4);
								} catch (e) {}
							}
						}
					}
				}
				
				DV_AjaxCarregando.style.display = 'none';
			}
		}
		
		if (Len >2) {
			for (var i = 0; i < q.length; i++) {
				_query += "query_"+i+"="+(this.convertObjs(q[i]))+"&";
				_types += "_types"+i+"="+this.convertObjs(types[i])+"&";
			}

			_query = _query.substring(0, _query.length-1);
			_types = _types.substring(0, _types.length-1);
		} else {
			_query = "query_0="+(this.convertObjs(q));
			_types = "types_0="+this.convertObjs(types);
		}
		
		this.ajax.send(_query +"&" +_types+ "&class=" +_className+ "&method=" +_method.substring(1,_method.length)+ "&total=" +((Len >2) ? q.length : 1) +"&id="+ _REQUEST['id']);
	}

	//doAjax('Ajax/ajax_teste.calcular', Array(this.value, obj2.value));
	this.doAjax = function (strMethod, argList, objAction) {
		var myClass   = null;
		var Ajax      = new c_Ajax();
		var action    = strMethod.split("/");
		var method    = action[1].split(".");
		var objAction = (objAction == null) ? null : Ajax.convertObjs(objAction);

		var jsClass = "myClass = { "+method[1]+" : function (result) { try { var objAction = "+objAction+"; if (objAction != null) { var strAction = \"objAction."+method[1]+"(result)\"; eval(strAction); } else { eval(result); } } catch (e) {}; } }";
		var sMethod = "myClass." +method[1];
		var sClone  = method[0] + " = myClass;";

		eval(jsClass);
		eval(sClone);

		Ajax.register(action[0] +'/'+ method[0]);
		sMethod += "("

		if (typeof argList == 'string') sMethod += "'"+argList+"'";
		else {
			for (var i = 0; i < argList.length; i++) {
				sMethod += Ajax.convertObjs(argList[i]) + ", ";
			}   sMethod  = sMethod.substring(0, sMethod.length-2);
		}

		sMethod += ")";

		try {
			eval(sMethod);
		} catch (e) {
			try { sMethod; } catch (ee) {};
		};

		myClass = null;
		Ajax    = null;
	}

	this.createAjax = function (linkConnection, objClass) {
		this.Ajax = new c_Ajax();
		this.link = linkConnection;
		this.obj  = objClass;

		if (linkConnection.indexOf('.') == -1) {
			this.Ajax.register(linkConnection);
			return eval(linkConnection.split("/")[1]);
		}

		this.execute = function () {
			this.Ajax.doAjax(this.link, arguments, this.obj);
		}

		this.setSimple = function (value) { this.Ajax.setSimple(value); } 
	}
	
	this.setUrl        = function (valor) { this.url = valor; }
	this.setProjectUrl = function (valor) { this.projectUrl = valor; }

	this.setSimple = function (value) { this._simple_req = value; } 
}

var objAjax = new c_Ajax();