var bases_leidas=0;

function comprobar_enviar(nombreform)
{
	if (bases_leidas==0)
		alert ('Para poder continuar con la tramitación es necesario que abra el documento relativo a las bases de la convocatoria');
	else
	{
		if (nombreform=='gestidi_entidad')
			document.gestidi_entidad.submit();
		else
			document.gestidi_solicitante.submit();
	}
}

function validar_dni(nif, objeto){
	var let =nif.charAt(nif.length-1);
	    if (!isNaN(let))
 			{
		  alert('El formato del NIF ha de ser 99999999Z')
		  return false
		 }
	var dni=nif.substring(0,nif.length-1);
	var cadena="TRWAGMYFPDXBNJZSQVHLCKET";
    var posicion = dni % 23;
    var letra = cadena.substring(posicion,posicion+1);
if(letra.toUpperCase() != let.toUpperCase()){
	alert('El NIF introducido no es correcto');
	objeto.value='';
}

}
function validar_telefono(tfno, objeto){
	strreg =/^[0-9]{2,3}-? ?[0-9]{6,7}$/;

	var primero = tfno.charAt(0);
	//No se considera la longitud del telefono de 9 caracteres por poder ser una centralita.
	if(!strreg.test(tfno)){
		alert('El teléfono/fax introducido no es correcto.');
 		objeto.value='';
 	}
}

 function validar_cp(cp, objeto){
	strreg =/^([1-9]{2}|[0-9][1-9]|[1-9][0-9])[0-9]{3}$/;
	if(!strreg.test(cp)){
		alert('El código postal introducido no es correcto.');
 		objeto.value='';
 	}
}
 function validar_mail(email, objeto){
	strreg =/[\w-\.]{3,}@([\w-]{2,}\.)*([\w-]{2,}\.)[\w-]{2,4}/;
	if(!strreg.test(email)){
		alert('El email introducido no es correcto.');
 		objeto.value='';
 	}
}

function validar_anno(valor, objeto){
	//var hoy = new Date();
	//var valor2 = document.gestidi_solicitante.f_fin.value;
	//var anno=parseInt(hoy.getYear());
	strreg = /^(?:\+|-)?\d+$/;
	if(!strreg.test(valor) || valor<1900 || valor>2100 ){
		alert('El valor introducido no es un año valido.');
		objeto.value='';
	}
	else if(valor>2010 ){
		alert('No puede introducir un año posterior al año actual.');
		objeto.value='';
	}
	/*else{
		if(valor2 != ''  && valor2 < valor) {
		alert('La fecha de fin ha de ser mayor o igual a la de inicio.');
		objeto.value='';
		}
	}*/
}

function validar_enteroporsitivo(valor, objeto){
	strreg = /^(?:\+|-)?\d+$/;
	if(!strreg.test(valor) || valor<0 ){
		alert('El valor introducido no es un número valido.');
		objeto.value='';
	}

}


/*function validar_fin(valor, objeto){
	var hoy = new Date();
	var valor2 = document.gestidi_solicitante.f_inicio.value;
	strreg =/^(?:\+|-)?\d+$/;
	if(!strreg.test(valor) || valor<0 || valor > hoy.getYear()){
		alert('El valor introducido no es un año válido.' + hoy.getFullYear());
		objeto.value='';
	}else{
		if(valor2 != ''  && valor2 > valor) {
		alert('La fecha de fin ha de ser mayor o igual a la de inicio.');
		objeto.value='';
		}
	}
}*/

/*function validar_nie(nif, objeto){
	var primero = nif.charAt(0);
	var mayuscula = primero.toUpperCase();
	var cadena="TRWAGMYFPDXBNJZSQVHLCKET";
	var ultimo = nif.substring(1,nif.length);
	srtregentero =/^(?:\+|-)?\d+$/;
	if(!(srtregentero.test(ultimo) && ultimo.length==8)|| cadena.indexOf(mayuscula)<0 ){
 		alert('El NIE escrito no es crrecto el formato ha de ser Z99999999');
 		objeto.value='';
 	}
}
*/
function es_nie_o_nif(nif, objeto){
   var primero = nif.charAt(0);
 	srtreg =/^(?:\+|-)?\d+$/;
 	if(srtreg.test(primero)){
 		validar_dni(nif, objeto);
 	}
 	/*else{
 		validar_nie(nif, objeto);
 	}*/
}


function habilitar_siguiente1(){
	var nif = document.gestidi_solicitante.nif.value;	
	
	//var foto = document.gestidi_solicitante.fotografia.value;
	var foto=imagensubidaok;
	var apellidos = document.gestidi_solicitante.apellidos.value;
	var nombre = document.gestidi_solicitante.nombre.value;
	var lugar_naci = document.gestidi_solicitante.lugarnacimiento.value;
	var fecha_naci = document.gestidi_solicitante.fechanacimiento.value;	
	var poblacion = document.gestidi_solicitante.poblacion.value;
	var provincia = document.gestidi_solicitante.provincia.options[document.gestidi_solicitante.provincia.selectedIndex].value;
	var pais = document.gestidi_solicitante.pais.options[document.gestidi_solicitante.pais.selectedIndex].value;
	//var pais='hoola';
	var telefono = document.gestidi_solicitante.telefono.value;
	var email = document.gestidi_solicitante.email.value;
	var confirmaremail = document.gestidi_solicitante.confirmaremail.value;

	if(foto==0)
		alert('Debe seleccionar una fotografía');
	else if (apellidos!='' && nombre!='' && lugar_naci!='' && fecha_naci!='' && nif!='' && poblacion!='' && provincia!='' && pais!='' && telefono!='' && email != '' && confirmaremail != '')
	{
		if (email != confirmaremail)
				alert('Los emails no coinciden');
		else
			mostrardiv('paso2');
	}else{
		alert('Debe rellenar todos los campos obligatorios (los que contienen (*))');
		//document.gestidi_solicitante.siguiente1.disabled =true;
	}
	paso1++;
}

function habilitar_pronto(){
alert(paso1);
if(paso1>6){
	habilitar_siguiente1();
}

}

function pulsar(e) {
	tecla=(document.all) ? e.keyCode : e.which;
  if(tecla==13 &&  document.getElementById('paso1').style.display != 'none'){
  habilitar_siguiente1();
  	return false;
	}
}

function mostrarocultardiv (div,estado)
{
	document.getElementById(div).style.display=estado;
	bases_leidas=1;
}

function mostrarocultarresp ()
{
	if (document.getElementById('MismaResPro').selectedIndex==0)
	{
		document.getElementById('tbl_respons_pro').style.display='none';
		document.getElementById('res_pro_nombre').value='';
		document.getElementById('res_pro_apellidos').value='';
		document.getElementById('res_pro_puesto').value='';
		document.getElementById('res_pro_departamento').value='';
		document.getElementById('res_pro_direccion').value='';
		document.getElementById('res_pro_telefono').value='';
		document.getElementById('res_pro_fax').value='';
		document.getElementById('res_pro_email').value='';
	}
	else
		document.getElementById('tbl_respons_pro').style.display='';
}


function aceptarlopd(){
	if (document.gestidi_solicitante.aceptalopd.checked==true){
			document.gestidi_solicitante.enviarsolicitud.disabled=false;
	}else{
			document.gestidi_solicitante.enviarsolicitud.disabled=true;
	}
}

function mostrarffin(nombrediv)
{
	if (document.getElementById('Cursa'+nombrediv).selectedIndex==0)
	{
		document.getElementById('DivCursa'+nombrediv).style.display='none';
		document.getElementById(nombrediv).value='';
	}
	else
		document.getElementById('DivCursa'+nombrediv).style.display='';
}

function mostrarpertenecegrupo(nombrediv)
{
	if (document.getElementById('cmb'+nombrediv).selectedIndex==0)
	{
		document.getElementById('div'+nombrediv).style.display='none';
		document.getElementById('txt'+nombrediv).value='';
	}
	else
		document.getElementById('div'+nombrediv).style.display='';
}

function mostrardiv(paso)
      {
	//alert ('hola 1');
	
	
	document.getElementById('pasox').style.display = 'none';
        document.getElementById('pestana1').className="";
        document.getElementById('pestana2').className="";
        document.getElementById('pestana3').className="";
        document.getElementById('pestana4').className="";
        document.getElementById('pestana5').className="";
        document.getElementById('pestana6').className="";

	//alert ('hola 2');
	
        if (paso=='paso1')
          document.getElementById('pestana1').className="seccionactiva";
        else if (paso=='paso2')
          document.getElementById('pestana2').className="seccionactiva";
        else if (paso=='paso3')
          document.getElementById('pestana3').className="seccionactiva";
        else if (paso=='paso4')
          document.getElementById('pestana4').className="seccionactiva";
        else if (paso=='paso5')
          document.getElementById('pestana5').className="seccionactiva";
        else if (paso=='paso6')
          document.getElementById('pestana6').className="seccionactiva";
	
	//alert ('hola 3');
	
        document.getElementById('paso1').style.display = 'none';
	//alert ('hola 3.1');
        document.getElementById('paso2').style.display = 'none';
	//alert ('hola 3.2');
        document.getElementById('paso3').style.display = 'none';
	//alert ('hola 3.3');
        document.getElementById('paso4').style.display = 'none';
	//alert ('hola 3.4');
        document.getElementById('paso5').style.display = 'none';
	//alert ('hola 3.5');
        document.getElementById('paso6').style.display = 'none';

	//alert ('hola 4');
	
        document.getElementById(paso).style.display = '';
	
	//alert ('hola 5');
      }

      function comprobarextensionimg()
      //vamos a comprobar que el archivo es correcto
      {
	var a = document.gestidi_solicitante.fotografia.value;
	a1 = a.indexOf('.gif');
	a2 = a.indexOf('.jpg');
	a3 = a.indexOf('.png');
	resultado=1;

	if  (!((a1 > 0) || (a2 >0)  || (a3 >0)))
	{
		resultado=0;
		alert ('El archivo no tiene un formato válido. \nPor favor, seleccione una imagen.');
		document.gestidi_solicitante.fotografia.value='';
	}
      } // fin de comprobarextensionimg()


function validar_fecha(cadena, objeto){
  strExpReg = /^(((0[1-9]|[12][0-9]|3[01])([/])(0[13578]|10|12)([/])(\d{4}))|(([0][1-9]|[12][0-9]|30)([/])(0[469]|11)([/])(\d{4}))|((0[1-9]|1[0-9]|2[0-8])([/])(02)([/])(\d{4}))|((29)(\.|-|\/)(02)([/])([02468][048]00))|((29)([/])(02)([/])([13579][26]00))|((29)([/])(02)([/])([0-9][0-9][0][48]))|((29)([/])(02)([/])([0-9][0-9][2468][048]))|((29)([/])(02)([/])([0-9][0-9][13579][26])))$/;

  	if(!strExpReg.test(cadena)){
  		alert('La fecha introducida debe cumplir el siguiente formato: dd/mm/aaaa y ser una fecha verdadera')
  		objeto.value='';
  		objeto.focus();
  	}
  return strExpReg.test(cadena);

}

function mostrar_ramas(uri, action, divid){
$.ajax({
		type: "POST",
		url: uri,
		data: action,
		success: function(msg){
		document.getElementById(divid).innerHTML = msg;
		},
		error: function(xho){
			document.getElementById(divid).innerHTML = "Error:"+xho.responseText;
					}
	});
	}

function habilitar_siguiente2()
{
	//Comprobamos si ha introducido los datos obligatorios
	var cuantos=0;
	var i=0;
	for (i=0;i<100;i++)
	{
		if(document.getElementById("tblTitulac_Grado["+i+"]"))
		{
				cuantos=1;
				i=100;
		}
	}
	if (cuantos==0)
		alert('Para pasar al siguiente paso, al menos debe insertar una titulacion.');
	else
	{	
		//comprobamos si ha escrito algo en TITULACION y se le ha olvidado pasarlos
		var grado = document.gestidi_solicitante.gradotitulacion.options[document.gestidi_solicitante.gradotitulacion.selectedIndex].value;
		var titulacion = document.gestidi_solicitante.titulacion.value;
		var centro = document.gestidi_solicitante.centro.value;
		var f_inicio = document.gestidi_solicitante.f_inicio.value;
		if (grado != '' || titulacion != '' || f_inicio != '' || centro != '')
		{
			
			alert ('No ha guardado los datos de TITULACIÓN. Debe guardarlos o borrarlos antes de continuar.');
		}
		else
		{
			//Comprobamos si ha escrito algo en OTROS ESTUDIOS y se le ha olvidado pasarlos
			if ((document.getElementById("EstRegGrado").value!='') ||
			    (document.getElementById("EstRegTitulo").value!='') ||
			    (document.getElementById("EstRegCentro").value!='') ||
			    (document.getElementById("EstRegFIni").value!=''))
			{
				
				alert ('No ha guardado los datos de OTROS ESTUDIOS. Debe guardarlos o borrarlos antes de continuar.');
			}
			else
			{
				//Comprobamos si ha escrito algo en OTROS DATOS DE INTERES y se le ha olvidado pasarlos
				if ((document.getElementById("OtrEstEstud").value!='') ||
				    (document.getElementById("OtrEstAnno").value!='') ||
				    (document.getElementById("OtrEstDurac").value!=''))
				{
					
					alert ('No ha guardado los datos de OTROS DATOS DE INTERÉS. Debe guardarlos o borrarlos antes de continuar.');
				}
				else
				{
					mostrardiv('paso3');
				}			
			}
		}
	}
}

function habilitar_siguiente3()
{
	var cuantos=0;
	var i=0;
	for (i=0;i<100;i++)
	{
		if(document.getElementById("tblIdioma_Idioma["+i+"]"))
		{
				cuantos=1;
				i=100;
		}
	}
	if (cuantos==0)
	{
		
	}
	else
	{
		//Comprobamos si ha escrito algo en OTROS ESTUDIOS NO REGLADOS y se le ha olvidado pasarlos
		if ((document.getElementById("NoRegCurso").value!='') ||
		    (document.getElementById("NoRegCentro").value!='') ||
		    (document.getElementById("NoRegAnno").value!=''))
		{
			alert ('No ha guardado los datos de OTROS ESTUDIOS NO REGLADOS. Debe guardarlos o borrarlos antes de continuar.');
		}
		else
		{
			//Comprobamos si ha escrito algo en IDIOMAS y se le ha olvidado pasarlos
			var idioma = document.gestidi_solicitante.categoria2.value;
			var nivel = document.gestidi_solicitante.idinivel.value;
	
			if (idioma != '' || nivel)
			{
				alert ('No ha guardado los datos de IDIOMAS. Debe guardarlos o borrarlos antes de continuar.');
			}
			else
			{
				mostrardiv('paso4');
			}
			
		}		
	}

}

function habilitar_siguiente4()
{
	//Comprobamos si ha escrito algo en EXPERIENCIA PROFESIONAL y se le ha olvidado pasarlos
	if ((document.getElementById("ExpPuesto").value!='') ||
	    (document.getElementById("ExpRelacion").value!='') ||
	    (document.getElementById("ExpEmpresa").value!='') ||
	    (document.getElementById("ExpAnno").value!=''))
	{
		alert ('No ha guardado los datos de EXPERIENCIA PROFESIONAL. Debe guardarlos o borrarlos antes de continuar.');
	}
	else
	{
		mostrardiv('paso5');
	}
}		


function validar_paso5(){
	var opc1 = document.gestidi_solicitante.provincia1.checked;
	var opc2 = document.gestidi_solicitante.provincia2.checked;
	var opc3 = document.gestidi_solicitante.provincia3.checked;
	var opc4 = document.gestidi_solicitante.provincia4.checked;
	var opc5 = document.gestidi_solicitante.provincia5.checked;
	var opc6 = document.gestidi_solicitante.provincia6.checked;
	var opc7 = document.gestidi_solicitante.provincia7.checked;
	var opc8 = document.gestidi_solicitante.provincia8.checked;
	var opc9 = document.gestidi_solicitante.provincia9.checked;

	if(opc1 || opc2 || opc3 || opc4 || opc5 || opc6 || opc7 || opc8 || opc9){
		mostrardiv('paso6');
	}else{
		alert('Debe seleccionar al menos una provincia donde tenga disponibilidad.');
	}

}

function valida_cif_nif_nie(uri, action, objeto, caso){
$.ajax({
		type: "POST",
		url: uri,
		data: action,
		success: function(msg){
		var cad='';
		switch(msg)
			{
			case '-3':
				cad='NIE';
			break;
			case '-2':
				cad='CIF';
			break;
			case '-1':
				cad='NIF';
			break;
			case '-0':
				cad = 'valor';
			break;

			}

	if(caso=='1' && msg%2==0){
		cad='valor';
	}else{
		if(caso=='2' && msg%3==0){
			cad='valor';
		}
	}
	if(cad!=''){
		objeto.value='';
		alert('El '+cad+' introducido no es correcto');

	}

		},
		error: function(xho){
			alert('el nif introducido no es correcto')
					}
	});
	}

function comprobar_paso1_entidades(){
	var formulario = document.gestidi_entidad;
	var requiereubicacion = false;
	var indiceradio = devolver_radio_seleccionado(formulario.cen_tra_misma);
	if(formulario.cen_tra_misma[indiceradio].value==0 && (formulario.cen_tra_provincia.value=='' || formulario.cen_tra_pais.value=='')){
		requiereubicacion=true;
	}

	if (requiereubicacion ||
	    formulario.rep_leg_apellidos.value=='' ||
	    formulario.rep_leg_nombre.value=='' ||
	    formulario.rep_leg_cargo.value=='' ||
	    formulario.rep_leg_telefono.value=='' ||
	    formulario.gastoidi1.value=='' ||
	    formulario.gastoidi2.value=='' ||
	    formulario.gastoidi3.value=='' ||
	    formulario.facturacion1.value=='' ||
	    formulario.facturacion2.value=='' ||
	    formulario.facturacion3.value=='' ||
	    formulario.personas3.value=='' ||
	    formulario.personas2.value=='' ||
	    formulario.personas1.value=='' ||
	    formulario.plantilla1.value=='' ||
	    formulario.plantilla2.value=='' ||
	    formulario.plantilla3.value=='' ||
	    formulario.telefono.value=='' ||
	    formulario.sector.value=='' ||
	    formulario.fechaconstitucion.value=='' ||
	    formulario.email.value == '' ||
	    formulario.provincia.value=='' ||
	    formulario.pais.value == '' || 
	    formulario.razonsocial.value == '' ||
	    formulario.nif.value =='' ||
	    formulario.provincia.value =='')
	{
		alert('Debe completar todos los campos obligatorios de la pagina.');
	}
	else if ((document.getElementById('MismaResPro').selectedIndex==1) && (formulario.res_pro_nombre.value=='' ||
		formulario.res_pro_apellidos.value=='' ||
		formulario.res_pro_telefono.value==''  ||
		formulario.res_pro_puesto.value=='' ||
		formulario.res_pro_departamento.value=='' ||
		formulario.res_pro_email.value==''))
	    {
		alert('Debe completar los campos obligatorios de la persona responsable del programa, si esta es distinta del representante legal.');
	    }
	else if ((document.getElementById('cmb_pertenece_grupo').selectedIndex==1) && (formulario.txt_pertenece_grupo.value==''))
	    {
		alert('Debe indicar a qué grupo empresarial pertenece su empresa.');
	    }
	else
	{
		mostrardivent('pasob');
	}	
}

function comprobar_paso2_entidades(){
	var formulario = document.gestidi_entidad;
	var chk1=false;
	var chk2=false;
	var chk3=false;
	var chk4=false;
	var chk5=false;

	var indiceradio = devolver_radio_seleccionado(formulario.idi_caracter_sino);
	if(formulario.idi_caracter_sino[indiceradio].value==1 && formulario.idi_caracter_texto.value == ''){
		chk1=true;
	}
	var indiceradio = devolver_radio_seleccionado(formulario.idi_estructura_sino);
	if(formulario.idi_estructura_sino[indiceradio].value==1 && formulario.idi_estructura_texto.value == ''){
		chk2=true;
	}
	var indiceradio = devolver_radio_seleccionado(formulario.idi_colaboracionreg_sino);
	if(formulario.idi_colaboracionreg_sino[indiceradio].value==1 && (formulario.idi_colaboracionreg_texto.value == '' || formulario.idi_colaboracionreg_tipo.value=='' || formulario.idi_colaboracionreg_nombre.value=='')){
		chk3=true;
	}

	var indiceradio = devolver_radio_seleccionado(formulario.idi_colaboracioneu_sino);
	if(formulario.idi_colaboracioneu_sino[indiceradio].value==1 && (formulario.idi_colaboracioneu_tipo.value == '' || formulario.idi_colaboracioneu_nombre.value=='' || formulario.idi_colaboracioneu_texto.value=='')){
		chk4=true;
	}
	var indiceradio = devolver_radio_seleccionado(formulario.idi_financiacion_sino);
	if(formulario.idi_financiacion_sino[indiceradio].value==1 && (!formulario.idi_financiacion_r.checked && !formulario.idi_financiacion_n.checked && !formulario.idi_financiacion_e.checked && !formulario.idi_financiacion_i.checked) ){
		chk5=true;
	}

if(chk1 || chk2 || chk3 || chk4 || chk5){
	alert('Debe completar todos los campos obligatorios de la pagina.');
}else{
		mostrardivent('pasoc');
	}


}


function comprobar_paso3_entidades(){
	var formulario = document.gestidi_entidad;
	var encontrado = false;
	var total = numero_fila;
	var cont = 0;
	while (cont < total && !encontrado){
		if(document.getElementById("tblTitulac_Grado["+cont+"]")){
			encontrado = true;
		}
		cont++;
	}

	if(!encontrado || formulario.pro_for_objetivos.value== '' || formulario.pro_for_actividades.value== '' || formulario.pro_for_medios.value== '' || formulario.pro_for_nombretutor.value== '' || formulario.pro_for_cargotutor.value== '' || formulario.pro_for_justificacion.value== '' || formulario.pro_for_perspectivas.value== ''){
		alert('Debe completar todos los campos obligatorios de la pagina.');
	}else{
		mostrardivent('pasofin');
	}
}


function aceptarlopd_entidades(){
if (document.gestidi_entidad.aceptalopd.checked==true){
			document.gestidi_entidad.enviarsolicitud.disabled=false;
	}else{
			document.gestidi_entidad.enviarsolicitud.disabled=true;
	}
}
function devolver_radio_seleccionado(radio)
{
var indice=null;
for (var i=0; i < radio.length; i++)
   {
   if (radio[i].checked)
      {
      indice=i;
      }
   }
   return indice;
}


function validar_float(valor, objeto){
	var strreg=/^\$?(?:\d+|\d{1,3}(?:.\d{3})*)(?:\,\d{1,2}){0,1}$/;
	if(!strreg.test(valor) || valor<0 ){
		alert('El valor introducido no es un n�mero valido.');
		objeto.value='';
	}

}


