Preview:
(function ($) {
    /*
     * Accordion jquery 
     */
    $.accordion = (function () {
        var init = function (element) {
            $('[data-toggle="expand"]').click(function (e) {
                e.preventDefault();
                if (!$(this).hasClass('collapsed')) {
                    $(this).addClass('collapsed');
                } else {
                    $(this).removeClass('collapsed');
                }
            });
        };
        return {
            init: init
        };
    })();

    $(document).ready(function () {
        if ($('[data-function="fc-accordion"]').length > 0) {
            $.accordion.init();
        }
    });
})(jQuery);

/*Refrescador de pagina por seguridad*/
setTimeout(securityReload, 3600000);
      function securityReload() {
        location.reload();
}

/*Desplegable de idiomas*/
$(document).ready(function() {
  var selectLang = 0;
  
  loadLanguageOptions();
  
  $(".endesa-header-language").click(function(e) {
    e.stopPropagation(); // Evitar que el evento se propague
    $(".endesa-header-language__list").slideToggle("fast");
    selectLang = !selectLang; // Alternar el estado
  });
  
  $(document).on("click", function() {
    $(".endesa-header-language__list").slideUp("fast");
    selectLang = 0;
  });
});

function loadLanguageOptions() {
  var languageOpt1Url = document.getElementById('landing1').value;
  var languageOpt1Name = document.getElementById('landing1name').value;
  var languageOpt2Url = document.getElementById('landing2').value;
  var languageOpt2Name = document.getElementById('landing2name').value;
  
  var languageOptionsHTML = 
    '<li class="endesa-header-language__item" data-function="fc-item">' +
      '<a class="endesa-header-language__link" data-function="fc-link" href="' + languageOpt1Url + '" title="' + languageOpt1Name + '">' + 
        languageOpt1Name + 
      '</a>' +
    '</li>' +
    '<li class="endesa-header-language__item" data-function="fc-item">' +
      '<a class="endesa-header-language__link" data-function="fc-link" href="' + languageOpt2Url + '" title="' + languageOpt2Name + '">' + 
        languageOpt2Name + 
      '</a>' +
    '</li>';
  
  document.getElementById('fcMenu').innerHTML += languageOptionsHTML;
  
  document.getElementById('fcMenu').style.display = "none";
}


/*Muestra los mensajes de error del formulario*/
function showError(inputError, subError) {
    stopSending();
    switch (inputError) {
        case 2:
            document.getElementById('documentGroup').classList.add("endesa-form__group--invalid");
            switch (subError) {
                case 1:
                    document.getElementById('documentError').innerHTML = nifErrorMessage;
                    break;
                case 2:
                    document.getElementById('documentError').innerHTML = nieErrorMessage;
                    break;
                case 3:
                    document.getElementById('documentError').innerHTML = cifErrorMessage;
                    break;
                case 4:
                    document.getElementById('documentError').innerHTML = passaportErrorMessage;
                    break;
                default:
                    document.getElementById('documentError').innerHTML = documentErrorMessage;
            }
            break;
        case 3:
            switch (subError) {
                case 1:
                    document.getElementById('emailGroup').classList.add("endesa-form__group--invalid");
                    document.getElementById('emailError').innerHTML = emailErrorMessage;
                    break;
                case 2:
                    document.getElementById('emailCGroup').classList.add("endesa-form__group--invalid");
                    document.getElementById('emailCError').innerHTML = emailErrorMessage;
                    break;
                case 3:
                    document.getElementById('emailsGroup').classList.add("endesa-form__group--invalid");
                    document.getElementById('emailsError').innerHTML = emailSameErrorMessage;
                    break;
                default:
                    document.getElementById('emailsGroup').classList.add("endesa-form__group--invalid");
                    document.getElementById('emailCError').innerHTML = emailErrorMessage;
            }
            break;
      case 4:
            break;
        default:
            document.getElementById('documentGroup').classList.add("endesa-form__group--invalid");
            document.getElementById('documentError').innerHTML = documentErrorMessage;

            document.getElementById('emailsGroup').classList.add("endesa-form__group--invalid");
            document.getElementById('emailsError').innerHTML = emailErrorMessage;
    }
}

/*Oculta Mensajes de Error del formulario*/
function hiddenErrors(inputError) {
    switch (inputError) {
        case 2:
            document.getElementById('documentGroup').classList.remove("endesa-form__group--invalid");
            document.getElementById('documentError').innerHTML = "";
            document.getElementById('documentSupraGroup').classList.remove("endesa-form__group--invalid");
            document.getElementById('documentSupraError').innerHTML = "";
            break;
        case 3:
            document.getElementById('emailGroup').classList.remove("endesa-form__group--invalid");
            document.getElementById('emailCGroup').classList.remove("endesa-form__group--invalid");
            document.getElementById('emailsGroup').classList.remove("endesa-form__group--invalid");
            document.getElementById('emailsError').innerHTML = "";
            document.getElementById('emailError').innerHTML = "";
            document.getElementById('emailCError').innerHTML = "";
            break;
        case 5:
            document.getElementById('emailCError').innerHTML = "";
        case 6: 
            document.getElementById('emailError').innerHTML = "";
        default:

            document.getElementById('documentGroup').classList.remove("endesa-form__group--invalid");
            document.getElementById('documentError').innerHTML = "";

            document.getElementById('documentSupraGroup').classList.remove("endesa-form__group--invalid");
            document.getElementById('documentSupraError').innerHTML = "";

            document.getElementById('emailGroup').classList.remove("endesa-form__group--invalid");
            document.getElementById('emailCGroup').classList.remove("endesa-form__group--invalid");
            document.getElementById('emailsGroup').classList.remove("endesa-form__group--invalid");
            document.getElementById('emailsError').innerHTML = "";
            document.getElementById('emailError').innerHTML = "";
            document.getElementById('emailCError').innerHTML = "";
    }
};

function changeDocument() {
    validDocument();
    validFormat();
}
                                                  
/*
 * Document validation
 */
function validDocument() {
    var select = document.getElementById("documentType");
    var opc = select.options[select.selectedIndex].value;
    var userDocument = document.getElementById('document').value;
    userDocument = userDocument.replace('-','');
    userDocument = userDocument.replace('-','');
    document.getElementById("documentHidden").value = userDocument;
                      
    switch (opc) {
        case "nif":
            if (!validateDNI(userDocument)) {
                showError(2, 1);
                lockButton();
                return false
            } else {
                hiddenErrors(2);
                return true
            }
            break;
        case "nie":
            if (!validateNIE(userDocument)) {
                showError(2, 2);
                lockButton();
                return false
            } else {
                hiddenErrors(2);
                return true
            }
            break;
        case "cif":
            if (!validateCIF(userDocument)) {
                showError(2, 3);
                lockButton();
                return false
            } else {
                hiddenErrors(2);
                return true
            }
            break;
        case "pasaporte":
            if (!validatePASSAPORT(userDocument)) {
                showError(2, 4);
                lockButton();
                return false
            } else {
                hiddenErrors(2);
                return true
            }
            break;
        default:
            showError(2);
            lockButton();
            return false
    };
};

function validateDNI(dni) {
    if (dni.length == 9) {
        var letras = ['T', 'R', 'W', 'A', 'G', 'M', 'Y', 'F', 'P', 'D', 'X', 'B', 'N', 'J', 'Z',
            'S', 'Q', 'V', 'H', 'L', 'C', 'K', 'E', 'T'
        ];
        var numero = dni.substring(0, 8);
        var letra = dni.substring(8, 9);
        letra = letra.toUpperCase();
        if (numero < 0 || numero > 99999999) {
            return false;
        } else {
            var letraCalculada = letras[numero % 23];
            if (letraCalculada != letra) {
                return false;
            } else {
                return true;
            }
        }
    } else {
        return false;
    }
};

function validateNIE(nie) {
    nie = nie.toUpperCase();
    // Basic format test
    if (!nie.match(
            '((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)')) {
        return false;
    }
    // Test NIE
    //T
    if (/^[T]{1}/.test(nie)) {
        return (nie[8] === /^[T]{1}[A-Z0-9]{8}$/.test(nie));
    }
    //XYZ
    if (/^[XYZ]{1}/.test(nie)) {
        return (
            nie[8] === "TRWAGMYFPDXBNJZSQVHLCKE".charAt(
                nie.replace('X', '0')
                .replace('Y', '1')
                .replace('Z', '2')
                .substring(0, 8) % 23));
    }
    return false;
}

function validateCIF(cif) {
    // Quitamos el primer caracter y el ultimo digito
    var sum, num = [],
        value, controlDigit, validar, result;
    var valueCif = cif.substr(1, cif.length - 2);
    var suma = 0;
    value = cif.toUpperCase();
    // Sumamos las cifras pares de la cadena 
    for (var i = 1; i < valueCif.length; i = i + 2) {
        suma = suma + parseInt(valueCif.substr(i, 1));
    }
    for (var i = 0; i < 9; i++) {
        num[i] = parseInt(cif.charAt(i), 10);
    }
    var suma2 = 0;
    // Sumamos las cifras impares de la cadena
    for (var i = 0; i < valueCif.length; i = i + 2) {
        result = parseInt(valueCif.substr(i, 1)) * 2;
        if (String(result).length == 1) {
            // Un solo caracter
            suma2 = suma2 + parseInt(result);
        } else {
            // Dos caracteres. Los sumamos... 
            suma2 = suma2 + parseInt(String(result).substr(0, 1)) + parseInt(String(result)
                .substr(1, 1));
        }
    }
    // Sumamos las dos sumas que hemos realizado
    suma = suma + suma2;
    var unidad = String(suma).substr(1, 1);
    unidad = 10 - parseInt(unidad);
    var primerCaracter = cif.substr(0, 1).toUpperCase();
    if (primerCaracter.match(/^[FJKNPQRSUVW]$/)) {
        suma += '';
        controlDigit = 10 - parseInt(suma.charAt(suma.length - 1), 10);
        value += controlDigit;
        validar = num[8].toString() === String.fromCharCode(64 + controlDigit) || num[8]
            .toString() === value.charAt(value.length - 1);
        if (validar == true) return true;
        if (String.fromCharCode(64 + unidad).toUpperCase() == cif.substr(cif.length - 1, 1)
            .toUpperCase()) return true;
    }
    if (primerCaracter.match(/^[ABCDEFGHLM]$/)) {
        // Se revisa que el ultimo valor coincida con el calculo 
        if (unidad == 10) unidad = 0;
        suma += '';
        controlDigit = 10 - parseInt(suma.charAt(suma.length - 1), 10);
        value += controlDigit;
        validar = num[8].toString() === String.fromCharCode(64 + controlDigit) || num[8]
            .toString() === value.charAt(value.length - 1);
        if (validar == true) return true;
        if (String.fromCharCode(64 + unidad).toUpperCase() == cif.substr(cif.length - 1, 1)
            .toUpperCase()) return true;
    }
    return false;
};

function validatePASSAPORT(passport) {
    "use strict";
    return passport.length > 6 && passport.length < 18;
}

/*Valida uno u otro email*/
function validEmail(emailInput) {
    var validEmailValate = false;
    if (emailInput == 2) {
        var emailToValidate = document.getElementById('emailC').value;
    } else {
        var emailToValidate = document.getElementById('email').value;
    }
    var isEmail =
        /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    validEmailValate = isEmail.test(String(emailToValidate).toLowerCase());
    if (validEmailValate) {
        return true
    } else {
        return false
    };

}

/*Valida uno u otro email*/
function validEmails(emailInput) {
    var emailCToCompare = document.getElementById('emailC').value;
    var emailToCompare = document.getElementById('email').value;
    /*Si se ha modificado un imput de los emails*/
    if (emailInput) {
        console.log("Se ha modificado un input");
        if (emailInput == 2) {
            console.log("Se ha modificado el Email C");
            if (validEmail(2)) {
                console.log("El email C es valido");
                hiddenErrors(5);
                if (emailToCompare) {
                    console.log("Hay email A");
                    if (emailToCompare == emailCToCompare) {
                        console.log("Emails C iguales");
                        hiddenErrors(3);
                        return true
                    } else {
                        console.log("Email C no iguales");
                        showError(3, 3);
                        if(!validEmail(1)){
                            showError(3, 1);
                            console.log("Email A no valido");
                        }
                        lockButton();
                        return false
                    }
                } else {
                    console.log("No hay email A");
                    hiddenErrors(3);
                    lockButton();
                    return false
                }
            } else {
                console.log("El email C no es valido");
                showError(3, 2);
                lockButton();
                return false
            }
  } else {
            console.log("Se ha modificado el Email A");
            if (validEmail(1)) {
                console.log("El email A es valido");
                document.getElementById('emailError').innerHTML = "";
                if (emailCToCompare) {
                    console.log("Hay email C");
                    if (emailToCompare == emailCToCompare) {
                        console.log("Emails A iguales");
                        hiddenErrors(3);
                        return true
                    } else {
                        console.log("Email A no iguales");
                        showError(3, 3);
                        lockButton();
                        return false
                    }
                } else {
                    console.log("No hay email C");
                    hiddenErrors(3);
                    lockButton();
                    return false
                }
            } else {
                console.log("El email A no es valido");
                showError(3, 1);
                lockButton();
                return false
            }
        }

    } else {
        console.log("No se ha pasado ningun input");
        if (validEmail(1) && validEmail(2)) {
            if (emailToCompare == emailCToCompare) {
                console.log("Emails iguales");
                hiddenErrors(3);
                return true
            } else {
                showError(3, 3);
                lockButton();
                return false
            }
        } else {
            if(!validEmail(1)) {
    showError(3,1);
   } else {
    showError(3,2);
   }
            lockButton();
            return false
        }
    }
}

function proteccionDatosCheck() {
    console.log("Valida Proteccion Datos");
    if (document.getElementById('proteccionDatos').checked == true) {
        return true;
    } else {
        lockButton();
        return false;
    }
}


function otrasComunicacionesCheck() {
    console.log("Otras Comunicaciones");
    if (document.getElementById('otrasComunicaciones').checked == true) {
        return true;
    } else {
        lockButton();
        return false;
    }
}


function validFormat() {
    if ((validDocument()) && (validEmails()) && (proteccionDatosCheck())) {
        unlockButton();
        console.log("Formulario Valido");
        return true;
    } else {
        lockButton();
        console.log("Error en el formulario");
        return false;
    }
}

function unlockButton() {
    var btnSubmit = document.getElementById('btnSubmit');
    btnSubmit.removeAttribute("disabled");
    btnSubmit.classList.remove("endesa-form__btn--disable");
}

function lockButton() {
    var btnSubmit = document.getElementById('btnSubmit');
    btnSubmit.setAttribute("disabled", true);
    btnSubmit.classList.add("endesa-form__btn--disable");
}


/*Detecta si se han cambiado un check*/
function changeInput(input) {
    /*Recupera todos los inputs*/
    var documentInput = document.getElementById('document');
    var emailInput = document.getElementById('email');
    var emailCInput = document.getElementById('emailC');

        if ((documentInput.value) && (emailInput.value) && (emailCInput.value) && (proteccionDatosCheck())) {
            console.log("Con todos los datos");
            validFormat();
        } else {
            switch (input) {
                case 2:
                    validDocument();
                    console.log("Con Documento");
                    break;
                case 3:
                    validEmails(1);
                    console.log("Con Email");
                    break;
                case 4:
                    validEmails(2);
                    console.log("Con CEmail");
                    break;
                case 6:
                    proteccionDatosCheck();
                    console.log("Con Condiciones");
                    break;
                case 7:
                    otrasComunicacionesCheck();
                    console.log("Con Otras Comunicaciones");
                    break;
                default:
                    lockButton();
                    console.log("Sin datos");
            }
        }
    
}

function stopSending() {
    document.getElementById('SCForm').classList.remove("endesa-form--sending");
}
                                       
function visualSending() {
        if (validFormat()) {
            document.getElementById('SCForm').classList.add("endesa-form--sending");          
            /*ajax();*/
        } else {
            stopSending();
        }
    }   

/*Aviso Error Contrato y Documento*/
function errorContractDoc(errorType) {
    stopSending();
/*Muestra el error*/
   
        switch (errorType) {
            case 5:
                document.getElementById('documentSupraGroup').classList.add("endesa-form__group--invalid");
                document.getElementById('documentSupraError').innerHTML = docNoFound;
                //document.getElementById('documentSupraError').innerHTML = docInvent;
                break;
            case 11:
                document.getElementById('documentSupraGroup').classList.add("endesa-form__group--invalid");
                document.getElementById('documentSupraError').innerHTML = docInvalid;
                break;
            case 17:
                document.getElementById('documentSupraGroup').classList.add("endesa-form__group--invalid");
                /*document.getElementById('documentError').innerHTML = docNoRel;*/
                document.getElementById('documentSupraError').innerHTML = docInvalid;
                break;

            default:
                showError();
        }
    }
          
          
let ajaxFunction = document.getElementById('btnSubmit').addEventListener('click', ajaxPass);

var div = document.getElementById('contact-data-div');        

function ajaxPass() { 
 var idioma = document.getElementById('idiomaLanding').value;
 var ajaxResponse;
    var ajax = new XMLHttpRequest();


       ajax.onreadystatechange = function () {

            if (this.readyState == 4 && this.status == 200) {
 
                   ajaxResponse = this.responseText;
             
                    ajaxResponse = String(ajaxResponse)
              
   
              
if (ajaxResponse.indexOf('true') >= 0) {
  if (idioma == 'EN') { window.location.href = "https://cloud.dev.notificaciones.endesaclientes.com/Captacion-email-gracias-ML-EN";
          } 
  else if (idioma == 'CA') { window.location.href = "https://cloud.dev.notificaciones.endesaclientes.com/Captacion-email-gracias-ML-CA";
          }
  else { window.location.href = "https://cloud.dev.notificaciones.endesaclientes.com/Captacion-email-gracias-ML-ES";
          }
} else { 
  if (idioma == 'EN') { window.location.href = "https://cloud.dev.notificaciones.endesaclientes.com/Captacion-email-error-ML-EN";
          } 
  else if (idioma == 'CA') { window.location.href = "https://cloud.dev.notificaciones.endesaclientes.com/Captacion-email-error-ML-CA";
          }
  else { window.location.href = "https://cloud.dev.notificaciones.endesaclientes.com/Captacion-email-error-ML-ES";
          }
 }
             
              
                         }
               }
 
var paramsFormsToSent =  {     'Email':document.getElementById('email').value,
                               'Documento':document.getElementById('document').value,
                               'AccountId': div.getAttribute('data-account-id'),
                               'ContactId': div.getAttribute('data-contact-id'),
                               'otrasComunicaciones': document.getElementById("otrasComunicaciones").checked,
                               'proteccionDatos': document.getElementById("proteccionDatos").checked
          
                             }       
     console.log(paramsFormsToSent);                                          
               
     var ajaxUrl = "https://cloud.dev.notificaciones.endesaclientes.com/Captacion-email-ML-Ajax"
     
                     
     ajax.open("POST", ajaxUrl, "true");
     ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
     ajax.send("data="+JSON.stringify(paramsFormsToSent));
 
 }

          
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter