﻿function ___mostrar_capa(nombreCapa, numero_capas, nombrePestanya){
	for(i=1;i<numero_capas+1;i++){
		if (document.getElementById('capa'+i) != null)
			document.getElementById('capa'+i).style.display="none";
		if (document.getElementById('p'+i) != null)
			document.getElementById('p'+i).className="";
	}
	document.getElementById(nombreCapa).style.display="inline";
	document.getElementById(nombrePestanya).className='current';
}

// Comprueba para un campo que no existe un torneo con la misma fecha de inicio.
function __validateDate(daDate, iCType, iCurrentVersion) {
	var oAjax;
	oAjax = new WBE_AjaxClass();
	oAjax.clear();
	if (iCurrentVersion) oAjax.addPostParameter("ver_id", iCurrentVersion);
	oAjax.addPostParameter("content_ct_id", iCType);
	oAjax.addPostParameter("f_ini_torneo", daDate.value);
	var oXML = oAjax.throwEventXML("check_content_form_field");
	var iTotal = oAjax.getXMLNodeValue(oXML, "total");
	if (iTotal>1) {
		alert('Tienes ' + iTotal + ' torneos que empiezan en esta fecha. Asegurate que la fecha es correcta');
		daDate.select();
		return false;
	}
	return true;
}

// Mueve una capa de una a otra.
function __MoverCapas(origen, destino) {
  var oInscritos = document.getElementById(origen);
  var oDestino = document.getElementById(destino);
  if (oDestino && oInscritos) oDestino.appendChild(oInscritos);
}

// Llamada desde el buscador
function __GoTorneosLinkForm(link_page, position_id) {
  var daNow = new Date();
  var daFecha = daNow.getDate() + '/' + (daNow.getMonth()+1) + '/' + daNow.getYear();
  var oOrder = eval("document.forms[0].order_by_" + position_id);
  var oF1 = eval("document.forms[0].f2_v1_" + position_id);
  var oF2 = eval("document.forms[0].f2_v2_" + position_id);
  if (oOrder.value==1) {
    oOrder.value = oOrder.value=0;
    oF1.value = daFecha;
    oF2.value = '';
  } else {
    oOrder.value = oOrder.value=1;
    oF1.value = '';
    oF2.value = daFecha;
  }
  document.forms[0].order_by.value = oOrder.value;   // esto es necesario para la paginación
  eval("objJS_" + position_id + ".applyAttributeFilter()");
}

// Despublica una version (LA ELIMINA PARA MANTENER COMPATIBILIDAD)
function deleteInsc(sVerId, posId, pageId) {
	if (!confirm("¿Estás seguro que quieres eliminar la inscripción?")) return;
	var oAjax = new WBE_AjaxClass();
	oAjax.clear();
	oAjax.addPostParameter("ver_id", sVerId);
	oAjax.throwEvent2("cms_delete_version");
	document.location.reload();
}


function showOnlineForm(bDatesOk, bPaintOnlineForm) {
	if (bDatesOk && bPaintOnlineForm) document.getElementById("formulario_inscripcion").style.display = '';
	}

function showParejasForm(bVal) {
	if (!bVal) return;
	document.getElementById("title_participante_2").style.display = '';
	document.getElementById("form_participante_2").style.display = '';
}

// Comprueba que todos los campos de parejas están rellenados.
function prepareForm4Parejas(bParejas, objJS) 
{
	var oElem, name;
	if (!bParejas) return true;
	// Recorre todos los INPUT del formulario y comprueba que son de esta posiciÃƒÂ³n
	var oElems = document.getElementsByTagName("INPUT");
	for (i=0;i<oElems.length;i++) {
		oElem = oElems[i];
		//alert(oElem.name + "--" + oElem.getAttribute("required"));
		// Si es un elemento del formulario
		if (oElem.name != null && 
				oElem.name.indexOf('att_input_') == 0 &&
				oElem.name.indexOf('_' + objJS.posId) > 0 &&
				oElem.getAttribute("required")==null &&
				oElem.getAttribute("optional")==null) {
				//alert(oElem.tagName + "--" + oElem.name + "--" + oElem.getAttribute("required"));
				oElem.setAttribute("required", "1");
		}
	}
}

// Comprueba que los desplegables de sexo y categoría son correctos en los participantes
// en función del torneo.
function precheckForm(bParejas, iAgrupacion, iNivel)
{
	var aValores = new Array();
	var sErrorMsg = '';
	var v1, v2;

	// Comprobar parejas.
	var oElems = document.getElementsByTagName("SELECT");
	for (i=0;i<oElems.length;i++) {
		var oSelec = eval('document.forms[0].'+ oElems[i].name);
		aValores[aValores.length] = oSelec[oSelec.selectedIndex].value;
	}

	// Nivel 1er jugador
	v1 = aValores[1];
	
	// Nivel (para 1 participante)
	var bOk = (iNivel==5 && v1>=3) || (iNivel==6 && v1>=4) || (iNivel==7 && v1>=5) || (iNivel==8 && v1>=7) || (iNivel==140 && v1<=2) || (iNivel==130 && v1<=2) || iNivel<5
	if (!bOk) sErrorMsg = "El Nivel seleccionado no es el correcto para este torneo";
	
	if (!bParejas) {
		if (sErrorMsg!='') alert(sErrorMsg);
		return bOk;
	}

	/*ORIGNAL--if (!bParejas) {
		if (sErrorMsg!='') alert(sErrorMsg);
		return false;//bReturn;
	}*/

	/* ABEL--if (!bOk) {
		if (sErrorMsg!='') alert(sErrorMsg);
		return false;
	}
*/	
	// Comprobar agrupación del 1er y 2do concursante
	v1 = aValores[0];
	v2 = aValores[2];
	
	if (iAgrupacion==3 && v1!=v2) sErrorMsg += "\nLos jugadores deben ser del mismo sexo";
	if (iAgrupacion==4 && v1==v2) sErrorMsg += "\nLos jugadores deben ser de diferente sexo";

	// Nivel 2do participante
	v2 = aValores[3];
	bOk =  (iNivel==5 && v2>=3) || (iNivel==6 && v2>=4) || (iNivel==7 && v2>=5) || (iNivel==8 && v2>=7) || (iNivel==140 && v1<=2) || (iNivel==130 && v1<=2) || iNivel<5;
	if (!bOk) sErrorMsg += "\nEl Nivel seleccionado del segundo jugador es el correcto para este torneo";
	
	
	if (sErrorMsg!='') {
		alert(sErrorMsg);
		return false;
	}
		
	return true;
}
/*
// Guarda la inscripciónn
function ___saveInscripcion(curr_id, objJS, sGotoPage, bParejas, iAgrupacion, iNivel) {
	if (!curr_id || curr_id==null) {
		alert('Formulario mal configurado. Contacte con el administrador.')
		return;
	}
	var iContentID;
	var oL1 = document.getElementById("formulario_inscripcion");
	var oL2 = document.getElementById("form_ok_" + objJS.posId);
	if (objJS.isAllUploaded()) {
		var oAjax = new WBE_AjaxClass();
		prepareForm4Parejas(bParejas, objJS);
		var oValidator = new WBEFormValidator();
		if (!oValidator.validateForm(document.forms[0], objJS.posId) || !precheckForm(bParejas, iAgrupacion, iNivel)) return false;
		objJS.saveSubscription(getPrice(), 'Ds_Merchant_Titular=' + getTitular())
		objJS.getParams(oAjax);
		oL1.style.display = "none";
		oL2.style.display = "";
		xmlObj = oAjax.throwEventXML("inscripcion_torneo");
		iContentID = oAjax.getXMLNodeValue(xmlObj, "ver_id");
		//if (xmlObj) document.location.href=sGotoPage + "&ver_id=" + iContentID;
		if (xmlObj) document.location.href="resultado_inscripcion.html?ver_id=" + curr_id + "&insc=" + iContentID;
	}
}
*/


// Realiza la inscripción al torneo
function ___saveInscripcion(curr_id, objJS, sGotoPage, bParejas, iAgrupacion, iNivel, precio1, precioESPE) {
	var oPayType = document.forms[0].tipo_insc;	
	var boton = document.getElementById("boton_inscrp");
	boton.disabled = 'true';
	boton.value = 'Espere un momento';
	if(document.getElementById("licencia_2")) validarLicencia(document.getElementById("licencia_2"),curr_id);
	if(document.getElementById("licencia")) validarLicencia(document.getElementById("licencia"),curr_id);
	if (oPayType && oPayType.length && oPayType[0].checked) {
		if (confirm('Va a realizar el pago on-line mediante tarjeta.\nLa inscripción se registra al terminar el proceso de pago correctamente.')) {
			___saveAndPay(curr_id, objJS, sGotoPage, bParejas, iAgrupacion, iNivel, precio1, precioESPE);
		}
	} else {
		___saveNoPay(curr_id, objJS, sGotoPage, bParejas, iAgrupacion, iNivel)
	}
}

// Guarda la inscripción sin pagar
function __savePostInscripcion(xmlObj) {
	var oAjax = new WBE_AjaxClass();
	if (xmlObj==null) return;
	iContentID = oAjax.getXMLNodeValue(xmlObj, "id");
	document.location.href="resultado_inscripcion.html?ver_id=" + iContentID;
}
function ___saveNoPay(curr_id, objJS, sGotoPage, bParejas, iAgrupacion, iNivel) {
	if (!curr_id || curr_id==null) {
		alert('Formulario mal configurado. Contacte con el administrador.')
		return;
	}
	
	prepareForm4Parejas(bParejas, objJS);
	var oValidator = new WBEFormValidator();
	if (!oValidator.validateForm(document.forms[0], objJS.posId) || !precheckForm(bParejas, iAgrupacion, iNivel)) return false;

	objJS.useEvent='inscripcion_torneo';
	objJS.savePost = __savePostInscripcion;
	objJS.save();
/*	

	
	var iContentID;
	var oL1 = document.getElementById("formulario_inscripcion");
	var oL2 = document.getElementById("form_ok_" + objJS.posId);
	if (objJS.isAllUploaded()) {
		var oAjax = new WBE_AjaxClass();
		prepareForm4Parejas(bParejas, objJS);
		var oValidator = new WBEFormValidator();
		if (!oValidator.validateForm(document.forms[0], objJS.posId) || !precheckForm(bParejas, iAgrupacion, iNivel)) return false;
		objJS.saveSubscription(getPrice(), 'Ds_Merchant_Titular=' + getTitular())
		objJS.getParams(oAjax);
		oL1.style.display = "none";
		oL2.style.display = "";
		xmlObj = oAjax.throwEventXML("inscripcion_torneo");
		iContentID = oAjax.getXMLNodeValue(xmlObj, "ver_id");
		//if (xmlObj) document.location.href=sGotoPage + "&ver_id=" + iContentID;
		if (xmlObj) document.location.href="resultado_inscripcion.html?ver_id=" + curr_id + "&insc=" + iContentID;
	}
*/
}

function __GetPrice(iNivel, iP1, iP2) {
	return (iNivel>=3) ? iP2 : iP1;
}

function __GetTotalPrice(bParejas, iP1, iP2) {
	var aValores = new Array();
	// Comprobar parejas.
	var oElems = document.getElementsByTagName("SELECT");
	for (i=0;i<oElems.length;i++) {
		var oSelec = eval('document.forms[0].'+ oElems[i].name);
		aValores[aValores.length] = oSelec[oSelec.selectedIndex].value;
	}
	var iPrec1 = __GetPrice(aValores[1], iP1, iP2);
	var iPrec2 = (bParejas) ? __GetPrice(aValores[3], iP1, iP2) : 0;
	return iPrec1+iPrec2;
}

// Guarda la inscripcion
function ___saveAndPay(curr_id, objJS, sGotoPage, bParejas, iAgrupacion, iNivel, precio1, precioESPE) {
	if (!curr_id || curr_id==null) {
		alert('Formulario mal configurado. Contacte con el administrador.')
		return;
	}
	var iContentID;
//	var oL1 = document.getElementById("formulario_inscripcion");
//	var oL2 = document.getElementById("form_ok_" + objJS.posId);
	
//	var oAjax = new WBE_AjaxClass();
	prepareForm4Parejas(bParejas, objJS);
	var oValidator = new WBEFormValidator();
	if (!oValidator.validateForm(document.forms[0], objJS.posId) || !precheckForm(bParejas, iAgrupacion, iNivel)) return false;

	var iTotalPrice = __GetTotalPrice(bParejas, precio1, precioESPE);
	objJS.useEvent='pre_inscripcion_torneo_tpv';
	objJS.saveSubscription(iTotalPrice);

//	objJS.getParams(oAjax);
//	oL1.style.display = "none";
//	oL2.style.display = "";
//	xmlObj = oAjax.throwEventXML("inscripcion_torneo");
//	iContentID = oAjax.getXMLNodeValue(xmlObj, "ver_id");
	//if (xmlObj) document.location.href=sGotoPage + "&ver_id=" + iContentID;
	//if (xmlObj) document.location.href="resultado_inscripcion.html?ver_id=" + curr_id + "&insc=" + iContentID;
}

function validarLicencia(obj, ver_id) {
    var oAjax = new WBE_AjaxClass();
    var bReturn = true;
    var sError = "Este número de licencia ya está inscrito.";


    // Primero comprueba que los valores son diferentes entre sí.
    var o1 = document.getElementById("licencia");
    var o2 = document.getElementById("licencia_2");
    if (o1.value!='' && o2.value!='' && o1.value==o2.value) {
      bReturn=false;
      obj.focus();
      obj.value='';
      alert(sError);
    }

	// ajax    
    if (!obj || obj.value == "") return bReturn;
    oAjax.addPostParameter("ver_id", ver_id);
    oAjax.addPostParameter("lic", obj.value);
  	var xmlObj = oAjax.throwEventXML("validar_inscripcion_licencia");
  	iTotal = oAjax.getXMLNodeValue(xmlObj, "total");
  	if (iTotal > 0) {
      bReturn=false;
      obj.select();
      obj.value='';
      alert(sError)
    }
    return bReturn;
}

function __SearchTorneo(v1, v2, obj, pos_id) {
	eval("document.forms[0].f2_v2_" + pos_id).value = v2;
	obj.calendarGoToDay(v1, v2);
}

function __SetLicValidation(obj, iNivel, iLic) {
	if (iNivel==null || iNivel=='' || iLic==null || iLic=='') return;
	obj.removeAttribute("expresionRegular");
	var expReg, errMsg;
	var const_iProfesional = 140;
	if (iLic=='1') {
		if (iNivel!=const_iProfesional) {
			expReg = "^(L|l)(v|V)\\d{8}$";
			errMsg = "No es una licencia válida de la FGCV.\n El formato debe ser del tipo LV00000000";
		} else {
			expReg = "^(L|l)(v|V)\\d{6}-(P|p)$";
			errMsg = "No es una licencia profesional válida de la FGCV.\n El formato debe ser del tipo LV000000-P";
		}
	} else if (iLic=='2') {
		if (iNivel!=const_iProfesional) {
			expReg = "^[a-zA-Z0-9]{2}\\d{8}$";
			errMsg = "No es una licencia válida de la RFEG.\n El formato debe ser del tipo XX00000000 o 0000000000";
		} else {
			expReg = "^[a-zA-Z0-9]{2}\\d{6}-(P|p)$";
			errMsg = "No es una licencia profesional válida de la RFEG.\n El formato debe ser del tipo XX000000-P o 00000000-P";
		}
	}
	obj.setAttribute("expresionRegular", expReg);
	obj.setAttribute("errorMessage", errMsg);
}

// funcion pop -up imagenes
var ventana
var cont=0
var titulopordefecto = "IMAGEN AMPLIADA" 

function afoto(cual,titulo)
{
if(cont==1){ventana.close();ventana=null}
if(titulo==null){titulo=titulopordefecto}
ventana=window.open('','ventana','resizable=yes,scrollbars=no')
ventana.document.write('<html><head><title>' + titulo + '</title></head><body style="overflow:hidden" marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" scroll="no" onUnload="opener.cont=0"><img src="' + cual + '" onLoad="opener.redimensionar(this.width, this.height)">')
ventana.document.close()
cont++
}

function redimensionar(ancho,alto)
{
ventana.resizeTo(ancho+13,alto+53);
ventana.resizeTo(ancho+13,alto+53);
ventana.moveTo((screen.width-ancho)/2,(screen.height-alto)/2) //centra la ventana. Eliminar si no se quiere centrar el popup
}

//Si no hay categoría seleccionada obligo a que se seleccione la primera
function comprobarURLfitness()
{
	var s = window.location.href;
	if(s.match(/cat_id/) == null)
	{
		window.location.href = 'fitness.html?cat_id=1';
	}
		
}

//Login para sección fitness
function loginFitness()
{
	var licencia = document.getElementById('lic_fed').value;
	if(licencia == '')
	{
		alert('Escriba su número de licencia');
		document.getElementById('lic_fed').focus();	
	}
	else if(licencia.match(/^(LV)\d{8}$/i) == null)
	{
		alert('Número de licencia incorrecto');
		document.getElementById('lic_fed').focus();
	}
	else
	{
		var oAjax = new WBE_AjaxClass();
		var xmlObj = oAjax.throwEventXML('fitness_login');
		if(xmlObj != null)
		{
			var ok = oAjax.getXMLNodeValue(xmlObj, "loginFitness");
			if(ok == 1)
			{
				window.location.href = 'fitness.html';
			}
			else//Esto no va a ocurrir porque no se hace ninguna comprobación en el servidor. Ahora siempre se devuelve 1
			{
				alert('Los datos de su licencia son incorrectos');
			}
		}
		else
		{
			alert('Ocurrió un error de comunicación con el servidor. Inténtelo de nuevo más tarde.\x0ADisculpe las molestias');
		}
	}
}

//Capturar Enter en la caja de texto de Fitness Login
function EnterKeyPressed(event)
{
	if (event.which==13 || event.keyCode==13)
	{
		loginFitness();
	}
}
/*

var ventana
var cont=0
var titulopordefecto = "IMAGEN AMPLIADA" 

function afoto(cual,titulo)
{
if(cont==1){ventana.close();ventana=null}
if(titulo==null){titulo=titulopordefecto}
ventana=window.open('','ventana','resizable=yes,scrollbars=no')
ventana.document.write('<html><head><title>' + titulo + '</title></head><body style="overflow:hidden" marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" scroll="no" onUnload="opener.cont=0"><img src="' + cual + '" onLoad="opener.redimensionar(this.width, this.height)">')
ventana.document.close()
cont++
}

function redimensionar(ancho,alto)
{
ventana.resizeTo(ancho+13,alto+53);
ventana.resizeTo(ancho+13,alto+53);
ventana.moveTo((screen.width-ancho)/2,(screen.height-alto)/2) //centra la ventana. Eliminar si no se quiere centrar el popup
}
*/

//buscador de Fitness y Faq
function fbuscar()
{
	var sXml;
	var oDivFields;
	
	sXml = this.createXmlFilter()
	if (!this.searchId || this.searchId=='') this.searchId = this.posId;
	oDivFields = document.getElementById("att_filter_form_" + this.posId);
	oDivFields.innerHTML = '';
	oDivFields.appendChild(this.createINPUT("session_search_id", this.session_search_id));
	oDivFields.appendChild(this.createINPUT("new_filter_" + this.searchId, this.posId));
	oDivFields.appendChild(this.createINPUT("filter_xml_" + this.posId, sXml));

	if (this.filter_action && this.filter_action!='') {
		// Limpiamos los filter_action que acaban con un '&'
		if ( this.filter_action.substring(this.filter_action.length - 1, this.filter_action.length) == "&" ) {
			this.filter_action = this.filter_action.substring(0, this.filter_action.length - 1);
		}
		
		// quitamos este parametro para no ponerlo 2 veces
		if ( this.filter_action.indexOf('session_search_id') > 1 ) { 
			//todo: Detectar si hay mas parametros despues del session_search y no cortarlos
			this.filter_action = this.filter_action.substring(0, this.filter_action.indexOf('session_search_id')-1);
		}
		
		document.forms[0].action = this.filter_action
	}
	//asignar al forms[0] el valor de la URL
		var urlfinal;
		var posicion = document.URL.indexOf('cat_id');
	if(document.URL.indexOf('cat_id=2') > 0) {
		urlfinal = document.URL.substring(0,posicion);
		urlfinal = urlfinal.concat('cat_id=12');
		document.forms[0].action = urlfinal;
		//document.forms[0].action = 'http://www.golfcv.com/fitness.html?cat_id=12';
	} else {if(document.URL.indexOf('cat_id=4') > 0){
		urlfinal = document.URL.substring(0,posicion);
		urlfinal = urlfinal.concat('cat_id=14');
		document.forms[0].action = urlfinal;
		//document.forms[0].action = 'http://www.golfcv.com/fitness.html?cat_id=14';
	} else {document.forms[0].action = document.URL;}}
	
	
	if (document.forms[0].action.indexOf('?') > 0) document.forms[0].action += '&';	else document.forms[0].action += '?';
	document.forms[0].action += 'session_search_id=' + this.session_search_id;
	
	if (this.cat_var_name != '') {
		var oCatElem = eval('document.forms[0].' + this.cat_var_name + '_' + this.posId);
		if (oCatElem && (oCatElem.value != ''))
			document.forms[0].action += '&' + this.cat_var_name + '=' + oCatElem.value;
	}
		document.forms[0].submit();
}