function numero_valido(cadena){
	if (isNaN(cadena) || trim(cadena) == ""){
		return false;
	}else{
		return true;
	}//end if
}//end function

function ltrim(s) {
   return s.replace(/^\s+/, "");
}

function rtrim(s) {
   return s.replace(/\s+$/, "");
}

function trim(s) {
   return rtrim(ltrim(s));

}

function left(str, lng){
var resul = String(str);

	if (lng <= resul.length){
		resul = resul.substr(0, lng);
	}
	return resul;
}

function right(str, lng){
var resul = String(str);
    
	var fin = resul.length
	if (lng <= fin){
		resul =  resul.substring(fin, fin - lng);
    }
	return resul;
}

function etiquetaTieneClase(etiqueta, clase){
	return etiqueta.className.indexOf(clase) >= 0;
}

function aniadirClaseAEtiqueta(etiqueta, clase){
	if (!etiquetaTieneClase(etiqueta, clase)){
		etiqueta.className += ' ' + clase;
	}
}

function quitarClaseDeEtiqueta(etiqueta, clase){
	if (etiquetaTieneClase(etiqueta, clase)){
		var remp = etiqueta.className.match(' '+clase)?' '+clase:clase;
		etiqueta.className = etiqueta.className.replace(remp,'');
	}
}

function addLoadEventFirst(func){
	var oldonload = window.onload;
	if (typeof window.onload != 'function'){
		window.onload = func;
	}else{
		window.onload = function(){
			func();
			if (oldonload){
				oldonload();
			}
		}
	}
}

function addLoadEventLast(func){
	var oldonload = window.onload;
	if (typeof window.onload != 'function'){
		window.onload = func;
	}else{
		window.onload = function(){
			if (oldonload){
				oldonload();
			}
			func();
		}
	}
}

/*
 * EventManager.js
 * by Keith Gaughan
 *
 * This allows event handlers to be registered unobtrusively, and cleans
 * them up on unload to prevent memory leaks.
 *
 * Copyright (c) Keith Gaughan, 2005.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Common Public License v1.0
 * (CPL) which accompanies this distribution, and is available at
 * http://www.opensource.org/licenses/cpl.php
 *
 * This software is covered by a modified version of the Common Public License
 * (CPL), where Keith Gaughan is the Agreement Steward, and the licensing
 * agreement is covered by the laws of the Republic of Ireland.
 */

// For implementations that don't include the push() methods for arrays.
if (!Array.prototype.push) {
    Array.prototype.push = function(elem) {
        this[this.length] = elem;
    }
}

var EventManager = {
    _registry: null,

    Initialise: function() {
        if (this._registry == null) {
            this._registry = [];

            // Register the cleanup handler on page unload.
            EventManager.Add(window, "unload", this.CleanUp);
        }
    },

    /**
     * Registers an event and handler with the manager.
     *
     * @param  obj         Object handler will be attached to.
     * @param  type        Name of event handler responds to.
     * @param  fn          Handler function.
     * @param  useCapture  Use event capture. False by default.
     *                     If you don't understand this, ignore it.
     *
     * @return True if handler registered, else false.
     */
    Add: function(obj, type, fn, useCapture) {
        this.Initialise();

        // If a string was passed in, it's an id.
        if (typeof obj == "string") {
            obj = document.getElementById(obj);
        }
        if (obj == null || fn == null) {
            return false;
        }

        // Mozilla/W3C listeners?
        if (obj.addEventListener) {
            obj.addEventListener(type, fn, useCapture);
            this._registry.push({obj: obj, type: type, fn: fn, useCapture: useCapture});
            return true;
        }

        // IE-style listeners?
        if (obj.attachEvent && obj.attachEvent("on" + type, fn)) {
            this._registry.push({obj: obj, type: type, fn: fn, useCapture: false});
            return true;
        }

        return false;
    },

    /**
     * Cleans up all the registered event handlers.
     */
    CleanUp: function() {
        for (var i = 0; i < EventManager._registry.length; i++) {
            with (EventManager._registry[i]) {
                // Mozilla/W3C listeners?
                if (obj.removeEventListener) {
                    obj.removeEventListener(type, fn, useCapture);
                }
                // IE-style listeners?
                else if (obj.detachEvent) {
                    obj.detachEvent("on" + type, fn);
                }
            }
        }

        // Kill off the registry itself to get rid of the last remaining
        // references.
        EventManager._registry = null;
    }

	//Ejemplo uso: EventManager.Add(obj, click, fn);
}

function aniadirFuncionAOnload(funcion, posicion){
/*
posicion --> 1: Se añade la funcion en PRIMERA POSICION; antes de las que ya existan
		 --> <>1: Se añade la funcion en ULTIMA POSICION; despues de las que ya existan
*/
	if (posicion == 1){
		addLoadEventFirst(function(){
			eval(funcion + ";");
		});
	}else{
		addLoadEventLast(function(){
			eval(funcion + ";");
		});
	}
}

function deshabilitaFormulario(aplicar, frm){
	if (aplicar){
		for(var i = 0; i < frm.elements.length; i++){
			var node = frm.elements[i]
			if(node.tagName.toLowerCase() == "select" || node.tagName.toLowerCase() == "textarea" || node.tagName.toLowerCase() == "input"){
				node.setAttribute('readOnly','readonly');	
				if (node.type.toLowerCase() == "file") {
					node.setAttribute('disabled','disabled');
				}//end if
			}//end if
		}//end for
	}//end if
}//end function

function comprueba_extension(frm,iFile,hdImagen,bObl){ 
	var extensiones_permitidas = new Array(".gif", ".jpg", ".png"); 
	var err_o = "", err_f = "", err = "";
	var extension,permitida
	
	permitida = false; 
	if ((iFile.value == "")&& (hdImagen.value == "")){ 
		if (bObl == true){
			err_o += "\n\t" + "No has seleccionado ningún archivo ";
			if (err_o != "")
				err = "" + err_o;
			if (err_f != "")
				err += ((err != "")? "\n\n": "") + "" + err_f;
			if (err != ""){
				return err;
			}
		}
   }else{ 
   		var archivo = iFile.value;
		var archivoBd  = hdImagen.value;
		if (archivo!= ""){
			extension = (archivo.substring(archivo.lastIndexOf("."))).toLowerCase(); 
			for (var i = 0; i < extensiones_permitidas.length; i++) { 
				 if (extensiones_permitidas[i] == extension) { 
					permitida = true; 
					break; 
				 } 
			}
			if (!permitida) { 
				err_o = "Comprueba la extensión de los archivos a subir. \nSólo se pueden subir archivos con extensiones: " + extensiones_permitidas.join() +"\n";
				if (err_o != "")
					err = "" + err_o;
				if (err_f != "")
					err += ((err != "")? "\n\n": "") + "" + err_f;
				if (err != ""){
					iFile.value = "";
					return err;
				}
		   }else{ 
				err=""
				return err; 
		   } 
	   }else{
	   		if (archivoBd != ""){
				err=""
				return err;
			}
	   }
	}
}

function sustituriTextoMensaje(texto, sustitucion){
	return texto.replace('$1', sustitucion);
}


function quitarComas(v){
	var UltimoCaracter= v.charAt(v.length-1)
	if(UltimoCaracter == ","){
		//Quitamos la última como si la hay
		v = v.substr(0,v.length-1);
	}
	
	var PrimerCaracter = v.charAt(0)
	if(PrimerCaracter == ","){
		//Quitamos la priemra como si la hay
		v = v.substr(1,v.length);
	}
	v = v.replace(",,", ",");
	return v
}

function esCampoNulo(name){
	valor = document.getElementById(name).value;
	if( valor == null || valor.length == 0 || /^\s+$/.test(valor) ) {
		return true;
	}	
}


function serializarArrays(arr,brr){
	var t="";
	if (arr.length > 0){
		for(i=0; i<arr.length; i++){ 
			t=t+ arr[i] + "|" + brr[i] + ":";
		}
	}
	//quitamos los ultimos dos puntos
	
	t =t.substr(0,t.length-1);
	return t;
}

function include(file,opt){
       
        if(file=="") return;
 
        //Genera una id para el archivo con el fin de evitar que se cargue 2 veces.
        idfile = file.replace(location.hostname,"");
        idfile = idfile.replace(location.protocol,"");
        idfile = idfile.replace("//","");
 
        if(document.getElementById(idfile)){ return };
               
        if(typeof opt=="undefined") opt = {};
        if(typeof opt.cache=="undefined") opt.cache = true;
        if(typeof opt.dom=="undefined")  opt.dom = false;
        if(typeof opt.type=="undefined")  opt.type = "";
       
       
        ext = (opt.type!="") ? opt.type : file.substring(file.lastIndexOf('.')+1);
 
        if(!opt.cache){
            var random = new Date().getTime().toString();        
                if(file.indexOf("?")!=-1) file = file+"&"+random;
                else file = file+"?"+random;
        }
       
        if(opt.dom){
                var head = document.getElementsByTagName('head').item(0)       
        }
       
       
        switch(ext){
                case "css":
                  if(!opt.dom) 
                        document.write('<link rel="stylesheet" href="'+file+'" id="'+idfile+'" type="text/css"><\/link>');
                  else{
                    css = document.createElement('link');
                    css.rel  = 'stylesheet';
                    css.href = file;
                        css.type = 'text/css';
                        css.id = idfile;
                        head.appendChild(css);                 
                  }                    
                break;
               
                case "js":
                 if(!opt.dom){
                        document.write('<script type="text/javascript" id="'+idfile+'" src="'+file+'"><\/script>');
                 }
                 else{
                    script = document.createElement('script');
                    script.src = file;
                        script.type = 'text/javascript';
                        script.id = idfile;
                        head.appendChild(script);
                       
                        if(typeof opt.oncomplete!="undefined"){
                                //Para IE
                            script.onreadystatechange = function () {if (script.readyState == 'complete') {if(typeof opt.oncomplete == "function") {eval(opt.oncomplete());}}}
                                //Para Firefox
                            script.onload = function () {if(typeof opt.oncomplete == "function") {opt.oncomplete();}}
                        }              
                 }
 
                break;
        }
}

function crearNodo(tipo, idNodo){
	var nodo = document.createElement(tipo);
	if (idNodo+'' != ''){
		nodo.setAttribute("id", idNodo);
	}
	return nodo;
}

function crearNodoTexto(texto){
	var nodo = document.createTextNode(texto);
	return nodo;
}

function informacion_navegador(){
	this.nombre = navigator.appName;
	this.codigo_nobre = navigator.appCodeName;
	this.version = navigator.appVersion.substring(0,4);
	this.plataforma = navigator.platform;
	this.javaEnabled = navigator.javaEnabled();
	this.pantalla_ancho = screen.width;
	this.pantalla_alto = screen.height;
	this.isIE = (navigator.appVersion.indexOf('MSIE') >= 0);
	this.isIE6 = (navigator.appVersion.indexOf('MSIE 6') >= 0);
	this.isIE7 = (navigator.appVersion.indexOf('MSIE 7') >= 0);
	this.isIE8 = (navigator.appVersion.indexOf('MSIE 8') >= 0);
	this.isChrome = (navigator.appVersion.indexOf('Chrome') >= 0);
	this.isFireFox = (this.codigo_nobre == 'Mozilla' && !this.isIE);
}

function rellenarCampo(deEtiqueta, aNombreEtiqueta, siempre){
var valor

	valor = deEtiqueta.value;
	if (siempre || trim(valor) != ''){
		var etiquetaReceptora = document.getElementById(aNombreEtiqueta);
		etiquetaReceptora.value = valor;
	}
	return;
}

function generarNombre(){
	var resul

	var fecha = new Date();

	resul = '';
	resul += fecha.getFullYear();// - Devuelve el año en formato YYYY
	
	var mes = fecha.getMonth() + 1 + '';// - Devuelve el mes actual de 0 a 11
	if (mes.length < 2) mes = '0' + mes;
	resul += mes;
	
	var dia = fecha.getDate() + '';// - Devuelve el día del mes de 1 a 31
	if (dia.length < 2) dia = '0' + dia;
	resul += dia;
	
	var hora = fecha.getHours() + '';// - Devuelve la hora de 0 a 23
	if (hora.length < 2) hora = '0' + hora;
	resul += hora;
	
	var minuto = fecha.getMinutes() + '';// - Devuelve los minutos de 0 a 59
	if (minuto.length < 2) minuto = '0' + minuto;
	resul += minuto;
	
	var segundo = fecha.getSeconds() + '';// - Devuelve los segundos de 0 a 59
	if (segundo.length < 2) segundo = '0' + segundo;
	resul += segundo;
	
	var msegundo = fecha.getMilliseconds() + '';// - Devuelve los milisegundos (0-999)
	while(msegundo.length < 3){
		msegundo = '0' + msegundo;
	}
	resul += msegundo;
//	return anio + mes + dia + hora + minuto + segundo + msegundo;
	return resul;
}


function procesarFichero(origen){
var nombreF, nombreI, sNombreI
	
	if (origen.indexOf("_") == -1){
		destino = "nomfichero"
	}else{
		destino = "nomfichero_" + origen.split("_")[origen.split("_").length - 1]
	}
	nombreI = document.getElementById(origen).value;
	if (nombreI != ""){
		nombreF = generarNombre();
		if(nombreI.indexOf("\\")>-1){
			nombreI = nombreI.substr(nombreI.lastIndexOf("\\")+1,nombreI.length);
		}else if(nombreI.indexOf("/")>-1){
			nombreI = nombreI.substr(nombreI.lastIndexOf("/")+1,nombreI.length);	
		}
		nombreF = nombreF + "_" + nombreI
		if (document.getElementById(destino)){
			document.getElementById(destino).value = nombreF;
		}//end if
	}else{
		if (document.getElementById(destino)){
			document.getElementById(destino).value = "";
		}//end if
	}
	return;
}

function cogerCampoQ(nombre){

	var miHref = location.href;
	miHref = miHref.substring(0, (miHref.indexOf('#') > -1 ? miHref.indexOf('#') : miHref.length));
	miHref = miHref.split('?');
	if (miHref.length == 2){
		var parms = miHref[1].split('&');
		for (var i=0; i<parms.length; i++) {
			var pos = parms[i].indexOf('=');
			if (pos > 0) {
				if (parms[i].substring(0,pos).toLowerCase() == nombre.toLowerCase()){
					return parms[i].substring(pos+1);
				}
			}
		}
	}
	return "";
}

function mostrarCambioImg(alt,msj){
	var span
	if (document.getElementById('reloadCaptcha')){
		span = document.getElementById('reloadCaptcha');
		span.innerHTML = '<\a href="#" onclick="LBD_ReloadImage(\'SampleForm_CaptchaImage\',\''+msj+'\'); return false;"><\img src="../lib/captcha/reload.gif" alt="'+alt+'" /></\a>';
	}
	
	if (document.getElementById('CaptchaImage')){
		document.getElementById('CaptchaImage').style.height = '3em';
		document.getElementById('CaptchaImage').style.paddingBottom = '0.2em';
	}
	return;
}

function getScrollElementX(idElemento) {
	var scrOfX = 0, scrOfY = 0;
	if(typeof(document.getElementById(idElemento).pageYOffset) == 'number'){
		scrOfX = document.getElementById(idElemento).pageXOffset;
	}else if(document.getElementById(idElemento) && (document.getElementById(idElemento).scrollLeft)) {
		scrOfX = document.getElementById(idElemento).scrollLeft;
	}
	return scrOfX;
}

function getScrollElementY(idElemento) {
	var scrOfY = 0;
	
	if (typeof(document.getElementById(idElemento).pageYOffset) == 'number'){
		scrOfY = window.pageYOffset;
	}else if (document.getElementById(idElemento) && (document.getElementById(idElemento).scrollTop)) {
		scrOfY = document.getElementById(idElemento).scrollTop;
	}
	return scrOfY;
}

function setScrollElementY(idElemento, pos) {

	if (typeof(document.getElementById(idElemento).pageYOffset) == 'number'){
		document.getElementById(idElemento).pageYOffset = pos;
	}else if (document.getElementById(idElemento) && (typeof(document.getElementById(idElemento).scrollTop)) == 'number') {
		document.getElementById(idElemento).scrollTop = pos;
	}
}

function cerrarVentana(){
	window.close();
}

function abrirVentana(url, parametros, nombre){
	parametros = parametros || 'toolbar=0,location=0,scrollbars=1,directories=0,status=0,menubar=0,resizable=1,width=800,height=600';
	nombre = nombre || 'vent';

	var vent = window.open(url, nombre, parametros);
	return vent;
}

function activarDesactivarCampoTipoInput(frm, campoSelecc, operacion, idioma, requerido, combo){
//debugger;
var campo, elem, span, rq, cb
	requerido = requerido || '1'
	if (requerido == '0'){
		rq = false;
	}else{
		rq = true;
	}
	combo = combo || '0'
	if (combo == '0'){
		cb = false;
	}else{
		cb = true;
	}
	

	if (operacion == 'D'){
		for (i=0;i < frm.elements.length ; i++){
			campo = frm.elements[i];
			if (campo.name){
				if (campo.name.toLowerCase().indexOf(campoSelecc.toLowerCase()) == 0){
					if(campo.type=="checkbox" || campo.type=="file" || cb || campo.type=="radio"){
						campo.disabled = true;
					}
					campo.setAttribute('readOnly', 'readOnly');
					
					if (document.getElementById('spn_' + campo.name)){
						span = document.getElementById('spn_' + campo.name);
						if (rq){
							if (idioma=='S'){
								span.innerHTML = span.innerHTML.replace('** ', '');
							}else{
								span.innerHTML = span.innerHTML.replace('* ', '');
							}
						}
						aniadirClaseAEtiqueta(span, 'txtDesactivado');
						aniadirClaseAEtiqueta(campo, 'desactivado');
					}
				}//end if
			}//end if
		}//end for
	}else{
		for (i=0;i < frm.elements.length ; i++){
			campo = frm.elements[i];
			if (campo.name){
				if (campo.name.toLowerCase().indexOf(campoSelecc.toLowerCase()) == 0){
					if(campo.type=="checkbox" || campo.type=="file" || cb || campo.type=="radio"){
						campo.disabled = false;
					}
					campo.removeAttribute('readOnly');
					campo.removeAttribute('disabled');
					
					if (document.getElementById('spn_' + campo.name)){
						span = document.getElementById('spn_' + campo.name);
						if (rq){
							if (idioma=='S'){
								span.innerHTML = span.innerHTML.replace('** ', '');
								span.innerHTML = '** ' + span.innerHTML;
							}else{
								span.innerHTML = span.innerHTML.replace('* ', '');
								span.innerHTML = '* ' + span.innerHTML;
							}
						}
						if (etiquetaTieneClase(span, 'txtDesactivado')){
							quitarClaseDeEtiqueta(span, 'txtDesactivado');
						}
						if (etiquetaTieneClase(campo, 'desactivado')){
							quitarClaseDeEtiqueta(campo, 'desactivado');
						}
					}
				}//end if
			}//end if
		}//end for
	}

	externalLinks();
	return;
}
function activarDesactivarCampoTipoBoton(frm, campoSelecc, operacion){
//debugger;
var campo, elem, span

	if (operacion == 'D'){
		document.getElementById(campoSelecc).style.display = "none";
					 
	}else if(operacion == 'A2'){
		document.getElementById(campoSelecc).style.display = "";
	}else{
		document.getElementById(campoSelecc).style.display = "block";
	}

	externalLinks();
	return;
}
function seleccionarCategoria(ruta, hiddenCategorias, CategoriasTexto, tipoCategoria){
var frmI

	frmI = document.frmIntermedio;
	frmI.d.value = document.getElementById(hiddenCategorias).value;
	frmI.h.value = hiddenCategorias;
	frmI.ht.value = CategoriasTexto;
	
	var vent = abrirVentana('void.asp', 'toolbar=0,location=0,scrollbars=1,directories=0,status=0,menubar=0,resizable=1,width=800,height=700', 'miventana');
	frmI.target = 'miventana';
	frmI.action = ruta + 'Categorias/categoriasVent.asp?T=' + tipoCategoria;
	frmI.submit();

	vent.focus();
}

function eliminarDuplicados(arr){
	var i, len = arr.length, out = [], obj = {}; 
	
	for (i = 0; i < len; i++){
		obj[arr[i]]=0;
	}
	
	for (i in obj){
		out.push(i);
	}
	
	return out;
}


function getElementsByClassName(classname, node) {
	if (!node){
		node = document.getElementsByTagName("body")[0];
	}
	
	var a = [];
	var re = new RegExp('\\b' + classname + '\\b');
	var els = node.getElementsByTagName("*");

	for (var i=0,j=els.length; i<j; i++){
		if (re.test(els[i].className)){
			a.push(els[i]);
		}
	}
	return a;
}

