//---------------------------------------------------------------------------
// Fichero: fun_comun.js
// Objeto: Funciones javascript comunes para las páginas de la aplicación.
// Autor: Doo2Web Solutions
// (c) Copyright 2005, Doo2Web Solutions, S.L. Todos los derechos reservados.
// Para cualquier duda, pueden dirigirse a soporte@doo2web.com
//---------------------------------------------------------------------------
//-abrirv-//Esta función abre una nueva ventana
function abrirv(pagina,nombre,w,h){
	var opciones='';
	var scrol = '';
	var top = (screen.height-h)/2;
	var left = (screen.width-w)/2;
	if (screen.height < h || screen.width < w) {
		scrol = 'yes';
			if (screen.height < h) {
					h = screen.height - 50;				
			} else {
				h = h + 20;
			}
			if (screen.width < w) {
					w = screen.width - 20;				
			}
		top = 0;
		left = 0;
	} else {
		scrol = 'no';
	}
	opciones = 'scrollbars=1,resizable=yes,width='+w+',height='+h+',top='+top+',left='+left+'';
	window.open (pagina,nombre,opciones);
}
function ventanacurso(pagina,nombre,w,h){
	var top = (screen.height-h)/2;
	var left = (screen.width-w)/2;
	var opciones='';
	var scrol = '';
	opciones = 'scrollbars=1,resizable=no,width='+w+',height='+h+',top='+top+',left='+left+'';
	window.open (pagina,nombre,opciones);
}

function ventanademo(){
	var w = '569';
	var h = '400';
	var pagina = 'demo_ema.html';
	var nombre = 'demo';
	var opciones='';
	var scrol = '';
	var top = (screen.height-h)/2;
	var left = (screen.width-w)/2;
	if (screen.height < h || screen.width < w) {
		scrol = 'yes';
			if (screen.height < h) {
					h = screen.height - 50;				
			} else {
				h = h + 20;
			}
			if (screen.width < w) {
					w = screen.width - 20;				
			}
		top = 0;
		left = 0;
	} else {
		scrol = 'no';
	}
	opciones = 'scrollbars=1,resizable=yes,width='+w+',height='+h+',top='+top+',left='+left+'';
	window.open (pagina,nombre,opciones);
}
//-abrirvEva// Esta función abre una evaluación en una ventana nueva
function abrirvCur(curID) {
	var curso_path;
	if (curID.length == 1) { curso_path = '0' + curID; } else { curso_path = curID; }
	abrirv('cursos/' + curso_path + '/index.php','curVentana',screen.width,screen.height);
}

//-abrirvCronogramas// Esta función abre un tema en una nueva ventana
	function abrirvCronograma(curID,temID) {
		abrirv('cronogramas.php?CurID='+curID+'&TemID=' + temID,'temCrono',800,600);
	}

//-abrirvEva// Esta función abre una evaluación en una ventana nueva
function abrirvEva(curID,temID) {
	var curso_path;
	if (curID.length == 1) { curso_path = '0' + curID; } else { curso_path = curID; }
	abrirv('cursos/' + curso_path + '/index.php?eva=1&tID=' + temID,'evaVentana',800,600);
}

//-abrirvTema// Esta función abre un tema en una nueva ventana
function abrirvTema(curID,temID) {
	var curso_path;
	if (curID.length == 1) { curso_path = '0' + curID; } else { curso_path = curID; }
	abrirv('cursos/' + curso_path + '/index.php?vertema=1&tID=' + temID,'temVentana',screen.width,screen.height);
}

//-cambia_flecha_menu//
function cambia_flecha_menu(img,EntID) {
	var id = eval(EntID);
	myarray = img.src.split ("/");
	if (myarray[myarray.length-1]  == "menu_flecha_dcha_" + id + ".gif") {
		img.src = "img/menu_flecha_abajo_" + id + ".gif";
	} else {
		img.src = "img/menu_flecha_dcha_" + id + ".gif";
	}
}

//-cuentaCaracteres// Esta función cuenta (y limita) los caracteres de un campo
function cuentaCaracteres(campo,campoCont,maxlimit) {
	// Si excede el límite...
	if (campo.value.length > maxlimit){
		campo.value = campo.value.substring(0, maxlimit);
	}
	// En caso contrario actualizamos el valor del campo contador
	else {
		campoCont.value = maxlimit - campo.value.length;
	}
}
//-compruebaCCC// Esta función comprueba el valor de un select
function compruebaCCC(valor) {
	
	if (valor == 4 || valor == 7 || valor == 8){
		document.getElementById('ccc').style.display="";
	} else {
 		document.getElementById('ccc').style.display="none";
	}
}
//Esta función muestra la fecha -:cliente:- (formato dd de mmmm de aaaa)
function muestraFecha() {
       var hoy = new Date();
       var a_o = hoy.getFullYear();
       var fecha = hoy.getDate();
       dias = new Array("Domingo","Lunes","Martes","Mi&eacute;rcoles","Jueves","Viernes","S&aacute;bado");
       meses = new Array("enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre");
	document.writeln(dias[hoy.getDay()] + ", " + fecha + " de " + meses[hoy.getMonth()] + " de " + a_o);
}
//-estaVacio-//Esta función comprueba si un campo está vacío
function estaVacio(campo, etiqueta) {
	if (campo.value.length == 0) {
		alert("Atención, el valor del campo requerido (" + etiqueta.toUpperCase() + ") no puede estar vacío.");
		campo.focus();
		return true;
	}
	return false;
}
//-longitud-//Esta función comprueba la longitud de cualquier campo
function tieneLongitud(campo, etiqueta, valor1, valor2) {
    if (!(campo.value.length == 0))
	{
		if (campo.value.length < valor1 || campo.value.length > valor2) {
			if (valor1 == valor2)
			{
			alert("Atención, el valor del campo requerido (" + etiqueta.toUpperCase() + ") tiene que tener " + valor1 + " caracteres.");
			}
			else {
			alert("Atención, el valor del campo requerido (" + etiqueta.toUpperCase() + ") tiene que tener entre " + valor1 + " y " + valor2 + " caracteres.");
			}

			campo.focus();
			return true;
		}
		return false;
	}
	return false;
}
//-cif - nif valido //Esta función comprueba que el cif se valido (8 numeros y una letra)
function cif_valido (campo, etiqueta) {
    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;
	}
		alert("Atención, el valor del campo requerido (" + etiqueta.toUpperCase() + ") debe ser correcto.");
		campo.focus();
		return true;	
}

//-noNumerico-//Estas funciones comprueban si el campo es numérico
function noNumerico(campo, etiqueta) {
	if (!esNum(campo.value)) {
		// alert("Atención, el valor del campo requerido " + etiqueta.toUpperCase() + " debe ser numérico.");
		// Modificado por hviera (30/03/2006)
		alert("Atención, el valor del campo requerido " + etiqueta.toUpperCase() + " debe ser un número entero no negativo.");
		campo.focus();
		return true;
	}
	return false;
}
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);
}
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;
	}
}
function esComilla(c){
	if ((c!='\'') && (c!='\"')) {
		return false;
	} else {
		return true;
	}
}
//-noNumerico-//Estas funciones comprueban si el campo es numérico con ,
function noNumerico2(campo, etiqueta) {
	if (!esNum2(campo.value) || tiene2Comas(campo.value)) {
		alert("Atención, el valor del campo requerido " + etiqueta.toUpperCase() + " debe ser numérico.");
		campo.focus();
		return true;
	}
	return false;
}
function esNum2(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 (esNumero2(subdato)==false) {
				vabien = false;
			}
		}
		return(vabien);
}
function esNumero2(d){
	if ((d!='0') && (d!='1') && (d!='2') && (d!='3') && (d!='4') && (d!='5') &&
		(d!='6') && (d!='7') && (d!='8') && (d!='9') && (d!='.') && (d!='-')) {
		return false;
	}else{
		return true;
	}
}
//-tiene2Comas-//Esta función comprueban que no se teclee más de 1 coma (,)
function tiene2Comas(campo) {
	var numchars=0;
	var numcomas=0;
	numchars=eval(campo.length);
	for (var i=0;i<numchars;i++){
		subdato = campo.substring(i,i+1);
		if (subdato==".") {
			numcomas++;
		}
	}
	if (numcomas >=2) {
		return true;
	} else {
		return false;
	}
}

//-esFechaValida-//Esta función comprueba si una fecha es válida
function esFechaValida(CampoDia, CampoMes, CampoAnno, etiqueta) {
	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) {
		alert ("Atención, la fecha no es válida. Campo: "+ etiqueta.toUpperCase() + ".");
		CampoDia.focus();
		return false;
	}
	if (mes > 12) {
		alert ("Atención, el mes no es correcto. Campo: "+ etiqueta.toUpperCase() + ".");
		campo.focus();
		return false;
	}
	if (anno < 1950) {
		alert ("Atención, el año debe ser posterior a 1950. Campo: "+ etiqueta.toUpperCase() + ".");
		campo.focus();
		return false;
	}
	return true;
}
//-esFechaValida2-//Esta función comprueba si una fecha es válida
function esFechaValida2(campo, etiqueta) {
	var sFecha = campo.value;
	var dia = parseInt(sFecha.substring(0,2));
	var mes = parseInt(sFecha.substring(3,5));
	var anno = parseInt(sFecha.substring(6,10));
	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) {
		alert ("Atención, la fecha no es válida. Campo: "+ etiqueta.toUpperCase() + ".");
		campo.focus();
		return false;
	}
	if (mes > 12) {
		alert ("Atención, el mes no es correcto. Campo: "+ etiqueta.toUpperCase() + ".");
		campo.focus();
		return false;
	}
	if (anno < 1950) {
		alert ("Atención, el año debe ser posterior a 1950. Campo: "+ etiqueta.toUpperCase() + ".");
		campo.focus();
		return false;
	}
	return true;
}

//-sonIguales-//Esta función comprueba que la nueva password sea igual las dos veces
function sonIguales(pass1, pass2) {
	if (pass1.value == pass2.value) {
		return true;
	} else {
		alert("ERROR: La Contraseña no se ha tecleado igual las 2 veces." );
		return false;		
	}
}
//Esta función comprueba si es una dirección valida
	function noEsMail(campo, etiqueta) {
		var sArroba=/^(.+)@(.+)$/;
		if (campo.value.match(sArroba)==null) {
			alert("ERROR: Campo incorrecto (" + 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) {
			alert("ERROR: Campo incorrecto (" + etiqueta.toUpperCase() + ").");
			campo.focus();
			return true;
		}
		return false;
	}
function transforma(str) {
      str=(str.split(",")).join("."); 
	  return str;
}
function destransforma(str) {
      str=(str.split(".")).join(","); 
	  return str;
}
//-imprimir-//Esta función envía la ventana a imprimir
function imprimir(sFrame){
	if (!window.print){
		alert("Para imprimir la página necesita un navegador versión 4 o superior.");
		return false;
	} else {
		top.frames(sFrame).focus();
		top.frames(sFrame).print();
	}
}

function mostrarResultado(mostrar)	{
	//0: no mostramos el resultado, 1: mostramos
	var contDiv;
	if (mostrar == 0){
		if (document.layers) {
			contDiv = document.layers['vacio'].text;
		} else if (document.all) {
			contDiv = document.all['vacio'].innerHTML;
		} else if (document.getElementById) {
			contDiv = document.getElementById('vacio').innerHTML;		
		}
	}
	if (mostrar == 1){
		if (document.layers) {
			contDiv = document.layers['resultadosbkp'].text;
		} else if (document.all) {
			contDiv = document.all['resultadosbkp'].innerHTML;
		} else if (document.getElementById) {
			contDiv = document.getElementById('resultadosbkp').innerHTML;		
		}
	}
  	llenarcapa ('resultados', contDiv);
}

// Función de creación de contenido de la capa
function llenarcapa (id, html) {
  if (document.layers) {
    var l = document[id];
    l.document.open();
    l.document.write(html);
    l.document.close();
  }
  else if (document.all) {
    document.all[id].innerHTML = html;
  }
  else if (document.getElementById) {
    var range = document.createRange();
    var l = document.getElementById(id);
    while (l.hasChildNodes())
      l.removeChild(l.firstChild);
    range.setStartAfter(l);
    var docFrag = range.createContextualFragment(html)
    l.appendChild(docFrag);
  }
}

//-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;
						}
                      }
              }
      }
}

function destransforma(str) {
      str=(str.split(".")).join(","); 
	  return str;
}

//-- Esta función muestra un elemento dado
function Show(div){ 
	document.getElementById(div).style.display="";
}
//-- Esta función oculta un elemento dado
function Hide(div){ 
	document.getElementById(div).style.display="none";
}
// Esta función muestra u oculta un elemento dado
function ShowHide(div){ 
	if (document.getElementById(div).style.display=="none"){
		document.getElementById(div).style.display="";
	}
		else{
		document.getElementById(div).style.display="none";
	} 
}

//- validaContactaForm -// Esta función valida el formulario para enviar un mensaje a tutor o alumno antes de enviarlo
function validaContactaForm(formulario,destPerID) {
	// Envíos a tutores
	if (destPerID = 2) { 
		if (estaVacio(formulario["toID"], "Tutor") || 
			estaVacio(formulario["subject"], "Asunto") || 
			estaVacio(formulario["message"], "Mensaje")) { return false; } else { return true; }
	}
	// Envíos a alumnos
	else {
		if (estaVacio(formulario["toID"], "Alumno") || 
			estaVacio(formulario["subject"], "Asunto") || 
			estaVacio(formulario["message"], "Mensaje")) { return false; } else { return true; }
	}
}

//- validaMasInfoCurForm -// Esta función valida el formulario para enviar mas información acerca de un curso a un usuario
function validaMasInfoCurForm(formulario) {
		if (estaVacio(formulario["nombre"], "Nombre") || 
			estaVacio(formulario["telefono"], "Teléfono") || 
			estaVacio(formulario["email"], "Email") || noEsMail(formulario["email"],"Email")) { return false; } else { return true; 
		}
		if (estaVacio(formulario["nombre"], "Nombre") || 
			estaVacio(formulario["telefono"], "Teléfono") || 
			estaVacio(formulario["email"], "Email") || noEsMail(formulario["email"],"Email")) { return false; } else { return true; 
		}
}

//- verCurso -// Esta función envía el formulario para ver más info de un curso
function verCurso(frmID,CurID) {
	document.forms["frm" + frmID + "VerCur" + CurID].submit();
}


<!-- FUNCIONES AJAX -->
function EnvioAjax (method, divContenedor, queryString, bAsync, bMostrarImgCarga, msgCarga)
{
	var ajax = false;
	var strResponse = "";
	
 	// Creamos un nuevo objeto XmlHttpRequest
	try {
 		ajax = new ActiveXObject("Msxml2.XMLHTTP");
 	} catch (e) {
 		try {
 			ajax = new ActiveXObject("Microsoft.XMLHTTP");
 		} catch (E) {
 			ajax = false;
 		}
  	}
	if (!ajax && typeof XMLHttpRequest!='undefined') {
 		ajax = new XMLHttpRequest();
	}

	if (ajax != null) {
		ajax.open(method, "IBSA_EMA_AJAX.php", bAsync);
		ajax.onreadystatechange=function() {
			if (ajax.readyState>=1 && ajax.readyState<4) {
				if (bMostrarImgCarga == true) {
					strResponse = "<img src='img/ajax-loader.gif' border='0'>";
				}
				if (msgCarga != false) {
					strResponse = strResponse + " <span style='color:gray;'>" + msgCarga + "</span>";
				}
				document.getElementById(divContenedor).innerHTML = strResponse;
			}
			else if (ajax.readyState==4) {
				if(ajax.status==200){
					document.getElementById(divContenedor).innerHTML = ajax.responseText;
					delete ajax;
					ajax = null;
				}
				else if(ajax.status==404) {
					document.getElementById(divContenedor).innerHTML = "La direccion no existe";
				}
				else {
					document.getElementById(divContenedor).innerHTML = "Error: ".ajax.status;
				}
			}
		}
		ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		ajax.setRequestHeader("encoding", "ISO-8859-1");
		ajax.send(queryString)
	}
}
<!-- FIN FUNCIONES AJAX -->