// ajax copyright 2001-2007 ismael canales Luis
// Under the LGPL license
// this software do not have any garanty implicit or explicit



function ajax(){

	this.print=print
	this.get=get
	this.post=post
	this.wget=wget
	this.onEndRequest=onEndRequest
	this.push=push_html;
	this.pop=pop_html;


	function push_html(id)
	{
		o=document.getElementById(id)
		if(o){
			try{
				o.cache.push(o.innerHTML);
			}catch(e){
				o.cache=new Array();
				o.cache.push(o.innerHTML);
			}
		}
	}


	function pop_html(id)
	{
		o=document.getElementById(id)
		if(o){
			try{
				o.innerHTML=o.cache.pop();
			}catch(e){
			}
		}
	}




	function onEndRequest(status,content){
		return 0+1;	
	}	


	function print(msg,object_id,operation)
	{
	//	if(operation == 'set_html' || operation==null){
				obj=document.getElementById(object_id);
				if(obj)
					obj.innerHTML='<span style="font-face:arial; font-size: 12px; color: white; background-color: #BC00BC">'+msg+'</span><br>'+obj.innerHTML;
	//	}

	}


	// no funciona  es asincrono el ajax automelon xDDD
	function wget (url) {

		this.req=false

		this.wget_ok=false

		// Constructor
		if (this.req==false) {
			if (window.XMLHttpRequest) {
				try {
					this.req=new XMLHttpRequest()
				} catch (e) {
					this.req=false
				}
			} else if (window.ActiveXObject) {
				try {
					this.req=new ActiveXObject("Msxml2.XMLHTTP")
				} catch (e) {
					try {
						this.req=new ActiveXObject("Microsoft.XMLHTTP")
					} catch (e) {
						this.req=false
					}
				}
			}

			if (this.req) {
				var request=this.req
				// Se llama cuando se recibe una respuesta y la procesa
				this.req.onreadystatechange=function () {
					// Cuando me llamen porque ya esta cargada la respuesta
					if (request.readyState==4) {
						// Si todo fue bien...
						if (request.status!=200) {	// OK
							alert(request.status+': No se ha podido acceder a la url "'+url+'"')
						}else{
							this.wget_ok=true
						}
					}
				}
				if(this.wget_ok){
					return this.request.responseText;
				}
				// Envia la peticion
				this.req.open("GET",url,true)
				this.req.send(null)
			} else {
				alert("Ajax not supported")
			}
		}
	}

	// Ajax: Recibe un fichero remoto en el que hacer la peticion, y una cadena de parametros GET
	// Hace una llamada a la 'url', y cambia el contenido del objeto 'object_id' aplicando la accion 'operation'
	function get (url,object_id,operation) {

		this.req=false

		if(operation == ''){
			operation='set_html';
		}

		// Constructor
		if (this.req==false) {
			if (window.XMLHttpRequest) {
				try {
					this.req=new XMLHttpRequest()
				} catch (e) {
					alert(e);
					this.req=false
				}
			} else if (window.ActiveXObject) {
				try {
					this.req=new ActiveXObject("Msxml2.XMLHTTP")
				} catch (e) {
					try {
						this.req=new ActiveXObject("Microsoft.XMLHTTP")
					} catch (e) {
						this.req=false
					}
				}
			}

			if (this.req) {
				var request=this.req
				var oer=this.onEndRequest;
				this.req.onreadystatechange=function () {
					// Cuando me llamen porque ya esta cargada la respuesta
					if (request.readyState==4) {
						// Si todo fue bien...
						if (request.status==200) {	// OK
							try {
								// Sustituye el contenido en el objeto 'object_id', realizando la accion 'operation'
								refreshHTMLContent(request.responseText,object_id,operation,url)
							
							} catch (e) {
								alert('El contenido del id "'+object_id+'" no se pudo actualizar')
								alert('Error al procesar la respuesta de ajax '+e)
								//alert('El contenido de la respuesta es\n'+request.responseText)
							}
							oer(request.status,request.responseText);
						} else {
							alert(request.status+': No se ha podido acceder a la url "'+url+'"')
						}

						//document.getElementsByTagName('body')[0].style.cursor='default';
					}
				}
				// Envia la peticion
				this.req.open("GET",url,true)
				this.req.send(null)
				if(operation!="append")
				this.print("Cargando...",object_id,operation);
			} else {
				alert("Ajax not supported")
			}
		}
	}

	function post (url,object_id,f,operation) {

			if(operation == ''){
				operation='set_html';
			}
			this.req=false;

			if (window.XMLHttpRequest) {
				try {
					this.req=new XMLHttpRequest()
				} catch (e) {
					this.req=false
				}
			} else if (window.ActiveXObject) {
				try {
					this.req=new ActiveXObject("Msxml2.XMLHTTP")
				} catch (e) {
					try {
						this.req=new ActiveXObject("Microsoft.XMLHTTP")
					} catch (e) {
						this.req=false
					}
				}
			}

			if (this.req) {
				var request=this.req
				// Se llama cuando se recibe una respuesta y la procesa
				
				var oer=this.onEndRequest;
				this.req.onreadystatechange=function () {
					// Cuando me llamen porque ya esta cargada la respuesta
					if (request.readyState==4) {
						// Si todo fue bien...
						if (request.status==200) {	// OK
							try {
								// Sustituye el contenido en el objeto 'object_id', realizando la accion 'operation'
								refreshHTMLContent(request.responseText,object_id,operation,url)
								oer(request.status,request.responseText);
							} catch (e) {
								alert('El contenido del id "'+object_id+'" no se pudo actualizar')
								alert('Error al procesar la respuesta de ajax '+e)
								//alert('El contenido de la respuesta es\n'+request.responseText)
							}
						} else {
							alert('No se ha podido acceder a la url "'+url+'" para hacer la peticion code='+request.status)
						}
					}else{

					}
				}

				// Envia la peticion
				parameters="";
				if(f.elements != null){

					for(i=0;i<f.elements.length;i++){
						try{
							type=f.elements[i].type.toUpperCase();
							if( type == 'SELECT'){
								val=f.elements[i].options[f.elements[i].selectedIndex].value
							}else if ( type == 'CHECKBOX'){
								val=f.elements[i].checked ? f.elements[i].value : null
							}else if ( type == 'RADIOBUTTON'){
								if(f.elements[i].checked){
									val=f.elements[i].value;
								}else continue;
							}else if (type == 'BUTTON' || type=='IMAGE'){
								continue;
							}else{
								val=f.elements[i].value;
							}	
							parameters+=encodeURI(f.elements[i].name)+'='+encodeURI(val)+"&";
						}catch(e){
							alert(e)
						}
						
					}
				}else{
					for(key in f){
						try{
							parameters+=encodeURI(key)+'='+encodeURI(f[key])+"&";
						}catch(e){
							alert(e)
						}
					}
				}
				this.req.open('POST', url, true);
				url=url+'?'+parameters
				this.req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				this.req.setRequestHeader("Content-length", parameters.length);
				this.req.setRequestHeader("Connection", "close");
				this.req.send(parameters);
				this.print("Conectando...",object_id,operation);
				
			} else {
				alert("Ajax not supported")
			}
	}

}

// Realiza una accion sobre un objeto html
// 	- content puede ser html, javascript, o un valor, etc (lo que vayamos a cambiar)
//	- object_id define el objeto sobre el que va a actuar la operacion
// 	- operation define la operacion a realizar sobre el objeto 'object_id', por defecto, la operacion es 'set_value'
//		Tipos de operaciones:
//			- set_value
//			- set_html
//			- funcion javascript con los parametros (id, value)

function ajump(url,container_id,handler,observer)
{
	a= new ajax()
	a.push(container_id)
	if(observer)
		a.onEndRequest=observer
	a.get(url,container_id,handler)
}


function wget(url)
{
	a= new ajax()
	return a.wget(url)
}

function apost(url,object_id,operation,f) {

	a= new ajax()
	a.push(object_id)
	a.post(url,object_id,f,operation)
}

function ajax_pop(id)
{
	a=new ajax()
	a.pop(id)
}

function ajax_clean(id)
{
	o=get(id);
	o.cache=new Array()
	o.innerHTML="";
}


function refreshHTMLContent (content,object_id,operation,url)
{
	var result=true


	// Default operation
	if (operation==null || operation=='') {
		if( object_id == null || object_id == ''){
			operation='just_call'
		}else{
			operation='set_value'
		}
	}


	flag_eval=0;

	var js_code="";
	
	if( content.match(/<script.*?>/)){
		try{
			var cont=js_parser(content);
			js_code=cont[1];
			content=cont[0];
			flag_eval=1;
		}catch(e){
			alert("Error evaluando javascript (js_parser):\n"+js_code+e);
		}
	}else{
		try{	// sistema antiguo por json perro
			content=eval(content);	
			js_code=content[1]
			flag_eval=1;
			content=content[0];
		}catch(e){  // parser de <script>
		}
	}

	switch (operation) {
	// Para campos de formularios, establece el valor del campo
		case 'set_value':
			setObjectValue(object_id,content)
			break

		case 'call':
			// operacion call, no cambia ningun inner ni nada de la pagina
			break;

		case 'reload':
			window.document.location.href=window.document.location.href
			break;

		case 'reload_opener':
			opener.document.location.href=opener.document.location.href
			break;

		case 'append':
			var obj=document.getElementById(object_id)
			obj.ajax_url=url
			if(!content)content="";
			obj.innerHTML+=content
			break;

		case '':
		case 'set_html':
			var obj=document.getElementById(object_id)
			if(obj){
				obj.ajax_url=url
				if(!content)content="";
				obj.innerHTML=content;
			}
			break

		default:
			operation()
			break;
	}

	if( flag_eval ){
			kk=eval(js_code);	
	}
	return content
}
