//Valida los campos que deban ser numericos y comprueba la longitud mínima y máxima que puede tener el campo.
function validarNumeros(campo, num, minl, maxl) {
    if (num.value.length != 0) {
        error = '';
        if (minl == undefined) {
            minl = 0;
        } else {
            if (num.value.length < minl) {
                error += 'El campo "' + campo + '" debe contener almenos ' + minl + ' caractéres.\n';
            }
        }
        
        if (maxl == undefined) {
            maxl = 50;
        } else {
            if (num.value.length > maxl) {
                error += 'El campo "' + campo + '" debe contener ' + maxl + ' caractéres como máximo.\n';
            }
        }
        
        if (isNaN(num.value)) {
            error += 'El campo "' + campo + '" debe ser numérico.';
        }
        
        if (error != '') {
            alert(error);
            num.focus();
            num.select();
            return false;
        }
    }
    return true;
}

function checkCIF(cf) {
    var i = temp = 0;
    var v1 = new Array(0, 2, 4, 6, 8, 1, 3, 5, 7, 9);
    cf = cf.toUpperCase();
    if (checkNIF(cf)) 
        return true;
    else if (!/^[A-Za-z0-9]{9}$/.test(cf)) 
        return false
    else if (!/^[ABCDEFGHKLMNPQS]/.test(cf)) 
        return false
    else {
        for (i = 2; i <= 6; i += 2) {
            temp += v1[parseInt(cf.substr(i - 1, 1))];
            temp += parseInt(cf.substr(i, 1));
        }
        temp = temp + v1[parseInt(cf.substr(7, 1))];
        temp = (10 - (temp % 10));
        if (temp == 10 && (cf.charAt(cf.length - 1) == 'J' || cf.charAt(cf.length - 1) == 0)) 
            return true;
        else if (cf.charAt(cf.length - 1) == temp || cf.charAt(cf.length - 1) == String.fromCharCode(64 + temp)) 
            return true;
        else return false;
    }
}

function checkNIF(nif) {
    if (!nif) 
        return false;
    var letras = 'TRWAGMYFPDXBNJZSQVHLCKE';
    if (nif.length != 9) 
        return false;
    else {
        letra = nif.substr(8, 1);
        letra = letra.toUpperCase();
        dni = nif.substr(0, 8);
        dni = dni.toUpperCase();
        dni = dni.replace('X', '0');
        dni -= parseInt(dni / 23) * 23;
        //alert (letras.charAt(dni) + " - " + letra);
        if (letras.charAt(dni) != letra) 
            return false;
        else return true;
    }
}


//Inicializamos JQuery
$(document).ready(function() {   
    if ($('#nuevo').val() == '1') {
        $('.ocultableTurismo').hide();
    } else {
        $('.ocultableTurismo').show();
    }
    
    //Esconde y muestra, según el estado del turismo(Nuevo o Usado), los campos necesarios para cada caso.
    $('#nuevo').change(function() {
        if ($('#nuevo').val() == '1') {
            $('.ocultableTurismo').hide("slow");
        } else {
            $('.ocultableTurismo').show("slow");
        }
    });
    
    //Validamos el formulario de inserción de turismos
    $('#frmIngresarTurismo').submit(function() {
        error = '';
        if ($('#frmIngresarTurismo #nuevo').val() == '') {
            error = '<p>El campo "Estado" es obligatorio.<p/>\n';
        }
        
        if ($('#frmIngresarTurismo #marca').val() == '') {
            error += '<p>El campo "Marca" es obligatorio.</p>\n';
        }
        
        if ($('#frmIngresarTurismo #serie').val() == '') {
            error += '<p>El campo "Modelo" es obligatorio.</p>\n';
        }
        
        if ($('#frmIngresarTurismo #categoria').val() == '') {
            error += '<p>El campo "Categoría" es obligatorio.</p>\n';
        }
        
        if ($('#nuevo').val() == '0') {
        
            var fechaactual = new Date();
            fecha_aaaa_mm = fechaactual.getFullYear() + '-' + (fechaactual.getMonth() + 1);
            
            if (($('#frmIngresarTurismo #fabricado_anyo').val() + '-' + $('#frmIngresarTurismo #fabricado_mes').val()) > fecha_aaaa_mm) {
                error += '<p>La fecha de registro introducida es incorrecta.</p>\n';
            }
            
            if ($('#frmIngresarTurismo #fabricado_mes').val() == '') {
                error += '<p>El campo "Primer registro -Mes-" es obligatorio.</p>\n';
            }
            
            if ($('#frmIngresarTurismo #fabricado_anyo').val() == '') {
                error += '<p>El campo "Primer registro -Año-" es obligatorio.</p>\n';
            }
            
            if ($('#frmIngresarTurismo #kilometros').val() == '') {
                error += '<p>El campo "Kilometros" es obligatorio.</p>\n';
            }
        }
        
        if ($('#frmIngresarTurismo #precio').val() == '') {
            error += '<p>El campo "Precio" es obligatorio.</p>\n';
        }
        
        if ($('#frmIngresarTurismo #precio').val() < 1 || isNaN($('#frmIngresarTurismo #precio').val())) {
            error += '<p>El "Precio" debe ser mayor que 0.</p>\n';
        }
        
        if ($('#frmIngresarTurismo #moneda').val() == '') {
            error += '<p>El campo "Moneda" es obligatorio.</p>\n';
        }
        
        if ($('#frmIngresarTurismo #combustible').val() == '') {
            error += '<p>El campo "Combustible" es obligatorio.</p>\n';
        }
        
        if ($('#frmIngresarTurismo #pais').val() == '') {
            error += '<p>El campo "País" es obligatorio.</p>\n';
        }
        
        if ($('#frmIngresarTurismo #color').val() == '') {
            error += '<p>El campo "Color" es obligatorio.</p>\n';
        }
        
        if ($('#frmIngresarTurismo #subcategoria').val() == '') {
            error += '<p>El campo "Subcategoría" es obligatorio.</p>\n';
        }
        
        if (error != '') {
            $('#errores').html(error);
            
            document.location.href = '#errores';
            return false;
        }
        return true;
    });
    
    $('#frmIngresarTurismo #marca').change(function() {
        var t = this;
        $.ajax({
            url: '?seccion=ofertararticulo',
            data: 'action=get_serie&brand=' + t.value,
            dataType: 'html',
            type: 'get',
            success: function(j) {
                $('#frmIngresarTurismo #serie').html(j);
            }
        });
    });
    
    $('#frmIngresarTurismo #serie').change(function() {
        var t = this;
        $.ajax({
            url: '?seccion=ofertararticulo',
            data: 'action=get_models&serie=' + t.value,
            dataType: 'html',
            type: 'get',
            success: function(j) {
                $('#frmIngresarTurismo #modelo').html(j);
            }
        });
    });
    
    $('#frmIngresarTurismo #modelo').change(function() {
        var t = this;
        $.ajax({
            url: '?seccion=ofertararticulo',
            data: 'action=get_version&modelo=' + t.value,
            dataType: 'html',
            type: 'get',
            success: function(j) {
                $('#frmIngresarTurismo #version').html(j);
            }
        });
    });
    
    $('#categoria').change(function() {
        var t = this;
        $.ajax({
            url: '?seccion=ofertararticulo',
            data: 'action=get_subcats&cat=' + t.value,
            dataType: 'html',
            type: 'get',
            success: function(j) {
                $('#subcategoria').html(j);
            }
        });
    });
    
    $('#frmEnvioQueja').submit(function() {
        var error = '';
        if ($('#frmEnvioQueja #motivo').val() == 'NULL') {
            error += '"Motivo" es un campo obligatorio.\n';
        }
        
        if ($('#frmEnvioQueja #email').val() == '') {
            error += '"E-Mail" es un campo obligatorio.\n';
        }
        
        if (error != '') {
            alert(error);
            return false;
        }
        
        return true;
    });
});
