﻿function Ajax(url,f,loading){
// FUNCIONAMIENTO GENERAL (XML) /////////////////////////////////////////////
	// VARIABLES LOCALES /////////////////////

	var intentos=0;
	var self;
	var indicemodal=0;
	var indicetooltip=0;

	// PROPIEDADES ///////////////////////////

	this.xmlDoc = null;
	this.url = url? url : null;
	this.f = f? f: null;
	this.loading = loading? loading : null;
	this.loaderror = null;
	this.running = false;
	this.post = null;
	this.id = Math.random();
	this.nocache = false;

	// MÉTODOS ///////////////////////////////
	// Iniciamos el objeto

	this.init = function(){	
		if (window.XMLHttpRequest) {
			this.xmlDoc = new XMLHttpRequest();
			this.xmlDoc.onreadystatechange = check;
		} 
		else if (window.ActiveXObject) {			
			this.xmlDoc = new ActiveXObject("Microsoft.XMLHTTP");
			if (this.xmlDoc)
				this.xmlDoc.onreadystatechange = check;
		} 
		else
			alert('Tu navegador no puede soportar el script');
	}

	// Ejecutamos

	this.run = function(run_url,run_f,run_loading){
		// Si nos llegan  parámetros los recogemos
		this.url = run_url? run_url : this.url;
		this.f = run_f? run_f: this.f;
		this.loading = run_loading? run_loading : this.loading;

		// Iniciamos objeto
		try{
			this.init();
		} catch(e){
			// ActiveX desactivado
			return false;
		}
		this.running = true;

		// Función cargando
		if (this.loading!=null)
			if(typeof(self.loading)=='function')
				self.loading();
			else
				eval(self.loading);
			eval(this.loading);

		// Prevenimos cacheo con IE
		if (this.nocache){
			if(this.url.indexOf('?')>0)
				this.url+='&ajax-random='+Math.random()
			else
				this.url+='?ajax-random='+Math.random()
		}

		// Cargamos la URL


			this.xmlDoc.open((this.post==null?'GET':'POST'), this.url, true);
			if(this.post!=null)
				this.xmlDoc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=ISO-8859-1');
			this.xmlDoc.send(this.post);
			this.post=null;
	}	

	// FUNCIONES PRIVATE ///////////////////////

	// Chequeamos el resultado
	function check() {
		if (self.xmlDoc.readyState==4)
			if (self.xmlDoc.status==200){
				self.running = false;
				if(typeof(self.f)=='function')
					self.f();
				else
					eval(self.f);
				intentos = 0;
			}
			else
				checkerror();	
	}

	function checkerror(){
		self.running = false;
		if(self.loaderror!=null)
			if(typeof(self.loaderror)=='function')
				self.loaderror();
			else
				eval(self.loaderror);
		else
			self.errorLabel('Error en la b&#250;squeda. Int&#233;ntelo m&#225;s tarde.');
			
		return;
	}


// EFECTOS Y MENSAJES ////////////////////////////////////////////////
	// VARIABLES LOCALES /////////////////////
	var label;

	var modal2Html = '';

	var tooltipTimeout;

	// PROPIEDADES ///////////////////////////
	this.hideTimeout = 2;

	this.errorTimeout = 5;

	// MÉTODOS ///////////////////////////////
	// Mostrar mensaje en etiqueta arriba a la derecha, tipo Google

	this.showLabel = function(msg){
		crearEtiqueta();
		label.innerHTML = msg;
		label.style.display = '';
	}


	// Ocultar etiqueta (si se pasa un texto como parámetro se muestra con fondo verde durante 2 segundos)

	this.hideLabel = function(msg){
		if(msg){
			crearEtiqueta();
			label.style.color = '#FFF';
			label.style.background = '#093';
			label.innerHTML = msg;
			setTimeout(function(){if($('_ajax_label')) $('contenido').removeChild($('_ajax_label'))},this.hideTimeout*1000);
		}
		else 
			if($("_ajax_label")) 
				$('contenido').removeChild($("_ajax_label"));
	}

	// Ocultar etiqueta mostrando un mensaje con fondo rojo durante 5 segundos

	this.errorLabel = function(msg){
		crearEtiqueta();
		label.style.color = '#000';
		label.style.background = '#FFF';
		label.innerHTML = msg;
		setTimeout(function(){if($('_ajax_label')) $('contenido').removeChild($('_ajax_label'))},this.errorTimeout*1000);
	}

	// FUNCIONES PRIVATE ///////////////////////

	function crearEtiqueta(){

		if($('_ajax_label'))

			label = $('_ajax_label');

		else{

			label = document.createElement('DIV');
			label.style.cssText = 'position: absolute; left:190px; top:250px; padding: 2px 20px 2px 20px; font-family: arial; font-size: 13px; font-weight: bold; z-index: 99';		
			label.id = '_ajax_label';
			$('contenido').appendChild(label);
		}
	}

	function $(id){return document.getElementById(id);}

	// Necesario para poder instanciar la clase en el onreadystatechange

	self = this;

}

function getAbsoluteElementPosition(element) {
  if (typeof element == "string")
    element = document.getElementById(element)
    
  if (!element) return { top:0,left:0 };
  
  var y = 0;
  var x = 0;
  while (element.offsetParent) {
    x += element.offsetLeft;
    y += element.offsetTop;
    element = element.offsetParent;
  }
  return {top:y,left:x};
}
