/*$(document).ready (function (){
	$('.mas').each(function (i){
		$(this).click(function() {
			$(this).toggleClass('menos');
			$('#apoyo'+$(this).attr('id')).slideToggle('fast');
		});
	});
	
	$('#linkequipos').click(function(){
		$('#submenu').slideToggle('normal');
	});
	
});*/

function MM_openBrWindow(theURL,winName,features) {
	window.name='principal';
	window.open(theURL,winName,features);
}

function ajaxObject(){
    var ajOb = null;
    if (window.XMLHttpRequest) {
        ajOb = new XMLHttpRequest();
    }
    else {
        ajOb = new ActiveXObject("Microsoft.XMLHTTP");
    }
    return ajOb;
}

function votarticulo(puntos, idarticulo){
    var ajaxReq = ajaxObject();
    ajaxReq.open("get", "/backend/votar_articulo.php?p=" + puntos + "&id=" + idarticulo);
    ajaxReq.onreadystatechange = function(){
        if (ajaxReq.readyState == 4) {
            if (ajaxReq.responseText) {
                gracias = "<div class=label>Gracias por votar</div>";
                document.getElementById('votar_estrellas').innerHTML = gracias;
                getVotos(idarticulo);
            }
        }
    };
    ajaxReq.send(null);
}

function getVotos(idarticulo){
    var ajaxReq = ajaxObject();
    ajaxReq.open("get", "/backend/votos_articulo.php?id=" + idarticulo);
    ajaxReq.onreadystatechange = function(){
        if (ajaxReq.readyState == 4) {
            if (ajaxReq.responseText) {
                datos = ajaxReq.responseText.split(";");
                var numvotos = datos[0];
                var mediavotos = datos[1].split(".");
                
                if (numvotos == 1) {
                    txt = "<div class=label>" + numvotos + " voto</div>";
                }
                else {
                    txt = "<div class=label>" + numvotos + " votos</div>";
                }
                
                for (i = 0; i < mediavotos[0]; i++) {
                    txt += "<img src=\"/img/star_on.gif\" alt=\"" + i + " votos\" />";
                }
                if (mediavotos[1] > 49) {
                    txt += "<img src=\"/img/star_med.gif\" alt=\"" + mediavotos[0] + " votos\" />";
                }
                document.getElementById('votos_estrellas').innerHTML = txt;
            }
        }
    };
    ajaxReq.send(null);
}

function getNumComentarios(idarticulo){
    var ajaxReq = ajaxObject();
    ajaxReq.open("get", "/backend/num_comentarios.php?id=" + idarticulo);
    ajaxReq.onreadystatechange = function(){
        if (ajaxReq.readyState == 4) {
            if (ajaxReq.responseText) {
                document.getElementById('numcomentarios').innerHTML = '(' + ajaxReq.responseText + ')';
            }
        }
    };
    ajaxReq.send(null);
}


var formatoFecha = 'dd/mm/yyyy'; // Formato de fecha que vamos a utilizar
var arrMeses = Array("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");

// Función de validación de email
function emailValido(valor){
    var EmailOk = true;
    var AtSym = valor.indexOf('@');
    var Period = valor.lastIndexOf('.');
    var Space = valor.indexOf(' ');
    var Length = valor.length - 1;
    if ((AtSym < 1) || (Period <= AtSym + 1) || (Period == Length) || (Space != -1)) {
        EmailOk = false;
    }
    return EmailOk;
}

function dniValido(valor){
    var DNIok = true;
    exp_reg = /^[0-9]{8}[a-zA-Z]{1}$/;
    if (exp_reg.test(valor) == false) 
        DNIok = false;
    else {
        numeros = valor.substring(0, 8);
        letra = valor[8];
        letra2 = letraDNI(numeros);
        if (letra.toUpperCase() != letra2.toUpperCase()) 
            DNIok = false;
    }
    return DNIok;
}

function letraDNI(dni){
    cadena = "TRWAGMYFPDXBNJZSQVHLCKET";
    posicion = dni % 23;
    l = cadena.substring(posicion, posicion + 1);
    return l;
}


// Función de validación de fecha
function fechaValida(valor){
    var formatoFechaReg = formatoFecha;
    formatoFechaReg = formatoFechaReg.replace('dd', '([0-2][0-9]|3[0-1])');
    formatoFechaReg = formatoFechaReg.replace('mm', '(0[0-9]|1[0-2])');
    formatoFechaReg = formatoFechaReg.replace(/y/g, '[0-9]');
    formatoFechaReg = "^" + formatoFechaReg + "$";
    var ExpReg = new RegExp(formatoFechaReg);
    var fechaOK = ExpReg.test(valor);
    return fechaOK;
}

// Función de validación de fotos
function fotoValida(valor){
    var formatoFoto = "^(.*)(\\\\|/)[\\w:/_-]+\\.(jpeg|jpg|gif)$";
    var ExpRegFoto = new RegExp(formatoFoto, "i");
    var fotoOK = ExpRegFoto.test(valor);
    return fotoOK;
}

// Función de validación de videos
function videoValido(valor){
    var formatoVideo = "^(.*)(\\\\|/)[\\w:/_-]+\\.(wmv|avi|mov)$";
    var ExpRegVideo = new RegExp(formatoVideo, "i");
    var videoOK = ExpRegVideo.test(valor);
    return videoOK;
}

function checkForm(frm){
    for (i = 0; i < frm.length; i++) {
        campoForm = frm.elements[i];
        if (campoForm.disabled == false) {
            var datosCheck = campoForm.id.split('00');
            texto_explicativo = "";
            if (datosCheck[2]) 
                texto_explicativo = datosCheck[2];
            if (datosCheck[0].indexOf('r') != -1) {
                if (campoForm.value == "") {
                    alert('No has rellenado el campo ' + datosCheck[1].replace('_',' ','g'));
                    campoForm.focus();
                    return false;
                }
            }
            if (datosCheck[0].indexOf('numero') != -1) {
                if (isNaN(campoForm.value)) {
                    alert('El campo ' + datosCheck[1] + ' tiene que ser numérico.' + texto_explicativo);
                    campoForm.focus();
                    return false;
                }
            }
            if (datosCheck[0].indexOf('dni') != -1) {
                if (!dniValido(campoForm.value)) {
                    alert('El DNI es incorrecto');
                    campoForm.focus();
                    return false;
                }
            }
            if (datosCheck[0].indexOf('email') != -1) {
                if (!emailValido(campoForm.value)) {
                    alert('El campo ' + datosCheck[1] + ' tiene que ser un email');
                    campoForm.focus();
                    return false;
                }
            }
            if ((datosCheck[0].indexOf('fecha') != -1) && (campoForm.value != "")) {
                if (!fechaValida(campoForm.value)) {
                    alert('El formato del campo ' + datosCheck[1] + ' no es válido');
                    campoForm.focus();
                    return false;
                }
            }
            if (datosCheck[0].indexOf('checkbox') != -1) {
                if (campoForm.checked == false) {
                    alert('No has rellenado el campo ' + datosCheck[1]);
                    return false;
                }
            }
            if (datosCheck[0].indexOf('radio') != -1) {
                var radioCheck = 0;
                eval('var radioElemento = frm.' + campoForm.name);
                for (j = 0; j < radioElemento.length; j++) {
                    if (radioElemento[j].checked) {
                        radioCheck = 1;
                        break;
                    }
                }
                if (radioCheck == 0) {
                    alert('No has rellenado el campo ' + datosCheck[1]);
                    return false;
                }
            }
            if (datosCheck[0].indexOf('select') != -1) {
                if (campoForm.selectedIndex == 0) {
                    alert('No has rellenado el campo ' + datosCheck[1]);
                    campoForm.focus();
                    return false;
                }
            }
            if (datosCheck[0].indexOf('selectMultiple') != -1) {
                seleccion = 0
                for (j = 1; j < campoForm.length; j++) {
                    if (campoForm.options[j].selected == true) 
                        seleccion = 1
                }
                if (seleccion == 0) {
                    alert('No has rellenado el campo ' + datosCheck[1]);
                    return false;
                }
            }
            var expReg = /[^A-Za-z0-9ñÑáéíóúÁÉÍÓÚüÜ_\s\¿\?\¡\!\<\>\.\,\:\;\(\)\@\#\$\€\%\&\\\/\*\=\+\-\{\}\[\]\ç\º\ª]/i;
            if (datosCheck[0].indexOf('parsear') != -1) {
                if (expReg.test(campoForm.value)) {
                    alert('El campo ' + datosCheck[1] + ' no es válido\n');
                    campoForm.focus();
                    return false;
                }
            }
            if (datosCheck[0].indexOf('min') != -1) {
                posicion = datosCheck[0].indexOf('min') + 3;
                limite = "0";
                while ((!isNaN(datosCheck[0].substring(posicion, posicion + 1))) && (posicion < datosCheck[0].length)) {
                    limite = limite + datosCheck[0].substring(posicion, posicion + 1);
                    posicion = posicion + 1;
                }
                limite = parseInt(limite, 10);
                if (campoForm.value.length < limite) {
                    alert('El campo ' + datosCheck[1] + ' tiene que tener al menos ' + limite + ' caracteres\n');
                    campoForm.focus();
                    return false;
                }
            }
            if (datosCheck[0].indexOf('max') != -1) {
                posicion = datosCheck[0].indexOf('max') + 3;
                limite = "0";
                while ((!isNaN(datosCheck[0].substring(posicion, posicion + 1))) && (posicion < datosCheck[0].length)) {
                    limite = limite + datosCheck[0].substring(posicion, posicion + 1);
                    posicion = posicion + 1;
                }
                limite = parseInt(limite, 10);
                if (campoForm.value.length > limite) {
                    alert('El campo ' + datosCheck[1] + ' tiene que como máximo ' + limite + ' caracteres\n');
                    campoForm.focus();
                    return false;
                }
            }
            if (datosCheck[0].indexOf('foto') != -1) {
                if ((campoForm.value != "") && !fotoValida(campoForm.value)) {
                    alert('El formato de la foto no es correcta. Por favor, verifica que es un JPEG o un GIF o que el nombre no tiene espacios, acentos o caracteres extraños.');
                    campoForm.focus();
                    return false;
                }
            }
            if (datosCheck[0].indexOf('video') != -1) {
                if ((campoForm.value != "") && !videoValido(campoForm.value)) {
                    alert('El formato del vídeo no es correcto. Por favor, verifica que es un WMV o un AVI o un MOV o que el nombre no tiene espacios, acentos o caracteres extraños.');
                    campoForm.focus();
                    return false;
                }
            }
            if (datosCheck[0].indexOf('acepto') != -1) {
                if (campoForm.checked == false) {
                    alert('Te rogamos que leas y aceptes las condiciones de uso antes de continuar');
                    return false;
                }
            }
            if (datosCheck[0].indexOf('precio') != -1) {
                if ((campoForm.value != "") && !precioValido(campoForm.value)) {
                    alert('El formato del precio no es correcto. El formato correcto es 1000,11.');
                    campoForm.focus();
                    return false;
                }
            }
        }
    }
    return true;
}


function enviar(frm){
    return checkForm(frm);
}


function enviarEquipo(){
    var frm = document.frmonceideal;
    var esquema = frm.esquema.value;
    //alert(esquema);
    if (esquema == '442') {
        if (frm.DF1_442.value == frm.DF2_442.value || frm.DF1_442.value == frm.DF3_442.value || frm.DF1_442.value == frm.DF4_442.value || frm.DF2_442.value == frm.DF3_442.value || frm.DF2_442.value == frm.DF4_442.value || frm.DF3_442.value == frm.DF4_442.value) {
            alert("hay defensas repetidos");
            return;
        }
        if (frm.M1_442.value == frm.M2_442.value || frm.M1_442.value == frm.M3_442.value || frm.M1_442.value == frm.M4_442.value || frm.M2_442.value == frm.M3_442.value || frm.M2_442.value == frm.M4_442.value || frm.M3_442.value == frm.M4_442.value) {
            alert("hay medios repetidos");
            return;
        }
        if (frm.DL1_442.value == frm.DL2_442.value) {
            alert("hay delanteros repetidos");
            return;
        }
    }
    else 
        if (esquema == '451') {
            if (frm.DF1_451.value == frm.DF2_451.value || frm.DF1_451.value == frm.DF3_451.value || frm.DF1_451.value == frm.DF4_451.value || frm.DF2_451.value == frm.DF3_451.value || frm.DF2_451.value == frm.DF4_451.value || frm.DF3_451.value == frm.DF4_451.value) {
                alert("hay defensas repetidos");
                return;
            }
            if (frm.M1_451.value == frm.M2_451.value || frm.M1_451.value == frm.M3_451.value || frm.M1_451.value == frm.M4_451.value || frm.M1_451.value == frm.M5_451.value || frm.M2_451.value == frm.M3_451.value || frm.M2_451.value == frm.M4_451.value || frm.M2_451.value == frm.M5_451.value || frm.M3_451.value == frm.M4_451.value || frm.M3_451.value == frm.M5_451.value) {
                alert("hay medios repetidos");
                return;
            }
        }
        else 
            if (esquema == '433') {
                if (frm.DF1_433.value == frm.DF2_433.value || frm.DF1_433.value == frm.DF3_433.value || frm.DF1_433.value == frm.DF4_433.value || frm.DF2_433.value == frm.DF3_433.value || frm.DF2_433.value == frm.DF4_433.value || frm.DF3_433.value == frm.DF4_433.value) {
                    alert("hay defensas repetidos");
                    return;
                }
                if (frm.M1_433.value == frm.M2_433.value || frm.M1_433.value == frm.M3_433.value || frm.M2_433.value == frm.M3_433.value) {
                    alert("hay medios repetidos");
                    return;
                }
                if (frm.DL1_433.value == frm.DL2_433.value || frm.DL1_433.value == frm.DL3_433.value || frm.DL2_433.value == frm.DL3_433.value) {
                    alert("hay delanteros repetidos");
                    return;
                }
            }
    frm.accion.value = 'enviaronceideal';
    frm.submit();
    
}	
function cambiaEsquema(esquema) {
	var frm = document.frmonceideal;
	if(esquema == '442' ){
			frm.esquema.value = '442';	
			document.getElementById("esquema442").style.display = 'block';	  	
		  document.getElementById("esquema451").style.display = 'none';	
		  document.getElementById("esquema433").style.display = 'none';
	}else if(esquema =='451'){
			frm.esquema.value = '451';
			document.getElementById("esquema442").style.display = 'none';	  	
		  document.getElementById("esquema451").style.display = 'block';	
		  document.getElementById("esquema433").style.display = 'none';
	}else{
			frm.esquema.value = '433';
			document.getElementById("esquema442").style.display = 'none';	  	
		  document.getElementById("esquema451").style.display = 'none';	
		  document.getElementById("esquema433").style.display = 'block';
	}	  
}
