// Image Functions
function preload(imgObj,imgSrc) {
	if (document.images) {
		eval(imgObj+' = new Image()')
		eval(imgObj+'.src = "'+imgSrc+'"')
	}
}
function changeImage(layer,imgName,imgObj) {
	if (document.images) {
		if (document.layers && layer!=null) eval('document.'+layer+'.document.images["'+imgName+'"].src = '+imgObj+'.src')
		else document.images[imgName].src = eval(imgObj+".src")
	}
}

// COMUN
function Hoy() {
  var oDay   = ['Domingo','Lunes','Martes','Miércoles','Jueves','Viernes','Sábado'];
  var oMonth = ['Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'];
  var oFecha  = new Date();
  var sFecha  = oDay[oFecha.getDay()] + ", "+ oFecha.getDate() + " " + oMonth[oFecha.getMonth()] + " " + oFecha.getYear();	
  //return sFecha;
  document.getElementById('tdfecha').innerHTML = sFecha;
}

// MENUS

actual=0;
adentro=false;
dentro=false;
function ver(cual) { 
   entro()
   if (actual!=0) document.getElementById('submenu'+actual).style.visibility = 'hidden'; 
   document.getElementById('submenu'+cual).style.visibility = 'visible'; 
   actual=cual;
   }
function entro() { adentro=true; }
function salgo() { adentro=false; }
function donde(valor) { dentro=valor; }
function oculta(cual) {
   if (cual!=null) { document.getElementById('submenu'+cual).style.visibility = 'hidden'; }
   else {
          if (actual!=0) document.getElementById('submenu'+actual).style.visibility = 'hidden';
          if (actual2!=0) document.getElementById('submenu'+actual2).style.visibility = 'hidden';
        }
   actual=0;
   }
function cierra() {
   if ((actual!=0) && (!dentro) & (!adentro)) {
     document.getElementById('submenu'+actual).style.visibility = 'hidden';
     actual=0;
     }
   setTimeout('cierra()',2000)
   }

// SUBMENUS

actual2=0;
adentro2=false;
dentro2=false;
function ver2(cual) { 
   entro2()
   if (actual2!=0) document.getElementById('submenu'+actual2).style.visibility = 'hidden'; 
   document.getElementById('submenu'+cual).style.visibility = 'visible'; 
   actual2=cual;
   }
function entro2() { adentro2=true; }
function salgo2() { adentro2=false; }
function donde2(valor) { dentro2=valor; }
function oculta2(cual) {
   if (cual!=null) { document.getElementById('submenu'+cual).style.visibility = 'hidden'; }
   else { if (actual2!=0) document.getElementById('submenu'+actual2).style.visibility = 'hidden'; }
   actual2=0;
   }
function cierra2() {
   if ((actual2!=0) && (!dentro2) & (!adentro2)) {
     document.getElementById('submenu'+actual2).style.visibility = 'hidden';
     actual2=0;
     }
   setTimeout('cierra2()',1000)
   }

// EFECTO MOUSEOVER PARA TDs

function on(obj)  { document.getElementById(obj).className = 'tdon'; }
function off(obj) { document.getElementById(obj).className = 'tdoff'; }
function go(url)  { document.location.href = url; }

// VENTANAS
function ventana(url,w,h)  {  window.open(url,"vnds","toolbar=no,scrollbars=no,width="+w+",height="+h);  }
function ventanaS(url,w,h) {  window.open(url,"vnds","toolbar=no,scrollbars=yes,status=yes,resizable=yes,width="+w+",height="+h); }

// ACTIVAR CAMPOS
activado=false
function activar(f) {
  if (!activado) {
    f.fdd.disabled = false;
    f.fdh.disabled = false;
    f.cli.disabled = false;
    f.so.disabled = false;
    f.da.disabled = false;
    activado=true;
    }
  else {
    f.fdd.disabled = true;
    f.fdh.disabled = true;
    f.cli.disabled = true;
    f.so.disabled = true;
    f.da.disabled = true;
    activado=false;
    }
  }
  
function avisolegal(){
	direccion="avisolegal.php";
	window.open(direccion,'aviso','top=100,left=100,width=450,height=400,resize=1,scrollbars=1');
}
function privacidad(){
	direccion="privacidad.php";
	window.open(direccion,'privacidad','top=100,left=100,width=450,height=400,resize=1,scrollbars=1');
}
function avisolegalback(){
	direccion="../avisolegal.php";
	window.open(direccion,'aviso','top=100,left=100,width=450,height=400,resize=1,scrollbars=1');
}
function privacidadback(){
	direccion="../privacidad.php";
	window.open(direccion,'privacidad','top=100,left=100,width=450,height=400,resize=1,scrollbars=1');
}
function faqusuarios(){
	direccion="faqs_usuarios.htm";
	window.open(direccion,'fu','toolbar=no,menubar=no,location=no,directories=no,status=no,scrollbars=no,resizable=no,width=540,height=426,top=10,left=10');
}
function guardarfavoritos(){
var url="http://www.topformacion.com" 
var titulo="Topformacion.com"

if (document.all)
window.external.AddFavorite(url,titulo)

}
function validarbuscador(){
	f=document.buscador;
	
	if ((f.libre.value=="")&&(f.categoria_id.value=="")&&(f.tipo.value==""))
		alert("Se más específico en tu búsqueda");
	else
		f.submit();

}

function emailCheck (emailStr) {
/* The following pattern is used to check if the entered e-mail address
   fits the user@domain format.  It also is used to separate the username
   from the domain. */
var emailPat=/^(.+)@(.+)$/
/* The following string represents the pattern for matching all special
   characters.  We don't want to allow special characters in the address. 
   These characters include ( ) < > @ , ; : \ " . [ ]    */
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
/* The following string represents the range of characters allowed in a 
   username or domainname.  It really states which chars aren't allowed. */
var validChars="\[^\\s" + specialChars + "\]"
/* The following pattern applies if the "user" is a quoted string (in
   which case, there are no rules about which characters are allowed
   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
   is a legal e-mail address. */
var quotedUser="(\"[^\"]*\")"
/* The following pattern applies for domains that are IP addresses,
   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
   e-mail address. NOTE: The square brackets are required. */
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
/* The following string represents an atom (basically a series of
   non-special characters.) */
var atom=validChars + '+'
/* The following string represents one word in the typical username.
   For example, in john.doe@somewhere.com, john and doe are words.
   Basically, a word is either an atom or quoted string. */
var word="(" + atom + "|" + quotedUser + ")"
// The following pattern describes the structure of the user
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
/* The following pattern describes the structure of a normal symbolic
   domain, as opposed to ipDomainPat, shown above. */
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


/* Finally, let's start trying to figure out if the supplied address is
   valid. */

/* Begin with the coarse pattern to ????????.?A.?º?°simply break up user@domain into
   different pieces that are easy to analyze. */
var matchArray=emailStr.match(emailPat)
if (matchArray==null) {
  /* Too many/few @'s or something; basically, this address doesn't
     even fit the general mould of a valid e-mail address. */
	alert("La dirección de correo parece inválida (comprobar @ and .'s)")
	return false
}
var user=matchArray[1]
var domain=matchArray[2]

// See if "user" is valid 
if (user.match(userPat)==null) {
    // user is not valid
    alert("El usuario no parece ser válido.")
    return false
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
   host name) make sure the IP address is valid. */
var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
    // this is an IP address
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	        alert("IP de destino incorrecta.")
		return false
	    }
    }
    return true
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
	alert("El dominio no parece ser válido.")
    return false
}

/* domain name seems valid, but now make sure that it ends in a
   three-letter word (like com, edu, gov) or a two-letter word,
   representing country (uk, nl), and that there's a hostname preceding 
   the domain or country. */

/* Now we need to break up the domain to get a count of how many atoms
   it consists of. */
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 || 
    domArr[domArr.length-1].length>3) {
   // the address must end in a two letter or three letter word.
   alert("La dirección debe terminar con un dominio de 3 letras, o un nombre de país de dos letras.")
   return false
}

// Make sure there's a host name preceding the domain.
if (len<2) {
   var errStr="¡A esta dirección le falta un nombre de host!"
   alert(errStr)
   return false
}

// If we've gotten this far, everything's valid!
return true;
}
function aceptarboletin(){
if (emailCheck(document.boletin.email.value)){
	direccion="boletin.php?email="+document.boletin.email.value;
	window.open(''+direccion+'','boletin','toolbar=no,menubar=no,location=no,directories=no,status=no,scrollbars=no,resizable=no,width=540,height=610,top=10,left=10');
}
}


function AvisoCargando() {
	var capa = null;
	try {
		var regexp = new RegExp("(/back/)|(/master/)|(/masters/)|(/curso/)|(/cursos/)|(/oposiciones/)|(/postgrado/)|(/postgrados/)|(/diplomatura/)|(/diplomaturas/)|(/licenciatura/)|(/licenciaturas/)|(/paginascategorias/)", "g");
		if (location.href.match(regexp) != null) {
			document.write("<div id='avisoCargando' style='display: none; visibility: hidden; background-color: white; border: 1px solid #7aab00; width: 200px; height: 20px; position: absolute; top: 0px; right: 0px; font-family: verdana; font-size: 10px;font-weight: regular; color: #7D7D7D; text-decoration: none;'><img src='../images/cargando.gif' onError='this.onerror = new Function(); this.src=\"./images/cargando.gif\";' style='width: 16px; height: 16px; border: 0px solid white; margin: 1px 2px; vertical-align: middle;'/><span>&nbsp;&nbsp;Cargando, por favor espere...</span></div>");
		} else {
			document.write("<div id='avisoCargando' style='display: none; visibility: hidden; background-color: white; border: 1px solid #7aab00; width: 200px; height: 20px; position: absolute; top: 0px; right: 0px; font-family: verdana; font-size: 10px;font-weight: regular; color: #7D7D7D; text-decoration: none;'><img src='./images/cargando.gif' onError='this.onerror = new Function(); this.src=\"../images/cargando.gif\";' style='width: 16px; height: 16px; border: 0px solid white; margin: 1px 2px; vertical-align: middle;'/><span>&nbsp;&nbsp;Cargando, por favor espere...</span></div>");
		}
		this.capa = document.getElementById("avisoCargando");
		capa = this.capa;
	}
	catch (excepcion) {}

	this.setVisible = function(visible) {
		try {
			if (visible) {
				this.capa.style.display = "block";
				this.capa.style.visibility = "visible";

				if (typeof(document.body) == "undefined") {
					this.capa.style.left = ((parseInt(document.width, 10) / 2) - (parseInt(this.capa.offsetWidth, 10) / 2)) + "px";
					this.capa.style.top = ((parseInt(document.height, 10) / 2) - (parseInt(this.capa.offsetHeight, 10) / 2) + document.body.scrollTop) + "px";
				} else {
					this.capa.style.left = ((parseInt(document.body.clientWidth, 10) / 2) - (parseInt(this.capa.offsetWidth, 10) / 2)) + "px";
					this.capa.style.top = ((parseInt(document.body.clientHeight, 10) / 2) - (parseInt(this.capa.offsetHeight, 10) / 2) + document.body.scrollTop) + "px";
				}
			} else {
				this.capa.style.display = "none";
				this.capa.style.visibility = "hidden";
			}
		} catch(excepcion) {}
	}

	function eventoMoverRaton(evento) {
		try {
			if (typeof(evento) == "undefined") {
				evento = window.event;
			}

			var posicionX = 0;
			var posicionY = 0;

			if (typeof (evento.clientX) == "undefined") {
				posicionX = parseInt(evento.pageX, 10) + 15;
				posicionY = parseInt(evento.pageY, 10) + parseInt(document.body.scrollTop)

			} else {
				posicionX = parseInt(evento.clientX, 10) + 15;
				posicionY = parseInt(evento.clientY, 10) + parseInt(document.body.scrollTop);
			}

			if (posicionX + capa.offsetWidth + 20 > document.body.offsetWidth){
				posicionX -= (15 + capa.offsetWidth);
			}

			capa.style.left = posicionX  + "px";
			capa.style.top =  posicionY + "px";	
		} catch(excepcion) {}
	}

	if (typeof (window.attachEvent) == "undefined") {
		document.addEventListener("mousemove", eventoMoverRaton, false);
	} else {
		document.attachEvent("onmousemove", eventoMoverRaton);
	}
}

function onSubmitAvisoCargando(){
	try {
		avisoCargando.setVisible(true);
	} catch (excepcion) {}
}

function onLoadAvisoCargando() {
	try {
		avisoCargando.setVisible(false);

		// para cada formulario que tenga target=="_self" o target=="" o target nulo hacemos lo siguiente
		for (var i = 0; i < document.forms.length; i++) {
			var formulario = document.forms[i];
			if (typeof(formulario.target) == "undefined" || formulario.target == "" || formulario.target == "_self") {
				if (typeof (window.attachEvent) == "undefined") {
					formulario.addEventListener("submit", onSubmitAvisoCargando, false);
				} else {
					formulario.attachEvent("onsubmit", onSubmitAvisoCargando);
				}
				formulario.submitAnterior = formulario.submit;
				formulario.submit = function() {
					try {
						avisoCargando.setVisible(true);
					}
					catch(excepcion){}

					this.submitAnterior();
				}
			}
		}
	} catch (excepcion) {}
}

var avisoCargando =  null;
try {
	avisoCargando = new AvisoCargando();
	avisoCargando.setVisible(true);

	if (typeof (window.attachEvent) == "undefined") {
		window.addEventListener("load", onLoadAvisoCargando, false);
	} else {
		window.attachEvent("onload", onLoadAvisoCargando);
	}
}
catch (excepcion) {}

function enviarPaginacion(numero){
	f=document.fPaginacion;
	f.pagina.value=numero;
	f.submit();
}

/* obtiene la posición absoluta de una capa */
function getYGlobal(elemento) {
	try {
		if (typeof(elemento.offsetParent) == "undefined" || elemento.offsetParent == null) {
			return 0;
		} else {
			return parseInt(elemento.offsetTop, 10) + getYGlobal(elemento.offsetParent || elemento.offsetParent == document);
		}
	} catch(excepcion) {
		return 0;
	}
}
/* obtiene la posición absoluta de una capa */
function getXGlobal(elemento) {
	try {
		if (typeof(elemento.offsetParent) == "undefined" || elemento.offsetParent == null || elemento.offsetParent == document) {
			return 0;
		} else {
			return parseInt(elemento.offsetLeft, 10) + getXGlobal(elemento.offsetParent);
		}
	} catch(excepcion) {
		return 0;
	}
}
/* ejecuta una función o una expresión javascript en una cadena cuando se carga el documento */
function putInicio(funcion) {
	if (typeof(funcion) == "undefined"){
		return;
	} else if (typeof(funcion) != "function") {
		funcion = new Function(funcion);
	}
	if (typeof (window.attachEvent) == "undefined") {
		window.addEventListener("load", funcion, false);
	} else {
		window.attachEvent("onload", funcion);
	}
}
/* muestra una capa */
function setDisplay(capa, display) {
	if (typeof(capa) == "string") {
		capa = document.getElementById(capa);
	}
	capa.style.display = display ? "" : "none";
}

/* devuelve true si la capa se dibuja en el documento false si no lo hace */
function isDisplayed(capa) {
	if (typeof(capa) == "string") {
		capa = document.getElementById(capa);
	}
	return capa.style.display != "none";
}
function moverCapa(capa, x, y) {
	if (typeof(capa) == "string") {
		capa = document.getElementById(capa);
	}
	capa.style.position = "absolute";
	capa.style.left = parseInt(x, 10) + "px";
	capa.style.top = parseInt(y, 10) + "px";
}

function setAnchoMaximo(capa, ancho) {
	if (typeof(capa) == "string") {
		capa = document.getElementById(capa);
	}

	capa.style.whiteSpace = "nowrap";
	capa.style.width = (capa.offsetWidth ? Math.min(parseInt(ancho, 10), parseInt(capa.offsetWidth, 10)) : parseInt(ancho, 10)) + "px" ;
	capa.style.whiteSpace = "normal";

}

JMLib = {}
JMLib.Ajax = new function() {
    var _objRequest = null;
    var _timerAjax = null;
    var _peticionesPendientes = $A();

    var AjaxSender = function() {
        var _onSuccess = Prototype.emptyFunction;
        var _onError = Prototype.emptyFunction;
        var _parametros = $H();
        var _url = null;
        var _form = null;
        var _asincrono = true;
        var _metodo = 'post';
        var _codificacion = 'ISO-8859-1';
        var _this = this;

        function ejecutarPeticionAjax() {
            _timerAjax = null;
            if(_objRequest == null || _objRequest._complete) {
                if(_peticionesPendientes.length) {
                    var peticionAjax = _peticionesPendientes.shift();
                    _objRequest = new Ajax.Request(peticionAjax.url, peticionAjax.datos);
                }
            }
            if(_peticionesPendientes.length) {
                _timerAjax = window.setTimeout(ejecutarPeticionAjax, 50);
            }
        }

        function encolarPeticionAjax(url, datos) {
            _peticionesPendientes.push({
                'url': url,
                'datos' : datos
            });
            if(_objRequest == null || _objRequest._complete && _peticionesPendientes.length == 1) {
                ejecutarPeticionAjax();
            } else {
                if(_timerAjax == null) {
                    _timerAjax = window.setTimeout(ejecutarPeticionAjax, 50);
                }
            }
        }

        function evaluar(funcion, parametro, hashParametros) {
            switch(typeof funcion) {
                case "function":
                    funcion(parametro, hashParametros);
                    return true;
                case "string":
                    eval(funcion);
                    return true;
                default:
                    return false;
            }
        }

        this.setOnSuccess = function(onSuccess) {
            _onSuccess = onSuccess;
        }

        this.setOnError = function(onError) {
            _onError = onError;
        }

        this.addParams = function(nombres, valores) {
            if(!nombres.length || !valores.length) {
                throw {
                    msj: 'Error: Ajax::addParmas - Los parmetros nombres y valores deben ser un array'
                };
            }
            if(nombres.length != valores.length) {
                throw {
                    msj: 'Error: Ajax::addParmas - Los parmetros nombres y valores no coinciden en longitud'
                };
            }
            $A(nombres).each(function(nombre, indice) {
                _this.addParam(nombre, valores[indice]);
            });
        }

        this.addParam = function(nombre, valor) {
            var parametro = _parametros.get(nombre);
            if(!parametro) {
                parametro = $A();
            }
            if(Object.isArray(valor)) {
                parametro = parametro.concat(valor);
            } else {
                parametro.push(valor);
            }
            _parametros.set(nombre, parametro);
        }

        this.clearParams = function() {
            _parametros = $H();
        }

        this.getParamString = function() {
            var cadenaParametros = '';
            var nombre = null;
            var valor = null;
            _parametros.each(function(param) {
                nombre = param.key;
                valores = param.value;
                if(valores) {
                    valores.each(function(valor) {
                        if(Object.isFunction(encodeURIComponent)) {
                            valor = encodeURIComponent(valor);
                        }
                        cadenaParametros += (!cadenaParametros.length ? '?' : '&') + nombre + '=' + valor;
                    });
                }
            });
            return cadenaParametros;
        }

        this.setUrl = function(url) {
            _url = url ? url.replace('?', '') : url;
        }

        this.setAsincrono = function(asincrono) {
            _asincrono = !!asincrono;
        }

        this.setMetodo = function(metodo) {
            _metodo = metodo ? metodo : 'post';
        }

        this.setCodificacion = function(codificacion) {
            _codificacion = codificacion ? codificacion : 'ISO-8859-1'; //'UTF-8'
        }

        this.setForm = function(form) {
            _form = form;
        }

        this.send = function() {

            if(_form != null) {
                this.prepareForm();
            }

            var cadenaParametros = this.getParamString();

            var datos = {
                asynchronous: _asincrono,
                method: _metodo,
                encoding: _codificacion,
                onSuccess: function(transport){
                    evaluar(_onSuccess, transport.responseText, _parametros);
                },
                onFailure: function() {
                    evaluar(_onError, null, null);
                },
                parameters: cadenaParametros
            }
            encolarPeticionAjax(_url, datos);
        }

        this.sendUrl = function(url, parametros, valores, metodo) {
            this.clearParams();

            this.setUrl(url);
            this.addParams(parametros, valores);
            this.setMetodo(metodo);

            this.send();
        }

        this.prepareForm = function() {
            this.clearParams();

            this.setMetodo(_form.method);
            this.setUrl(_form.action);

            $A(_form.elements).each(function(elemento) {
                if(elemento.name && !elemento.name.blank()) {
                    if( elemento.type != "checkbox" ||
                       (elemento.type == "checkbox" && elemento.checked)) {
                        _this.addParam(elemento.name, $(elemento).getValue());
                    }
                }
            });
        }

        this.sendForm = function(form) {
            this.setForm(form);
            this.send();
        }

        this.sendExt = function(url, parametros, valores, onSuccess, onError, asincrono, metodo) {
            this.setOnSuccess(onSuccess);
            this.setOnError(onError);
            this.setAsincrono(!!asincrono);

            this.sendUrl(url, parametros, valores, metodo);
        }

        this.sendFormExt = function(form, onSuccess, onError, asincrono, metodo) {
            this.setForm(form);
            this.setOnSuccess(onSuccess);
            this.setOnError(onError);
            if(typeof asincrono != 'undefined' && asincrono != null) {
                this.setAsincrono(!!asincrono);
            }
            if(typeof metodo != 'undefined' && metodo != null) {
                this.setMetodo(metodo);
            }
            this.send();
        }

        return this;
    }

    this.Sender = AjaxSender;
    this.getSender = function() {
        return new AjaxSender();
    }
    this.cancelAll = function() {
        try {
            if(_timerAjax) {
                window.clearTimeout(_timerAjax);
            }
        } catch(e) {}
        _objRequest = null;
        _timerAjax = null;
        _peticionesPendientes.clear();
    }

    return this;
}

function procesarPeticionAjaxForm(form, onSuccess, onError, asincrono, metodo) {
    new JMLib.Ajax.Sender().sendFormExt(form, onSuccess, onError, asincrono, metodo);
}

function procesarPeticionAjax(url, parametros, valores, onSuccess, onError, asincrono, metodo) {
    new JMLib.Ajax.Sender().sendExt(url, parametros, valores, onSuccess, onError, asincrono, metodo);
}

function getNavegador() {
    var navegador = {IE: false, OPERA: false, SAFARI: false, KONQUEROR: false, MOZILLA: false, FIREFOX: false, NETSCAPE: false, version : null};

    var browserType = navigator.userAgent.toLowerCase();

    if(browserType.indexOf("msie") != -1) {
        navegador.IE = true;

        var tempStr = browserType.substr(browserType.indexOf("msie"));
        navegador.version = tempStr.substring(4, tempStr.indexOf(";"));
    }
    if ((browserType.indexOf("mozilla") != -1) &&
        (browserType.indexOf("spoofer") == -1) &&
        (browserType.indexOf("compatible") == -1)) {

        if (browserType.indexOf("firefox") != -1) {
            navegador.FIREFOX = true;
        } else if (browserType.indexOf("netscape") != -1) {
            navegador.NETSCAPE = true;
        } else {
            navegador.MOZILLA = true;
        }

        var posicionVersion = browserType.indexOf("/");
        if(posicionVersion != -1) {
            navegador.version = browserType.substring(posicionVersion + 1, posicionVersion + 5);
        }
    }

    navegador.OPERA = browserType.indexOf("opera") != -1;
    navegador.SAFARI = browserType.indexOf("safari") != -1;
    navegador.KONQUEROR = browserType.indexOf("konqueror") != -1;

    if(navegador.version != null) {
        navegador.version = parseFloat(navegador.version);
    }

    return navegador;
}

/**
 * selecciona los combos de fechas del modo indicado
 * @param fechaDesde prefijo de los campos de fecha desde
 * @param fechaHasta prefijo de los campos de fecha hasta
 * @param modo indica el modo de selección de las fechas
 *		modos:
 *			0: día anterior
 *			1: semana anterior
 *			2: mes anterior
 * @param nombreSelectores prefijo de los campos para seleccionar el día anterior, el semana anterior o el mes anterior
 */
function seleccionarFecha(fechaDesde, fechaHasta, modo, nombreSelectores) {
    /* combos de fechas desde y hasta [combo día, combo mes, combo año] */
    var cDesde = [$(fechaDesde + 'Dia'), $(fechaDesde + 'Mes'), $(fechaDesde + 'Ano')];
    var cHasta = [$(fechaHasta + 'Dia'), $(fechaHasta + 'Mes'), $(fechaHasta + 'Ano')];
    /* lista de fechas desde y hasta [[diaDesde, mesDesde, añoDesde], [diaHasta, mesHasta, añoHasta]] */
    var fechas = [[cDesde[0].value, cDesde[1].value, cDesde[2].value], [cHasta[0].value, cHasta[1].value, cHasta[2].value]];
    var f = new Date();
    switch(modo) {
        case 0: /* día anterior */
            fechas = getRangoFechasDiaAnterior();
            break;
        case 1: /* semana anterior */
            fechas = getRangoFechasSemanaAnterior();
            break;
        case 2: /* mes anterior */
            fechas = getRangoFechasMesAnterior();
            break;
        default:
            break;
    }
    /* asignamos las fechas a los combos */
    for(var i = 0; i < 3; i++) {
        cDesde[i].value = fechas[0][i];
        cHasta[i].value = fechas[1][i];
    }

    if(nombreSelectores) {
        var selectores = [$(nombreSelectores + 'DiaAnt'),
        $(nombreSelectores + 'SemanaAnt'),
        $(nombreSelectores + 'MesAnt')];
        $A(selectores).each(function(selector, i) {
            if(selector != null) {
                selector.checked = modo == i;
                selector.disabled = modo == i;
            }
        });
    }
}

function comprobarFechaSelector(campoDia, campoMes, campoAno) {
    var dia = parseInt($(campoDia).value, 10);
    var mes = parseInt($(campoMes).value, 10) - 1;
    var ano = parseInt($(campoAno).value, 10);

    var fecha = new Date(ano, mes, dia);
    if(fecha.getMonth() != mes) {
        fecha = new Date(ano, mes + 1, 0);
        $(campoDia).value = fecha.getDate();
        $(campoMes).value = fecha.getMonth() + 1;
        $(campoAno).value = fecha.getFullYear();
    }
}
/**
 * obtiene el rango de fechas [fechaDesde, fechaHasta] representando el día anterior.
 * @return devuelve una lista de la siguente forma [[diaDesde, mesDesde, añoDesde], [diaHasta, mesHasta, añoHasta]]
 */
function getRangoFechasDiaAnterior() {
    var f = new Date();
    f.setDate(f.getDate() - 1);
    var fDesde = [f.getDate(), f.getMonth() + 1, f.getFullYear()];
    return [fDesde, fDesde];
}
/**
 * obtiene el rango de fechas [fechaDesde, fechaHasta] representando la semana anterior.
 * @return devuelve una lista de la siguente forma [[diaDesde, mesDesde, añoDesde], [diaHasta, mesHasta, añoHasta]]
 */
function getRangoFechasSemanaAnterior() {
    var f = new Date();
    var dSemana = f.getDay() == 0 ? 7 : f.getDay();
    f.setDate(f.getDate() - dSemana);
    var fHasta = [f.getDate(), f.getMonth() + 1, f.getFullYear()];
    f.setDate(f.getDate() - 6);
    var fDesde = [f.getDate(), f.getMonth() + 1, f.getFullYear()];
    return [fDesde, fHasta];
}
/**
 * obtiene el rango de fechas [fechaDesde, fechaHasta] representando el mes anterior.
 * @return devuelve una lista de la siguente forma [[diaDesde, mesDesde, añoDesde], [diaHasta, mesHasta, añoHasta]]
 */
function getRangoFechasMesAnterior() {
    var f = new Date();
    f.setDate(0);
    var fHasta = [f.getDate(), f.getMonth() + 1, f.getFullYear()];
    f.setDate(1);
    fDesde = [f.getDate(), f.getMonth() + 1, f.getFullYear()];
    return [fDesde, fHasta];
}
/**
 * comprueba si los campos representando la fecha desde y la fecha hasta tienen seleccionado
 * el día anterior, la semana anterior o el mes anterior
 * @param fechaDesde prefijo de los campos de fecha desde
 * @param fechaHasta prefijo de los campos de fecha hasta
 * @param nombreSelectores prefijo de los campos para seleccionar el día anterior, el semana anterior o el mes anterior
 */
function comprobarFecha(fechaDesde, fechaHasta, nombreSelectores) {
    /* combos de fechas desde y hasta [combo día, combo mes, combo año] */
    var fDesde = [$(fechaDesde + 'Dia').value, $(fechaDesde + 'Mes').value, $(fechaDesde + 'Ano').value];
    var fHasta = [$(fechaHasta + 'Dia').value, $(fechaHasta + 'Mes').value, $(fechaHasta + 'Ano').value];
    /* lista de fechas desde y hasta [[diaDesde, mesDesde, añoDesde], [diaHasta, mesHasta, añoHasta]] */
    var fechas = [fDesde, fHasta];

    var iguales = function(fechas1, fechas2) {
        for(var i = 0, len1 = fechas1.length; i < len1; i++) {
            for(var j = 0, len2 = fechas2.length; j < len2; j++) {
                if(parseInt(fechas1[i][j], 10) != parseInt(fechas2[i][j], 10)) {
                    return false;
                }
            }
        }
        return true;
    }
    var modo = -1;
    if(iguales(fechas, getRangoFechasDiaAnterior())) {
        modo = 0;
    }
    if(iguales(fechas, getRangoFechasSemanaAnterior())) {
        modo = 1;
    }
    if(iguales(fechas, getRangoFechasMesAnterior())) {
        modo = 2;
    }
    if(nombreSelectores) {
        var selectores = [$(nombreSelectores + 'DiaAnt'),
        $(nombreSelectores + 'SemanaAnt'),
        $(nombreSelectores + 'MesAnt')];
        var selector = null;
        for(var i = 0, len = selectores.length; i < len; i++) {
            selector = selectores[i];
            if(selector != null) {
                selector.checked = modo == i;
                selector.disabled = modo == i;
            }
        }
    }
}
/* muestra y oculta una capa según esté la capa. Si está visible la oculta, si está visible la muestra */
function toggleBlind(e) {
    e = $(e);
    if(e.visible()) {
        Effect.BlindUp(e);
    } else {
        Effect.BlindDown(e);
    }
}

function isContenido(x1, y1, ancho, alto, x, y) {
    var x2 = x1 + ancho;
    var y2 = y1 + alto;

    return x1 <= x && x2 >= x && y1 <= y && y2 >= y;
}
function isDentro(capa, x, y) {
    var p = Element.cumulativeOffset(capa);
    return isContenido(p.left, p.top, capa.offsetWidth - 1, capa.offsetHeight - 1, x, y);
}

/* mueve los camos del comboOrigen al comboDestino ordenando los campos según el combo */
function moverEntreCombos(comboOrigen, comboDestino) {
    var seleccionados = recuperarYBorrar(comboOrigen, false);
    seleccionados = seleccionados.concat(recuperarYBorrar(comboDestino, true));
    seleccionados.sort(function(a, b) {
        if(a.value == '' || a.value == '0') {
            return -1;
        }
        if(b.value == '' || b.value == '0') {
            return 1;
        }
        return a.text.toLowerCase() <= b.text.toLowerCase() ? -1 : 1;
    });
    var posicion = 0;
    for(var i = 0, len = seleccionados.length; i < len; i++) {
        comboDestino.options[i] = seleccionados[i];
    }
    if(comboDestino.funcionOnChange) {
        comboDestino.funcionOnChange();
    }
    if(comboOrigen.funcionOnChange) {
        comboOrigen.funcionOnChange();
    }
}

/* obtiene una lista con los valores seleccionados de un combo y los borra del mismo */
function recuperarYBorrar(campo, todos) {
    var valores = new Array();
    var o = campo.options;
    for (var i = o.length - 1; i >= 0 ; i--) {
        if ((o[i].selected || todos) && o[i].value != '') {
            valores[valores.length] = o[i];
            o[i] = null;
        }
    }
    return valores.reverse();
}

function seleccionarComboMultiple(combo, seleccionar) {
    combo = $(combo);
    for(var i = 0, o = combo.options, len = o.length; i < len; i++) {
        o[i].selected = o[i].value != '' && seleccionar;
    }
}

function setValorComboMultiple(combo, valor, seleccionar) {
    for(var i = 0, o = combo.options, len = combo.length; i < len; i++) {
        if(o[i].value == valor) {
            o[i].selected = seleccionar;
        }
    }
}

function getDescValorCombo(combo, valor) {
    combo = $(combo);
    for(var i = 0, o = combo.options, len = o.length; i < len; i++) {
        if(o[i].value == valor) {
            return o[i].text;
        }
    }
    return null;
}

function setComboCargando(combo, cargando) {
    combo.options.length = 0;
    if(cargando) {
        combo.options[0] = new Option('Cargando...', '');
        combo.classNameOld = combo.className;
        combo.className = 'cargando';
        combo.options[0].className = 'cargando';
    } else {
        combo.options.length = 0;
        combo.className = combo.classNameOld;
    }
    combo.disabled = cargando;
}

function setVisibleCombos(visible, forzar, capa) {
    var navegador = getNavegador();
    if(forzar || (Prototype.Browser.IE && navegador.version < 7.0)) {
        var selects = $$("select");
        selects.each(function(select) {
            if(!capa || !select.descendantOf(capa)) {
                if(visible && (typeof select.visibleAnt == 'undefined' || select.visibleAnt)) {
                    select.show();
                } else {
                    select.visibleAnt = $(select).visible();
                    select.hide();
                }
            }
        });
    }
    ocultarFlashs(visible, capa);
}

function ocultarFlashs(visible, capa) {
//    $$('embed, object').invoke(visible ? 'show' : 'hide');
    var flashs = $$('embed, object');
    flashs.each(function(flash) {
        if(!capa || !flash.descendantOf(capa)) {
            if(visible && (typeof flash.visibleAnt == 'undefined' || flash.visibleAnt)) {
                flash.show();
            } else {
                flash.visibleAnt = $(flash).visible();
                flash.hide();
            }
        }
    });
}

/**
 * rellena un string con relleno hasta alcanzar la longitud dada
 * tipo indica el tipo de relleno 0: izda, 1: dcha
 */
function padString(cadena, longitud, relleno, tipo) {
	while(cadena.length < longitud) {
		if(!tipo) {
			cadena = relleno + cadena;
		} else {
			cadena += relleno;
		}
	}
	var inicio = tipo ? 0 : cadena.length - longitud;
	return cadena.substr(inicio, longitud);
}

function formatearNumero(numero, decimales) {
    if(isNaN(numero)) {
        return numero;
    }
    var numeroAux = new String(numero);
    numeroAux = numeroAux.split('.');
    var parteEntera = numeroAux[0];
    var parteDecimal = numeroAux.length > 1 ? numeroAux[1] : '';

    var parteEnteraAux = parteEntera.toArray().reverse();
    parteEntera = '';
    parteEnteraAux.each(function(e, i) {
        if(i % 3 == 0 && i != 0) {
            parteEntera = '.' + parteEntera;
        }
        parteEntera = e + parteEntera;
    });

    parteDecimal = padString(parteDecimal, decimales, '0', 1).substr(0, decimales);

    return parteEntera + (decimales ? (',' + parteDecimal) : '');
}

function centrarCapaPantalla(capa) {
    capa = $(capa);
/*
    var d = null;
    if(window.innerWidth && window.innerHeight) {
        d = {left: 0, top: 0, width: window.innerWidth, height: window.innerHeight}
    } else {
        d = document.viewport.getDimensions();
    }
*/
    var d = document.viewport.getDimensions();
    var d2 = Element.getDimensions(capa);
	var o = document.viewport.getScrollOffsets();
    capa.absolutize();

    capa.style.left = (d.width / 2 - (d2.width / 2)) + o.left + "px";
    capa.style.top = Math.max(0, (d.height / 2 - (d2.height / 2)) + o.top) + "px";
}

function ponerControlChecksListado(checkCabecera, checksLista) {
    checkCabecera = $(checkCabecera);

    if(!Object.isArray(checksLista)) {
        checksLista = $A([checksLista]);
    } else {
        checksLista = $A(checksLista);
    }

    var comprobarCheckCabecera = function() {
        var seleccionar = true;
        $A(checksLista).each(function(check){
            if(!check.checked) {
                seleccionar = false;
                throw $break;
            }
        });
        checkCabecera.checked = seleccionar;
    }

    $A(checksLista).each(function(check) {
        Event.observe(check, 'click', comprobarCheckCabecera);
    });
    Event.observe(checkCabecera, 'click', function() {
        var seleccionar = checkCabecera.checked;
        $A(checksLista).each(function(check){
            if((seleccionar && !check.checked) ||
               (!seleccionar && check.checked)) {
                check.click();
            }
        });
        checkCabecera.checked = seleccionar;
    });
}

function getCapaFundido() {
	var cF = $('_capaFundido');
    if(!cF) {
        cF = new Element('div', {
            'id': '_capaFundido',
            'style': 'display: none; z-index: 1000; position: absolute; top: 0; left: 0; background-color: black;'
        });
        document.body.appendChild(cF);
    }
    return cF;
}

var _efectoFundido = null;
function mostrarFundido(visible, capaDatos) {
	var cF = getCapaFundido();

    if(_efectoFundido) {
        _efectoFundido.cancel();
    }
    if(!visible) {
        if(cF.visible()) {
            //_efectoFundido = new Effect.Fade(cF);
            cF.hide();
        }
		//cF.fade();
		if(capaDatos) {
			setVisibleCombos(true, false, capaDatos);
		}
	} else if(!cF.visible() && visible) {
		if(capaDatos) {
			setVisibleCombos(false, false, capaDatos);
		}
		//_efectoFundido = new Effect.Appear(cF, {from: 0.0, to: 0.25});
        cF.setOpacity(0.25);
        cF.show();
		var alto = Math.max(document.body.offsetHeight, document.body.scrollHeight);
		if(window.scrollMaxY) {
			alto = Math.max(alto, window.scrollMaxY);
		}
		cF.setStyle({
			height: alto + 'px',
			width: $(document.body).getWidth() + 'px'
		});
	}
}

function getCapaMensaje() {
	var cD = $('_capaMsj');
    if(!cD) {
        if(document.all) {
            cD = new Element('div', {
                'id': '_capaMsj',
                'style': 'position: absolute; top: ' + (document.viewport.getScrollOffsets().top + 8) + 'px; right: 8px; text-align: left; z-index: 1001; padding: 8px;',
                'class': 'ayuda'
            });
            Event.observe(window, 'scroll', function() { cD.setStyle({top: document.viewport.getScrollOffsets().top + 8 + 'px'});});
        } else {
            cD = new Element('div', {
                'id': '_capaMsj',
                'style': 'position: fixed; top: 8px; right: 8px; text-align: left; z-index: 1001; padding: 8px;',
                'class': 'ayuda'
            });
        }
        document.body.appendChild(cD);
    }
    return cD;
}

var _mesajeTimeout = null;
function setMensajeVisible(visible) {
    var cD = getCapaMensaje();
	if(visible) {
        if(_mesajeTimeout) {
            window.clearTimeout(_mesajeTimeout);
        }
        if(cD.visible()) {
            cD.highlight();
        } else {
            cD.show();
        }
        _mesajeTimeout = window.setTimeout(setMensajeVisible, 5000, false);
	} else {
		cD.hide();
	}
}

function mostrarMensaje(msj) {
    setMensajeVisible(true);
    getCapaMensaje().update(msj);
}

function ocultarFormulario() {
    setMensajeVisible(false);
}

function setMensajeCapa(msj) {
    getCapaMensaje().update(msj);
}

function getCapaCargando() {
	var cC = $('_capaCargando');
    if(!cC) {
        cC = new Element('div', {
            'id': '_capaCargando',
            'style': 'display: none; background-image: url(../images/back/cargando_peq.gif); background-repeat: no-repeat; background-color: white; z-index: 1002; position: absolute; left: 0; top: 0; border: 2px solid #7AAB00; padding: 8px 8px 8px 28px; text-align: center; background-position: 4px center;'
        });
        document.body.appendChild(cC);
    }
    return cC;
}

function setCargando(visible, msj) {
    var cC = getCapaCargando();
    if(msj) {
        cC.update(msj);
    }
	if(visible) {
		mostrarFundido(true, cC);
		cC.show();
		centrarCapaPantalla(cC);
	} else {
		mostrarFundido(false, cC);
		cC.hide();
	}
}

var _efectoCampoObligatorio1 = null;
var _efectoCampoObligatorio2 = null;
function avisarCampoObligatorio(campo, msj) {
    var padre = $(campo.parentNode);
    campo = $(campo);
    if(msj) {
        alert(msj);
    }
    if(_efectoCampoObligatorio1) {
        _efectoCampoObligatorio1.cancel();
    }
    if(_efectoCampoObligatorio2) {
        _efectoCampoObligatorio2.cancel();
    }
    _efectoCampoObligatorio1 = new Effect.Highlight(padre, {
        afterFinish: function() {
            try {
                padre.setStyle({backgroundColor: ''});
                padre.style.backgroundColor = '';
            } catch(e) {}
        }
    });
    _efectoCampoObligatorio2 = new Effect.Pulsate(campo, {
        afterFinish: function() {
            campo.setOpacity(1);
        }
    });
    try {
        campo.focus();
        campo.scrollTo();
    } catch(e) {}
}

function comprobarCampos(form, campos, msjsError) {
    var resultado = true;
    $A(campos).each(function(campo, i) {
        var campoAux = form[campo];
        if(!!campoAux && typeof(campoAux.value) != "undefined" && campoAux.value.blank()) {
           resultado = false;
           avisarCampoObligatorio(campoAux, msjsError[i]);
           throw $break;
        }
    });
    return resultado;
}

function comprobarCamposAux(campos, msjsError) {
    var resultado = true;
    $A(campos).each(function(campo, i) {
       if(campo && campo.value.blank()) {
           resultado = false;
           avisarCampoObligatorio(campo, msjsError[i]);
           throw $break;
       }
    });
    return resultado;
}

function getCapaDatos() {
	var cC = $('_capaDatos');
    if(!cC) {
        cC = new Element('div', {
            'id': '_capaDatos',
            'style': 'display: none; width: 600px; height: 400px; border: 1px solid #7D7D7D; padding: 6px; position: absolute; top: 0; left: 0; background-color: white; z-index: 2000;'
        });
        document.body.appendChild(cC);
    }
    return cC;
}

_eventoCapaDatos = null;
function setCapaDatos(visible, contenido) {
    if(_eventoCapaDatos) {
        _eventoCapaDatos.cancel();
    }
    var cD = getCapaDatos();
    if(contenido) {
        cD.update(contenido);
    }
	if(visible) {
		mostrarFundido(true, cD);
		_eventoCapaDatos = new Effect.Appear(cD);
		centrarCapaPantalla(cD);
	} else {
		mostrarFundido(false, cD);
        _eventoCapaDatos = new Effect.Fade(cD);
	}
}

function getDescCombo(combo, valor) {
    if(combo.selectedIndex >= 0 && !valor) {
        return combo.options[combo.selectedIndex].text;
    } else {
        var resultado = '';
        $A(combo.options).each(function(o) {
            if(o.value == valor) {
                resultado = o.text;
                throw $break;
            }
        });
        return resultado;
    }
    return '';
}

