// ********************* Funciones Para los menus que siempre te salgan en pantalla con el nombre tabla_desplazar

function estableceValorImagen(nombreVariable, valorVariable) {
	if (nombreVariable!="") {
		document.formulario.click_imagen.value="1";
		document.formulario.nombre_variable.value=nombreVariable;
		document.formulario.valor_variable.value=valorVariable;
		enviarFormularioPagina(); return false;
	}
}

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 openBigWindow(url) {
	window.open(url,"","resizable=yes,status=1,scrollbars=1,width=540,height=480",false);
}

function ltrim(s) {
   return s.replace(/^\s+/, "");
}

function rtrim(s) {
   return s.replace(/\s+$/, "");
}

function trim(s) {
   return rtrim(ltrim(s));
}


function getElement( id, ndoc) {
	var element;
	if (ndoc==null) doc=document;
	else doc=ndoc;
	if (doc.getElementById==null) {
		element = doc.all[id];
	} else {
		element =doc.getElementById(id);
	}
	return element;
}




function esVacio(cadena) {
	if (trim(cadena)=="") return true;
	else return false;
}


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





// code for IE
	if (window.ActiveXObject)
	 	 xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
// code for Mozilla, etc.
	else if (document.implementation &&
	document.implementation.createDocument)
		xmlDoc= document.implementation.createDocument("","",null);
function loadXML(xmlFile){
  //load xml file
	if (window.ActiveXObject)
	  xmlDoc.onreadystatechange=verify;

	xmlDoc.load(xmlFile);

  //xmlObj=xmlDoc.documentElement;
}



function verify(){
  // 0 Object is not initialized
  // 1 Loading object is loading data
  // 2 Loaded object has loaded data
  // 3 Data from object can be worked with
  // 4 Object completely initialized
  if (xmlDoc.readyState != 4)
  {
    return false;
  }
}


function getValor(item) {

	var res=null;
	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 set(nombre, valor) {
        var mivalor = valor;
        var strEval = "window.top."+nombre+"=valor;"
        eval(strEval);
}

function get(variable) {
        var strEval, res;
        strEval = "window.top."+variable;
        res = eval(strEval);
        if (res==undefined) res="";
    return res;
}


function setOpener(nombre, valor) {
        var mivalor = valor;
        var strEval = "window.opener.top."+nombre+"=valor;"
        eval(strEval);
}

function getOpener(variable) {
        var strEval, res;
        strEval = "window.opener.top."+variable;
        res = eval(strEval);
        if (res==undefined) res="";
    return res;
}

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 to check valid email address
function isValidDigit(str){
	var validRegExp = /^[0-9]+$/i;
	res=true;
	// search email text for regular exp matches
	if (str.search(validRegExp) == -1) {
		res=false;
	}
	return res;
}

function esNumericoDecimal(str){
	var validRegExp = /^[0-9]+(\,[0-9]+)?$/i;
	res=true;
	// search email text for regular exp matches
	if (str.search(validRegExp) == -1) {
		res=false;
	}
	return res;
}

function esNumerico(str){
	var validRegExp = /^[0-9]+$/i;
	res=true;
	// search email text for regular exp matches
	if (str.search(validRegExp) == -1) {
		res=false;
	}
	return res;
}

function numDigitos(numero, numDigitos) {
	var res=""+numero;
	while (res.length<numDigitos) {
		res = "0"+res;
	}
	return res;
}

function compruebaFecha(strFecha) {
	var mmddaaaa = strFecha.substring(3,5) +"/"+ strFecha.substring(0,2) +"/"+ strFecha.substring(6,10);
	var sep1 = strFecha.substring(2,3);
	var sep2 = strFecha.substring(5,6);

	if ((sep1!='/' && sep1!='-') || (sep2!='/' && sep2!='-') || (sep1!=sep2)){
		return false;
	}

	if (isDate(mmddaaaa))
		return true;
	else
		return false;
}

function compruebaHora(strHora) {
	if (strHora.length==7)
		strHora='0' + strHora;

	if (strHora.length!=8)
	  return false;

	var strhora = strHora.substring(0,2);
	var strminuto = strHora.substring(3,5);
	var strseg = strHora.substring(6,8);
	var puntos1 = strHora.substring(2,3);
	var puntos2 = strHora.substring(5,6);
	if (puntos1!=':' || puntos2!=':')
		return false;

	var hora = parseInt(strhora, 10);
	var minuto = parseInt(strminuto, 10);
	var seg = parseInt(strseg, 10);
	if (!isInteger(strhora) || !isInteger(strminuto) || !isInteger(strseg))
		return false;
	else if (hora>23 || hora<0)
		return false;
	else if (minuto>59 || minuto<0)
		return false;
	else if (seg>59 || seg<0)
		return false;

	return true;
}


/*** FUNCIONES DE FECHA ***/
/*** FUNCIONES DE FECHA ***/
/*** FUNCIONES DE FECHA ***/

var dtCh= "/";
var minYear=1000;
var maxYear=3000;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   }
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		//alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		//alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		//alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		//alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		//alert("Please enter a valid date")
		return false
	}
	return true
}

function ValidateForm(){
	var dt=document.frmSample.txtDate
	if (isDate(dt.value)==false){
		dt.focus()
		return false
	}
    return true
 }
/*** FIN FUNCIONES DE FECHA ***/
/*** FIN FUNCIONES DE FECHA ***/
/*** FIN FUNCIONES DE FECHA ***/


// Funciones de AlbertO LopeZ
var MAXSELEC=50; //numero maximo de variables para las seleciones de variables en una consulta

function ChequearTodos(chkbox,form)
{
	for (var i=0;i < form.elements.length;i++){
		var elemento = form.elements[i];
		if (elemento.type == "checkbox" && elemento.id== "campos" && chkbox.id== "Todos1"){
		elemento.checked = chkbox.checked
		}
		if (elemento.type == "checkbox" && elemento.id== "estudios" && chkbox.id== "Todos1"){
		elemento.checked = chkbox.checked
		}
		if (elemento.type == "checkbox" && elemento.id== "clientes" && chkbox.id== "Todos1"){
		elemento.checked = chkbox.checked
		}
		if (elemento.type == "checkbox" && elemento.id== "ficheros" && chkbox.id== "Todos1"){
		elemento.checked = chkbox.checked
		}
		if (elemento.type == "checkbox" && elemento.id== "contactos" && chkbox.id== "Todos1"){
		elemento.checked = chkbox.checked
		}
		if (elemento.type == "checkbox" && elemento.id== "estados" && chkbox.id== "Todos2"){
		elemento.checked = chkbox.checked
		}
		if (elemento.type == "checkbox" && elemento.id== "usuarios" && chkbox.id== "Todos2"){
		elemento.checked = chkbox.checked
		}
		if (elemento.type == "checkbox" && elemento.id== "incidencias" && chkbox.id== "Todos3"){
		elemento.checked = chkbox.checked
		}
		if (elemento.type == "checkbox" && elemento.id== "tipos" && chkbox.id== "Todos3"){
		elemento.checked = chkbox.checked
		}
		if (elemento.type == "checkbox" && elemento.id== "usuariosage" && chkbox.id== "Todosage"){
		elemento.checked = chkbox.checked
		}
		if (elemento.type == "text" && chkbox.id == "Activar"){
		elemento.disabled = !elemento.disabled
		}
		if (elemento.type == "text" && chkbox.id == "Activar1" && elemento.id!="descripcion"){
		elemento.disabled = !elemento.disabled
		}
		if (elemento.type == "checkbox" && elemento.id== "contactos" && chkbox.id== "Todos"){
		elemento.checked = chkbox.checked
		}
		if (elemento.type == "checkbox" && elemento.id== "datos" && chkbox.id== "Todos1"){
			elemento.checked = chkbox.checked
		}
	}
}

function ChequearBtnTodos(chkbox){
	if(chkbox.id=="campos" && chkbox.type=="checkbox" && !chkbox.checked)
		document.form1.Todos1.checked=chkbox.checked;

	if(chkbox.id=="estudios" && chkbox.type=="checkbox" && !chkbox.checked)
		document.form1.Todos1.checked=chkbox.checked;

	if(chkbox.id=="clientes" && chkbox.type=="checkbox" && !chkbox.checked)
		document.form1.Todos1.checked=chkbox.checked;

	if(chkbox.id=="usuarios" && chkbox.type=="checkbox" && !chkbox.checked)
		document.form1.Todos2.checked=chkbox.checked;

	if(chkbox.id=="estados" && chkbox.type=="checkbox" && !chkbox.checked)
		document.form1.Todos2.checked=chkbox.checked;

	if(chkbox.id=="incidencias" && chkbox.type=="checkbox" && !chkbox.checked)
		document.form1.Todos3.checked=chkbox.checked;

	if(chkbox.id=="tipos" && chkbox.type=="checkbox" && !chkbox.checked)
		document.form1.Todos3.checked=chkbox.checked;

	if(chkbox.id=="usuariosage" && chkbox.type=="checkbox" && !chkbox.checked)
		document.formulario.Todosage.checked=chkbox.checked;

	if(chkbox.id=="contactos" && chkbox.type=="checkbox" && !chkbox.checked)
		document.form1.Todos.checked=chkbox.checked;

	if(chkbox.id=="ficheros" && chkbox.type=="checkbox" && !chkbox.checked)
		document.form1.Todos1.checked=chkbox.checked;

	if(chkbox.id=="datos" && chkbox.type=="checkbox" && !chkbox.checked)
		document.form1.Todos1.checked=chkbox.checked;
}

function moverarriba(){
	i=1;
	while (i<document.form1.ordenar.length){

		if(document.form1.ordenar.options[i].selected){
			opcion = new Option (document.form1.ordenar.options[i].text,document.form1.ordenar.options[i].value,"defaultSelected", "selected");
			opcion2 = new Option (document.form1.ordenar.options[i-1].text,document.form1.ordenar.options[i-1].value);
			document.form1.ordenar.options[i-1]=opcion;
			document.form1.ordenar.options[i]=opcion2;
			return
			}
		i++;
		}
}
function moverabajo(){
	i=0;
	while (i<(document.form1.ordenar.length-1)){
		if(document.form1.ordenar.options[i].selected){
			opcion = new Option (document.form1.ordenar.options[i].text,document.form1.ordenar.options[i].value,"defaultSelected", "selected");
			opcion2 = new Option (document.form1.ordenar.options[i+1].text,document.form1.ordenar.options[i+1].value);
			document.form1.ordenar.options[i+1]=opcion;
			document.form1.ordenar.options[i]=opcion2;
			return
			}
		i++;
		}
}

var selec=0;

function formatselecs(maximo){
		var i=0;
		if (maximo!=null)
			MAXSELEC=maximo;
		while ((i<document.form1.Var.length) && (selec<MAXSELEC)){
			if(document.form1.Var.options[i].selected){
					opcion = new Option (document.form1.Var.options[i].text,document.form1.Var.options[i].value);
					document.form1.Selec.options[selec]=opcion;
					document.form1.Var.remove(i);
					selec++;
			}else{
					i++;
			}

		}
}

function formatdesselecs(){
		var i=0;
		while (i<document.form1.Selec.length){
		var k=document.form1.Var.length;
		if(document.form1.Selec.options[i].selected){
					//document.form1.Var.add(1);
					opcion = new Option (document.form1.Selec.options[i].text,document.form1.Selec.options[i].value);
					document.form1.Var.options[k]=opcion;
					document.form1.Selec.remove(i);
					selec--;
			}else{
					i++;
			}

		}

}

function formatselecsusuarios(vector){
		var i=0;
		while ((i<document.form1.usuadmin.length)){
			if(document.form1.usuadmin.options[i].selected){
					opcion = new Option (document.form1.usuadmin.options[i].text,document.form1.usuadmin.options[i].value);
					document.form1.usuaut.options[form1.usuaut.length]=opcion;
					document.form1.usuadmin.remove(i);
				    vector.push(0);
					selec++;
			}else{
					i++;
			}
		}
		var i=0;
		while ((i<document.form1.usuentre.length)){
			if(document.form1.usuentre.options[i].selected){
					opcion = new Option (document.form1.usuentre.options[i].text,document.form1.usuentre.options[i].value);
					document.form1.usuaut.options[form1.usuaut.length]=opcion;
					document.form1.usuentre.remove(i);
				    vector.push(3);
					selec++;
			}else{
					i++;
			}
		}
		var i=0;
		while ((i<document.form1.usucli.length)){
			if(document.form1.usucli.options[i].selected){
					opcion = new Option (document.form1.usucli.options[i].text,document.form1.usucli.options[i].value);
					document.form1.usuaut.options[form1.usuaut.length]=opcion;
					document.form1.usucli.remove(i);
				    vector.push(4);
					selec++;
			}else{
					i++;
			}
		}
}

function formatdesselecsusuarios(vector){
	var i=0;
	while (i<document.form1.usuaut.length){
	var k=document.form1.usuadmin.length;
	var j=document.form1.usuentre.length;
	var h=document.form1.usucli.length;
	if(document.form1.usuaut.options[i].selected){
				//document.form1.Var.add(1);
				opcion = new Option (document.form1.usuaut.options[i].text,document.form1.usuaut.options[i].value);
				if(vector[i]==0){
				  document.form1.usuadmin.options[k]=opcion;
				}
				if(vector[i]==3){
				  document.form1.usuentre.options[j]=opcion;
				}
				if(vector[i]==4){
				  document.form1.usucli.options[h]=opcion;
				}
				vector.splice(i, 1);
				document.form1.usuaut.remove(i);
				selec--;
		}else{
				i++;
		}
	}
}

function preloadImages() {
  var d=document;
  if(d.images){
  	if(!d.p)
		d.p=new Array();
    	var i,j=d.p.length,a=preloadImages.arguments;
		for(i=0; i<a.length; i++)
    		if (a[i].indexOf("#")!=0){
				d.p[j]=new Image;
				d.p[j++].src=a[i];
			}
  }
}

function swapImgRestore() {
  var i,x,a=document.sr;
  for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++)
  	x.src=x.oSrc;
}

function findObj(n, d) {
  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=findObj(n,d.layers[i].document);
  if(!x && d.getElementById)
  	x=d.getElementById(n);

  return x;
}

function swapImage() {
  var i,j=0,x,a=swapImage.arguments;
  document.sr=new Array;
  for(i=0;i<(a.length-2);i+=3)
  	if ((x=findObj(a[i]))!=null){
		document.sr[j++]=x;
		if(!x.oSrc)
			x.oSrc=x.src;
		x.src=a[i+2];
	}
}

function CargaFlash(ruta,nombre,ancho,alto,flashvar){
  document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="' + ancho + '" height="' + alto + '" id="' + nombre + '" align="middle">\n');
  document.write('<param name="allowScriptAccess" value="sameDomain">\n');
  document.write('<param name="wmode" value="transparent">\n');
  document.write('<param name="movie" value="' + ruta + '">\n');
  document.write('<param name="quality" value="high">\n');
  document.write('<param name="menu" value="false">\n');
  document.write('<param name="bgcolor" value="#ffffff">\n');
  document.write('<param name="flashVars" value="'+ flashvar +'">\n');
  document.write('<embed src="' + ruta + '" quality="high" flashVars="'+ flashvar +'" bgcolor="#ffffff" wmode=transparent width="' + ancho + '" height="' + alto + '" name="' + nombre + '" align="middle" swLiveConnect="true" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer">\n');
  document.write('</object>\n');
}

function resize(){
		window.moveTo(0,0);
		window.resizeTo(screen.availWidth,screen.availHeight);
}

function checkMaxLength(maxlength,area){
	if(area.value.length>=maxlength){
		area.value=area.value.substring(0,maxlength);
	}
}

// Fin Funciones AlbertO LopeZ
// Funciones Carlos Anduj
function storeCaret (textEl) {
	if (textEl.createTextRange)
	textEl.caretPos = document.selection.createRange().duplicate();
}

function insertatoken(textEl, text){
	if (textEl.createTextRange && textEl.caretPos) {
		var caretPos = textEl.caretPos;
		caretPos.text =caretPos.text.charAt(caretPos.text.length - 1) == ' ' ?
		text + ' ' : text;}
	else
	textEl.value += text;
	textEl.focus(text);
}

// Carles; 05/07/2006; Modificamos la funci&oacute;n para pasar componentes de un SELECT a otro
function formatseltc(){
	var i=0;
	while (i<document.form1.Var.length){
		var k=document.form1.Selec.length;
		if(document.form1.Var.options[i].selected){
			opcion = new Option (document.form1.Var.options[i].text,document.form1.Var.options[i].value);
			document.form1.Selec.options[k]=opcion;
			document.form1.Var.remove(i);
			selec++;
		}else{
			i++;
		}
	}
}

function compararFecha(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;
}

// converteix un número d'un caracter a 2
function lz(x){
	return (x<0||x>9?"":"0")+x;
}

function obtenirData(){
	var date = new Date();
	return lz(date.getDate())+'/'+lz(date.getMonth()+1)+'/'+date.getFullYear();
}

function obtenirHora(){
	var date = new Date();
	return lz(date.getHours())+':'+lz(date.getMinutes())+':'+lz(date.getSeconds());
}

function obtenirDataHora(){
	var date = new Date();
	return lz(date.getHours())+':'+lz(date.getMinutes())+':'+lz(date.getSeconds())+' '+lz(date.getDate())+'/'+lz(date.getMonth()+1)+'/'+date.getFullYear();
}

// GESTIÓ DE CAPES
function deshabilitarPagina() {
	var doc;
	doc = document.getElementById('capa_principal');
	if (doc==null)
		doc = window.parent.document;
	else
		doc = window.document;

	// deshabil·litar video i audio si hi hagueren
	i=0;
	while (doc.getElementById('multim_'+i)!=null){
		doc.getElementById('multim_'+i).style.visibility = 'hidden';
		i++;
	}
	doc.getElementById('capa_principal').style.opacity = 0.4;
	doc.getElementById('capa_principal').style.filter = 'alpha(opacity=40)';
}

function habilitarPagina() {
	//window.parent.document.getElementById('ventana_emergente').width=0;
	//window.parent.document.getElementById('ventana_emergente').height=0;
	if (window.parent.document.getElementById('capa_principal').style.opacity!="0.4"){
		doc = window.parent.parent.document;
	} else {
		doc = window.parent.document;
	}
	//alert(window.parent.document.getElementById('capa_principal').style.opacity)
	// habil·litar video i audio si hi hagueren
	i=0;
	while (doc.getElementById('multim_'+i)!=null){
		doc.getElementById('multim_'+i).style.visibility = 'visible';
		i++;
	}
	try{
		doc.getElementById('capa_desactivar').style.visibility = 'hidden';
		doc.getElementById('capa_loading').style.visibility = 'hidden';
		doc.getElementById('texto_loading').innerHTML = '';
		doc.getElementById('display_aux').innerHTML = '';
		doc.getElementById('capa_alert').style.visibility = 'hidden';
		doc.getElementById('capa_principal').style.opacity = 1;
		doc.getElementById('capa_principal').style.filter = 'alpha(opacity=100)';
		
		sig = doc.getElementById('siguiente');
		if (sig!=null)
			sig.focus();
		
	}catch(e){}
}

function abrirPopUp(url,height,width,posx,posy){
	document.getElementById('ventana_emergente').src=url;
	document.getElementById('ventana_emergente').height=height;
	document.getElementById('ventana_emergente').width=width;
	if (posx!=null || posy!=null){
		document.getElementById('ventana_emergente').style.position='absolute';
		document.getElementById('ventana_emergente').style.left=posx;
		document.getElementById('ventana_emergente').style.top=posy;
	}
}

function recargarPopUp(url,height,width){
	window.parent.document.getElementById('capa_desactivar').style.visibility = 'hidden';
	window.parent.document.getElementById('ventana_emergente').src=url;
	window.parent.document.getElementById('ventana_emergente').height=height;
	window.parent.document.getElementById('ventana_emergente').width=width;
}

function abrirLoading(texto){
	if (texto!=null)
		window.document.getElementById('texto_loading').innerHTML = texto;
	window.document.getElementById('capa_loading').style.visibility = 'visible';
	// si està definida la funció cancelar_loading() habilite el link que la crida en capa_loading
	if (isDefined("cancelar_loading")){
		window.document.getElementById('cancel_loading').style.visibility = 'inherit';
	}
}

function abrirLoadingPadre(texto){
	window.parent.document.getElementById('capa_desactivar').style.visibility = 'hidden';
	if (texto!=null)
		window.parent.document.getElementById('texto_loading').innerHTML = texto;
	window.parent.document.getElementById('capa_loading').style.visibility = 'visible';
	// si està definida la funció cancelar_loading() habilite el link que la crida en capa_loading
	if (isDefined("cancelar_loading")){
		window.document.getElementById('cancel_loading').style.visibility = 'inherit';
	}
}

/* aquesta funció simula el missatges de alert i confirm que es poden generar amb javascript;
   per a aconseguir-ho utilitza la div 'capa_alert' definida en el top
   - mensaje: missatge que es mostrarà en el recuadre
   - tipo [opcional]: tipus de diàleg. Els casos possibles són: error, warning, ok, info i question
   		la configuració per defecte és warning
   		si es selecciona question tens dos botons Aceptar i Cancelar
   - titulo [opcional]: text que apareix com a títol de la finestra del missatge
   - scriptOk [opcional]: codi javascript que volem que s'execute quan es polse el botó Aceptar
   - scriptCancelar (sols vàlid amb tipus question)[opcional]: codi javascript que volem que s'execute quan es polse el botó Cancelar (sols en tipus question)
   - botonPredeterminado (sols vàlid amb tipus question)[opcional]: indica quin és el botó que tindrà el focus. Per defecte és Aceptar.
   		valors possibles: 'aceptar' i 'cancelar'
*/
function mostrarMensaje(mensaje,tipo,titulo,scriptOk,scriptCancel,botonPredeterminado){
	var doc;
	doc = document.getElementById('capa_principal');
	if (doc==null){
		doc = window.parent.document;
		if (window.parent.parent.document.getElementById('capa_desactivar') != null && window.parent.parent.document.getElementById('capa_desactivar').style.visibility == "hidden")
			doc = window.parent.parent.document;
	} else {
		doc = window.document;
	}
	// deshabil·litar video i audio si hi hagueren
	i=0;
	while (doc.getElementById('multim_'+i)!=null){
		doc.getElementById('multim_'+i).style.visibility = 'hidden';
		i++;
	}
	// deshabil·litar pantalla principal
	doc.getElementById('capa_principal').style.opacity = 0.4;
	doc.getElementById('capa_principal').style.filter = 'alpha(opacity=40)';
	// mostrar capa de missatge
	doc.getElementById('capa_alert').style.visibility = 'visible';
	// possar valors
	if (mensaje!=null && mensaje!=''){
		doc.getElementById('mensa_texto').innerHTML = mensaje;
    if (doc.getElementById('mensa_texto').offsetWidth>600)
      doc.getElementById('tabla_capa_alert').width=600;
  }
	if (titulo!=null && titulo!='')
		doc.getElementById('mensa_titol').innerHTML = titulo;
	else
		titulo = 'Gandia Integra';
	// per defecte el botó cancelar no es veu	
	doc.getElementById('capa_boton_cancelar').style.display = 'none';
	// per defecte el tipus és warning
	if (tipo==null || tipo=='')
		tipo = 'warning';
	/*
	switch (tipo){
		case 'error': 	doc.getElementById('mensa_titol').innerHTML = 'Error :: '+titulo;
						break;
		case 'warning': doc.getElementById('mensa_titol').innerHTML = 'Aviso :: '+titulo;
						break;
		case 'question':	doc.getElementById('mensa_titol').innerHTML = 'Pregunta :: '+titulo;
							doc.getElementById('capa_boton_cancelar').style.display = 'inline';
						break;
	}*/
	doc.getElementById('mensa_titol').innerHTML = titulo;
	if (tipo=='question')
		doc.getElementById('capa_boton_cancelar').style.display = 'inline';
	doc.getElementById('mensa_imatge').src = 'img/'+tipo+'.png';
	// assigne el codi als botons
	if (scriptOk!=null){
		doc.code_ok = scriptOk;
		if (scriptOk.search(/mostrarMensaje/)!=-1)
			doc.recursiveOk = true;
	} else {
		doc.code_ok = '';
	}
	if (scriptCancel!=null){
		doc.code_cancel = scriptCancel;
		if (scriptCancel.search(/mostrarMensaje/)!=-1)
			doc.recursiveCancel = true;
	} else {
		doc.code_cancel = '';
	}
	// pose el foco
	if (botonPredeterminado=='cancelar')
		doc.getElementById('mensa_boton_cancelar').focus();
	else
		doc.getElementById('mensa_boton_aceptar').focus();
}

function clickMensa(mode){
	if (mode==0){ // ok
		if (document.code_ok!=''){
			eval(document.code_ok);
			if (!document.recursiveOk){
				document.code_ok='';
				document.code_cancel='';
			}
		}
	} else{ // cancel
		if (document.code_cancel!=''){
			eval(document.code_cancel);
			if (!document.recursiveCancel){
				document.code_ok='';
				document.code_cancel='';
			}
		}
	}
	//document.getElementById('capa_boton_cancelar').style.display = 'none';
	if (!document.recursiveOk && !document.recursiveCancel){
		document.getElementById('capa_alert').style.visibility = 'hidden';
		document.getElementById('capa_principal').style.opacity = 1;
		document.getElementById('capa_principal').style.filter = 'alpha(opacity=100)';
		// habil·litar video i audio si hi hagueren
		i=0;
		while (document.getElementById('multim_'+i)!=null){
			document.getElementById('multim_'+i).style.visibility = 'visible';
			i++;
		}
	} else {
		document.recursiveOk = false;
		document.recursiveCancel = false;
	}
}

var id_timer_inci;
function refrescoiframe(script, incidencia){
	// script 0=anotar_incidencia, 1=resto
	// anotar incidencia 6 i 7;
	if (script==0 && incidencia!=7 && incidencia!=6){
		// particular
		if (incidencia==-1)
			if(document.getElementById('inciparticular').value=="")
				document.getElementById('inciparticular').value=document.getElementById('inciparticular').options[1].value;
		if (onSub())
			document.forms[0].submit();
	} else {
		habilitarPagina();
	}
}

function timeout(temps,script,incidencia){
	if (typeof(id_timer_inci)!="undefined")
		clearTimeout(id_timer_inci);
	id_timer_inci=setTimeout( 'refrescoiframe('+script+','+incidencia+')', temps * 1000 );
}

function realizarExportacion(){
	if(!document.documentElement.outerHTML){
	  Node.prototype.getAttributes = function(){
	    var attStr = "";
	    if(this && this.attributes.length > 0){
	      for(a = 0; a < this.attributes.length; a ++){
	        attStr += " " + this.attributes.item(a).nodeName + "=\"";
	        attStr += this.attributes.item(a).nodeValue + "\"";
	      }
	    }
	    return attStr;
	  }

	  Node.prototype.getInsideNodes = function(){
	    if(this){
	      var cNodesStr = "", i = 0;
	      var iEmpty = /^(img|embed|input|br|hr)$/i;
	      var cNodes = this.childNodes;
	      for(i = 0; i < cNodes.length; i ++){
	        switch(cNodes.item(i).nodeType){
	          case 1 :
	            cNodesStr += "<" + cNodes.item(i).nodeName.toLowerCase();
	            if(cNodes.item(i).attributes.length > 0){
	              cNodesStr += cNodes.item(i).getAttributes();
	            }
	            cNodesStr += (cNodes.item(i).nodeName.match(iEmpty))? "" : ">";
	            if(cNodes.item(i).childNodes.length > 0){
	              cNodesStr += cNodes.item(i).getInsideNodes();
	            }
	            if(cNodes.item(i).nodeName.match(iEmpty)){
	              cNodesStr += " />";
	            } else {
	              cNodesStr += "</" + cNodes.item(i).nodeName.toLowerCase() + ">";
	            }
	            break;
	          case 3 :
	            cNodesStr += cNodes.item(i).nodeValue;
	            break;
	          case 8 :
	            cNodesStr += "<!--" + cNodes.item(i).nodeValue + "-->";
	            break;
	        }
	      }
	      return cNodesStr;
	    }
	  }

	  if (HTMLElement) {
			var element = HTMLElement.prototype;
			if (element.__defineGetter__) {
				element.__defineGetter__("outerHTML",	function () {
	        var strOuter = "";
	        var iEmpty = /^(img|embed|input|br|hr)$/i;
	        switch(this.nodeType){
	          case 1 :
	            strOuter += "<" + this.nodeName.toLowerCase();
	            strOuter += this.getAttributes();
	            if(this.nodeName.match(iEmpty)){
	              strOuter += " />";
	            } else {
	              strOuter += ">" + this.getInsideNodes();
	              strOuter += "</" + this.nodeName.toLowerCase() + ">";
	            }
	            break;
	            case 3 :
	              strOuter += this.nodeValue;
	              break;
	            case 8 :
	              cNodesStr += "<!--" + this.nodeValue + "-->";
	              break;
	        }
	        return strOuter;
				});
			}
	  }
	}

	// Obtenemos todas las tablas cuyo id empiece por exportar
	var tablas=document.getElementsByTagName('table');
	var html='';
	for (var i=0;i<tablas.length;i++){
		if (tablas[i].id.substring(0,8)=="exportar"){
			html+=document.getElementById(tablas[i].id).outerHTML;
		}
	}
	document.getElementById("html").value=html;
	deshabilitarPagina();
	abrirLoading('Espere por favor, se est&aacute; generando el fichero pdf...');
	document.formexportar.submit();
}

// Función que ordena alfabéticamente los ítems de un objeto SELECT (lista HTML)
function sortSelect(obj){
  var o = new Array();
  for (var i=0; i<obj.options.length; i++){
      o[o.length] = new Option(obj.options[i].text, obj.options[i].value, obj.options[i].defaultSelected, obj.options[i].selected);
  }
  o = o.sort(
      function(a,b){
          if ((a.text+"") < (b.text+"")) { return -1; }
          if ((a.text+"") > (b.text+"")) { return 1; }
          return 0;
      }
  );

  for (var i=0; i<o.length; i++){
      obj.options[i] = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
  }
}

function basename(path, suffix) {
    // http://kevin.vanzonneveld.net

    var b = path.replace(/^.*[\/\\]/g, '');
    if (typeof(suffix) == 'string' && b.substr(b.length-suffix.length) == suffix) {
        b = b.substr(0, b.length-suffix.length);
    }
    return b;
}

function esMultiple(valor){
	var arr = valor.split(";");
	for (var i=0; i < arr.length; i++){
		if (!isInteger(arr[i]))
			return false;
	}
	return true;
}

function esVariableNumerica(valor,enteros,decimales){
	var expresion = new RegExp("^-?[0-9]{1,"+enteros+"}(\\,[0-9]{0,"+decimales+"})?$");
	if (valor.search(expresion)==-1)
		return false;
	else
		return true;
}

// Carles; 30-03-2009; Comparamos si una fecha-hora es menor que otra fecha-hora
function compararFechaHora(fecha1,fecha2,hora1,hora2){
	var arrfec1=fecha1.split('/');
	var arrfec2=fecha2.split('/');
	var arrhora1=hora1.split(':');
	var arrhora2=hora2.split(':');
	var date1=new Date(parseInt(arrfec1[2],10),parseInt(arrfec1[1],10)-1,parseInt(arrfec1[0],10),
								parseInt(arrhora1[0],10),parseInt(arrhora1[1],10),parseInt(arrhora1[2],10));

	var date2=new Date(parseInt(arrfec2[2],10),parseInt(arrfec2[1],10)-1,parseInt(arrfec2[0],10),
								parseInt(arrhora2[0],10),parseInt(arrhora2[1],10),parseInt(arrhora2[2],10));

	if (date2.getTime()>date1.getTime())
		return true;
	else
		return false;
}

function fechaHoraMenorActual(fecha,hora){
	var arrfec1=fecha.split('/');
	var arrhora1=hora.split(':');

	var date1=new Date(parseInt(arrfec1[2],10),parseInt(arrfec1[1],10)-1,parseInt(arrfec1[0],10),
								parseInt(arrhora1[0],10),parseInt(arrhora1[1],10),parseInt(arrhora1[2],10));
	var date2=new Date();

	if (date2.getTime()>date1.getTime())
		return true;
	else
		return false;
}

function restarFechas(fecha1,fecha2){
	var arrfec1=fecha1.split('/');
	var arrfec2=fecha2.split('/');
	var date1 = new Date(parseInt(arrfec1[2],10),parseInt(arrfec1[1],10)-1,parseInt(arrfec1[0],10));
	var date2 = new Date(parseInt(arrfec2[2],10),parseInt(arrfec2[1],10)-1,parseInt(arrfec2[0],10));

	// Resta fechas y redondea
	var diferencia = date2.getTime() - date1.getTime();
	var dias = Math.floor(diferencia / (1000 * 60 * 60 * 24));
	return dias;
}

function isDefined(variable) {
    return (typeof(window[variable]) == "undefined")?  false: true;
}

function isNumeric(sText){
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;
   if (sText.length==0)
     IsNumber = false;
   for (i = 0; i < sText.length && IsNumber == true; i++){
      Char = sText.charAt(i);
      if (ValidChars.indexOf(Char) == -1){
         IsNumber = false;
      }
   }
   return IsNumber;
}

