/*
@summary: clase de soporte para ajax
@author: Jose Carlos Calvo Tudela
@revision: Rafael Higuera Matas
*/


function AJAXObject(){

	var _objXml=null;	
	var _this=this;
	var _requiereAutenticacion = true;
	var _error=false;


	_init=function(){
	
		_error=false;
		try{
			_objXml = new XMLHttpRequest();
		}
		catch (error){
			try{_objXml = new ActiveXObject("Microsoft.XMLHTTP");}
			catch (error){
				alert('Esta pagina necesita tener activada la ejecución ActiveX de su navegador');
				return false;
			}
		}
		
		_objXml.onreadystatechange=function(){
				if(_objXml.readyState == 4){
					if(!_comprobarError(_dF(_objXml.responseText))){
						//alert(instanciaAjax.GetResponse())
						_this.onFinish();
					}
					else{
						_this.onError();
					}

				}
			}		
		return true;	
	}
	
	
	this.getRequiereAutenticacion=function(){
		_error=false;
		return _requiereAutenticacion;
	}
	
	this.setRequiereAutenticacion=function(value){
		_error=false;
		_requiereAutenticacion=value;
	}
	
	this.setError=function(value){
		_error=value;
	}
	
	this.getError=function(){
		return _error;
	}
	
	
	this.OnFinish=function(){
		return onFinish();
	}
	

	this.onFinish=function(){
		_error=false;
		return false;
	}

	this.onError = function() {
		return false;
	}

	this.GetResponse=function(){
		_error=false;
		return _dF(_objXml.responseText);
	}
	
	this.getResponse==function(){		
		return GetResponse();
	}
	
	
	this.Open=function(){
		return open();
	}
		

	this.open=function(method,url,usarCache){		
		_error=false;
		
		if (usarCache==undefined)
			usarCache=true;
			
		if (!usarCache && method.toLowerCase()=="get")
			url+="&_random=" + Math.random();
		_objXml.open(method,url);
		_objXml.send(null);
	}
	
		
	this.Send = function(object){
		return send(object);
	}
	
	this.send = function(object){
		_error=false;
		return false;
	}
	
	
	function _comprobarError(xml){
		var errorAutenticacion=false;
		if ((xml.substring(0,7) == '<error>') || (xml.indexOf('<DatosError>') != -1)){
			_error = true;				

			//TODO: comprobar si el error es de autenticacion			
			if(errorAutenticacion && _requiereAutenticacion){
				//alert(xml);
				//window.location.reload();		
			}
			return true;
		}else{
			return false;
		}

	}
		
	function _trim(str)
	{
	   return str.replace(/^\s*/, '').replace(/\n\s*/g, '\n');
	}

	function _dF(s){
		var tmp, i;
		tmp = s;
		tmp = tmp.replace( /&quot;/g, String.fromCharCode(34) ) ;
		tmp = tmp.replace( /&lt;/g  , String.fromCharCode(60) );
		tmp = tmp.replace( /&gt;/g  , String.fromCharCode(62) );
		tmp = tmp.replace( /&amp;/g , String.fromCharCode(38) );
		tmp = tmp.replace( /&nbsp;/g, String.fromCharCode(32) );

		return tmp;
	}
	
		
	_init();

}



