var JadeAjax = function() {
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	var obj= new Object();
	if (!(window.XMLHttpRequest!=null && (obj.xmlhttp=new XMLHttpRequest())!=null
	|| window.ActiveXObject!=null && (obj.xmlhttp=new ActiveXObject("MSXML2.XMLHTTP"))!=null
	|| window.ActiveXObject!=null && (obj.xmlhttp=new ActiveXObject("MSXML2.XMLHTTP.3.0"))!=null
	|| window.ActiveXObject!=null && (obj.xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"))!=null))
	{
		alert("Your browser don't support XMLHTTP");
	}
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	obj.method="POST";
	obj.text=null;
	obj.json=null;
	obj.xml=null;
	obj.params = '';
	obj.post_params=[];
	obj.state = 0;
	obj.status=null;
	obj.secure=false;
	obj.url='';
	obj.dontwait=true;
	obj.progessive=false;
	obj.ready=true;
	obj.debug_id=null;
	obj.debug_class='';
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	obj.Sendit = function(){
		if(DEBUG_MODE){
			var text=this.DebugTitle()+'\n';
			text += '<h1>Params:</h1>';
					
			for(var i=0,iLen=this.post_params.length; i<iLen; i++){
				text += '<b>'+this.post_params[i].name+'</b> '+this.post_params[i].value+'<br/>';
			}
			
			this.debug_id=$.Debug.Add(text, 'debug');
		}
		if(this.ready){
			this.ready=false;
			this.xmlhttp.open(this.method,this.url,this.dontwait);
			this.xmlhttp.onreadystatechange=this._statechange;
			this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
			this.xmlhttp.setRequestHeader("charset", "UTF-8");
			this.xmlhttp.send(this.params);
		}
	}
	obj.Send = function (url,dontwait) {
		if(typeof(dontwait)=="undefined") { dontwait=true; }
		this.SetSend(url,dontwait,false);
		this.Sendit();
	}
	obj.Run = function(url){
		if(typeof(url)!="undefined"){ this.url=url; }
		else{ url=this.url; }
		
		this.xmlhttp.open('POST', this.url, false);
		this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
		this.xmlhttp.setRequestHeader("charset", "UTF-8");
		this.xmlhttp.send(this.params);
		this._parse_result();
	}
	obj.SetSend = function(url,dontwait){
		if(typeof(dontwait)=="undefined") { dontwait=true; }	
		this.url=url;
		this.dontwait=dontwait;
	}
		
	obj._manager_send = function(){
		this.Sendit();
	}
	
	obj.Add = function(manager, group){ manager.group[group].Add(this); }
	
	obj.AddParam = function(name, value){
		value=$.Convert.ToString(value);
		value=encodeURIComponent(value);
		value=value.replace(/\+/gi,'%2B');
		obj.params+='&'+name+'='+value;
		this.post_params.push({'name': name, 'value': value});
	}
	obj.AddParamArray = function(name,value){
		if(value.join){ value = value.join("||"); }
		this.AddParam(name,value);
		obj.post_params.push({'name': name, 'value': value});
	}
	obj.ClearParams = function(){
		obj.params = null;
		obj.post_params = [];
	}
	
	obj._statechange = function(){
		if(typeof(obj._manager_statechange)!="undefined") { obj._manager_statechange(); }
		obj.state=obj.xmlhttp.readyState;
		if(obj.xmlhttp.readyState==4 && obj.xmlhttp.status==200){
			obj.ready=true;
			obj._parse_result();
			if(typeof(obj.oncomplete)!="undefined") { obj.oncomplete(); }
			if(typeof(obj._manager_complete)!="undefined") { obj._manager_complete(); }
		}
		
		if(DEBUG_MODE){
			$.Debug.Title(obj.debug_id, obj.DebugTitle()); 
			if(obj.xmlhttp.readyState==4 && obj.xmlhttp.status==200){
				var strHeaders = obj.xmlhttp.getAllResponseHeaders();
				var headers = strHeaders.split('\n');
				strHeaders='';
				for(var i=0, iLen=headers.length; i<iLen; i++){
					var head=headers[i];
					var sep=head.indexOf(':');
					if(sep!=-1){
						strHeaders += '<b>'+head.substring(0,sep)+':</b>';
						strHeaders += '&nbsp;&nbsp;'+head.substring(sep+1)+'<br />';
					}
				}
				$.Debug.AddContent(obj.debug_id, '<h1>Headers:</h1>'+strHeaders);
				$.Debug.AddContent(obj.debug_id, '<h1>Result:</h1>'+obj.xmlhttp.responseText);
			}
		}
	}
	obj._parse_result = function(){
		this.text=this.xmlhttp.responseText;
		this.status=this.xmlhttp.status;
		try{ this.json=eval("(" + this.text + ")");  }
		catch(e){ if(this.text!=''){ this.json={'error': e.message, length: 0}; } }
		if($.isDefined(this.json) && $.isDefined(this.json.error) && $.isString(this.json.error) && this.json.error.indexOf("Changed database context to")>-1){	this.json.error=''; }
	}
	
	obj.Save = function(table,fields,values,key){
		if(typeof(table)!="undefined" && typeof(fields)!="undefined" && typeof(values)!="undefined"){
			this.debug_class='Save';
			this.AddParam('save',table);
			if(typeof(key)!="undefined" && key!=null){ this.AddParam('key', key); }
			this.AddParamArray('fields', fields);
			this.AddParamArray('values', values);
			this.AddParam('company', COMPANY.code);
			this.Run('lib/php/ajax_db.php');
			if(DEBUG_MODE && this.json.error){ $.Debug.Add(this.json.error); }
			this.ClearParams();
			return this.json;
		}
		else{ $.Debug.Add("$.Ajax.Save() didn't have all required arguments","error"); }
	}
	obj.del = function(table,key){
		if(typeof(table)!="undefined" && typeof(key)!="undefined"){
			this.debug_class='Delete';
			this.AddParam('delete',table);
			this.AddParam('key',key);
			this.AddParam('company', COMPANY.code);
			this.Run('lib/php/ajax_db.php');
			if(this.json.error){ $.Debug.Add(this.json.error); }
			this.ClearParams();
			return this.json;
		}
		else{ $.Debug.Add("$.Ajax.del() didn't have all required arguments","error"); }
	}
	obj.DebugTitle = function(){
		var text = '<b>Ajax '+this.method+':</b>&nbsp;&nbsp;'+this.url+'&nbsp;&nbsp;';
		text += this.debug_class!=''?'<b>'+this.debug_class+'</b>&nbsp;&nbsp;':'';
		if(this.xmlhttp.readyState==4){ text += '<span>'+this.xmlhttp.status+' '+this.xmlhttp.statusText+'</span>'; }
		return text; 
	}
	return obj;
}
var JadeAjaxManager = function() {
	var obj= {};
	obj.group = {};
	obj.Create = function(key) {
		this.group[key] = new JadeAjaxManager_Group();
	}
	return obj;
}
var JadeAjaxManager_Group = function() {
	var obj = new Object();
	obj.scripts = new Array;
	obj.times ='';
	obj.state = false;
	obj.Add = function (object) {
		object.index_manager = 	this.scripts.length;
		this.scripts.push(object);
		
		object._manager_complete = function() {
			var state=true;
			//this.progessive=false;
			for(var i in obj.scripts){
				if(obj.scripts[i].state!=4){state=false; break; }
			}
			if(this.progessive){
				
				var next = this.index_manager + 1;
				if(next<obj.scripts.length) {
					obj.scripts[next].progessive=true;
					obj.scripts[next]._manager_send();
				}
			}
			obj.state = state;
			if(state && typeof(obj.oncomplete)!="undefined") { obj.oncomplete(); }
		}
	}
	obj.Start = function (object) {
		if(this.scripts.length==0 && typeof(obj.oncomplete)!="undefined") { obj.oncomplete(); }
		for(var i=0,iLen=this.scripts.length;i<iLen;i++){
			this.scripts[i]._manager_send();
		}
	}
	obj.ProgessiveStart = function(object) {
		if(this.scripts.length>0) {
			this.scripts[0].progessive = true;
			this.scripts[0]._manager_send(); 
		}
	}
	return obj;
}
var JadeAjaxDB = function(query, action){
	var obj=$.Ajax();
	obj.debug_class='DB';
	
	if(typeof(COMPANY)!="undefined"){ query=query.replace(/\{c\}/gi, COMPANY.code); }
	obj.AddParam('query', query);
	obj.url='lib/php/ajax_db.php';
	if(typeof(action)=="undefined"){ action=Ajax.Manager; }
	switch(action){
		case Ajax.Manager:
			obj.dontwait=true;
			break;
		case Ajax.Dontwait:
			obj.dontwait=true;
			obj.Sendit();
			break;
		case Ajax.Wait:
			obj.dontwait=false;
			obj.Run();
			break;
	}
	return obj;
}
var JadeAjaxDBSave=function(table,fields,values,key){
	table=table.replace(/\{c\}/gi, COMPANY.code);
	var obj=$.Ajax();
	return obj.Save(table,fields,values,key);
}
var JadeAjaxDBDelete=function(table,key){
	table=table.replace(/\{c\}/gi, COMPANY.code);
	var obj=$.Ajax();
	return obj.del(table, key);
}
var JadeDBImage=function(field, table, where){
	table=table.replace(/\{c\}/gi, COMPANY.code);
	var link = "lib/php/bd_image.php?f="+field+"&t="+table+"&w="+where;
	if(DEBUG_MODE){ $.Debug.Add('<b>DBImage:</b>&nbsp;&nbsp;'+link,'debug'); }
	return link;
	
}

$.sajax=function(url, params){
	var ajax=$.Ajax();
	ajax.url=url;
	for(param in params){
		ajax.AddParam(param, params[param]);
	}
	ajax.Sendit();
	
	return ajax;
}

var Ajax={Manager:0,Wait:1,Dontwait:2};
$.LoadLibrary('Ajax',JadeAjax);
$.LoadLibrary('AjaxDB',JadeAjaxDB);
$.LoadLibrary('AjaxDBSave',JadeAjaxDBSave);
$.LoadLibrary('AjaxDBDelete',JadeAjaxDBDelete);
$.LoadLibrary('DBImage',JadeDBImage);
$.LoadLibrary('AjaxManager',JadeAjaxManager);