//---------------------------------------------------------------------------
// Fichero: fun_comun.js										
// Objeto : Funciones javascript comunes para las páginas de la aplicación						
// Creado : 07/04/2006														
// Autor  : Mice Multimedia, S.L.											
// (c) Copyright 2006, Mice Multimedia, S.L. Todos los derechos reservados.		
//---------------------------------------------------------------------------

// Idiomas
// 1 - Español
// 2 - Inglés

//-abrirvImg-// Esta función abre una nueva ventana autoresizable al contenido
function abrirvImg(imageURL,imageTitle){
	// Horizontal and vertical position for the popup
	PositionX = 15;
	PositionY = 15;
	// These value approximately 20 pixels greater than the
	// size of the largest image to be used (needed for Netscape)
	defaultWidth  = 444;
	defaultHeight = 560;
	// Autoclose true to have the window close automatically
	// Autoclose false to allow multiple popup windows
	var AutoClose = true;
	// Background color of the popup window
	var bgColor = "19302D";
	
	if (parseInt(navigator.appVersion.charAt(0))>=4){
	var isNN=(navigator.appName=="Netscape")?1:0;
	var isIE=(navigator.appName.indexOf("Microsoft")!=-1)?1:0;}
	var optNN='scrollbars=no,width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY;
	var optIE='scrollbars=no,width=150,height=100,left='+PositionX+',top='+PositionY;
	if (isNN){imgWin=window.open('about:blank','',optNN);}
	if (isIE){imgWin=window.open('about:blank','',optIE);}
	with (imgWin.document){
	writeln('<html><head><title>Cargando...</title><style>body{margin:0px;}</style>');writeln('<sc'+'ript>');
	writeln('var isNN,isIE;');writeln('if (parseInt(navigator.appVersion.charAt(0))>=4){');
	writeln('isNN=(navigator.appName=="Netscape")?1:0;');writeln('isIE=(navigator.appName.indexOf("Microsoft")!=-1)?1:0;}');
	writeln('function reSizeToImage(){');writeln('if (isIE){');writeln('window.resizeTo(100,100);');
	writeln('width=100-(document.body.clientWidth-document.images[0].width);');
	writeln('height=100-(document.body.clientHeight-document.images[0].height);');
	writeln('window.resizeTo(width,height);}');writeln('if (isNN){');       
	writeln('window.innerWidth=document.images["Img"].width;');writeln('window.innerHeight=document.images["Img"].height;}}');
	writeln('function doTitle(){document.title="'+imageTitle+'";}');writeln('</sc'+'ript>');
	if (!AutoClose) writeln('</head><body bgcolor=000000 scroll="no" onload="reSizeToImage();doTitle();self.focus()">')
	else writeln('</head><body bgcolor='+ bgColor +' scroll="no" onload="reSizeToImage();doTitle();self.focus()" onblur="self.close()">');
	writeln('<img name="Img" src='+imageURL+' style="display:block"><!-- Analytics -->
<? include ('../inc/analytics.inc.php'); ?>
<!-- Fin Analytics -->
</body>
</html>');
	close();
	}
}

//-cif - nif valido //Esta función comprueba que el cif se valido (8 numeros y una letra)
function cif_valido (campo, etiqueta, idioma) {
   
    if ( 
	(esNum (campo.value.substring(0,8)) || esNum (campo.value.substring(1,8)) ) 
	&& (!esNum (campo.value.substring(0,1)) || !esNum (campo.value.substring(8))) 
	&& !esComilla (campo.value.substring(0,1)) && !esComilla (campo.value.substring(8)))
	{
	return false;
	}
		if (idioma == 1) {
			alert("Atención, el valor del campo requerido (" + etiqueta.toUpperCase() + ") debe ser correcto.\nFormato: 8 números 1 letra, o bien: 1 letra 8 números");
		}
		else if (idioma == 2) {
			alert("Attention, required field (" + etiqueta.toUpperCase() + ") value is incorrect.\nFormat: Either 8 numeric digits and 1 letter or 1 letter and 8 numeric digits.");
		}
		campo.focus();
		return true;
}

//-confirma-// Esta función pide confirmación antes de enviar un form
function confirma(formulario, msg) {
	var msg;
	msg = confirm(msg);
	if (msg == true) {
		formulario.submit();
	}
	else {
		return false;
	}
}

//-esComilla--//
function esComilla(c){
	if ((c!='\'') && (c!='\"')) {
		return false;
	} else {
		return true;
	}
}

//-esFechaMayorQueFecha-//
function esFechaMayorQueFecha(fecha1, fecha2) {
	var dia1 = fecha1.value.substring(0,2);
	var mes1 = fecha1.value.substring(3,5);
	var anno1 = fecha1.value.substring(6,10);
	var dia2 = fecha2.value.substring(0,2);
	var mes2 = fecha2.value.substring(3,5);
	var anno2 = fecha2.value.substring(6,10);
	
	if (anno1<anno2 ||
			anno1==anno2 && mes1<mes2 ||
			anno1==anno2 && mes1==mes2 && dia1 <= dia2)
	{
		return false;
	}
	else
	{
		return true;
	}
	return true;
}

//-esFechaMenorQueFecha-
function esFechaMenorQueFecha(fecha1, fecha2) {
	var dia1 = fecha1.value.substring(0,2);
	var mes1 = fecha1.value.substring(3,5);
	var anno1 = fecha1.value.substring(6,10);
	var dia2 = fecha2.value.substring(0,2);
	var mes2 = fecha2.value.substring(3,5);
	var anno2 = fecha2.value.substring(6,10);
	
	if (anno1<anno2 ||
			anno1==anno2 && mes1<mes2 ||
			anno1==anno2 && mes1==mes2 && dia1 < dia2)
	{
		return true;
	}
	else
	{
		return false;
	}
	return true;
}

//-esFechaValida-//Esta función comprueba si una fecha es válida
function esFechaValida(CampoDia, CampoMes, CampoAnno, etiqueta, idioma) {
	var dia = parseInt(CampoDia.options[CampoDia.selectedIndex].value);
	var mes = parseInt(CampoMes.options[CampoMes.selectedIndex].value);
	var anno = parseInt(CampoAnno.options[CampoAnno.selectedIndex].value);
	var diasmes = 31;
	switch (mes) {
		case 4: case 6: case 9: case 11:
			diasmes = 30;
			break;
		case 2:
			if ((anno % 4 == 0 && anno % 100 != 0) || anno % 400 == 0) {
				diasmes = 29;
			}
			else {
				diasmes = 28;
			}
			break;
		default:
			diasmes = 31;
	}
	if (dia > diasmes) {
		if (idioma == 1) { // Español
			alert ("Atención, la fecha no es válida. Campo: "+ etiqueta.toUpperCase() + ".");
		}
		else if (idioma == 2) { // Inglés
			alert ("Attention, date is not valid. Field: "+ etiqueta.toUpperCase() + ".");
		}
		CampoDia.focus();
		return false;
	}
	if (mes > 12) {
		if (idioma == 1) { // Español
			alert ("Atención, el mes no es correcto. Campo: "+ etiqueta.toUpperCase() + ".");
		}
		else if (idioma == 2) { // Inglés
			alert ("Attention, month is not valid. Field: "+ etiqueta.toUpperCase() + ".");
		}
		campo.focus();
		return false;
	}
	if (anno < 1950) {
		if (idioma == 1) { // Español
			alert ("Atención, el año debe ser posterior a 1950. Campo: "+ etiqueta.toUpperCase() + ".");
		}
		else if (idioma == 2) { // Inglés
			alert ("Attention, year must be greater than 1950. Field: "+ etiqueta.toUpperCase() + ".");
		}
		campo.focus();
		return false;
	}
	return true;
}

//-esNum-//
function esNum(dato){
	var numchars=0;
	var vabien=true;
	var subdato;
	
		numchars=eval(dato.length);
		for (var c=0;c<numchars;c++){
			subdato = dato.substring(c,c + 1);
			if (esNumero(subdato)==false) {
				vabien = false;
			}
		}
		return(vabien);
}

//-esNumero-//
function esNumero(d){
	if ((d!='0') && (d!='1') && (d!='2') && (d!='3') && (d!='4') && (d!='5') &&
		(d!='6') && (d!='7') && (d!='8') && (d!='9')) {
		return false;
	}else{
		return true;
	}
}

//-estaVacio-//Esta función comprueba si un campo está vacío
function estaVacio(campo, etiqueta, idioma) {
	if (campo.value.length == 0) {
		if (idioma == 1) {
			alert("Atención, el valor del campo requerido (" + etiqueta.toUpperCase() + ") no puede estar vacío.");
		}
		else if (idioma == 2) {
			alert("Attention, required field (" + etiqueta.toUpperCase() + ") can not be empty.");
		}
		campo.focus();
		return true;
	}
	return false;
}

//-noEsMail-// Esta función comprueba si es una dirección valida
function noEsMail(campo, etiqueta, idioma) {
	var sArroba=/^(.+)@(.+)$/;
	if (campo.value.match(sArroba)==null) {
		if (idioma == 1) {
			alert("ERROR: Campo incorrecto (" + etiqueta.toUpperCase() + ").");
		}
		else if (idioma == 2) {
			alert("ERROR: Invald field (" + etiqueta.toUpperCase() + ").");
		}
		campo.focus();
		return true;
	}	
	var sPunto=campo.value.match(sArroba)[2];
	var iPunto=sPunto.length;
	var encontrado=0;
	for (i=0;i<iPunto;i++) {
		if (sPunto.charAt(i)==".") {
			encontrado = 1;
		}
	}
	if (!encontrado) {
		if (idioma == 1) {
			alert("ERROR: Campo incorrecto (" + etiqueta.toUpperCase() + ").");
		}
		else if (idioma == 2) {
			alert("ERROR: Invalid field (" + etiqueta.toUpperCase() + ").");
		}
		campo.focus();
		return true;
	}
	return false;
}

//-reordenar-//Esta función reordena los selects ()
function reordenar(eSelect, iCurrentField, numSelects) {
    var eForm = eSelect.form;
    var iNewOrder = eSelect.selectedIndex + 1;
	var iNewValor = eSelect.selectedIndex + 1;
      var iPrevOrder;
      var positions = new Array(numSelects);
      var ix;
      for (ix = 0; ix < numSelects; ix++)
      {
              positions[ix] = 0;
      }
      for (ix = 0; ix < numSelects; ix++)
      {
              positions[eSelect.form["FormPosition" + ix].selectedIndex] = 1;
      }
      for (ix = 0; ix < numSelects; ix++)
      {
              if (positions[ix] == 0)
              {
                      iPrevOrder = ix + 1;
                      break;
              }
      }
      if (iNewOrder != iPrevOrder)
      {
              var iInc = iNewOrder > iPrevOrder? -1:1
              var iMin = Math.min(iNewOrder, iPrevOrder);
              var iMax = Math.max(iNewOrder, iPrevOrder);
              for (var iField = 0; iField < numSelects; iField++)
              {
                      if (iField != iCurrentField)
                      {
                              if (eSelect.form["FormPosition" + iField].selectedIndex + 1 >= iMin && eSelect.form["FormPosition" + iField].selectedIndex + 1<= iMax)
                              {
						       eSelect.form["FormPosition" + iField].selectedIndex += iInc;
						}
                      }
              }
      }
}


//-selectHayAlgunoSeleccionado-//Esta función comprueba que se seleccione una opción
function selectHayAlgunoSeleccionado(combo) {
	if (combo.selectedIndex==0 || combo.value == "0") {
		return false;
	}
	return true;
}


//-sonIguales-//Esta función comprueba que la password sea igual las dos veces
function sonIguales(pass1, pass2, idioma) {
	if (pass1.value == pass2.value) {
		return true;
	} else {
		if (idioma == 1) {
			alert("ERROR: La contraseña no se ha tecleado igual las 2 veces." );
		}
		else if (idioma == 2) {
			alert("ERROR: Passwords typed are not equal." );
		}
		return false;		
	}
}

//-tieneLongitud-//Esta función comprueba la longitud del usuario y el password
function tieneLongitud(campo, etiqueta, valor1, valor2, idioma) {
    if (!(campo.value.length == 0))
	{
		if (campo.value.length < valor1 || campo.value.length > valor2) {
			if (valor1 == valor2) {
				if (idioma == 1) {
					alert("Atención, el valor del campo requerido (" + etiqueta.toUpperCase() + ") tiene que tener " + valor1 + " caracteres.");
				}
				else if (idioma == 2) {
					alert("Attention, required field  (" + etiqueta.toUpperCase() + ") must have " + valor1 + " characters.");
				}
			}
			else {
				if (idioma == 1) {
					alert("Atención, el valor del campo requerido (" + etiqueta.toUpperCase() + ") tiene que tener entre " + valor1 + " y " + valor2 + " caracteres.");
				}
				else if (idioma == 2) {
					alert("Attention, required field (" + etiqueta.toUpperCase() + ") must have a value of between " + valor1 + " and " + valor2 + " characters.");
				}
			}

			campo.focus();
			return true;
		}
		return false;
	}
	return false;
}

function ocultaTodasRazones(){
	var i = 1;
	var myContainer = document.getElementById(i);
	while(myContainer != undefined){
		ocultaRazon(myContainer);
		i++;
		myContainer = document.getElementById(i);
	}
}

function ocultaRazon(id){
	id.className = "cnone";
}

function muestraRazon(id){
	id.className = "cblock";
}

function activaRazon(numQ){
	var myContainer = document.getElementById(numQ);
	if(myContainer == undefined){
		alert("ERROR: No existe el indicador \"q" + numQ + "\"");
		return;
	}
	if(myContainer.className == "cnone"){
		ocultaTodasRazones();
		muestraRazon(myContainer);
	}else{
		ocultaTodasRazones();
	}
}
