// JavaScript Request
var ER_DECIMAL = /^\d+(\.\d{0,3})?$/;
var ER_ENTERO = /^[+-]?\d+$/;
var ER_NATURAL = /^\d+$/;
var ER_VACIO = /^$/;
var ER_FECHA = /([0][1-9]|[12]\d|3[01])(\/|-)(0[1-9]|1[012])(\/|-)(\d{4})$/;
var ER_ALFANUMERICO = /^[\wαινσϊΑΙΝΣΪρΡδλοφόΔΛΟΦά][\wαινσϊΑΙΝΣΪρΡδλοφόΔΛΟΦά \.\(\)]*[\wαινσϊΑΙΝΣΪρΡδλοφόΔΛΟΦά\.\(\)]$|^[\wαινσϊΑΙΝΣΪρΡδλοφόΔΛΟΦά]$/;
//var ER_STR = /^[a-zA-ZαινσϊΑΙΝΣΪρΡδλοφόΔΛΟΦά][a-zA-ZαινσϊΑΙΝΣΪρΡδλοφόΔΛΟΦά \.\(\)]*[a-zA-ZαινσϊΑΙΝΣΪρΡδλοφόΔΛΟΦά\.\(\)]$|^[a-zA-ZαινσϊΑΙΝΣΪρΡδλοφόΔΛΟΦά]$/;
var ER_STR = /^([^ \t\n\r]([ \t\n\r]|[^ \t\n\r])*[^ \t\n\r])+$|^[^ \t\n\r]$/;
var ER_STR_ESPECIAL = /^([\S]([\S\s])*[\S])?$|^[\S]$/;
var ER_EMAIL = /^[a-z0-9_\.\-]+@[a-z0-9_\-]+(\.[a-z0-9_\-]{2,20})*\.[a-z]{2,6}$/;
var ER_HORA = /^(0?\d|1\d|2[0-3]):([0-5]\d)$/;
var ER_NIF = /^([A-Za-z]-)?[0-9]{8}-[A-Za-z]{1}$/;
var ER_NATURAL_NOCERO = /^[1-9]+[0-9]*$/;
var SEP_AND = "|&|";
var SEP_IGUAL = "|=|";

function $(e){
	return document.getElementById(e);
}

function ltrim(str){
	return str.replace(/^(\s+)/g, '');
}

function rtrim(str){
	return str.replace(/(\s+)$/g, '');
}

function trim(str){
	return ltrim(rtrim(str));
}

Request = function(oListener, metodo){
	this.pedido = new crearXHR()
	this.esperar = true
	this.respuestaXML = null
	this.respuestaHTML = null
	this.archivo=null
	this.valores=null
	this.listener=oListener
	if(metodo=='POST' || metodo=='GET') this.metodo = metodo
	else this.metodo = 'POST'
};
Request.prototype.pedir = function(a, v, m){
	//inicializamos
	if(a) this.archivo = a
	if(v) this.valores = v
	if(m) this.metodo = m
	//
	cancelarPedido(this.pedido)
	//
	var oClase = this;
	this.pedido.onreadystatechange = function(){ oClase.procesar() }//LINEA DEL HONGO!!!!! HACE LEAKS A 2 MANOS
	//
	this.pedido.open(this.metodo, this.archivo, true)
	//
	if(this.valores) this.pedido.send(this.valores);
	else this.pedido.send('LOGin');
};
Request.prototype.procesar = function(){
	//alert("procesando")
	//if(this.pedido && this.pedido.readyState) alert(this.pedido.readyState)
	if(this.pedido && this.pedido.readyState == 4){
		//alert(this.pedido.status+this.pedido.statusText+this.pedido.responseText)
		if(this.pedido.status == 200){
			this.respuestaXML = this.pedido.responseXML.documentElement
			this.respuestaHTML = this.pedido.responseText
			
			//alert(this.listener)
			cancelarPedido(this.pedido)
			if(this.listener && this.listener.onRequestLoad) this.listener.onRequestLoad()
			else if(typeof(this.listener)=='function') this.listener()
		}
		else{
			alert("Error JS Request.procesar(): Status "+this.pedido.status+" "+this.pedido.statusText+" "+this.archivo+" "+this.metodo)
			cancelarPedido(this.pedido)
		}
	}
	this.esperar = false
};
/* FUNCION DE CREACION DE XMLHttpRequest */
crearXHR = function(){
    var r = null
    if (window.XMLHttpRequest) r = new XMLHttpRequest()
    else if(window.ActiveXObject) {
		var msp = new Array('Msxml2.XMLHTTP.5.0', 'Msxml2.XMLHTTP.4.0', 'Msxml2.XMLHTTP.3.0', 'Msxml2.XMLHTTP', 'Microsoft.XMLHTTP')
        for(var i = 0; i < msp.length; i++){
            try { r = new ActiveXObject(msp[i]) } catch (e){}
        }
    }
    return r
};
/* FUNCION DE DETENCION DE XMLHttpRequest */
cancelarPedido = function(reqXHR){
	if(reqXHR!=null){
		reqXHR.onreadystatechange=new Function()//una funcion vacia...
		reqXHR.abort()
	}
};
var SEP_AND = '|&|';
var SEP_IGUAL = '|=|';



// JavaScript Navegador
Navegador = function(){
	this.esIE = false;// Internet Explorer
	this.esIE6 = false;
	this.esIE7 = false;
	this.esMz = false;// Mozilla
	this.esOp = false;// Opera
	this.esNs = false;// Netscape
	
	if(window.navigator.appVersion.search(RegExp("MSIE","im"))!=-1){
		this.esIE = true;
		if(window.navigator.appVersion.search(RegExp("6","im"))!=-1) this.esIE6 = true;
		else if(window.navigator.appVersion.search(RegExp("7","im"))!=-1) this.esIE7 = true;		
	}
	else if(window.navigator.appName.search(RegExp("Opera","im"))!=-1) this.esOp = true;
	else if(window.navigator.appName.search(RegExp("Netscape","im"))!=-1) this.esMz = true;
};
var Nav = new Navegador();



// JavaScript Add/Remove/Fire Event
AddEvent = function(o, e, f){
	if(Nav.esIE) o.attachEvent('on'+e, f);
	else if(Nav.esMz || Nav.esOp) o.addEventListener(e, f, true);
};
RemEvent = function(o, e, f){
	if(Nav.esIE) o.detachEvent('on'+e, f);
	else if(Nav.esMz || Nav.esOp) o.removeEventListener(e, f, true);
};
FireEvent = function(o, e){
	var evt = null;
	if(Nav.esIE) o.fireEvent('on'+e);
	else{
		if(e=='click' || e=='dblclick' || e=='mousedown' || e=='mousemove' || e=='mouseout' || e=='mouseover' || e=='mouseup'){
			evt = document.createEvent("MouseEvents");
			evt.initMouseEvent(e, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
		}else if(e=='keydown' || e == 'keypress' || e == 'keyup'){
			evt = document.createEvent("KeyboardEvent");
			evt.initKeyEvent(e, true, true, null, false, false, false, false, 9, 0);
		}else{
			evt = document.createEvent("Event");
			evt.initEvent(e, true, false);
		}
		o.dispatchEvent(evt);
	}
}
StopEvent = function(e){
	if(Nav.esIE){
		event.returnValue = false;
		event.cancelBubble = true;
	}
	else{
		event = e;
		event.preventDefault();
		event.stopPropagation();
	}
}



// JavaScript closure
Function.prototype.closure = function(obj){
	// Init object storage.
	if (!window.__objs){
		window.__objs = [];
		window.__funs = [];
	}
	
	// For symmetry and clarity.
	var fun = this;
	
	// Make sure the object has an id and is stored in the object store.
	var objId = obj.__objId;
	if (!objId) __objs[objId = obj.__objId = __objs.length] = obj;
	
	// Make sure the function has an id and is stored in the function store.
	var funId = fun.__funId;
	if (!funId) __funs[funId = fun.__funId = __funs.length] = fun;
	
	// Init closure storage.
	if (!obj.__closures) obj.__closures = [];
	
	// See if we previously created a closure for this object/function pair.
	var closure = obj.__closures[funId];
	if (closure) return closure;
	
	// Clear references to keep them out of the closure scope.
	obj = null;
	fun = null;
	
	// Create the closure, store in cache and return result.
	var o = __objs[objId].__closures[funId] = function (){
		if(!!__funs[funId] && !!__objs[objId]) return __funs[funId].apply(__objs[objId], arguments);
		else return false;
	};
	o.__funId = funId;
	return o;
	
};
EliminarClosures = function(o){
	var i = 0;
	if(o.__objId){
		for(i in o.__closures){
			delete(window.__funs[i]);
			delete(o.__closures[i]);
		}
		delete(window.__objs[o.__objId]);
		/*delete(o.__closures);
		delete(o.__objId);*/
		o.__closures = null;
		o.__objId = null;
	}
	i = null;
}
var LimpiarClosures = function(){
	if(!!Nav && Nav.esMz) window.addEventListener('unload', LimpiarClosures, false);
	else window.detachEvent("onunload",LimpiarClosures);
	
	if(window.__objs){
		for(i in window.__objs) EliminarClosures(window.__objs[i]);
	}
	window.__objs = [];
	window.__funs = [];
};
Limpiar = function(){
	if(!!Nav && Nav.esMz) window.addEventListener('unload', LimpiarClosures, false);
	else window.attachEvent("onunload", LimpiarClosures);
}();
document.LimpiarClosures  = LimpiarClosures;




// JavaScriptS
function opacidad(e, n){
	var o = (typeof(e)=='object')? e : document.getElementById(e);
	if(!!o){
		if(Nav.esIE) o.style.filter = 'alpha(opacity='+n+')';
		else if(Nav.esMz) o.style.MozOpacity = (n < 100)? '.'+n : 1;
		else if(Nav.esOp) o.style.opacity = (n < 100)? '.'+n : 1;
	}
	o = null;
}
function getBodyDims(){
	if(Nav.esOp) return {w:document.body.clientWidth, h:document.body.clientHeight};
	else if(Nav.esMz) return {w:self.innerWidth, h:self.innerHeight, a:'Mz'};
	else if(Nav.esIE) return {w:document.body.offsetWidth, h:document.body.offsetHeight, a:'b'};
	else return {w:0, h:0};
}

function WScreen(){ return (Nav.esIE)? document.documentElement.clientWidth : window.innerWidth; }
function HScreen(){ return (Nav.esIE)? document.documentElement.clientHeight : window.innerHeight; }
function YPos(){ return (Nav.esIE)? document.documentElement.scrollTop : window.pageYOffset; }
function XPos(){ return (Nav.esIE)? document.documentElement.scrollLeft : window.pageXOffset; }
function HBody(){ return document.documentElement.scrollHeight; }
function WBody(){ return document.documentElement.scrollWidth; }


function showFocus(obj){
	if(!document.getElementById) return;
	obj.style.border = "1px solid #56a4f5";//1111FF
}
function showBlur(obj){
	if(!document.getElementById) return;
	obj.style.border = "1px solid #999999";
}

var seleccionada='';
function seleccionar(objeto){
	if(seleccionada!=undefined && seleccionada!=""){
		seleccionada.onmouseout = new Function("this.style.backgroundColor=''");
		seleccionada.style.backgroundColor='';
	}
	objeto.onmouseout='';
	objeto.style.backgroundColor = '#33cc00';
	return objeto;
}

function darFoco(form, objeto){
	obj = document.forms[form].elements[objeto];
	obj.focus();
}

function validarER(valor,contenido,blanco,expre){//V2 Gallo
	if(valor.search(expre)==-1){
		mostrarError(contenido,blanco);
		return false;
	}
	else return true;
}

function hideShowCovered (self){
	is_khtml = /Konqueror|Safari|KHTML/i.test(navigator.userAgent);
	function continuation_for_the_fucking_khtml_browser() {
		
		function getAbsolutePos (el) {
			var SL = 0, ST = 0;
			var is_div = /^div$/i.test(el.tagName);
			if (is_div && el.scrollLeft) SL = el.scrollLeft;
			if (is_div && el.scrollTop) ST = el.scrollTop;
			var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };
			if (el.offsetParent) {
				var tmp = getAbsolutePos(el.offsetParent);
				r.x += tmp.x;
				r.y += tmp.y;
			}
			return r;
		};
		
		function getVisib(obj){
			var value = obj.style.visibility;
			if (!value){
				// Gecko W3C
				if (document.defaultView && typeof (document.defaultView.getComputedStyle) == "function"){
					if (!is_khtml) value = document.defaultView.getComputedStyle(obj, "").getPropertyValue("visibility");
					else value = '';
				}// IE
				else if (obj.currentStyle) value = obj.currentStyle.visibility;
				else value = '';
			}
			return value;
		};
	
		var tags = new Array("applet", "iframe", "select");
		var el = self;
		
		var p = getAbsolutePos(el);
		var EX1 = p.x;
		var EX2 = el.offsetWidth + EX1;
		var EY1 = p.y;
		var EY2 = el.offsetHeight + EY1;
		
		for (var k = tags.length; k > 0; ) {
			var ar = document.getElementsByTagName(tags[--k]);
			var cc = null;
			
			for (var i = ar.length; i > 0;) {
				cc = ar[--i];
				
				p = getAbsolutePos(cc);
				var CX1 = p.x;
				var CX2 = cc.offsetWidth + CX1;
				var CY1 = p.y;
				var CY2 = cc.offsetHeight + CY1;
	
				if (self.hidden || (CX1 > EX2) || (CX2 < EX1) || (CY1 > EY2) || (CY2 < EY1)) {
					if (!cc.__msh_save_visibility) cc.__msh_save_visibility = getVisib(cc);
					cc.style.visibility = cc.__msh_save_visibility;
				} else {
					if (!cc.__msh_save_visibility) cc.__msh_save_visibility = getVisib(cc);
					cc.style.visibility = "hidden";
				}
			}
		}
	};
	if (is_khtml) setTimeout("continuation_for_the_fucking_khtml_browser()", 10);
	else continuation_for_the_fucking_khtml_browser();
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

var centrarContenidoPantalla = function(nombreObjeto){
	var objeto = document.getElementById(nombreObjeto);
		if(objeto.style.display != "none"){
			var d  = getBodyWHAvaible();
			var top = Math.round((d.h-objeto.offsetHeight)/2);
			var left = Math.round((d.w-objeto.offsetWidth)/2);	
			objeto.style.top = top+"px";
			objeto.style.left = left+"px";	
		}

}
var centrarContenidoPantalla2 = function(nombreObjeto){
	objeto = document.getElementById(nombreObjeto);
	if(objeto.style.display == "block"){
		var d  = getBodyWHAvaible();
		var top = Math.round((d.h-objeto.offsetHeight)/2);
		var left = Math.round((d.w-objeto.offsetWidth)/2);	
		objeto.style.marginTop = top+"px";
		objeto.style.marginLeft = left+"px";	
	}
}

var reubicar = function(){
	var d = getBodyWHAvaible();
	var contP = $("contenedorPrincipal");
	if(contP){
		contP.style.width = d.w+"px";
		contP.style.height = d.h+"px";	
	}
	if($('main')){
		centrarContenidoPantalla("main");
	}
	//if($('login'))centrarContenidoPantalla("login");
}


var centrarContenido = function(objeto,bodyDims){
	if(bodyDims)var d  = getBodyDims();
	else var d  = getBodyWHAvaible();
	if(d.h == 0)d = getWindowDims();
	var top = Math.round((d.h-objeto.offsetHeight)/2);
	var left = Math.round((d.w-objeto.offsetWidth)/2);
	objeto.style.top = top+"px";
	objeto.style.left = left+"px";	
}

function getScrollPos(){
	if(Nav.esOp) return {y:window.pageYOffset, x:window.pageXOffset};
	else if(Nav.esMz || Nav.esIE) return {y:document.documentElement.scrollTop, x:document.documentElement.scrollLeft};
	else return {x:0, y:0};
}
function getWindowDims(){
	if(Nav.esOp) return {w:window.innerWidth, h:window.innerHeight};
	else if(Nav.esMz) return {w:document.documentElement.clientWidth, h:document.documentElement.clientHeight};
	else if(Nav.esIE) return {w:document.body.clientWidth, h:document.body.clientHeight};
	else return {w:0, h:0}
}
function getBodyWHAvaible(){
	if(Nav.esOp) return {w:window.innerWidth, h:window.innerHeight};
	else if(Nav.esIE || Nav.esMz) return {w:document.documentElement.clientWidth, h:document.documentElement.clientHeight};
	else return {w:0, h:0}
}

/***************************************/
//Func:  Add/Remove/Fire Event

var mostrarBlockeador = function(display){
	var blockeador = $('blockeador');
	if(blockeador){
		if(display){
			if(Nav.esIE || Nav.esIE7) blockeador.style.filter = 'alpha(opacity=45)';
			else blockeador.style.MozOpacity = ".45";			
			d = getBodyWHAvaible();
			if(d.h == 0)d = getWindowDims();

			blockeador.style.width = d.w+"px";
			blockeador.style.height = d.h+"px"
			blockeador.style.display = "block";
		}
		else blockeador.style.display = "none";
	}
}
var ocultarContenido = function(objeto,conBlockeador){
	objeto.style.visibility = "hidden";
	objeto.style.top = "-5000px";
	if(conBlockeador)mostrarBlockeador();	
}
var centrarContenidoScroll = function(objeto){
	var scr = getScrollPos();
	var d  = getBodyWHAvaible();
	var top = Math.round((d.h-objeto.offsetHeight)/2)+scr.y;
	var left = Math.round((d.w-objeto.offsetWidth)/2);	
	objeto.style.top = top+"px";
	objeto.style.left = left+"px";	

}

/*PREGUNTA SOBRE RESPONDER ENCUESTA*/

var mostrarBlockGeneral = function(){
	var c = $('blockGeneral');
	c.style.height = (HBody() ) + 'px';
	c.style.width = (WBody() ) + 'px';
	c.style.visibility = 'visible';
}

var aceptarMostrarEncuestas = function(){
	var c = $('blockGeneral');
	c.style.height = (HBody() ) + 'px';
	c.style.width = (WBody() ) + 'px';
	c.style.visibility = 'visible';
	centrarContenido($('solapaEncuesta'),true);	
	$('solapaEncuesta').style.visibility = 'visible';	

	ocultarContenido($('preguntarEncuesta'));
}
var cancelarMostrarEncuestas = function(){
	ocultarContenido($('preguntarEncuesta'));
	var ReqEnc = new Request(null);
	ReqEnc.pedir('requests/blockearEncuesta.php','blockear'+SEP_IGUAL+1+SEP_AND);
}
var mostrarPreguntarEncuesta = function(){
	centrarContenido($('preguntarEncuesta'),true);
	$('preguntarEncuesta').style.visibility = 'visible';		
	if(!Nav.esIE)$('preguntarEncuestaFondo').style.marginLeft = "0px";	

}
var cerrarListaEncuestas = function(){
	ocultarContenido($('solapaEncuesta'));
	$('blockGeneral').style.visibility = 'hidden';	
}

function loadTab(){
	//Pro
	this.sHTML = '';
	this.sScript = '';
	this.bHideLoad = true;
	
	//Fun
	this.init = function(sPathHTML, sPathScript, bHideLoad){
		this.sHTML = sPathHTML;
		this.sScript = sPathScript;
		this.bHideLoad = (!bHideLoad)? false : true;
		this.loadHTML();
	}
	this.loadHTML = function(){
		this.showLoading();
		this.req.pedir(this.sHTML, 'nada=si');
	}
	this.loadScript = function(){
		var e = document.createElement('script');
		document.body.appendChild(e);
		e.type = 'text/javascript';
		e.src = this.sScript;
		if(this.bHideLoad) this.hideLoading();
	}
	//
	this.showLoading = function(){
		var c = $('blockGeneral');
		c.style.height = (HBody() ) + 'px';
		c.style.width = (WBody() ) + 'px';
		c.style.visibility = 'visible';
		c = $('cargador');
		centrarContenido(c,true);
/*		c.style.top = (YPos() + Math.floor((HScreen() - c.offsetHeight) / 2)) + 'px';
		c.style.left = (XPos() + Math.floor((WScreen() - c.offsetWidth) / 2)) + 'px';*/
		c.style.visibility = 'visible';
	}
	this.hideLoading = function(){
//		$('blockGeneral').style.visibility = 
		$('cargador').style.visibility = 'hidden';
	}
	
	//Obj
	this.req = new Request();
	this.req.listener = function(){
		var d = this.req.respuestaXML, e = null;
		
		if(!d){ alert("Ha ocurrido un error."); 
					alert('-'+this.req.respuestaHTML);
		}
		else{
			e = document.createElement('span');
			document.body.appendChild(e);
			e.innerHTML = d.firstChild.data;
			this.loadScript();
		}
		
		e = null;
	}.closure(this);
}

//ENCUESTA
var argEncuesta = null;
oEncuesta = {'pedirEncuesta':function(){
	var oLTab = null;
	if(!!argEncuesta) return false;
	oLTab = new loadTab();
	argEncuesta = arguments;
	if(argEncuesta[argEncuesta.length-1]){
		StopEvent(argEncuesta[argEncuesta.length-1]);
		argEncuesta[argEncuesta.length-1] = null;
	}
	oLTab.init(DIR_ROOT + 'requests/cargar.php?file=../oEncuesta.php', DIR_ROOT + 'js/oEncuesta.js', true);
}}

