// ********************* Funciones Para los menus que siempre te salgan en pantalla con el nombre tabla_desplazar
function findScrollTop() {
	if (window.pageYOffset != null)
		return window.pageYOffset;
	if (document.body.scrollWidth != null)
		return document.body.scrollTop;
	return null;
}
var offsetTablaInicial = null;

function miOnScroll() {
	var top;
	//alert("scroll");
	if ( offsetTablaInicial==null) {
		offsetTablaInicial = document.all["tabla_desplazar"].offsetTop;
	} else {
		top = findScrollTop();
		if (top!=null) {
			if (top>offsetTablaInicial) {
				document.all["tabla_desplazar"].style.top = top;				
			} else {
				document.all["tabla_desplazar"].style.top = offsetTablaInicial;
			}
		}				
	}
}


function getValor(item) {
		var res;
		res="";
		if (item!=null) {
			if (item.value==null) {
				for (i=0;i<item.length;i++) {
						if (item[i].checked==true) {
								res=item[i].value;
						}
				}
			} else {
					res = item.value;
			}
		}
		return res;
}



function eliminarEntradaAsiento(numero) {
	if (confirm("¿Seguro que desea eliminar esta linea?")) {
		eval("document.formulario.importe_"+numero+".value='';");
		eval("document.formulario.cuenta_"+numero+".value='';");
	}
	return;
}

function changeDisplay(id) {
	//Permite ocultar o ver un elemento:
	var nodo=document.all[id];
	if (nodo.style.display=="none") {
		nodo.style.display="block";
	} else {
		nodo.style.display="none";
	}
}

function openWindow(url, ancho, alto) {
	strancho=ancho;
	stralto=alto;
	if (ancho==null) strancho = 600;
	if (alto==null) stralto = 360;
	window.open(url,"","resizable=yes,status=1,scrollbars=1,width="+strancho+",height="+stralto,false);
}

function esVacio(cadena) {
	if (trim(cadena)=="") return true;
	else return false;
}

function comprobarTabla(form) {
	var res;
	res = true;
	if (form.op.value=="guardar_cliente") {
		if (trim(form.empresa.value)=="") {
			alert("El nombre de la empresa no puede ser vacio");
			res = false;
		}
	} else if (form.op.value=="guardar_contacto") {
		if (trim(form.nombre.value)+trim(form.apellidos.value)=="") {
			alert("El nombre o los apellidos del Contacto no puede ser Vacio");
			res = false;
		}
	} else if (form.op.value=="guardar_centro") {
		if (trim(form.centro.value)=="") {
			alert("El nombre del Centro no puede ser Vacio");
			res = false;
		}
	} else if (form.op.value=="guardar_consumo") {
		if (trim(form.idproducto.value)=="") {
			alert("El nombre del Producto no puede ser Vacio");
			res = false;
		}
	}
	return res;
}

function openLogin() {
	var url="popup_login.php";
	window.open(url,"","resizable=0,status=0,scrollbars=0,width=200,height=140",false);
	//window.open(url,"","",false);
}

function openBigWindow(url) {
	window.open(url,"","resizable=yes,status=1,scrollbars=1,width=540,height=480",false);
}

function setEmpresa(nombre, id) {
	//Si la nueva empresa es distinta, borro el codigo del centro
	if (window.opener.document.formulario.idempresa.value != id) {
		window.opener.document.formulario.idcentro.value="";
	}
	window.opener.document.formulario.idempresa.value=id;
	window.opener.document.formulario.empresa.value=nombre;
	window.close();
}

function setProducto(id, codigo, nombre) {
	window.opener.document.formulario.idproducto.value=id;
	window.opener.document.formulario.producto.value=nombre;
	window.opener.document.formulario.codigo.value=codigo;
	window.close();
}

function setEmpresaFromCentro(nombre, id) {
	window.opener.document.formulario.idempresa.value=id;
	window.opener.document.formulario.empresa.value=nombre;
	window.close();
}

function setCentro(nombre, id, nombre_empresa, idempresa) {
	window.opener.document.formulario.idempresa.value=idempresa;
	window.opener.document.formulario.empresa.value=nombre_empresa;
	window.opener.document.formulario.idcentro.value=id;
	window.opener.document.formulario.centro.value=nombre;
	window.close();
}

function setDireccion( form ) {
	var documentForm = window.opener.document.formulario;
	if (documentForm.direccion!=null) documentForm.direccion.value=form.direccion.value;
	if (documentForm.poblacion!=null) documentForm.poblacion.value=form.poblacion.value;
	if (documentForm.cp!=null) documentForm.cp.value=form.cp.value;
	if (documentForm.idprovincia!=null) documentForm.idprovincia.value=form.idprovincia.value;
	if (documentForm.pais!=null) documentForm.pais.value=form.pais.value;
	if (documentForm.telefono!=null) documentForm.telefono.value=form.telefono.value;
	if (documentForm.fax!=null) documentForm.fax.value=form.fax.value;
	if (documentForm.direccion_matiz!=null) documentForm.direccion_matiz[1].checked=true;
	window.close();
}

function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function

function resaltarGuardar() {
	var element = document.getElementById("boton_guardar");
	if (element!=null) {
		element.innerHTML ="* Guardar *";
	}
}

function abrirMail() {
	if (event.ctrlKey) {
		event.returnValue=false;
		window.open('http://www.varaderoweb.com/cgi-bin/sqwebmail');
		return false;
	}
}

function getElement( id, doc ) {
	var element;
	if (doc==null) doc = document;
	if (doc.getElementById==null) {
		element = doc.all[id];
	} else {
		element =doc.getElementById(id);
	}
	return element;
}

function toggleOcultacion(partner) {
	var table = getElement(partner);
	if (table!=null) {
		if (table.style.display=="none") table.style.display="block";
		else table.style.display="none";
	}
}

function mostrarOcultacion(partner) {
	var table = getElement(partner);
	table.style.display="block";	
}

function ocultarOcultacion(partner) {
	var table = getElement(partner);
	table.style.display="none";	
}

function onchange_data() {
	var f = document.form_q;
	var seccion=f.seccion.options[f.seccion.selectedIndex].value;
	var proveedor=f.proveedor.options[f.proveedor.selectedIndex].value;
	var marca=f.marca.options[f.marca.selectedIndex].value;
	var modelo=f.modelo.value;
	window.location.href="cm_ls_productos.php?seccion="+seccion+"&proveedor="+proveedor+"&marca="+marca+"&modelo="+modelo;
}

function urlencode(ch) {
   ch = escape(ch);
   ch = ch.replace(/[+]/g,"%2B");
   return  ch;
}

function setLeft(url) {

	top.fraLeft.location = url;
}

function setTop(url) {
	top.fraTop.location = url;
}

 


function setRight(url) {
	top.fraRight.location = url;
}

function history_back(w) {
	w.history.go(-1);
}

function setImagen(patron, msj, doc) {
	 //alert(patron+msj);
	 
	var resto="img_gestion,img_inicio,img_unidades,img_materiales,img_autoevaluacion,img_tutorias,img_salas,img_glosario,img_contenidos,img_trabajos";
	var v = resto.split(",");
	var nombre,nodo;
	for (i=0;i<v.length;i++ ) {
		nombre = v[i].substr(4);
		nodo = getElement(v[i], doc);
		if (nodo!=null) {
			nodo.src="img/cab_boton_"+nombre+"_normal.gif";
			nodo.background="img/cab_boton_"+nombre+"_normal.gif";
			if (nombre=="tutorias" && msj > 0){
				nodo.src="img/cab_boton_"+nombre+"_msj.gif";
				nodo.background="img/cab_boton_"+nombre+"_msj.gif";
			}
			//alert(i+nodo.src);
		}
		
	}	
	nombre = patron.substr(4);
	nodo = getElement(patron, doc);
	
	if (nodo!=null) {
	
		nodo.src="img/cab_boton_"+nombre+"_sobre.gif";
		nodo.background="img/cab_boton_"+nombre+"_sobre.gif";
		if (nombre=="tutorias" && msj > 0){
			nodo.src="img/cab_boton_"+nombre+"_msj.gif";
			nodo.background="img/cab_boton_"+nombre+"_msj.gif";
		}
		 
	}


}



function setSeccion(patron, doc) {
	 //alert(doc);
	var resto="Inicio,Contenidos,Unidades didácticas,Materiales,Trabajos,Glosario,Autoevaluaciones,Tutorías,Aula virtual";
	var v = resto.split(",");
	var nombre,nodo;
	for (i=0;i<v.length;i++ ) {
	 
		nodo = getElement(v[i], doc);
		if (nodo!=null) {
			
			nodo.className = "secciones"; 
			
		}
		
	}	
	nodo = getElement(patron, doc);
	if (nodo!=null) { 
		nodo.className = "seccionesactivo"; 
	 
	}

}


function replaceSubstring(inputString, fromString, toString) {
   // Goes through the inputString and replaces every occurrence of fromString with toString
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist
      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      // Next, replace the "inbetween" string with the "toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp; // Send the updated string back to the user
} // Ends the "replaceSubstring" function


function construyeUrlMenosMas(url,lista,itemsMas) {
	var res,urlBase,resto,w,x,i,atributo,valor,nresto;
	var v = url.split("?");
	if (v.length==1) {
		res = url+"?"+itemsMas;
	} else {
		nresto="";
		urlBase = v[0];
		resto = v[1];
		w = resto.split("&");
		for (i=0;i<w.length;i++) {
			if (w[i]!=""){
				x = w[i].split("=");
				atributo = x[0];
				valor="";
				if (x.length>0) valor = x[1];
				if (valor!="") {
					if (!perteneceLista(atributo,lista)) {
						nresto = nresto + "&" + atributo + "=" + valor;
					}
				}
			}
		}
		nresto += "&" + itemsMas;
		if (nresto!="") nresto=nresto.substring(1);
		res = urlBase + "?" + nresto;
	}
	return res;
}

function perteneceLista(valor,lista) {
        var res=false;
        pos =(","+lista+",").indexOf(","+valor+",");
        if (pos!=-1) {
                res=true;
        }
        return res;
}


	function esMail(valor){
		if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor)){
  
			return (true)
		} else {
 
			return (false);
		}

	}

	
	function compruebaAlias(valor){
		var validRegExp = /(?!^[\t\n\r\v]*$)^([a-zA-Z0-9]{1,8})$/;

		if (valor.length>8){
			return (false);
		}else if (valor.match(validRegExp)){
			return (true);
		
		}else{
			return (false);
		}

	}

	function numDigitos( valor, ancho) {
		var res, i;
		res = valor +"";
		for (i=(res+"").length; i<ancho; i++) {
			res ="0"+ res;
		}
		return res;
	}

	function compruebaNum(valor) {
		var str = valor
		var validRegExp = /^[0-9]+([,][0-9]*)?$/i;
		res=true;
		// search email text for regular exp matches
		if (str.search(validRegExp) == -1) {
			res=false;
		} 

		if (esVacio(str)) {
			res=true;
		}
		return res; 	
	}


	function compruebaFecha(str_datetime) {
		var re_date = /^(\d+)\/(\d+)\/(\d+)\s*$/;
		var res = true;
		if (!re_date.exec(str_datetime)) {
			
			res=false;
		}
	
		return res; 	
	}

	function decimal2js(cadena){
		var res = cadena.replace(",", ".");
		return res
	}

	function openWindowFoto(url) {
	
		var strancho;
		var stralto;
		//if (ancho==null) strancho = 530;
		//if (alto==null) stralto = 360;

		a = new Image();
		a.src=url;
		strancho = a.width+30;
		stralto = a.height+30;

		
		window.open("view_foto.php?imagen="+url,"","resizable=yes,status=1,scrollbars=0,width="+strancho+",height="+stralto,false);
	}

	function getLeftToLast(cadena, delim, num) {
        var pos;
        var res=cadena;
        for(i=0;i<num;i++) {
                pos = res.lastIndexOf(delim);
                if (pos!=-1) {
                        res = res.substring(0,pos);
                }
        }
        return res;
	}

	function cambiaValorTipocontenidos(item) {

		//var valor = getRightToLast(item.id,"_",1);

		var nodoPagina = getElement("div_paginas");
		var nodoEnlace = getElement("div_enlace");
	//	var nodoContenido = getElement("div_contenido_"+valor);

		nodoPagina.style.display="none";
		nodoEnlace.style.display="none";
		//nodoContenido.style.display="none";
		if (item.checked) {
			if (item.value=="P" ) nodoPagina.style.display="block";
			else if (item.value=="U" ) nodoEnlace.style.display="block";
			//else if (item.value=="R" ) nodoContenido.style.display="block";
		}
	}


	function getRightToLast(cadena, delim, num) {
        var pos;
        var res="";
        var tmp=cadena;
        for(i=0;i<num;i++) {
                pos = tmp.lastIndexOf(delim);
                if (pos!=-1) {
                        res = tmp.substring(pos) + res;
                        tmp = tmp.substring(0,pos);
                } else {
                        res = tmp + res;
                        tmp = "";
                }
        }
        if (res.length>=delim.length) {
                if (res.substring(0,delim.length)==delim) {
                        res = res.substring(delim.length);
                }
        }
        return res;
} 

function Comparar_Fecha(fecha1,fecha2) 
	{
	String1 = fecha1;
	String2 =fecha2;
	// Si los dias y los meses llegan con un valor menor que 10 
	// Se concatena un 0 a cada valor dentro del string 
	if (String1.substring(1,2)=="/") {
	String1="0"+String1
	}
	if (String1.substring(4,5)=="/"){
	String1=String1.substring(0,3)+"0"+String1.substring(3,9)
	}

	if (String2.substring(1,2)=="/") {
	String2="0"+String2
	}
	if (String2.substring(4,5)=="/"){
	String2=String2.substring(0,3)+"0"+String2.substring(3,9)
	}

	dia1=String1.substring(0,2);
	mes1=String1.substring(3,5);
	anyo1=String1.substring(6,10);
	dia2=String2.substring(0,2);
	mes2=String2.substring(3,5);
	anyo2=String2.substring(6,10);


	if (dia1 == "08") // parseInt("08") == 10 base octogonal
	dia1 = "8";
	if (dia1 == '09') // parseInt("09") == 11 base octogonal
	dia1 = "9";
	if (mes1 == "08") // parseInt("08") == 10 base octogonal
	mes1 = "8";
	if (mes1 == "09") // parseInt("09") == 11 base octogonal
	mes1 = "9";
	if (dia2 == "08") // parseInt("08") == 10 base octogonal
	dia2 = "8";
	if (dia2 == '09') // parseInt("09") == 11 base octogonal
	dia2 = "9";
	if (mes2 == "08") // parseInt("08") == 10 base octogonal
	mes2 = "8";
	if (mes2 == "09") // parseInt("09") == 11 base octogonal
	mes2 = "9";

	dia1=parseInt(dia1);
	dia2=parseInt(dia2);
	mes1=parseInt(mes1);
	mes2=parseInt(mes2);
	anyo1=parseInt(anyo1);
	anyo2=parseInt(anyo2);

	if (anyo1>anyo2)
	{
	return false;
	}

	if ((anyo1==anyo2) && (mes1>mes2))
	{
	return false;
	}
	if ((anyo1==anyo2) && (mes1==mes2) && (dia1>dia2))
	{
	return false;
	} 

	return true;
}

function date2str(valor){
	dia=valor.substring(6,8);
	mes=valor.substring(4,6);
	anio=valor.substring(0,4);
	return (new String (dia + "/" + mes + "/" + anio));
}
function compruebaDNI(abc){
 
	nif=abc.substring(0,abc.length-1);
	let=abc.charAt(abc.length-1)
	if (!isNaN(let)){

	 
		return false
	 }
	 
	return(true)
 
}


function compruebaLetraDNI(abc)
{
 
nif=abc.substring(0,abc.length-1);
let=abc.charAt(abc.length-1)
if (!isNaN(let)){
 
 }else{
  cadena="TRWAGMYFPDXBNJZSQVHLCKET"
  posicion = nif % 23
  letra = cadena.substring(posicion,posicion+1)
  if (letra!=let.toUpperCase())
   {
 
   
    return false;
   }
 }
 
return(true)
 
}


function getstrCalificacionesEliminar() {

	var f = document.form_generacion;

	var strIds ="";
	patron="calif_";
	
	for(i=0;i<f.all.length;i++) {	
		var campo = f[i];
		if (campo!=null) {
			var nombreCampo = campo.name;
			if( nombreCampo.substring(0, patron.length)==patron && campo.checked == false ){
				var valor = campo.value;
		 
				strIds += "," + campo.value ;
				
				
			}
		}
	}
	if (strIds!="") strIds=strIds.substring(1);
	
	return strIds;
}


function strIdsSeleccionados() {

	var f = document.form_generacion;


	var strIds ="";
	patron="set_";
	
	for(i=0;i<f.length;i++) {	
		var campo = f[i];
		if (campo!=null) {
			var nombreCampo = campo.name;
			if( nombreCampo.substring(0, patron.length)==patron && campo.checked == true ){
				var valor = campo.value;
		 
				strIds += "," + campo.value ;
				
				
			}
		}
	}
	if (strIds!="") strIds=strIds.substring(1);
	
	return strIds;
}


function getNombreArchivo(archivo) {
	 
	var res ="";
	var pos ="";
	archivo = archivo.replace(/\\/g,"/");
	//archivo = archivo.split("\\").join("/");
 
	 pos = archivo.lastIndexOf("/"); 
	if (pos>0) {
		res= archivo.substr(pos+1);
	}

	pos = res.lastIndexOf(".");
	if (pos>0) {
		res= res.substr(0,pos);
	}
	 
	return res;
}
