﻿/********************************************************************************************** 
FUNCIONES PARA MATRICULACIONES
**********************************************************************************************/
var alumnos = new Array();
var isLogged = false;
var isParticular = false;
var userLoggedVerId = null;
var matriculaTotal = 0;
var bTieneMatricula = 0;

//Añade un alumno al array de alumnos en la posición indicada
function add_alumno(iVerId, iPos)
{
	alumnos[iPos - 1] = iVerId;
}

function delete_alumno(iPos)
{
	alumnos[iPos - 1] = null;
}

//Realiza las acciones necesarias al perder el foco el campo de mail o dni
function check_user_on_blur(strField, strValue, iPos)
{
	if (strValue != '')
	{
		var alum_id = chek_user_exists(strField, strValue);
		add_alumno(alum_id, iPos);		
		if (alum_id != "-1")
		{
			document.getElementById('existing_user_msg_' + iPos).style.display = 'block';
			document.getElementById('existing_user_' + iPos).style.display = 'none';
			document.getElementById('lbl_user_name_' + iPos).innerHTML = strValue;
			document.getElementById('nombre_' + iPos).value = '';
		}
	}
}

function check_owner_on_blur()
{
	if(!isLogged)
	{
		var strValue = document.getElementById('datos_email').value;
		if (strValue != '')
		{
			var alum_id = chek_user_exists('mail', strValue);
			if(alum_id != "-1")
			{
				//MostrarPutPassword(); //Esto está en la XSL
				if (confirm('Ya existe un usuario registrado con ese mail en nuestra base de datos. Por favor, vuelva a iniciar el proceso de inscripción como usuario registrado. El nombre de usuario es el mail, pulse en recordar contraseña o llámenos al 91.351.50.94 si no recuerda los datos de acceso.¿Desea volver a la página de inicio del proceso de inscripción?'))
				{
					document.location.href='javascript:window.history.back();';
				}
				
				return false;				
			}
			return true;
		}
		return true;
	}
	return true;
}

function cancel_inscription(iPos)
{
	document.getElementById('email_' + iPos).value = '';
	document.getElementById('existing_user_msg_' + iPos).style.display = 'none';
	document.getElementById('existing_user_' + iPos).style.display = 'block';
	delete_alumno(iPos);
	return false;//PARA QUE EL SCROLL DEL NAVEGADOR NO SUBA AUTOMATICAMENTE AL CLICAR
	
}

//Comprueba si existe un usuario mediante email o dni. 
//strField = 'dni' o 'mail' para que el servidor sepa qué campo comprobar
//devuelve -1 si el usuario no existe. Si existe devuelve su id
function chek_user_exists(strField, strValue)
{
	var oAjax = new WBE_AjaxClass();
	oAjax.clear();
	oAjax.addPostParameter('field', strField);
	oAjax.addPostParameter('value', strValue);
	var xmlObj = oAjax.throwEventXML('check_user_exists');
	/*if(xmlObj == null){alert('null');return}*/
	
	//En el nodo id viene el id de usuario si existe, sino -1
	var alum_id = oAjax.getXMLNodeValue(xmlObj, "id");
	return alum_id;
}

//Incrementa por click los Tags de la Nube de Tags el curso
function increment_cloud_tags(strEtiqueta, strNube)
{	
	var oAjax = new WBE_AjaxClass();
	oAjax.clear();
	oAjax.addPostParameter('etiqueta', strEtiqueta);
	oAjax.addPostParameter('IdNube', strNube);
	var xmlObj = oAjax.throwEventXML('event_increment_click_tags');
	//Debemos llamar al buscador oculto y lanzar la busquedad en funcion de la etiqueta
	document.getElementById("text").value=strEtiqueta;
	//Lanzo la bÃºsquedad
	__SearchGeneral__();
	//document.location.href='http://www.icemd.com/resultados_de_la_busqueda.html?q='+strEtiqueta;
}


//Cambia el precio para el resto del curso de un alumno y actualiza precios y descuentos del formulario
function change_resto_price(iCounter, iPositionId)
{
	var infoDiv = document.getElementById('resto_selected_price_' + iCounter);
	//var infoCombo = document.getElementById('resto_price_' + iCounter);
	var arrRadiosRestoPrice = document.getElementsByName("resto_price_" + iCounter);	
	
	if(!arrRadiosRestoPrice[0].checked)//infoCombo.selectedIndex > 0)
	{
		var selectedPrice = GetSelectedRestoPrice(iCounter);
		var selectedDescription = GetSelectedRestoDescription(iCounter);
		var texto = selectedDescription + ": " + "<strike>" + arrRadiosRestoPrice[0].value + " \u20AC</strike>  " + selectedPrice + " \u20AC";//infoCombo[infoCombo.selectedIndex].text + ": " + "<strike>" + infoCombo[0].value + " \u20AC</strike>  " + infoCombo.value + " \u20AC";
		infoDiv.innerHTML = texto; 
	}
	else
		infoDiv.innerHTML = GetSelectedRestoDescription(iCounter) + ": " + GetSelectedRestoPrice(iCounter) + " \u20AC"; 
		
	//Actualizar precio total 
	eval('objJS_' + iPositionId + '.setPrice()');
	
	UpdateAhorroTotal();
}

function UpdateAhorroTotal()
{
	//Actualizar descuento total en la parte superior, columna descuentos (si es particular)
	
		var iMatIni = 0.0;
		if(document.getElementById('total_mat_sin_descuento'))
		{
			var strMatIni = document.getElementById('total_mat_sin_descuento').innerHTML;
			if(strMatIni != '')
				iMatIni = parseFloat(strMatIni.replace(/\./g, ''));
		}
		
		var iMatFinal = 0.0;
		if(document.getElementById('total_mat_price'))
		{
			var strMatFinal = document.getElementById('total_mat_price').innerHTML;
			if(strMatFinal != '')
				iMatFinal = parseFloat(strMatFinal.replace(/\./g, ''));			
		}
		
		var iRestIni = 0.0;
		if(document.getElementById('total_resto_price_sin_descuentos'))
		{
			var strRestIni = document.getElementById('total_resto_price_sin_descuentos').innerHTML;
			if(strRestIni != '')
				iRestIni = parseFloat(strRestIni.replace(/\./g, ''));
		}
		
		var iRestFinal = 0.0;
		if(document.getElementById('total_resto_price'))
		{
			var strRestFinal = document.getElementById('total_resto_price').innerHTML;				
			if(strRestFinal != '')
				iRestFinal = parseFloat(strRestFinal.replace(/\./g, ''));
		}
		
		if(iRestIni == 0) iRestFinal = 0;
		if(iMatIni == 0) iMatFinal = 0;
			
		valor = (iMatIni - iMatFinal) + (iRestIni - iRestFinal);
		
		if(valor != 0)
		{
			document.getElementById('ahorro_total').innerHTML = "Ahorro: " + FormatNumberInMaMode(valor) + " €";
			if(isParticular)
			{
				if (GetSelectedRestoDescription(1) != 'Sin condiciones especiales'){
					document.getElementById('resto_particular_desc').innerHTML = GetSelectedRestoPorcentaje() + "% " + GetSelectedRestoDescription(1);
				}	
			}
		}
		else
		{
			document.getElementById('ahorro_total').innerHTML = '';
			document.getElementById('resto_particular_desc').innerHTML = '';
		}
	
}

function GetSelectedRestoPrice(iAlumno)
{
	var arrChecks = document.getElementsByName('resto_price_' + iAlumno);
	if(arrChecks != null)
	{
		var menor = parseInt(arrChecks[0].value);
		for(var i = 1; i < arrChecks.length; i++)
		{
			if(arrChecks[i].checked && menor > parseInt(arrChecks[i].value))
				menor = parseInt(arrChecks[i].value);		
		}
		return menor;
	}
	return 0;
	/*
	var arrRadios = document.getElementsByName('resto_price_' + iAlumno);
	for(var i = 0; i < arrRadios.length; i++)
	{
		if(arrRadios[i].checked) return arrRadios[i].value;
	}
	*/
}

function GetSelectedRestoDescription(iAlumno)
{
	var arrChecks = document.getElementsByName('resto_price_' + iAlumno);
	var menor = parseInt(arrChecks[0].value);
	var index = 0;
	for(var i = 1; i < arrChecks.length; i++)
	{
		if(arrChecks[i].checked && menor > parseInt(arrChecks[i].value))
		{
			menor = parseInt(arrChecks[i].value);	
			index = i;
		}
	}
	
	return document.getElementById('resto_price_description_' + iAlumno + '_' + (index + 1)).innerHTML;
}

function GetSelectedRestoPorcentaje()
{
	var i = GetSelectedRestoIndex(1);
	return arrRestoPorcentajes[i];
	
}

function GetSelectedRestoIndex(iAlumno)
{
	var arrChecks = document.getElementsByName('resto_price_' + iAlumno);
	var menor = parseInt(arrChecks[0].value);
	var index = 0;
	for(var i = 1; i < arrChecks.length; i++)
	{
		if(arrChecks[i].checked && menor > parseInt(arrChecks[i].value))
		{
			index = i;
		}
	}
	return index;
}

//Esta funcion sobreescribe "reloadNumForm2" de suscription_list.js
function reload_form_alumnos()
{
	var i = 1;
	this.numForm2Active = this.getElemValue('sel_num_form2_' + this.posId);
	var elem2 = document.getElementById('fs_form2_' + this.posId + '_' + i);
	var elem3 = document.getElementById('fs_form2_special_' + this.posId + '_' + i);
	while (elem2) {
		if (i <= this.numForm2Active) {
			elem2.style.display = '';
			elem3.style.display = '';
		} else {
			elem2.style.display = 'none';
			elem3.style.display = 'none';
		}
		i++;
		elem2 = document.getElementById('fs_form2_' + this.posId + '_' + i);
		elem3 = document.getElementById('fs_form2_special_' + this.posId + '_' + i);
	}
	this.setPrice();
	UpdateAhorroTotal();
};

function fecha_sistema(){
	var one_day=1000*60*60*24;
	
	var fecha_sis = new Date();
	
	var dia = document.getElementById('dia_ini').value;
	var mes = (document.getElementById('mes_ini').value)-1;
	var ao = document.getElementById('a_ini').value;
	
	var fecha_ini = new Date(ao,mes,dia);
	
	var total = Math.ceil((fecha_ini.getTime()-fecha_sis.getTime())/(one_day));
	
	return total;
}


//Esta funcion sobreescribe "setPrice" de suscription_list.js
function put_all_prices()
{
	var dias = fecha_sistema();

	//Precios de la matrícula
	var dTotal = 0.0;
	var dTotalSinDescuentos = 0.0;
	var matTemp = document.getElementById('precio_mat_temprana').value;
	var hdn_mat = 'precio_mat_temprana';
	if(matTemp == 'NaN')//CAMBIAR ESTO DESDE LA XSL, POR AHORA SIRVE
		hdn_mat = 'precio_mat_normal';
	for (var i = 1; i <= this.numForm2Active; i++)
	{
		dTotal += 1 * document.getElementById(hdn_mat).value;//this.getSelectedPrice(i);
		dTotalSinDescuentos += 1 * document.getElementById('precio_mat_normal').value;
	}
	//Precios del resto
	dResto = 0.0;
	dRestoSinDescuentos = 0.0;
	for (var i = 1; i <= this.numForm2Active; i++)
	{
		dResto += 1 * GetSelectedRestoPrice(i);//1 * document.getElementById('resto_price_' + i).value;
		dRestoSinDescuentos += 1 * document.getElementsByName("resto_price_" + i)[0].value;//1 * document.getElementById('resto_price_' + i)[0].value;
	}
	
	if(dTotalSinDescuentos == dTotal)
	{
		var theDiv = document.getElementById('container_descuentos_mat');
		if(theDiv) theDiv.style.display = 'none';
	}
	else
	{	
		if(dias<30)
		{
			var theDiv = document.getElementById('container_descuentos_mat');
			if(theDiv)
			{
				theDiv.style.display = 'none';
				document.getElementById('nota2_pronto').style.display = 'none';
			}
		}
		else
		{
			var theDiv = document.getElementById('container_descuentos_mat');
			if(theDiv)
			{
				theDiv.style.display = 'inline';
				document.getElementById('nota2').style.display = 'inline';
			}
			
			theDiv = document.getElementById('total_mat_sin_descuento');
			if(theDiv) theDiv.innerHTML = FormatNumberInMaMode(dTotalSinDescuentos);
		}
	}
	
	if(dRestoSinDescuentos == dResto)
	{
		var theDiv = document.getElementById('container_descuentos_resto');
		if(theDiv) theDiv.style.display = 'none';
	}
	else
	{
		var theDiv = document.getElementById('container_descuentos_resto');
		if(theDiv) theDiv.style.display = 'inline';
		
		theDiv = document.getElementById('total_resto_price_sin_descuentos');
		if(theDiv)
		{
			theDiv.innerHTML = FormatNumberInMaMode(dRestoSinDescuentos);
			document.getElementById('nota2').style.display = 'inline';
		}
	}
	
	if(dTotal == 0)
	{
		document.getElementById('precio_mat_container').style.display = 'none';
		document.getElementById('resto_descrp').style.display = 'none';
	}
	
	if(dias<30)
	{
		document.getElementById('total_mat_price').innerHTML = FormatNumberInMaMode(dTotalSinDescuentos);
		matriculaTotal = dTotalSinDescuentos;
	}
	else
	{
		document.getElementById('total_mat_price').innerHTML = FormatNumberInMaMode(dTotal);
		matriculaTotal = dTotal;
	}
	
	
	document.getElementById('total_resto_price').innerHTML = FormatNumberInMaMode(dResto);
	
	if(dias<30)
	{
		document.getElementById('total_price_' + this.posId).innerHTML = FormatNumberInMaMode(dTotalSinDescuentos + dResto);
	}
	else
	{
		document.getElementById('total_price_' + this.posId).innerHTML = FormatNumberInMaMode(dTotal + dResto);	
	}
}

//Esta funcion sobreescribe "validarCampos" de suscription_list.js
function validate_matricula_form()
{
	var oValidator = new WBEFormValidator();
	//Formulario de arriba
	if(!oValidator.validateForm(document.InmediaFrm, '0_' + this.posId)) return false;
	//Formularios de abajo
	for (i = 1; i <= this.numForm2Active; i++)
	{
		if(alumnos[i-1] == "-1" && alumnos[i-1] != null)//document.getElementById('existing_user_' + i).style.display == 'block')
			if(!oValidator.validateForm(document.InmediaFrm, '2_' + i + '_' + this.posId)) return false;
	}
	return true;	
}

// Esta funcion sobreescribe "save_order" de suscription_list.js
// Guarda los datos de la inscripcion
function save_order_override(sUrl){
 /* Guarda el pedido */
 var oAjax = new WBE_AjaxClass();
 this.setLineParams(oAjax);
 this.setOrderParams(oAjax, sUrl);
  oAjax.addPostParameter('bTieneMatricula', bTieneMatricula); 
 xmlObj = oAjax.throwEventXML('subscription_save_order');
 this.postProcessSaveOrder(xmlObj);
}

// Esta funcion sobreescribe "saveForm1" de suscription_list.js
// Guarda los datos de la inscripcion
function save_matricula_datos()
{
	// si es particular hay que guardar el nif y el telefono en la factura, para empresas ya lo guarda la xsl
	if(isParticular)
	{
	document.getElementById('datos_cif').value = document.getElementById('datos_nif').value;
	document.getElementById('datos_telefono').value = document.getElementById('datos_movil').value;
	}
    
    // si no esta logado... damos de alta el usuario
	if(!isLogged)
	{
        NewUserOwner(this);
    	
	    // usuario para relacionar con el inscripcion
	    this.relation_ids = '(12|' + userLoggedVerId + '|c)';
    }

	var oAjax = new WBE_AjaxClass();

	//Guardar owner para 2º pago (AGUS: ESTO NO SE USA)
	//this.pagador = this.relationshipContentId;
    this.relationshipContentId = this.convocatoria_id;
	this.productId = this.relationshipContentId;	
	
	//this.order_line_id = this.convocatoria_id;
	
	// relacion entre inscripcion y convocatoria
	this.relation_ids += ',(10|' + this.relationshipContentId + '|p)';
	
	// parametros del POST
	oAjax.clear();
	this.getParams(oAjax, "0");
	oAjax.addPostParameter('relation_ids', this.relation_ids);

    // ejecuta el evento
	xmlObj = oAjax.throwEventXML(this.useEvent);
	
	// guarda el ID de la inscripcion	
	this.inscripcion_id = 0;
	if (xmlObj) {
	    var id = oAjax.getXMLNodeValue(xmlObj, 'id');
	    this.inscripcion_id = id;
	}
		
	this.postProcessForm1(xmlObj);
	
	this.relationshipContentId = this.inscripcion_id;
	//this.relationshipContentId = this.productId;
	
	return xmlObj;
}

//Lineas para primer pedido
function SetIcemdLineParams(oAjax)
{
	if(matriculaTotal > 0)//Si es matricula gratis no añadir
	{
		for (var i = 1; i <= this.numForm2Active; i++)
		{
			oAjax.addPostParameter('l_' + i + '_type_code', 'SUBSCRIPTION_LINE');
			oAjax.addPostParameter('l_' + i + '_price_id', this.getElemValue('form_sel_price_' + this.posId + '_2_' + i));
			oAjax.addPostParameter('l_' + i + '_parent', this.productId);
			oAjax.addPostParameter('l_' + i + '_child', this.LineCntIds[i - 1]);
		}
	}
	else//Añadir las líneas del resto, ya que la matrícula es gratis
	{
		for (var i = 1; i <= this.numForm2Active; i++)
		{
			oAjax.addPostParameter('l_' + i + '_type_code', 'SUBSCRIPTION_LINE');
			var selectedPriceIndex = GetSelectedRestoIndex(i);
			oAjax.addPostParameter('l_' + i + '_price_id', ArrIdRestoPrices[selectedPriceIndex]);
			oAjax.addPostParameter('l_' + i + '_parent', this.productId);
			oAjax.addPostParameter('l_' + i + '_child', this.LineCntIds[i - 1]);
		}
	}
}


function NewUserOwner(obj)
{
	var oIdsElem = eval('document.InmediaFrm.att_ids_0_842');
	var sId;
	var tempElem;

	var oAjax = new WBE_AjaxClass();
	oAjax.clear();
	
	/*
	for (var i = 0; i < oIdsElem.length; i++)
	{
		sId = oIdsElem[i].value;
		oAjax.addPostParameter('att_input_' + sId, GetValue(sId, '_0'));
	}
	*/
	
	
	//---------------------------------------------
	// Mapea Ids entre empresa y usuario (el que paga, owner)
	//---------------------------------------------
	NewUserOwnerAddInputParameter(oAjax, '260', '203');     // tipo via
	NewUserOwnerAddInputParameter(oAjax, '261', '195');     // direccion
	NewUserOwnerAddInputParameter(oAjax, '286', '196');     // num. portal
	NewUserOwnerAddInputParameter(oAjax, '264', '199');     // CP
	NewUserOwnerAddInputParameter(oAjax, '265', '200');     // Ciudad
	NewUserOwnerAddInputParameter(oAjax, '266', '198');     // Provincia
	NewUserOwnerAddInputParameter(oAjax, '267', '197');     // Pais
	NewUserOwnerAddInputParameter(oAjax, '287', '201');     // Telefono
	NewUserOwnerAddInputParameter(oAjax, '288', '211');     // Fax
	NewUserOwnerAddInputParameter(oAjax, '294', '172');     // Nombre
	NewUserOwnerAddInputParameter(oAjax, '295', '173');     // Apellido 1
	NewUserOwnerAddInputParameter(oAjax, '296', '187');     // Apellido 2
	NewUserOwnerAddInputParameter(oAjax, '190', '190');     // Tipo documento
	//NewUserOwnerAddInputParameter(oAjax, '191', '191');     // Documento
	NewUserOwnerAddInputParameter(oAjax, '297', '189');     // Sexo
	NewUserOwnerAddInputParameter(oAjax, '298', '174');     // E-mail
	//NewUserOwnerAddInputParameter(oAjax, '353', '');     // Info. laboral
	NewUserOwnerAddInputParameter(oAjax, '299', '212');     // Cargo
	NewUserOwnerAddInputParameter(oAjax, '300', '214');     // Departamento
	NewUserOwnerAddInputParameter(oAjax, '301', '210');     // Telefono directo
	//---------------------------------------------
	
	
    oAjax.addPostParameter('content_ct_code', 'usuarios');
	oAjax.addPostParameter('user_login', document.getElementById('datos_email').value);
	 
	if(!isParticular)
	{
		var passwInput = document.getElementById('datos_cif');
		oAjax.addPostParameter('att_input_257', passwInput.value);
	}
	else
	{
		var passwInput = document.getElementById('datos_nif');
		oAjax.addPostParameter('att_input_191', passwInput.value);
	}
	oAjax.addPostParameter('user_password', passwInput.value);
	oAjax.addPostParameter('user_type', '3');	
	var xmlObj = oAjax.throwEventXML("cms_user_signon_save_send_and_unpub");
	if (xmlObj) userLoggedVerId = oAjax.getXMLNodeValue(xmlObj, 'id');
	
}

// añade parametros al post de evento 'cms_user_signon_save'
function NewUserOwnerAddInputParameter(oAjax, att_origin, att_dest) {
    oAjax.addPostParameter('att_input_' + att_dest, GetValue(att_origin, '_0'));
}

function GetValue(sElemId, sSufix)
{
	var oElem = eval('document.forms[0].att_input_' + sElemId + sSufix + '_842');
	var sValue = '';
	if (oElem==null) return '';
	if (oElem.length)
	{ // n campos con el mismo nombre o un select
		for (var i = 0; i < oElem.length; i++)
		{
			if (oElem[i].checked)
			{
				if (sValue != '') sValue += ',';
				sValue += oElem[i].value;
			}
			else
			{
				if (oElem[i].selected)
				{
					if (sValue != '') sValue += ',';
					sValue += oElem[i].value;
				}
			}
		}
	}
	else
	{ // un solo campo
		if (oElem.type == "checkbox" || oElem.type == "radio") sValue = (oElem.checked) ? oElem.value : "";
		else sValue = oElem.value;
	}
	return sValue;
}


// Esta funcion sobreescribe "saveForm2" de suscription_list.js
// Crea los usuarios (alumnos)
function save_matricula_alumnos()
{
    // particulares, añade el id del usuario al array
    if (userLoggedVerId != null && this.numForm2Active == 1 && isLogged) {
        alumnos.push(userLoggedVerId);
    }

	var oAjax = new WBE_AjaxClass();
	this.useEventF2 = 'cms_user_signon_save_send_and_unpub';
	oAjax.clear();
	if(isParticular)
	{
	    this.LineCntIds[this.LineCntIds.length] = userLoggedVerId;
	}
	else
	{
		for (i = 1; i <= this.numForm2Active; i++)
		{
			if(alumnos[i-1] == "-1")
			{
				//Hay que comprobar que el alumno no existe en base de datos, caso de ordenante que es también alumno y no tiene cuenta.
				var al_id = chek_user_exists('mail', document.getElementById('email_' + i).value);
				if(al_id == "-1")//No existe en bdd
				{
					this.getParams(oAjax, 2, i);
					oAjax.addPostParameter('user_login', document.getElementById('email_' + i).value);
					oAjax.addPostParameter('user_password', document.getElementById('num_doc_' + i).value);
					oAjax.addPostParameter('user_type', '3');
										
					xmlObj = oAjax.throwEventXML(this.useEventF2);
					if (xmlObj) this.LineCntIds[this.LineCntIds.length] = oAjax.getXMLNodeValue(xmlObj, 'id');
				}
				else //Se ha creado uno con anterioridad en este mismo proceso de matriculación
				{
						this.LineCntIds[this.LineCntIds.length] = al_id;	
				}
			}
			else
			{
				this.LineCntIds[this.LineCntIds.length] = alumnos[i-1];			
			}
		}
	}	
}

// Esta funcion sobreescribe "postProcessSaveOrder" de suscription_list.js. 
// Crea líneas de pedido para el resto del curso (pago 2) y redirecciona según método de pago escogido
function post_save_mat(xmlObj)
{
//debugger;

	if (xmlObj)
	{
		var sUrl;
		var oAjax = new WBE_AjaxClass();
		sUrl = oAjax.getXMLNodeValue(xmlObj, 'url');
		
		if(matriculaTotal > 0)//La matrícula no es gratis por lo tanto sí hay que hacer segundo pedido para resto del curso
		{
			//GUARDAR LOS PEDIDOS PARA EL SEGUNDO PAGO
			var oAjax2 = new WBE_AjaxClass();
			oAjax2.clear();
			for (i = 1; i <= this.numForm2Active; i++)
			{
				oAjax2.addPostParameter('l_' + i + '_type_code', 'SUBSCRIPTION_LINE');
				var selectedPriceIndex = GetSelectedRestoIndex(i);//document.getElementById('resto_price_' + i).selectedIndex;
				oAjax2.addPostParameter('l_' + i + '_price_id', ArrIdRestoPrices[selectedPriceIndex]);//ID del precio del resto del curso
				
				// realaciona con la convocatoria, ¿ESTO ESTA BIEN?, creo que tendria que relacionarlo con al inscripcion
				//oAjax2.addPostParameter('l_' + i + '_parent', this.productId);
				//oAjax2.addPostParameter('l_' + i + '_parent', this.inscripcion_id);
				//oAjax2.addPostParameter('l_' + i + '_parent', this.convocatoria_id);
				//oAjax2.addPostParameter('l_' + i + '_parent', this.order_line_id);			
				oAjax2.addPostParameter('l_' + i + '_parent', this.resto_id);
				
				// relaciona con el alumno (usuario)
				oAjax2.addPostParameter('l_' + i + '_child', this.LineCntIds[i - 1]);				
			}
			
			oAjax2.addPostParameter('paymethod_id', this.getElemValue('sel_pm_' + this.posId));
			
			oAjax2.addPostParameter('owner_id', this.Owner);
			//oAjax2.addPostParameter('owner_id', this.inscripcion_id);		
			
			oAjax2.addPostParameter('def_url', sUrl);
			oAjax2.addPostParameter('isOrderResto',1);
			oAjax2.throwEventXML('subscription_save_order');
		}//FIN GUARDAR LOS PEDIDOS PARA EL SEGUNDO PAGO
		
		document.location.href = sUrl;
	}
	else
	{
		alert('Se ha producido un error al guardar la suscripcion');
	}
}

/**********************************************************************************************
FIN FUNCIONES PARA MATRICULACIONES
**********************************************************************************************/


/**********************************************************************************************
FUNCIONES DE INTERFAZ DE USUARIO PARA MATRICULACIONES
**********************************************************************************************/

function GoToAlumno(numAlumno)
{
    document.getElementById('combo_num_alumnos').disabled = 'disabled';
    HideAll();
    document.getElementById('user_container_' + numAlumno).style.display = '';
	SelectTopPaso(2);
	////////
	UpdateResumen();
}

function GoToDatos()
{
    document.getElementById('combo_num_alumnos').disabled = '';
    HideAll();
    document.getElementById('datos_empresa').style.display = '';
	SelectTopPaso(1);
	////////
	UpdateResumen();
}

function GoToPago()
{
    HideAll();
    document.getElementById('a_pagar').style.display = '';
	
	var auxDiv = document.getElementById('precio_mat_confirma');//Si no hay matricula este elemento no sale
	if(auxDiv) auxDiv.innerHTML = document.getElementById('total_mat_price').innerHTML;
	SelectTopPaso(3);
	////////
	UpdateResumen();
}

function GoToResumen()
{
	HideAll();
	document.getElementById('last_resumen').style.display = '';
	SelectTopPaso(4);
	///////Rellenar resumen
	//Nombre
	document.getElementById('r_nombre').innerHTML = document.getElementById('datos_nombre').value + " " + document.getElementById('datos_apellido1').value + " " + document.getElementById('datos_apellido2').value;
	//Documento
	if(isParticular) document.getElementById('r_doc').innerHTML = document.getElementById('datos_nif').value;
	else document.getElementById('r_doc').innerHTML = document.getElementById('datos_cif').value;
	//Dirección 
	document.getElementById('r_dir').innerHTML = document.getElementById('tipo_via').value + " " + document.getElementById('datos_direccion').value + " " + document.getElementById('datos_direccion_resto').value + "<br/>"
	+ document.getElementById('datos_cp').value + " " + document.getElementById('datos_ciudad').value + " " + document.getElementById('datos_provincia').value + " " + document.getElementById('datos_pais').value;
	//Email 
	document.getElementById('r_email').innerHTML = document.getElementById('datos_email').value;
	//Sexo (sí, gracias)
	document.getElementById('r_sexo').innerHTML = document.getElementById('datos_sexo').value;
	//Teléfono
	if(isParticular) document.getElementById('r_tel').innerHTML = document.getElementById('datos_movil').value;
	else document.getElementById('r_tel').innerHTML = document.getElementById('datos_telefono').value;
	//Forma de pago
	var sFormaPago = GetFormaPagoDescription();
	document.getElementById('r_forma_pago').innerHTML = sFormaPago;
	if(sFormaPago != "Pago Online seguro a través de tarjeta de crédito.")
		document.getElementById('btn_save_suscription').value = "Finalizar";
	else document.getElementById('btn_save_suscription').value = "Realizar pago";
		
	//Precio final 
	if(document.getElementById('total_mat_price').innerHTML == '0')//Cursos sin matrícula 
	{
		if(sFormaPago != "Finalizar inscripción y pagar más tarde")
		{
			document.getElementById('r_total').innerHTML = "<strong>Importe a pagar ahora:</strong> " + document.getElementById('total_resto_price').innerHTML + "€";
		}
		else document.getElementById('r_total').innerHTML = '<strong>Formalización de la Inscripción provisional</strong>';
	}
	else
	{
		if(sFormaPago != "Finalizar inscripción y pagar más tarde")
		{
			document.getElementById('r_total').innerHTML = document.getElementById('precio_mat_confirma') != null ? "<strong>Importe a pagar ahora:</strong> " + document.getElementById('precio_mat_confirma').innerHTML + "€" : "0€";
		}
		else document.getElementById('r_total').innerHTML = '<strong>Formalización de la Inscripción provisional</strong>';
	}
}

function GetFormaPagoDescription()
{
	//if(document.getElementById('pago_trans1').checked) return "Transferencia bancaria";
	//if(document.getElementById('pago_trans2') && document.getElementById('pago_trans2').checked) return "Sólo confirmar matrícula";
	if(document.getElementById('pago_tpv').checked) return "Pago Online seguro a través de tarjeta de crédito.";
	//if(document.getElementById('pago_cheque').checked) return "Cheque o Talon nominativo";
	return "Finalizar inscripción y pagar más tarde";
}

function CheckNieX(strCounter)
{
	var contador = strCounter != '' ? '_' + strCounter : '';
	if(document.getElementById('combo_tipo_doc' + contador).value == "NIE")
		document.getElementById('lbl_x' + contador).style.display = "";	
	else document.getElementById('lbl_x' + contador).style.display = "none";
}

function UpdateResumen()
{
	var alguno = false; //Si se queda a false es que no se ha terminado de rellenar ningún alumno, entonces ocultamos el div resumen
		
		
	var oTable = document.getElementById('tbl_resumen');
	
	var nun = oTable.rows.length;
	for(var i = nun-1; i >= 0; i--) oTable.deleteRow(oTable.rows[i]);
	
	___crateTableCabecera();
	
	var numActive = parseInt(document.getElementById('combo_num_alumnos').value);
	for (var i = 1; i <= numActive; i++)
	{
		if(document.getElementById('nombre_' + i).value != '' || document.getElementById('email_' + i).value != '')//Si no se cumple es que aun no se ha rellenado
		{
			alguno = true;
		
			___createTableRow(i);
			var arrRadiosRestoPrice = document.getElementsByName("resto_price_" + i);//var infoCombo = document.getElementById('resto_price_' + i);
			
			//NOMBRE
			var infoTd = document.getElementById("cell_alumno_" + i + "_nombre");
			var nameOrMail = document.getElementById('nombre_' + i).value;
			if(nameOrMail == '') nameOrMail = document.getElementById('email_' + i).value;
			infoTd.innerHTML = nameOrMail + " [<a href='javascript:GoToAlumno(" + i + ");'><span>Modificar</span></a>]";
			
			//DESCUENTOS
			infoTd = document.getElementById("cell_alumno_" + i + "_descuentos");
			var matTemp = document.getElementById('precio_mat_temprana').value;
			
			var dias = fecha_sistema();
			if(matTemp != '' && document.getElementById('precio_mat_temprana_descr').value != '')//Hay descuento por matrícula temprana
			{
				if(dias>30)
				{
					//alert('YES YES');
					infoTd.innerHTML = document.getElementById('precio_mat_temprana_descr').value + "<br/>";
				}

			}
			
			if(GetSelectedRestoIndex(1) != 0)//En la posición cero no hay condiciones especiales, porlo tanto no hay que poner nada
				infoTd.innerHTML += GetSelectedRestoPorcentaje() + "% " + GetSelectedRestoDescription(i);//infoCombo[infoCombo.selectedIndex].text;
				
			//MATRICULA
			infoTd = document.getElementById("cell_alumno_" + i + "_resto");
			if(matriculaTotal > 0)
			{
				if(matTemp != '' && document.getElementById('precio_mat_temprana_descr').value != '')
				{
					if(dias>30)
					{
						infoTd.innerHTML = "<strike>" + FormatNumberInMaMode(document.getElementById('precio_mat_normal').value) + " \u20AC</strike> <strong>" + FormatNumberInMaMode(matTemp) + " \u20AC</strong> Matricula<br/>";
					}
				}
				else infoTd.innerHTML = "<strong>" + FormatNumberInMaMode(document.getElementById('precio_mat_normal').value) + " \u20AC</strong> Mátricula<br/>";
			}
			//else infoTd.innerHTML = "Matricula gratis<br/>";
			
			
			//RESTO
			if(GetSelectedRestoIndex(1) != 0)//En la posición cero no hay condiciones especiales, porlo tanto no hay que tachar el precio anterior
				infoTd.innerHTML += "<strike>" + document.getElementById('resto_original_price').value + " \u20AC</strike> <strong>" + FormatNumberInMaMode(GetSelectedRestoPrice(i)) + " \u20AC</strong> Resto del curso";//infoCombo[0].value + " \u20AC</strike> <strong>" + infoCombo.value + " \u20AC</strong> Resto del curso";
			else infoTd.innerHTML += "<strong>" + FormatNumberInMaMode(GetSelectedRestoPrice(i)) + " \u20AC</strong> Resto del curso";
		}		
	}
	if(alguno) document.getElementById('div_resumen').style.display = 'block';
	else document.getElementById('div_resumen').style.display = 'none';
}

function SelectTopPaso(idPaso)
{
	if(!isParticular)
	{
		document.getElementById('pasos_particular').style.display = 'none';
		document.getElementById('pasos_empresa').style.display = '';
		document.getElementById('paso_datos').className = 'paso';
		document.getElementById('paso_alum').className = 'paso middle';
		document.getElementById('paso_pago').className = 'paso middle';
		document.getElementById('paso_resumen').className = 'paso middle';
		
		switch (idPaso)
		{
			case 1:
				document.getElementById('paso_datos').className = 'active';
				break;
			case 2:
				document.getElementById('paso_alum').className = 'active middle';
				break;
			case 3: 
				document.getElementById('paso_pago').className = 'active middle';
				break;
			case 4: 
				document.getElementById('paso_resumen').className = 'active middle';
				break;
		}
	}
	else
	{
		document.getElementById('pasos_particular').style.display = '';
		document.getElementById('pasos_empresa').style.display = 'none';
		document.getElementById('paso_datos_p').className = 'paso';
		document.getElementById('paso_pago_p').className = 'paso center';
		document.getElementById('paso_resumen_p').className = 'paso';
		switch (idPaso)
		{
			case 1:
			case 2:
				document.getElementById('paso_datos_p').className = 'active';
				break;
			case 3: 
				document.getElementById('paso_pago_p').className = 'active center';
				break;
			case 4: 
				document.getElementById('paso_resumen_p').className = 'active';
				break;
		}
	}
}

//Esta funcion sobreescribe "reloadNumForm2" de suscription_list.js
function ReloadFormMatriculas()
{
    var num = this.getElemValue('sel_num_form2_' + this.posId);
    this.numForm2Active = num;
    HideAndShowNextLinks(num);
    this.setPrice();
    GoToDatos();
	UpdateAhorroTotal();
	
}

function HideAndShowNextLinks(numAlumno)
{
    var i = 1;
    var elem1 = document.getElementById('lnk_next_alumno_' + i);
    var elem2 = document.getElementById('lnk_go_to_pago_' + i);
    while (elem1 && elem2)
    {
        elem1.style.display = '';
        elem2.style.display = 'none';
        i++;
        elem1 = document.getElementById('lnk_next_alumno_' + i);
        elem2 = document.getElementById('lnk_go_to_pago_' + i);
    }
    document.getElementById('lnk_next_alumno_' + numAlumno).style.display = 'none';
    document.getElementById('lnk_go_to_pago_' + numAlumno).style.display = '';
}

function HideAll()
{
    document.getElementById('datos_empresa').style.display = 'none';
	document.getElementById('last_resumen').style.display = 'none';
    document.getElementById('a_pagar').style.display = 'none';
    var i = 1;
    var elem2 = document.getElementById('user_container_' + i);
    while (elem2)
    {
        elem2.style.display = 'none';
        i++;
        elem2 = document.getElementById('user_container_' + i);
    }
}

function ValidateDatos(lng, sIsParticular)
{
    //CIF_NIF
	if(sIsParticular != '1')
	{
	    var datos_cif = document.getElementById('datos_cif').value;
	    if(datos_cif == '')
	    {
	        var message = lng == 'es' ? 'Escriba el numero de CIF' : 'Write the CIF number';
	        alert(message);
			ChangeStyleValidate('datos_cif', false);
	        return false;
	    }		
		
		var NIFValidator = new NIF_CIFValidator();
		if(!NIFValidator.checkCIF(datos_cif))
		{
			var message = lng == 'es' ? 'Formato de CIF incorrecto.\nNo se admiten guiones ni espacios.' : 'Wrong document format';
	        alert(message);
			ChangeStyleValidate('datos_cif', false);
	        return false;
		}
		ChangeStyleValidate('datos_cif', true);
	}
    //DENOMINACIÓN SOCIAL
	if(sIsParticular != '1')
	{
	    var denom_social = document.getElementById('datos_denom_social').value;
	    if(denom_social == '')
	    {
	        var message = lng == 'es' ? 'Escriba la denominación social' : 'Write the social name';
	        alert(message);
			ChangeStyleValidate('datos_denom_social', false);
	        return false;
	    }
		ChangeStyleValidate('datos_denom_social', true);
	}
    
	//INFO PERSONAL
	
	//NOMBRE 
    var datos_nombre = document.getElementById('datos_nombre').value;
    if(datos_nombre == '')
    {
        var message = lng == 'es' ? 'Escriba el nombre' : 'Write the name';
        alert(message);
		ChangeStyleValidate('datos_nombre', false);
        return false;
    }
	ChangeStyleValidate('datos_nombre', true);
	
    //APELLIDO 
    var datos_apellido1 = document.getElementById('datos_apellido1').value;
    if(datos_apellido1 == '')
    {
        var message = lng == 'es' ? 'Escriba sus apellidos' : 'Write your surname';
        alert(message);
		ChangeStyleValidate('datos_apellido1', false);
        return false;
    }
	ChangeStyleValidate('datos_apellido1', true);
	
    //MAIL 
    var datos_email = document.getElementById('datos_email').value;
    if(datos_email == '')
    {
        var message = lng == 'es' ? 'Escriba la direccion de email' : 'Write the email';
        alert(message);
		ChangeStyleValidate('datos_email', false);
        return false;
    }
    if(!datos_email.match("^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,4})+$"))
    {
        var message = lng == 'es' ? 'Formato de email incorrecto' : 'Incorrect email format';
        alert(message);
		ChangeStyleValidate('datos_email', false);
        return false;
    }
	ChangeStyleValidate('datos_email', true);
	
	//NIF
	if(sIsParticular == '1')
	{
		var datos_cif = document.getElementById('datos_nif').value;
		if(datos_cif == '')
		{
			var message = lng == 'es' ? 'Escriba el numero de documento' : 'Write the document number';
			alert(message);
			ChangeStyleValidate('datos_nif', false);
			return false;
		}
			
		if(document.getElementById('combo_tipo_doc').value != 'Otro')
		{
			var CIFValidator = new NIF_CIFValidator();
			if(!CIFValidator.checkNIF(datos_cif))
			{
				var message = lng == 'es' ? 'Formato de documento incorrecto.\nNo se admiten guiones ni espacios.' : 'Wrong document format';
				alert(message);
				ChangeStyleValidate('datos_nif', false);
				return false;
			}
			ChangeStyleValidate('datos_nif', true);
		}
	}
	
	//INFO DE CONTACTO
	
	//DIRECCIÓN 
    var datos_direccion = document.getElementById('datos_direccion').value;
    if(datos_direccion == '')
    {
        var message = lng == 'es' ? 'Escriba la direccion' : 'Write the addres';
        alert(message);
		ChangeStyleValidate('datos_direccion', false);
        return false;
    }
	ChangeStyleValidate('datos_direccion', true);
	
    //RESTO DIRECCIÓN 
    var datos_direccion_resto = document.getElementById('datos_direccion_resto').value;
    if(datos_direccion_resto == '')
    {
        var message = lng == 'es' ? 'Escriba el resto de la direccion' : 'Write the rest of the addres';
        alert(message);
		ChangeStyleValidate('datos_direccion_resto', false);
        return false;
    }
	ChangeStyleValidate('datos_direccion_resto', true);	
	
	//PROVINCIA 
	if(document.getElementById('datos_provincia_txt').style.display != 'none')
	{
		var datos_prov = document.getElementById('datos_provincia_txt').value;
		if(datos_prov == '')
		{
			var message = lng == 'es' ? 'Escriba la provincia' : 'Write the province/state';
			alert(message);
			ChangeStyleValidate('datos_provincia_txt', false);
			return false;
		}   
		ChangeStyleValidate('datos_provincia_txt', true);
	}
	
    //CIUDAD 
    var datos_ciudad = document.getElementById('datos_ciudad').value;
    if(datos_ciudad == '')
    {
        var message = lng == 'es' ? 'Escriba la ciudad' : 'Write the city';
        alert(message);
		ChangeStyleValidate('datos_ciudad', false);
        return false;
    }   
	ChangeStyleValidate('datos_ciudad', true);
	
	//CÓDIGO POSTAL
    var datos_cp = document.getElementById('datos_cp').value;
    if(datos_cp == '')
    {
        var message = lng == 'es' ? 'Escriba el codigo postal' : 'Write the postal code';
        alert(message);
		ChangeStyleValidate('datos_cp', false);
        return false;
    }
	if(document.getElementById('datos_pais').value == 'España')
	{
		if(!datos_cp.match("^\\d{5}$"))
		{
			var message = lng == 'es' ? 'Formato de codigo postal incorrecto' : 'Incorrect postal code format';
			alert(message);
			ChangeStyleValidate('datos_cp', false);
			return false;
		}
	}
	else
	{
		if(!datos_cp.match("^\\d{1,10}$"))
		{
			var message = lng == 'es' ? 'Formato de codigo postal incorrecto' : 'Incorrect postal code format';
			alert(message);
			ChangeStyleValidate('datos_cp', false);
			return false;
		}
	}
	ChangeStyleValidate('datos_cp', true);
	
    //TELÉFONO
	if(sIsParticular != '1')
	{
		var datos_telefono = document.getElementById('datos_telefono').value;
		if(datos_telefono == '')
		{
			var message = lng == 'es' ? 'Escriba el numero de telefono' : 'Write the telephone number';
			alert(message);
			ChangeStyleValidate('datos_telefono', false);
			return false;
		}
		if(document.getElementById('datos_pais').value == 'España')
		{
			if(!datos_telefono.match("^\\+{0,1}\\d{1,}$"))
			{
				var message = lng == 'es' ? 'Formato de telefono incorrecto' : 'Incorrect telephone format';
				alert(message);
				ChangeStyleValidate('datos_telefono', false);
				return false;
			}
		}
		ChangeStyleValidate('datos_telefono', true);
	}
	
	//MÓVIL
	if(sIsParticular == '1')
	{
		var datos_movil = document.getElementById('datos_movil').value;
		if(datos_movil == '')
		{
			var message = lng == 'es' ? 'Escriba el numero de telefono movil' : 'Write the mobile phone number';
			alert(message);
			ChangeStyleValidate('datos_movil', false);
			return false;
		}
		if(document.getElementById('datos_pais').value == 'España')
		{
			if(!datos_movil.match("^\\+{0,1}\\d{1,}$"))
			{
				var message = lng == 'es' ? 'Formato de telefono móvil incorrecto' : 'Incorrect mobile phone format';
				alert(message);
				ChangeStyleValidate('datos_movil', false);
				return false;
			}
		}
		ChangeStyleValidate('datos_movil', true);
	}    
	
	//OTROS DATOS FACTURA
	
    return true;
}

function ValidateDatosFacturacion(lng, sIsParticular)
{
	//if(sIsParticular != '1')//ESTE REQUISITO YA NO EXISTE PARA LOS DATOS DE FACTURACION
	//{
		if(document.getElementById('otros-datos-factura').style.display != 'none')
		{
			//CIF
			var datos_cif = document.getElementById('otros_cif').value;
			if(datos_cif == '')
			{
				var message = lng == 'es' ? 'Escriba el numero de CIF' : 'Write the CIF number';
				alert(message);
				ChangeStyleValidate('otros_cif', false);
				return false;
			}		
			
			var NIFValidator = new NIF_CIFValidator();
			if(!NIFValidator.checkCIF(datos_cif))
			{
				var message = lng == 'es' ? 'Formato de CIF incorrecto.\nNo se admiten guiones ni espacios.' : 'Wrong document format';
				alert(message);
				ChangeStyleValidate('otros_cif', false);
				return false;
			}
			ChangeStyleValidate('otros_cif', true);
			
			//DENOMINACION SOCIAL
			var denom_social = document.getElementById('otros_denom_social').value;
			if(denom_social == '')
			{
				var message = lng == 'es' ? 'Escriba la denomiación social' : 'Write the social name';
				alert(message);
				ChangeStyleValidate('otros_denom_social', false);
				return false;
			}
			ChangeStyleValidate('otros_denom_social', true);
			
			//DIRECCIÓN 
			var datos_direccion = document.getElementById('otros_datos_direccion').value;
			if(datos_direccion == '')
			{
				var message = lng == 'es' ? 'Escriba la direccion' : 'Write the addres';
				alert(message);
				ChangeStyleValidate('otros_datos_direccion', false);
				return false;
			}
			ChangeStyleValidate('otros_datos_direccion', true);
			
			//RESTO DIRECCIÓN 
			var datos_direccion_resto = document.getElementById('otros_direccion_resto').value;
			if(datos_direccion_resto == '')
			{
				var message = lng == 'es' ? 'Escriba el resto de la direccion' : 'Write the rest of the addres';
				alert(message);
				ChangeStyleValidate('otros_direccion_resto', false);
				return false;
			}
			ChangeStyleValidate('otros_direccion_resto', true);
			
			//CÓDIGO POSTAL
			var datos_cp = document.getElementById('otros_datos_cp').value;
			if(datos_cp == '')
			{
				var message = lng == 'es' ? 'Escriba el codigo postal' : 'Write the postal code';
				alert(message);
				ChangeStyleValidate('otros_datos_cp', false);
				return false;
			}
			if(!datos_cp.match("^\\d{5}$"))
			{
				var message = lng == 'es' ? 'Formato de codigo postal incorrecto' : 'Incorrect postal code format';
				alert(message);
				ChangeStyleValidate('otros_datos_cp', false);
				return false;
			}
			ChangeStyleValidate('otros_datos_cp', true);
			
			//CIUDAD 
			var datos_ciudad = document.getElementById('otros_datos_ciudad').value;
			if(datos_ciudad == '')
			{
				var message = lng == 'es' ? 'Escriba la ciudad' : 'Write the city';
				alert(message);
				ChangeStyleValidate('otros_datos_ciudad', false);
				return false;
			}   
			ChangeStyleValidate('otros_datos_ciudad', true);
		}
	//}
	return true;
}

function ValidateAlumno(numAlumno, lng, isParticular)
{
	var validar = document.getElementById('existing_user_msg_' + numAlumno).style.display == 'none';
    if(validar)
    {
		var esEspana = (document.getElementById('pais_alum_' + numAlumno).value == 'España');
	
        //NOMBRE
        var nombre = document.getElementById('nombre_' + numAlumno).value;
        if(nombre == '')
        {
            var message = lng == 'es' ? 'Escriba su nombre' : 'Write your name';
            alert(message);
			ChangeStyleValidate('nombre_' + numAlumno, false);
            return false;
        }
		ChangeStyleValidate('nombre_' + numAlumno, true);
		
        //APELLIDOS
        var apellidos = document.getElementById('apellidos_' + numAlumno).value;
        if(apellidos == '')
        {
            var message = lng == 'es' ? 'Escriba sus apellidos' : 'Write your surname';
            alert(message);
			ChangeStyleValidate('apellidos_' + numAlumno, false);
            return false;
        }
		ChangeStyleValidate('apellidos_' + numAlumno, true);
		
        //NÚMERO DE DOCUMENTO
        var num_doc = document.getElementById('num_doc_' + numAlumno).value;
        if(num_doc == '')
        {
            var message = lng == 'es' ? 'Escriba el número de documento' : 'Write the document number';
            alert(message);
			ChangeStyleValidate('num_doc_' + numAlumno, false);
            return false;
        }
		var NIFValidator = new NIF_CIFValidator();
		if(!NIFValidator.checkNIF(num_doc))
		{
			var message = lng == 'es' ? 'Formato de documento incorrecto.\nNo se admiten guiones ni espacios.' : 'Wrong document format';
	        alert(message);
			ChangeStyleValidate('num_doc_' + numAlumno, false);
	        return false;
		}
		ChangeStyleValidate('num_doc_' + numAlumno, true);
		
        //FECHA
        var ano = document.getElementById('anosCombo_' + numAlumno).value;
	    var mes = document.getElementById('mesesCombo_' + numAlumno).value;
	    var dia = document.getElementById('diasCombo_' + numAlumno).value;			
	    if(ano == -1 || mes == -1 || dia == -1)
	    {
            var message = lng == 'es' ? 'Escoja fecha de nacimiento' : 'Select your birthday date';
            alert(message);
			ChangeStyleValidate('anosCombo_' + numAlumno, false);
			ChangeStyleValidate('mesesCombo_' + numAlumno, false);
			ChangeStyleValidate('diasCombo_' + numAlumno, false);
            return false;
        }
		ChangeStyleValidate('anosCombo_' + numAlumno, true);
		ChangeStyleValidate('mesesCombo_' + numAlumno, true);
		ChangeStyleValidate('diasCombo_' + numAlumno, true);
		
		//MAIL
        var mail = document.getElementById('email_' + numAlumno).value;
        if(mail == '')
        {
            var message = lng == 'es' ? 'Escriba su direccion de email' : 'Write your email';
            alert(message);
			ChangeStyleValidate('email_' + numAlumno, false);
            return false;
        }
        if(!mail.match("^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,4})+$"))
        {
            var message = lng == 'es' ? 'Formato de email incorrecto' : 'Incorrect email format';
            alert(message);
			ChangeStyleValidate('email_' + numAlumno, false);
            return false;
        }
		ChangeStyleValidate('email_' + numAlumno, true);
		
        //TELEFONO
        var telefono = document.getElementById('telefono_' + numAlumno).value;
        if(telefono == '')
        {
            var message = lng == 'es' ? 'Escriba su numero de telefono' : 'Write your telephone number';
            alert(message);
			ChangeStyleValidate('telefono_' + numAlumno, false);
            return false;
        }
        if(!telefono.match("^\\+{0,1}\\d{1,}$"))
        {
            var message = lng == 'es' ? 'Formato de telefono incorrecto' : 'Incorrect telephone format';
            alert(message);
			ChangeStyleValidate('telefono_' + numAlumno, false);
            return false;
        }
		ChangeStyleValidate('telefono_' + numAlumno, true);
		
		
		//DATOS OPCIONALES

		
		//DATOS PROFESIONALES
		if(isParticular != "1")
		{
			//CARGO		
			var cargo = document.getElementById('cargo_' + numAlumno).value;
			if(cargo == '')
			{
				var message = lng == 'es' ? 'Escriba su cargo' : 'Write your position';
				alert(message);
				ChangeStyleValidate('cargo_' + numAlumno, false);
				return false;
			}
			ChangeStyleValidate('cargo_' + numAlumno, true);
			
			//DEPARTAMENTO
			var departamento = document.getElementById('departamento_' + numAlumno).value;
			if(departamento == '')
			{
				var message = lng == 'es' ? 'Escriba su departamento' : 'Write your department';
				alert(message);
				ChangeStyleValidate('departamento_' + numAlumno, false);
				return false;
			}
			ChangeStyleValidate('departamento_' + numAlumno, true);
		}
    }
    return true;
}

function ChangeStyleValidate(sControlId ,isValid)
{
	var ctrl = document.getElementById(sControlId);
	if(isValid)
	{
		ctrl.style.backgroundColor = '';
	}
	else
	{	
		ctrl.focus();
		ctrl.style.backgroundColor = 'rgb(255, 255, 204)';
	}
}

function PaisChanged(comboPais, prov_id)
{
	var prov_name = document.getElementById('name_provincia').value;

	if(comboPais.value == 'España')
	{
		var txtBox = document.getElementById(prov_id + "_txt");
		txtBox.style.display = 'none';
	
		var comboProv = document.getElementById(prov_id);
		comboProv.name = prov_name;
		comboProv.style.display = '';
		
		txtBox.name = 'no_name';
	}
	else
	{
		var comboProv = document.getElementById(prov_id);
		comboProv.style.display = 'none';
	
		var txtBox = document.getElementById(prov_id + "_txt");
		txtBox.name = prov_name;
		txtBox.style.display = '';
		
		comboProv.name = 'no_name';
	}
}

function PaisChangedDinamic(comboPais, prov_id, numAlumno)
{
	var prov_name = document.getElementById('name_provincia_' + numAlumno).value;

	if(comboPais.value == 'España')
	{
		var txtBox = document.getElementById(prov_id + "_" + numAlumno + "_txt");
		txtBox.style.display = 'none';
	
		var comboProv = document.getElementById(prov_id + "_" + numAlumno);
		comboProv.name = prov_name;
		comboProv.style.display = '';
		
		txtBox.name = 'no_name';
	}
	else
	{
		var comboProv = document.getElementById(prov_id + "_" + numAlumno);
		comboProv.style.display = 'none';
	
		var txtBox = document.getElementById(prov_id + "_" + numAlumno + "_txt");
		txtBox.name = prov_name;
		txtBox.style.display = '';
		
		comboProv.name = 'no_name';
	}
}

function ___crateTableCabecera()
{
	var oTable = document.getElementById('tbl_resumen');
	
	var iLastRow = oTable.rows.length;
	var oRow = oTable.insertRow(iLastRow);

	oCell = oRow.insertCell(0);
	oCell.innerHTML = 'Precio';
	oCell.style.color = "#CC0000";
    oCell.style.fontSize = "12px";
	oCell.style.fontWeight = "bold";

	oCell = oRow.insertCell(0);
	oCell.innerHTML = 'Descuento';
	oCell.style.color = "#CC0000";
    oCell.style.fontSize = "12px";
	oCell.style.fontWeight = "bold";
	
	var oCell = oRow.insertCell(0);
	oCell.innerHTML = 'Alumno';
	oCell.style.color = "#CC0000";
    oCell.style.fontSize = "12px";
	oCell.style.fontWeight = "bold";
}

function ___createTableRow(num_alumno)//, textName, textDescuentos, textResto)
{
	var oTable = document.getElementById('tbl_resumen');
	
	var iLastRow = oTable.rows.length;
	var oRow = oTable.insertRow(iLastRow);
	oRow.id = 'row_alumno_' + num_alumno;

	oCell = oRow.insertCell(0);
	oCell.id = "cell_alumno_" + num_alumno + "_resto";
	oCell.style.padding = "5px;";
	//oCell.innerHTML = textResto;

	oCell = oRow.insertCell(0);
	oCell.id = "cell_alumno_" + num_alumno + "_descuentos";
	oCell.style.padding = "5px;";
	//oCell.innerHTML = textDescuentos;
	
	var oCell = oRow.insertCell(0);
	oCell.width = "50%";
	oCell.id = "cell_alumno_" + num_alumno + "_nombre";
	oCell.style.padding = "5px;";
	//oCell.innerHTML = textName;
}
/**********************************************************************************************
FIN FUNCIONES DE INTERFAZ DE USUARIO PARA MATRICULACIONES
**********************************************************************************************/


/**********************************************************************************************
FUNCIONES PARA RELACIONES DE CURSOS Y USUARIOS
**********************************************************************************************/


/**** Relaciones de contenidos *****/
	// crea un hijo para el usuario loggeado. 
	function __addChildToUser(id_relation, iChildId) {
		var oAjax = new WBE_AjaxClass();
		oAjax.clear();
		oAjax.addPostParameter('cv_child_id', iChildId)
		oAjax.addPostParameter('relation_id', id_relation);
		oAjax.addPostParameter('content_ct_id', id_relation);
	
		oXmlDoc = oAjax.throwEventXML("cms_create_user_relation");
		return oXmlDoc;
	}
	
	//lo mismo que la funcion anterior , pero borra las caches
	function __addChildToUserWithCacheReset(id_relation, iChildId,ct_id) {
		var oAjax = new WBE_AjaxClass();
		oAjax.clear();
		oAjax.addPostParameter('cv_child_id', iChildId)
		oAjax.addPostParameter('relation_id', id_relation);
		oAjax.addPostParameter('content_ct_id', ct_id);

		oXmlDoc = oAjax.throwEventXML("cms_create_user_relation");
		return oXmlDoc;
	}	
	
	// añade la convocatoria al usuario (favoritos)
	// Relación usuario-convocatoria = 29
	function anyadirConvocatoriaFavorita(iChildId, relation) {
		var oXmlDoc = __addChildToUser(relation, iChildId);		
		return oXmlDoc;
	}
	
	// se elimina la convocatoria del usuario (favoritos)
	function deleteSimpleRelation(relationId, contentTypeId1, contentTypeId2) {
		var oAjax = new WBE_AjaxClass();		
		oAjax.clear();
		oAjax.addPostParameter('content_rel_id', relationId);		
		oAjax.addPostParameter('content_ct_id', contentTypeId1 + ',' + contentTypeId2);//PARA EL CMS_DELETE_CACHE		
		oAjax.throwEventXML("cms_delete_simple_relation");		
		window.location.reload();
	}
	
	function __delChildToUser(id_relation, ct_id)
	{
            var oAjax = new WBE_AjaxClass();
            oAjax.clear();
            oAjax.addPostParameter('content_rel_id', id_relation);
            oAjax.addPostParameter('ct_id', ct_id);
            oAjax.addPostParameter('cache_delete_codes', ct_id);
			oAjax.addPostParameter('content_ct_id', ct_id);
			
            oXmlDoc = oAjax.throwEventXML("cms_delete_simple_relation");
            return oXmlDoc;
	}
	
	function AddCursoToPlanificador(iChildId)
	{
		var oXmlDoc = __addChildToUser(34, iChildId);
		if(oXmlDoc)
		{
			alert('El curso ha sido añadido a tu planificador');
		}
		else
		{
			alert('Este curso ya está en tu planificador');
		}
	}

	//funciones para relacionar sedes a Usuarios
	function AddSedeToUsuario(iChildId)
	{
		var oXmlDoc = __addChildToUserWithCacheReset(35, iChildId,18);
		if(oXmlDoc)
		{
			alert('La sede ha sido añadida');
			window.location.reload();
		}
		else
		{
			alert('La sede ya está añadida en el listado');
		}
	}	
	
	function BorrarSedeXUsuario(ct_id)
	{
            if(!confirm('Confirma que deseas borrar la sede pulsando aceptar')) return;
            var a = __delChildToUser(ct_id,18);
            alert('Sede borrada correctamente');
            window.location.reload();
	}	
	
	function BorrarCursoPlanificadoUsuario(ct_id)
	{
            if(!confirm('Confirma que deseas quitar el curso de tu planificador')) return;
            var a = __delChildToUser(ct_id, 37);
            alert('Planificador actualizado correctamente');
            window.location.href = 'mi_planificador.html';
	}

	//funciones para relacionar disciplinas a Usuarios
	function AddDisciplinaToUsuario(iChildId)
	{
		var oXmlDoc = __addChildToUserWithCacheReset(36, iChildId,35);
		if(oXmlDoc)
		{
			alert('La disciplina ha sido añadida');
			window.location.reload();
		}
		else
		{
			alert('La disciplina ya está añadida en el listado');
		}
	}	
	
	function BorrarDisciplinaXUsuario(ct_id)
	{
            if(!confirm('Confirma que deseas borrar la disciplina pulsando aceptar')) return;
            var a = __delChildToUser(ct_id,35);
            alert('Disciplina borrada correctamente');
            window.location.reload();
	}		
	
	//funciones para relacionar servicios a Usuarios
	function AddServicioToUsuario(iChildId)
	{
		var oXmlDoc = __addChildToUserWithCacheReset(40, iChildId,66);
		if(oXmlDoc)
		{
			alert('El servicio ha sido añadido');
			window.location.reload();			
		}
		else
		{
			alert('El servicio ya está añadido en el listado');
		}
	}	
	
	function BorrarServicioXUsuario(ct_id)
	{
            if(!confirm('Confirma que deseas borrar el servicio pulsando aceptar')) return;
            var a = __delChildToUser(ct_id,66);
            alert('Servicio borrado correctamente');
            window.location.reload();
	}			


/**********************************************************************************************
FIN FUNCIONES CURSOS FAVORITOS
**********************************************************************************************/

var fechaselec = "";

function cambio_pestanas(muestra,oculta){
	document.getElementById(oculta).style.display="none";
	document.getElementById(muestra).style.display="";	
}

function enlazarProfesoresSede(){
	var id_sede = document.getElementById('comboProfesoresSede').value;
	if(id_sede!=-1)
	{
		window.location.href = "profesorado_de_una_sede.html?id_sede=" + id_sede;
	}
}

function enlazarProfesoresCurso(){
	var id_curso = document.getElementById('comboCursosSede').value;
	if(id_curso!=-1)
	{
		window.location.href = "ficha_de_un_curso_profesorado_de_un_curso.html?" + id_curso;
	}
}

function cambia(cual,como){
	if(como == 1) {	document.images[cual].src = "img/"+cual+"on.gif";	}

	if(como == 0) {	document.images[cual].src = "img/"+cual+".gif";	}
	}

function crear_swf(swf_archivo,swf_w,swf_h,swf_fondo,swf_wmode){
		document.write('\
		<OBJECT classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" \
			WIDTH="'+swf_w+'" HEIGHT="'+swf_h+'" id="hmi"> \
			<PARAM NAME=movie VALUE="'+ swf_archivo +'"> \
			<PARAM NAME=menu VALUE="false"> \
			<PARAM NAME=quality VALUE="high"> \
			<PARAM NAME=bgcolor VALUE="'+swf_fondo+'"> \
			<PARAM NAME=wmode VALUE="'+swf_wmode+'"> \
			<EMBED src="'+ swf_archivo +'" menu="false" quality="high" wmode="'+ swf_wmode +'" bgcolor="'+swf_fondo+'" WIDTH="'+swf_w+'" HEIGHT="'+swf_h+'" NAME="hmi" TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"></EMBED> \
		</OBJECT> \
		');
}

function destacarInput(oBjInput) {
	oBjInput.style.background = '#FFFFCC';
	oBjInput.style.border = '1px solid';
	oBjInput.style.borderColor = '#FF0000 #FFE2E2 #FFE2E2 #FF0000';
	oBjInput.focus();
}

function FijarFechaInscripcion(componente)
{							
	var cmbAno = document.getElementById('anosCombo_'+componente);
	var cmbMes = document.getElementById('mesesCombo_'+componente);
	var cmbDia = document.getElementById('diasCombo_'+componente);
	var ano = cmbAno[cmbAno.selectedIndex].value;
	var mes = cmbMes[cmbMes.selectedIndex].value;
	var dia = cmbDia[cmbDia.selectedIndex].value;							
	if(ano != -1 && mes != -1 && dia != -1)
	{
		
		var f = document.getElementsByName('att_input_188_2_'+componente+'_842')[0];
		f.value = dia + '/' + mes + '/' + ano;
	}
}	

// *********************************************************************************************
//  ************** Funciones para el proceso de inscripción: Ocultar / Mostrar capas *********************
// *********************************************************************************************

function desplegarOtrosDatosFactura(combo)
{	
	if(combo.value == 1)
		document.getElementById("otros-datos-factura").style.display="none";
	else if(combo.value == 2)
		document.getElementById("otros-datos-factura").style.display="block";	
}

//Formulario confirmacion asistencia a sesion informativa
function funcionOcultarOtrosModos()
{
	if(document.getElementById('comboValorOtros').value == 'Otros')
	{
		document.getElementById('campoOtros').style.display="block";
	}
	else if (document.getElementById('comboValorOtros').value != 'Otros')
	{
		document.getElementById('campoOtros').style.display="none";
	}
}

//Funciones para gestionar la fecha de inicio y fin del buscador avanzado
function FijarFechaBusqueda(opc)
{	
	if(opc=="fin")
	{
		var cmbAno = document.getElementById('anosComboFin');
		var cmbMes = document.getElementById('mesesComboFin');
		var cmbDia = document.getElementById('diasComboFin');
		var ano = cmbAno[cmbAno.selectedIndex].value;
		var mes = cmbMes[cmbMes.selectedIndex].value;
		var dia = cmbDia[cmbDia.selectedIndex].value;							
		if(ano != -1 && mes != -1 && dia != -1)
		{			
			var f = document.getElementsByName('f5_v2_537')[0];
			f.value = dia + '/' + mes + '/' + ano;
		}
	}
	else if (opc=="inicio")
	{
		var cmbAno = document.getElementById('anosComboInicio');
		var cmbMes = document.getElementById('mesesComboInicio');
		var cmbDia = document.getElementById('diasComboInicio');
		var ano = cmbAno[cmbAno.selectedIndex].value;
		var mes = cmbMes[cmbMes.selectedIndex].value;
		var dia = cmbDia[cmbDia.selectedIndex].value;							
		if(ano != -1 && mes != -1 && dia != -1)
		{
			
			var f = document.getElementsByName('f5_v1_537')[0];
			f.value = dia + '/' + mes + '/' + ano;
		}
	}
}
//*************************************** FIN *************************************************
//alert(FormatNumberInMaMode("2300"));
//alert(FormatNumberInMaMode("2300.58"));
//alert(FormatNumberInMaMode("230058.58"));


function FormatNumberInMaMode(strNumber)
{
	var theNumber = strNumber + '';;
	var theDecimals = '';
	var hasDecimals = theNumber.indexOf('.') != -1

	if(hasDecimals)
	{
		var auxNums = theNumber.split('.');
		theNumber = auxNums[0];
		theDecimals = auxNums[1];
				
	}
	
	var strAuxNumber = '';
	var count = 0;
	for(var i = theNumber.length - 1; i >= 0; i--)
	{
		strAuxNumber += theNumber.charAt(i);
		count++;
		if(count % 3 == 0 && i != 0)
			strAuxNumber += ".";
	}
	
	theNumber = ReverseString(strAuxNumber);
	
	if(hasDecimals)
		return theNumber + "," + theDecimals;
		
	return theNumber;
}

function ReverseString(strToReverse)
{
	var newString = '';
	var i = strToReverse.length - 1;	
	for (var x = i; x >=0; x--)
	{
		newString += strToReverse.charAt(x);
	}
	return newString;
}

// *********************************************************************************************
//  ******************** Funciones para las pestañas de la sección formación ***************************
// *********************************************************************************************

	function cambiarPestanya(opc) {
		//escondemos todos los contenidos
		document.getElementById("tab1").style.display="none";
		document.getElementById("tab2").style.display="none";
		document.getElementById("tab3").style.display="none";
		switch(opc)
		{
		case 1:
			//mostramos elcontenido de la primera opcion
			document.getElementById("tab1").style.display="block";
			break;
		case 2:
			//mostramos elcontenido de la segunda opcion
			document.getElementById("tab2").style.display="block";
			break;
		case 3:
			//mostramos elcontenido de la tercera opcion
			document.getElementById("tab3").style.display="block";
			break;
		}
	}
	
	function cambiarPestanyaPresencial(opc) {
		//escondemos todos los contenidos
		document.getElementById("tab1_presencial").style.display="none";
		document.getElementById("tab2_presencial").style.display="none";
		document.getElementById("tab3_presencial").style.display="none";
		switch(opc)
		{
		case 1:
			//mostramos elcontenido de la primera opcion
			document.getElementById("tab1_presencial").style.display="block";
			break;
		case 2:
			//mostramos elcontenido de la segunda opcion
			document.getElementById("tab2_presencial").style.display="block";
			break;
		case 3:
			//mostramos elcontenido de la tercera opcion
			document.getElementById("tab3_presencial").style.display="block";
			break;
		}
	}
	
	function cambiarPestanyaOnLine(opc) {
		//escondemos todos los contenidos
		document.getElementById("tab1_online").style.display="none";
		document.getElementById("tab2_online").style.display="none";
		switch(opc)
		{
		case 1:
			//mostramos elcontenido de la primera opcion
			document.getElementById("tab1_online").style.display="block";
			break;
		case 2:
			//mostramos elcontenido de la segunda opcion
			document.getElementById("tab2_online").style.display="block";
			break;
		}
	}

//*************************************** FIN *************************************************

//Funcion para mostrar detalles  del listado de cursos por la categoria de disciplina
function desesconderElElemento(idElemento){
			//alert("Entra en la funcion desconder!");
			document.getElementById(idElemento).style.display = 'block';	
			if(idElemento=="bloque_47")
			{				
				document.getElementById('bloque_2_47').style.display = 'block';
			}
			else if(idElemento=="bloque_48")
			{
				document.getElementById('bloque_2_48').style.display = 'block';
			}
			//alert("Sale de la funcion desconder!");
	}

//Funcion para ocultar detalles  del listado de cursos por la categoria de disciplina	
function esconderElElemento(idElemento){
	alert("Entra en la funcion esconder!");
	document.getElementById(idElemento).style.display = 'none';		
	
	if(idElemento=='bloque_47')	{
		document.getElementById('bloque_2_47').style.display = 'none';
	}else if(idElemento=='bloque_48'){
		document.getElementById('bloque_2_48').style.display = 'none';
	}
	
	document.getElementById('ocultado').style.display = 'none';	
	
	alert("Sale de la funcion esconder!");
}

/*function desesconderElElemento(idElemento){
			document.getElementById(idElemento).style.display = 'block';	
			if(idElemento=="bloque_47")
			{				
				document.getElementById('bloque_2_47').style.display = 'block';
			}
			else if(idElemento=="bloque_48")
			{
				document.getElementById('bloque_2_48').style.display = 'block';
			}
	}

*/


//JavaScript para rellenar el nombre de la ZONA PRIVADA - ICEMD
function RellenarNombreUsuario(nombre)
				{
					document.getElementById('nombreUsuario').innerHTML =  nombre;	
				}	

//JavaScript para el CHECK BOX del registro de usuarios
function CambioCheck(chk)
			{
				if(chk.checked == true) document.getElementById('btnGo').disabled='';
				else document.getElementById('btnGo').disabled='disabled';
			}

//Enviar a un amigo
function mySaveFunction()
{
	window.scroll(0, 0);
	this.uploadFiles();
	if (this.isAllUploaded()) {
		var oAjax = new WBE_AjaxClass();
		this.getParams(oAjax);
		// sromero 14-11-2007. Selecion de tipo de idioma en las alertas
		this.FormValidator.sLng=this.lngId;
		if(!this.FormValidator.validateForm(document.InmediaFrm, this.posId)) return false;							
		xmlObj = oAjax.throwEventXML(this.useEvent);							
		var respuesta = oAjax.getXMLNodeValue(xmlObj, "c");
		if(respuesta == '0')
		{
			alert('Ha sido imposible realizar el envío: El usuario al que quieres recomendar el curso consta en nuestras BBDD que no desea recibir informacion de ICEMD');
		}
		else
		{
			this.savePost(xmlObj);
		}	
	} 
	else {
			setTimeout(this.varName + '.save();', 1000);
	}																	
}
			
			
//JavaScript para EL ASESOR DE FORMACIÓN DE ICEMD
var caminoElegido=0;

function cambiarYComprobar(paso) {
				//escondemos todos los contenidos
				document.getElementById("titulo_paso_1").style.display="none";
				document.getElementById("titulo_paso_2").style.display="none";
				document.getElementById("marcador_de_pasos_1").style.display="none";
				document.getElementById("marcador_de_pasos_2").style.display="none";
				document.getElementById("marcador_de_pasos_3").style.display="none";
				document.getElementById("marcador_de_pasos_4").style.display="none";					
				document.getElementById("paso_1").style.display="none";
				document.getElementById("paso_2").style.display="none";
				document.getElementById("paso_3").style.display="none";
				document.getElementById("paso_4").style.display="none";
				document.getElementById("paso_5").style.display="none";
				document.getElementById("paso_6").style.display="none";
				document.getElementById("paso_7").style.display="none";
				document.getElementById("paso_8").style.display="none";
				switch(paso){
					case 3:
						if(document.getElementById('nombre').value == "" || document.getElementById('email').value == ""){							
							document.getElementById("titulo_paso_2").style.display="block";
							document.getElementById("marcador_de_pasos_1").style.display="block";
							document.getElementById("paso_2").style.display="block";		
							alert('Los campos Nombre y E-Mail son obligatorios');
						}
						else{					
							document.getElementById("titulo_paso_2").style.display="block";
							document.getElementById("marcador_de_pasos_2").style.display="block";
							document.getElementById("paso_3").style.display="block";						
						}
						break;
				}
			}
				
			function cambiar(paso) {
				//escondemos todos los contenidos
				document.getElementById("titulo_paso_1").style.display="none";
				document.getElementById("titulo_paso_2").style.display="none";
				document.getElementById("marcador_de_pasos_1").style.display="none";
				document.getElementById("marcador_de_pasos_2").style.display="none";
				document.getElementById("marcador_de_pasos_3").style.display="none";
				document.getElementById("marcador_de_pasos_4").style.display="none";					
				document.getElementById("paso_1").style.display="none";
				document.getElementById("paso_2").style.display="none";
				document.getElementById("paso_3").style.display="none";
				document.getElementById("paso_4").style.display="none";
				document.getElementById("paso_5").style.display="none";
				document.getElementById("paso_6").style.display="none";
				document.getElementById("paso_7").style.display="none";
				document.getElementById("paso_8").style.display="none";				
				switch(paso)
				{
					case 2:
						//datos de contacto
						document.getElementById("titulo_paso_2").style.display="block";
						document.getElementById("marcador_de_pasos_1").style.display="block";
						document.getElementById("paso_2").style.display="block";						
						break;
					case 3:
						//perfil						
						document.getElementById("titulo_paso_2").style.display="block";
						document.getElementById("marcador_de_pasos_2").style.display="block";
						document.getElementById("paso_3").style.display="block";						
						break;
					case 4:						
						//perfil
						document.getElementById("titulo_paso_2").style.display="block";
						document.getElementById("marcador_de_pasos_2").style.display="block";
						document.getElementById("paso_4").style.display="block";
						break;
					case 5:	
						//perfil
						document.getElementById("titulo_paso_2").style.display="block";
						document.getElementById("marcador_de_pasos_2").style.display="block";
						document.getElementById("paso_5").style.display="block";
						break;
					case 6:
						//motivacion
						document.getElementById("titulo_paso_2").style.display="block";
						document.getElementById("marcador_de_pasos_3").style.display="block";
						document.getElementById("paso_6").style.display="block";
						break;
					case 7:
						//disciplinas
						document.getElementById("titulo_paso_2").style.display="block";
						document.getElementById("marcador_de_pasos_4").style.display="block";
						document.getElementById("paso_7").style.display="block";
						break;
					case 8:
						//mensaje fin 
						document.getElementById("titulo_paso_2").style.display="block";
						document.getElementById("paso_8").style.display="block";
						break;
				}
			}
			
			function direccionar(){				
				if(document.getElementById('soy').value == "Estudiante"){
					cambiar(5);
					caminoElegido=1;
				}
				else if(document.getElementById('soy').value == "Profesional"){
					cambiar(4);
					caminoElegido=2;
				}
			}
			
			function direccionarAtras(){
				if(caminoElegido==1) cambiar(5);
				else if(caminoElegido==2) cambiar(4);
			}	

			//Fin de JavaScript para el asesor de formación
			

function ver_fecha() {

//if (valor == ""){
	var fecha=new Date();
//} else {
//	var fecha=new Date(valor);
//}
var diames=fecha.getDate();
var diasemana=fecha.getDay();
var mes=fecha.getMonth() +1 ;
var ano=fecha.getFullYear();

var textosemana = new Array (7);
  textosemana[0]="Domingo";
  textosemana[1]="Lunes";
  textosemana[2]="Martes";
  textosemana[3]="Miércoles";
  textosemana[4]="Jueves";
  textosemana[5]="Viernes";
  textosemana[6]="Sábado";

var textomes = new Array (12);
  textomes[1]="Enero";
  textomes[2]="Febrero";
  textomes[3]="Marzo";
  textomes[4]="Abril";
  textomes[5]="Mayo";
  textomes[6]="Junio";
  textomes[7]="Julio";
  textomes[7]="Agosto";
  textomes[9]="Septiembre";
  textomes[10]="Octubre";
  textomes[11]="Noviembre";
  textomes[12]="Diciembre";

//document.write("Fecha completa: " + fecha + "<br>");
//document.write("Dia mes: " + diames + "<br>");
//document.write("Dia semana: " + diasemana + "<br>");
//document.write("Mes: " + mes + "<br>");
//document.write("Año: " + ano + "<br>");
//document.write("Fecha: " + diames + "/" + mes + "/" + ano + "<br>");
//document.write("Fecha: " + textosemana[diasemana] + " " + diames + "/" + mes + "/" + ano + "<br>");
//document.write("Fecha: " + textosemana[diasemana] + ", " + diames + " de " + textomes[mes] + " de " + ano + "<br>");
document.write(textomes[mes] + " " + ano);
}

function ver_mes(valor) {

var fecha=new Date(valor);
var diames=fecha.getDate();
var diasemana=fecha.getDay();
var mes=fecha.getMonth() +1 ;
var ano=fecha.getFullYear();

var textomes = new Array (12);
  textomes[1]="Enero";
  textomes[2]="Febrero";
  textomes[3]="Marzo";
  textomes[4]="Abril";
  textomes[5]="Mayo";
  textomes[6]="Junio";
  textomes[7]="Julio";
  textomes[7]="Agosto";
  textomes[9]="Septiembre";
  textomes[10]="Octubre";
  textomes[11]="Noviembre";
  textomes[12]="Diciembre";

document.write(textomes[mes] + " " + ano);
}

function ver_year() {

var fecha=new Date();
var ano=fecha.getFullYear();

return ano;

}

function show_calendar_old(str_datetime) {
	var arr_months = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio","Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"];
	var week_days = ["Do", "Lu", "Ma", "Mi", "Ju", "Vi", "Sa"];
	var n_weekstart = 1; // dia de la semana por el que empieza (normalmente 0 o 1)

	var dt_datetime;
	if (str_datetime == null || str_datetime =="") {
		dt_datetime=new Date();
	} else {
		var re_date =str_datetime.split('/');
		var re2_date=re_date[2]+'/'+re_date[1]+'/'+re_date[0];
		dt_datetime=new Date(re2_date);
	}	
	var dt_hoy= new Date();
	
	var dt_prev_month = new Date(dt_datetime);
	dt_prev_month.setMonth(dt_datetime.getMonth()-1);
	var dt_next_month = new Date(dt_datetime);
	dt_next_month.setMonth(dt_datetime.getMonth()+1);
	var dt_firstday = new Date(dt_datetime);
	dt_firstday.setDate(1);
	dt_firstday.setDate(1-(7+dt_firstday.getDay()-n_weekstart)%7);
	var dt_lastday = new Date(dt_next_month);
	dt_lastday.setDate(0);
	

	var str_buffer = new String (
		"<TABLE id=\"calendarSmall\" cellSpacing=\"0\" cellPadding=\"0\" width=\"150\" align=\"center\" border=\"0\">\n"+
		"<TR>"+
		"<TD colSpan=\"7\" align=\"middle\">\n"+
		"<table cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\n"+
		"<tr>\n"+
		"<td valign=\"middle\">\n"+
		"<span>"+arr_months[dt_datetime.getMonth()]+"</span>\n"+
		"</td>\n"+"</tr>\n"+"</table>\n"+"</TD>\n"+"</TR>\n");

	var dt_current_day = new Date(dt_firstday);
	var s_hoy;
	// Pinta los dias de la semana
	str_buffer += "<tr>\n";
	for (var n=0; n<7; n++)
		str_buffer += "	<td>"+week_days[(n_weekstart+n)%7]+"</td>\n";
	// Pinta el calendario
	str_buffer += "</tr>\n";
	while (dt_current_day.getMonth() == dt_datetime.getMonth() ||
		dt_current_day.getMonth() == dt_firstday.getMonth()) {
		if (dt_current_day.getDate()<=dt_hoy.getDate() && (dt_current_day.getDate()+7)>=dt_hoy.getDate() && arguments[2]==1) str_buffer += "<tr id=\"selected_semana\">\n";
		else str_buffer += "<tr>\n";
		for (var n_current_wday=0; n_current_wday<7; n_current_wday++) {				
				if (dt_current_day.getMonth() == dt_datetime.getMonth())
					// pinta los dias de este mes--> si el dia es hoy lo destaca
					if (dt_current_day.getDate()==dt_hoy.getDate() && dt_current_day.getMonth()==dt_hoy.getMonth()) {
						str_buffer += "<td class=\"hoy\">"; 					
					}
					else str_buffer += "<td class=\"este_mes\">";
				else 
					// pinta los dias de otro mes
					str_buffer += "<td class=\"otro_mes\">";
				str_buffer += dt_current_day.getDate()+"</td>\n";
				dt_current_day.setDate(dt_current_day.getDate()+1);
		}
		str_buffer += "</tr>\n";
	}
	str_buffer +="</table>\n";
	if (arguments[1]==1) document.getElementById('a_calendar').innerHTML=str_buffer;
	else document.write (str_buffer);
	return s_hoy;
}


function show_calendar(str_datetime) {
	
	//alert(arguments[1]);
	var arr_months = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio","Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"];
	var week_days = ["Do", "Lu", "Ma", "Mi", "Ju", "Vi", "Sa"];
	var n_weekstart = 1; // dia de la semana por el que empieza (normalmente 0 o 1)

	var dt_datetime;
	
	if (str_datetime == null || str_datetime =="") {
		dt_datetime=new Date();
	} else {
		var re_date =str_datetime.split('/');
		var re2_date=re_date[2]+'/'+re_date[1]+'/'+re_date[0];
		dt_datetime=new Date(re2_date);
	}	
	var dt_hoy= new Date();
	
	var dt_prev_month = new Date(dt_datetime);
	dt_prev_month.setMonth(dt_datetime.getMonth()-1);
	var dt_next_month = new Date(dt_datetime);
	dt_next_month.setMonth(dt_datetime.getMonth()+1);
	var dt_firstday = new Date(dt_datetime);
	dt_firstday.setDate(1);
	dt_firstday.setDate(1-(7+dt_firstday.getDay()-n_weekstart)%7);
	var dt_lastday = new Date(dt_next_month);
	dt_lastday.setDate(0);
		
	var str_buffer = new String (
	"<ul><li class=\"mesNav\"  onclick=\"show_calendar('01/" + dt_datetime.getMonth()  + "/" + dt_datetime.getFullYear()  + "',1)\">&lt;&lt;&nbsp;&nbsp;" + "&nbsp;&nbsp;</li>" + 
	"<li class=\"mes\">" + arr_months[dt_datetime.getMonth()] + "&nbsp;&nbsp;" + dt_datetime.getFullYear() + "</li>" + 
	"<li class=\"mesNav\"  onclick=\"show_calendar('01/" + (dt_datetime.getMonth() + 2)  + "/" + dt_datetime.getFullYear()  + "',1)\">&gt;&gt;&nbsp;&nbsp;</li>") ;
	
	
	/*"<table cellspacing=0 cellspadding=0 border=0><tr><td onclick=\"show_calendar('01/" + 
	dt_datetime.getMonth()  + "/" + dt_datetime.getFullYear()  + 
	"',1)\">&lt;&lt;&nbsp;&nbsp;</td><td></td>" + arr_months[dt_datetime.getMonth()] + "<td onclick=\"show_calendar('01/" + 
	(dt_datetime.getMonth() + 2)  + "/" + dt_datetime.getFullYear()  + "',1)\">&gt;&gt;&nbsp;&nbsp;</td></tr></table>"*/
	
	 
	
	var dt_current_day = new Date(dt_firstday);
	var s_hoy;
	// Pinta los dias de la semana
	for (var n=0; n < 7; n++)
		str_buffer += "	<li class=\"dia\">" + week_days[(n_weekstart+n)%7] + "</li>\n";
	// Pinta el calendario
	while (dt_current_day.getMonth() == dt_datetime.getMonth() ||
		dt_current_day.getMonth() == dt_firstday.getMonth()) {
		//if (dt_current_day.getDate()<=dt_hoy.getDate() && (dt_current_day.getDate()+7)>=dt_hoy.getDate() && arguments[2]==1) str_buffer += "<tr id=\"selected_semana\">\n";
		//else str_buffer += "<tr>\n";	

//" + 	dt_current_day.getDate() + "/" + (dt_datetime.getMonth() + 1) + "/" + dt_datetime.getFullYear()) +"	
//alert("_" + 	dt_current_day.getDate() + "/" + (dt_datetime.getMonth() + 1) + "/" + dt_datetime.getFullYear()) +"_");
	for (var n_current_wday=0; n_current_wday<7; n_current_wday++) {		
		
				if (dt_current_day.getMonth() == dt_datetime.getMonth())
					// pinta los dias de este mes--> si el dia es hoy lo destaca
					if (dt_current_day.getDate()==dt_hoy.getDate() && dt_current_day.getMonth()==dt_hoy.getMonth()) 
						str_buffer += "<li class=\"hoy\" onclick=\"pickDate('" + dt_current_day.getDate() +
					"/" + (dt_current_day.getMonth() + 1) + "/" + dt_current_day.getFullYear() + "')\">"; 										
					else str_buffer += "<li onclick=\"pickDate('" + dt_current_day.getDate() +
					"/" + (dt_current_day.getMonth() + 1) + "/" + dt_current_day.getFullYear() + "')\">"; 					
				else 
					// pinta los dias de otro mes
					str_buffer += "<li class=\"otro_mes\" onclick=\"pickDate('" + dt_current_day.getDate() +
					"/" + (dt_current_day.getMonth() + 1) + "/" + dt_current_day.getFullYear() + "')\">"; 					
					
				str_buffer += dt_current_day.getDate()+"</li>\n";
				dt_current_day.setDate(dt_current_day.getDate()+1);
		}		
	}
	str_buffer +="</ul>\n";
	if (arguments[1]==1) document.getElementById('calendario').innerHTML=str_buffer;
	else document.write (str_buffer);
	return s_hoy;
}

function pickDate(sfecha)
{
	var dt = sfecha.split('/');
	var myDate=new Date();
	myDate.setFullYear(parseInt(dt[2]),parseInt(dt[1])-1,parseInt(dt[0]));
	var currentDate = new Date();
	//alert(myDate);
	//alert(currentDate);
		
	if(myDate >= currentDate)	
		document.getElementById('fecha_reserva').value = sfecha;
	else
		alert('Elija una fecha igual o posterior a hoy');
		
}


function toggleCompanyVisibility(oSender)
{
	var obj = document.getElementById('divDatosEmpresa');
	
	
		if (oSender.checked == false)
			obj.style.display='none';
		else
			obj.style.display ='block';
}

function hideCompany()
{
	var objC = document.getElementById('divDatosEmpresa');
	objC.style.display='none';
		
}

function showCompany()
{
	var objC = document.getElementById('divDatosEmpresa');
	
	objC.style.display ='block';	
}


function nextAvailableDays(txtAvailability)
{
	/*var objArrays;
	var previousDays;
	var nextDays;
	var objPreviousDays;
	var objNextDays;
	objArrays = txtAvailability.split('$');
	previousDays = objArrays[0];
	nextDays = objArrays[1];
	objPreviousDays = previousDays.split('#');
	objNextDays = nextDays.split('#');
		
	var objPreviousDays = new Array(previousDays.length);
	var objNextDays = new Array(objNextDays.length);
	
	for(i=0;i<previousDays.length;i++)
	{
		eval("arr" + i + " = previousDays[" + i + "].split(';')");
		eval("objPreviousDays[" + i + "] = arr" + i);		
	}
	
	for(j=0;i<objNextDays.length;j++)
	{
		eval("arr" + j + " = previousDays[" + j + "].split(';')");
		eval("objPreviousDays[" + j + "] = arr" + j);		
	}
	*/
	
	
	
}


//####################################################################
//		validador de fechas
//####################################################################

function validarFecha(sDT)
{
var objDT = sDT.split('/');
var dia;
var mes;
var anio;

dia = objDT[0];
mes = objDT[1];
anio = objDT[2];
var elMes = parseInt(mes);

if(elMes>12)
return 1;
// MES FEBRERO
if(elMes == 2){
if(esBisiesto(anio)){
if(parseInt(dia) > 29){
return 1;
}
else
return 0;
}
else{
if(parseInt(dia) > 28){
return 1;
}
else
return 0;
}
}
//RESTO DE MESES

if(elMes== 4 || elMes==6 || elMes==9 || elMes==11){
if(parseInt(dia) > 30){
return 1;
}
}
return 0;

}
//*****************************************************************************************
// esBisiesto(anio)
//
// Determina si el año pasado com parámetro es o no bisiesto
//*****************************************************************************************
function esBisiesto(anio)
{
var BISIESTO;
if(parseInt(anio)%4==0){
if(parseInt(anio)%100==0){
if(parseInt(anio)%400==0){
BISIESTO=true;
}
else{
BISIESTO=false;
}
}
else{
BISIESTO=true;
}
}
else
BISIESTO=false;

return BISIESTO;
}



/*
getHora(indice, horas, minutos)
Escribe en la página html el campo de la hora como un tipo <select> con valores
preseleccionados:
- indice: Nos sirve para dar el "name" a cada campo select que construyamos, de modo
que si hay varios en una misma página HTMK, cada uno tenga un nombre distinto
- hora: Hora predeterminado del campo select
- minutos: Minutos predeterminado
*/
function getHora(indice, horas, minutos)
{
var hh = "00";
var mm = "00";
if (arguments.length > 1)
{
hh = horas;
mm = minutos;
}
document.write("<select name='seHoraHH" + indice + "'>");
for(var i=0;i<24;i++)
{
var a;
if(i<10)
a="0"+i;
else
a=i;

if (a == hh)
{
document.write("<option value='"+a+"' selected>"+i+"</option>");
} else {
document.write("<option value='"+a+"'>"+i+"</option>");
}
}
document.write("</select>");
document.write(" : ");
document.write("<INPUT TYPE='text' MAXLENGTH='2' SIZE='2' NAME='txHoraMM" + indice + "' VALUE='" + mm + "'>");
} 

/* ------------------------------------------------------------------------------
* ------------------------------------------------------------------------------
*	Validador de CIF, NIF y Tarjeta de Residencia.
*	GEB.
*	------------------------------------------------------------------------------
*	------------------------------------------------------------------------------
*/
function NIF_CIFValidator() {

	this.NIF_Letters = "TRWAGMYFPDXBNJZSQVHLCKET";
	this.NIF_regExp = "^\\d{8}[a-zA-Z]{1}$";
	this.CIF_regExp = "^[a-zA-Z]{1}\\d{7}[a-jA-J0-9]{1}$";

	this.checkAll = function (value) {
		if (this.checkCIF(value))  { // Comprueba el CIF
			return true;
		} else if (this.checkTR(value)) { // Comprueba tarjeta de residencia
			return true;
		}else if (this.checkNIF(value)) { // Comprueba el NIF
			return true;
		} else  {           // Si no pasa por ninguno es false.
			return false;
		}
	}

	// VALIDA EL NIF
	this.checkNIF = function (nif) {
	// Comprueba la longitud. Los DNI antiguos tienen 7 digitos.
	if ((nif.length!=8) && (nif.length!=9)) return false;
	if (nif.length == 8) nif = '0' + nif; // Ponemos un 0 a la izquierda y solucionado
	
	// Comprueba el formato
	var regExp=new RegExp(this.NIF_regExp);
	if (!nif.match(regExp)) return false;

	var let = nif.charAt(nif.length-1);
	var dni = nif.substring(0,nif.length-1)
	var letra = this.NIF_Letters.charAt(dni % 23);
	return (letra==let.toUpperCase());
	}

	// VALIDA TARJETA DE RESIDENCIA
	this.checkTR = function (tr) {
		if ((tr.length!=10) && (tr.length!=9)) return false;
		if ((tr.charAt(0).toUpperCase() != "X")) return false;
		if (tr.length==9) {
			return this.checkNIF('0' + tr.substring(1,tr.length));
		} else {
			return this.checkNIF(tr.substring(1,tr.length));
		}
	}

	// VALIDA TARJETA DE RESIDENCIA
	this.checkCIF = function (cif) {
		var v1 = new Array(0,2,4,6,8,1,3,5,7,9);
		var tempStr = cif.toUpperCase(); // pasar a mayúsculas
		var temp = 0;
		var temp1;
		var dc;

		// Comprueba el formato
			var regExp=new RegExp(this.CIF_regExp);
		if (!tempStr.match(regExp)) return false;    // Valida el formato?
		if (!/^[ABCDEFGHKLMNPQS]/.test(tempStr)) return false;  // Es una letra de las admitidas ?

		for( i = 2; i <= 6; i += 2 ) {
			temp = temp + v1[ parseInt(cif.substr(i-1,1)) ];
			temp = temp + parseInt(cif.substr(i,1));
		};
		temp = temp + v1[ parseInt(cif.substr(7,1)) ];
		temp = (10 - ( temp % 10));
		if (temp==10) temp=0;
		dc  = cif.toUpperCase().charAt(8);
    return (dc==temp) || (temp==1 && dc=='A') || (temp==2 && dc=='B') || (temp==3 && dc=='C') || (temp==4 && dc=='D') || (temp==5 && dc=='E') || (temp==6 && dc=='F') || (temp==7 && dc=='G') || (temp==8 && dc=='H') || (temp==9 && dc=='I') || (temp==0 && dc=='J');
	}
}



// JavaScript Document: Funcion de aumentado y disminucion de la fuente

var fuente =14
var fuente2 = 12

function aumentar(){
fuente = fuente + 1
fuente2 = fuente2 + 1
if ((fuente > 20) || (fuente2 > 18))
{
fuente=20;
fuente2=18;
}
aumento_fuente = fuente+"px"
aumento_fuente2 = fuente2+"px"
document.getElementById("Tu_id").style.fontSize=aumento_fuente;
document.getElementById("Tu_id2").style.fontSize=aumento_fuente2;

}

function disminuir(){
fuente = fuente - 1
fuente2 = fuente2 - 1
if ((fuente < 8) || (fuente2 < 6))
{
fuente=8;
fuente2=6;
}
disminuir_fuente = fuente+"px";
disminuir_fuente2 = fuente2+"px";
document.getElementById("Tu_id2").style.fontSize=disminuir_fuente2;
document.getElementById("Tu_id").style.fontSize=disminuir_fuente;

}

function ImprimeFactura()
{
	//var dv = document.getElementById('lightbox');
	//dv.focus();
	window.print();
}

function DOM_Node_Move(id2Move, idDest)
{
	var oM = document.getElementById(id2Move);
	var oL = document.getElementById(idDest);	

	if (oL && oM) 
	{
		oL.appendChild(oM);
		oM.style.display='';
	}
}


/////////////////FUNCIONES PARA MENSAJERÍA PRIVADA
function MensajeLeido(sMensajeVerId)
{
	var oAjax = new WBE_AjaxClass();
	oAjax.clear();
	oAjax.addPostParameter('ver_id', sMensajeVerId);
	oAjax.addPostParameter('att_id', '362');
	oAjax.addPostParameter('lng_id', 'es');
	oAjax.addPostParameter('text', '1');
	oAjax.throwEventXML("css_save_att_value");
}

function MensajeBorrado(sMensajeVerId)
{
	var oAjax = new WBE_AjaxClass();
	oAjax.clear();
	oAjax.addPostParameter('ver_id', sMensajeVerId);
	oAjax.addPostParameter('att_id', '363');
	oAjax.addPostParameter('lng_id', 'es');
	oAjax.addPostParameter('text', '1');
	oAjax.throwEventXML("css_save_att_value");
	window.location.reload();
}

/////////////////FUNCIONES RECOGIDAS de la xsl user_login2.xslt
//Nos devolverá el valor solicitado
function gup( name ){
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp ( regexS );
	var tmpURL = window.location.href;
	var results = regex.exec( tmpURL );
	if( results == null )
		return"";
	else
		return results[1];
}


function IniciarMatriculaUno()
{	
	var id_convocatoria = gup( 'id_convocatoria' );

	if(document.getElementById('cond_1').checked) 
		window.location.href="formulario_de_inscripcion.html?subs_id="+id_convocatoria+"&p=1";
	else alert('Debe aceptar las condiciones de contratación para iniciar el proceso de matriculación');										
}

function IniciarMatriculaVarios()
{	
	var id_convocatoria = gup( 'id_convocatoria' );
	if(document.getElementById('cond_2').checked) 
		window.location.href="formulario_de_inscripcion.html?subs_id="+id_convocatoria;
	else alert('Debe aceptar las condiciones de contratación para iniciar el proceso de matriculación');										
}

function enlaceSinRegistrar()
{	
	var id_convocatoria = gup( 'id_convocatoria' );
	
	if(document.getElementById('valorDeAcceso').value==1)
	{
		window.location.href="formulario_de_inscripcion.html?subs_id="+id_convocatoria+"&p=1";																			
	}
	else if(document.getElementById('valorDeAcceso').value==2)
	{
		window.location.href="formulario_de_inscripcion.html?subs_id="+id_convocatoria;
	}												
}

function enlaceYaLogeado()
{	
	var id_convocatoria = gup( 'id_convocatoria' );
	
	if(document.getElementById('valorDeAcceso2').value==1)
	{
		window.location.href="formulario_de_inscripcion.html?subs_id="+id_convocatoria+"&p=1";
	}
	else if(document.getElementById('valorDeAcceso2').value==2)
	{
		window.location.href="formulario_de_inscripcion.html?subs_id="+id_convocatoria;
	}												
}


/////////////////////FUNCIONALIDADES ADICIONALES AGENDA MINI
function recogeEventoyCurso(fecha)
{
	var idsCC='';
	var idsCE='';
	//document.getElementById('midd_'+fecha).innerHTML = "&lt;img src='skin/images/ajax-loader.gif' /&gt; ";	
	for(i=0; i <= 30; i++)
	{
		var expresion = 'conv_cc_' + fecha+'_'+i;
		
		if (document.getElementById(expresion)){
			var valor = document.getElementById(expresion).value;
			
			if(document.getElementById(expresion).value!='')
			{
				if (idsCC != ''){
					idsCC= idsCC + ',' + document.getElementById(expresion).value;													
				}else{
					idsCC = document.getElementById(expresion).value;
				}
			}
			
		}
	}
				
	for(i=0; i <= 30; i++)
	{
		var expresion = 'conv_ce_' + fecha+'_'+i;
		
		if (document.getElementById(expresion)){
			var valor = document.getElementById(expresion).value;
			
			if(document.getElementById(expresion).value!='')
			{
				if (idsCE != ''){
					idsCE= idsCE + ',' + document.getElementById(expresion).value;													
				}else{
					idsCE = document.getElementById(expresion).value;
				}
			}
			
		}
	}
	//alert('Elementos idsCC:'+idsCC);	
	//alert('Elementos idsCE:'+idsCE);	
	
	/* Se realiza la llamada al proceso */
	var xmlObj;
	var oAjax = new WBE_AjaxClass();
	oAjax.clear();
	oAjax.addPostParameter("idsCC", idsCC);
	oAjax.addPostParameter("idsCE", idsCE);
	sEvent = 'event_name_curse_event';
	xmlObj = oAjax.throwEventXML(sEvent);
	//alert(sEvent);
	if (xmlObj){
		//alert(xmlObj.xml);
		//alert(oAjax.getXMLNodeValue(xmlObj, "s"));
		//var = texto =
		document.getElementById('midd_'+fecha).innerHTML = oAjax.getXMLNodeValue(xmlObj, "s")+ '</ul>';
	}
}		