// define variables for characters in input fields
var isNS = (navigator.appName=="Netscape")?1:0;
var phone = "+.0123456789";
var numb = "0123456789";
var ipaddr = "0123456789.";
var dom = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-.0123456789";
var domhost = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-.*0123456789";
var alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ _-'0123456789";
function cif(e,t,v){
    var w = "";
    if (isNS) {
        k = e.which;
    } else {
        k = e.keyCode;
    }

    if (k == 37) return;
    if (k == 39) return;
    if (k == 9) return;
    if (k == 13) return;
    if (k == 8) return;
    if (k == 46) return;
    for (i=0; i < t.value.length; i++) {
        x = t.value.charAt(i);
        if (v.indexOf(x,0) != -1) {
            w += x;
        }
    }
    t.value = w;
}

// Delete all DNS records/DNS domain
function dnsDeleteSOA(rec, txt) {
    if (confirm(txt)) {
        document.dnslistaction.deletesoa.value = rec;
        document.dnslistaction.submit();
    }
}
// Delete DNS record
function dnsDelete(rec, txt) {
    if (confirm(txt)) {
        document.dnsedit.deleterecid.value = rec;
        document.dnsedit.submit();
    }
}
function dnsEdit(rec) {
    document.dnsedit.editrecid.value = rec;
    document.dnsedit.submit();
}
function dnsSave(domain1,rec,txt1,txt2,txt3,txt4,txt5) {
    document.dnsedit.saverecid.value = rec;
    if (document.dnsedit.type.value == 'A') {
        if(verifyIP(document.dnsedit.savedata.value)) {
            document.dnsedit.submit();
        } else {
            alert(txt2);
        }
    }
    if (document.dnsedit.type.value == 'MX' || document.dnsedit.type.value == 'CNAME') {
        if (document.dnsedit.savedata.value != '') {
            var end = document.dnsedit.savedata.value.charAt(document.dnsedit.savedata.value.length - 1);
            if (end != '.') {
                if (confirm(txt3+document.dnsedit.savedata.value+"."+domain1+"\r\n"+txt4+"\r\n\r\n"+txt5)) {
                    document.dnsedit.submit();
                }
            } else {
                document.dnsedit.submit();
            }
        } else {
            alert(txt1);
        }
    }
    if (document.dnsedit.type.value == 'TXT') {
        if (document.dnsedit.savedata.value != '') {
            if (document.dnsedit.savedata.value.length > 255) {
                alert(txt2+' ('+document.dnsedit.savedata.value.length+')');
            } else {
                document.dnsedit.submit();
            }
        } else {
            alert(txt1);
        }
    }
}
function dnsAdd(domain1,txt1,txt2,txt3,txt4,txt5) {
    if (document.dnsedit.type.value == 'A') {
        if(verifyIP(document.dnsedit.data.value)) {
            document.dnsedit.add.value = '1';
            document.dnsedit.submit();
        } else {
            alert(txt2);
        }
    }
    if (document.dnsedit.type.value == 'MX' || document.dnsedit.type.value == 'CNAME') {
        if (document.dnsedit.data.value == '') {
            alert(txt1);
        } else {
            var end = document.dnsedit.data.value.charAt(document.dnsedit.data.value.length - 1);
            if (end != '.') {
                if (confirm(txt3+document.dnsedit.data.value+"."+domain1+"\r\n"+txt4+"\r\n\r\n"+txt5)) {
                    document.dnsedit.add.value = '1';
                    document.dnsedit.submit();
                }
            } else {
                document.dnsedit.add.value = '1';
                document.dnsedit.submit();
            }
        }
    }
    if (document.dnsedit.type.value == 'TXT') {
        if (document.dnsedit.data.value == '') {
            alert(txt1);
        } else {
            if (document.dnsedit.data.value.length > 255) {
                alert(txt2+' ('+document.dnsedit.data.value.length+')');
            } else {
                document.dnsedit.add.value = '1';
                document.dnsedit.submit();
            }
        }
    }
}

function dnsForwardSave (rec, txt1, txt2) {
    document.dnsedit.saveforwardid.value = rec;
    if (document.dnsedit.saveurl.value == '') {
        alert(txt1);
    } else {
        if (document.dnsedit.saveurl.value.length > 255) {
            alert(txt2);
        } else {
            document.dnsedit.submit();
        }
    }
}

function dnsForwardAdd (rec, txt1, txt2) {
    document.dnsedit.addforward.value = '1';
    if (document.dnsedit.url.value == '') {
        alert(txt1);
    } else {
        if (document.dnsedit.url.value.length > 255) {
            alert(txt2);
        } else {
            document.dnsedit.submit();
        }
    }
}

function dnsForwardDelete (rec, txt) {
    if (confirm(txt)) {
        document.dnsedit.deleteforwardid.value = rec;
        document.dnsedit.submit();
    }
}
// Check ip address
function verifyIP (IP) {
    var IPvalue = IP;
    var ipArray = IPvalue.split(".");
    if (IPvalue == "0.0.0.0" || IPvalue == "255.255.255.255" || IPvalue == '') {
        return false;
    }
    for (i = 0; i < 4; i++) {
        thisSegment = ipArray[i];
        if (thisSegment > 255 || thisSegment == '' || thisSegment == null) {
            return false;
        }
        if ((i == 0) && (thisSegment > 255)) {
            return false;
        }
    }
    return true;
}

// Check that at least one of the domains is selected
function checkdomainsselected() {
    var ok = false;
    for(i = 1; i <= document.getdomains.domaincount.value; i++) {
        var ch = 'document.getdomains.domain'+i+'.checked';
        var check = eval(ch);
        if (check) {
            ok = true;
        }
    }
	if (ok) {
		getdomains.submit();
	} else {
		alert('Please select at least one domain name');
	}
}

// Check that a domain name has been entered
function checkdomain() {
    var v1 = document.domainsearch.domain.value;
    if (v1.length < 2) {
        alert('You must enter a domain name with at least 2 characters!');
    } else {
        domainsearch.submit();
    }
}

// Check that a domain name is entered and at least 1 extension is selected
function checkdomainadvanced(howmany) {
    var count = 0;
    for (c = 1; c < howmany + 1; c++) {
        var line = 'document.dominio.domainext'+c+'.checked';
        ch = eval (line);
        if (ch == true) {
            count++;
        }
    }
    var v1 = document.dominio.domain.value;
    if (v1.length < 2) {
        alert('You must enter a domain name with at least 2 characters!');
    } else {
        if (count > 0) {
            dominio.submit();
        } else {
            alert('You have to select at least one domain extension!');
        }
    }
}

// buy-step3 - Which Payment pethod was selected ?
function paymethod() {
    if(document.pay.paytype.checked) {
        document.pay.action='https://tpv.4b.es/tpvv/teargral.exe';
        document.pay.submit();
    } else {
        document.pay.action='buy-step4.php';
        document.pay.submit();
    }
}

// buy-step1 - on submit
function checkstep1(NIFerr, NIEerr, CIFerr, MissingOrgErr, SelectCompanyErr) {

    typeofhandle = document.step1.OwnerESNICTypeOfHandle.options[document.step1.OwnerESNICTypeOfHandle.selectedIndex].value;
    typeofcompany = document.step1.OwnerESNICTypeOfCompany.options[document.step1.OwnerESNICTypeOfCompany.selectedIndex].value;
    if (typeofhandle == 1) { // Company
        if (document.step1.OwnerOrganization.value == '') {
            alert(MissingOrgErr);
            return false;
        }
        if (typeofcompany == '0') {
            alert(SelectCompanyErr);
            return false;
        }
    }

    typeofid = document.step1.OwnerESNICTypeOfID.options[document.step1.OwnerESNICTypeOfID.selectedIndex].value;
    id = document.step1.OwnerESNICId.value;

    if(validarIdentificacion(typeofid, id, NIFerr, NIEerr, CIFerr)) {
	   step1.action = 'buy-step3.php';
	   step1.submit();
    }

}

// buy-step1 - Show different input fields depending on if Person or Organisation
function HandleTypeSelect(type) {
    //type+'ESNICTypeOfHandle'
    w="document.step1."+type+"ESNICTypeOfHandle.options[document.step1."+type+"ESNICTypeOfHandle.selectedIndex].value";
    eval("which="+w);
    if (which == '') {
        for(i = 1; i <= 3; i++) {
            todo = "document.all['" + type + i + "'].style.display='none'";
            eval(todo);
        }
        for(i = 5; i <= 15; i++) {
            todo = "document.all['" + type + i + "'].style.display='none'";
            eval(todo);
        }
  //document.all['oldhandle1'].style.display='';
  //document.all['oldhandle2'].style.display='none';

    }
    if (which == '0') {
        for(i = 1; i <= 15; i++) {
            todo = "document.all['" + type + i + "'].style.display=''";
            eval(todo);
        }
        todo = "document.all['" + type + "3'].style.display='none'";
        eval(todo);
        todo = "document.all['" + type + "5'].style.display='none'";
        eval(todo);
    }
    if (which == '1') {
        for(i = 3; i <= 15; i++) {
            todo = "document.all['" + type + i + "'].style.display=''";
            eval(todo);
        }
        todo = "document.all['" + type + "1'].style.display='none'";
        eval(todo);
        todo = "document.all['" + type + "2'].style.display='none'";
        eval(todo);
    }
}

// buy-step1 - Only show the row where to input the Owner Handle
function showHandleStep1() {
  for(i = 1; i <= 15; i++) {
    todo = "document.all['Owner" + i + "'].style.display='none'";
    eval(todo);
  }
  document.all['oldhandle1a'].style.display='';
  document.all['oldhandle1b'].style.display='';
  document.all['oldhandle2'].style.display='none';
  document.step1.handleornewdata.value = 'handle';
}

// buy-step1 - Show inpout fields and hide Owner Handle row
function hideHandleStep1() {
  for(i = 1; i <= 15; i++) {
    todo = "document.all['Owner" + i + "'].style.display=''";
    eval(todo);
  }
  document.step1.OwnerHandle.value='';
  document.all['oldhandle1a'].style.display='none';
  document.all['oldhandle1b'].style.display='none';
  document.all['oldhandle2'].style.display='';
  document.step1.handleornewdata.value = 'newdata';
}

// buy-step2 - show window with Registrant info
function showreginfo() {
    document.all['Registrant'].style.visibility='visible';
    document.all['Registrant'].style.left = event.x;
    document.all['Registrant'].style.top = event.y;
}

// buy-step2 - hide window with Registrant info
function hidereginfo() {
    document.all['Registrant'].style.visibility='hidden';
}

// buy-step2 - show selected handle
function showHandleStep2(section) {
    switch (section) {
        case "Admin":
            var data = '<BR><INPUT NAME="AdminHandle" SIZE="20"><BR><BR>';
            data = data + '<B>OR</B> <A HREF="javascript:hideHandle(';
            data = data + "'Admin');";
            data = data + '">click here to enter contact information</A>';
            document.all['Adminoldhandle1'].innerHTML='<BR>Administrative Handle';
            document.all['Adminoldhandle2'].innerHTML=data;
            hideInput('Admin');
        break;
        case "Tech":
            var data='<BR><INPUT NAME="TechHandle" SIZE="20"><BR><BR>';
            data = data + '<B>OR</B> <A HREF="javascript:hideHandle(';
            data = data + "'Tech');";
            data = data + '">click here to enter contact information</A>';
            document.all['Techoldhandle1'].innerHTML='<BR>Technical Handle';
            document.all['Techoldhandle2'].innerHTML=data;
            hideInput('Tech');
        break;
        case "Bill":
            var data='<BR><INPUT NAME="BillHandle" SIZE="20"><BR><BR>';
            data = data + '<B>OR</B> <A HREF="javascript:hideHandle(';
            data = data + "'Bill');";
            data = data + '">click here to enter contact information</A>';
            document.all['Billoldhandle1'].innerHTML='<BR>Billing Handle';
            document.all['Billoldhandle2'].innerHTML=data;
            hideInput('Bill');
        break;
    }
}

// buy-step2 - hide selected handle
function hideHandleStep2(section) {
    switch (section) {
        case "Admin":
            var data='<BR><B>OR</B> <A HREF="javascript:showHandle(';
            data = data + "'Admin');";
            data = data + '">click here to specify a previously';
            data = data + ' created &quot;<B>Administrative Contact Handle</B>&quot;</A>';
            document.all['Adminoldhandle1'].innerHTML='';
            document.all['Adminoldhandle2'].innerHTML=data;
            showInput('Admin');
        break;
        case "Tech":
            var data='<BR><B>OR</B> <A HREF="javascript:showHandle(';
            data = data + "'Tech');";
            data = data + '">click here to specify a previously';
            data = data + ' created &quot;<B>Technical Contact Handle</B>&quot;</A>';
            document.all['Techoldhandle1'].innerHTML='';
            document.all['Techoldhandle2'].innerHTML=data;
            showInput('Tech');
        break;
        case "Bill":
            var data='<BR><B>OR</B> <A HREF="javascript:showHandle(';
            data = data + "'Bill');";
            data = data + '">click here to specify a previously';
            data = data + ' created &quot;<B>Billing Contact Handle</B>&quot;</A>';
            document.all['Billoldhandle1'].innerHTML='';
            document.all['Billoldhandle2'].innerHTML=data;
            showInput('Bill');
        break;
    }
}

// buy-step2 - hide/show handles depending on checkboxes
function same() {
    if (document.step2.AdminUseSameAsReg.checked) {
        hideInput('Admin');
        document.all['Admin16'].style.display='none';
    } else {
        showInput('Admin');
        document.all['Admin16'].style.display='';
    }
    if (document.step2.TechUseSameAsReg.checked) {
        hideInput('Tech');
        document.all['Tech16'].style.display='none';
    } else {
        showInput('Tech');
        document.all['Tech16'].style.display='';
    }
    if (document.step2.BillUseSameAsReg.checked) {
        hideInput('Bill');
        document.all['Bill16'].style.display='none';
    } else {
        showInput('Bill');
        document.all['Bill16'].style.display='';
    }

}

// buy-step2 - show selected table rows
function showInput(thename) {
    for(i = 1; i <= 15; i++) {
        data = thename + i;
        todo = "document.all['" + data + "'].style.display=''";
        eval(todo);
    }
}

// buy-step2 - hide selected table rows
function hideInput(thename) {
    for(i = 1; i <= 15; i++) {
        data = thename + i;
        todo = "document.all['" + data + "'].style.display='none'";
        eval(todo);
    }
}

// buy-step2 - check form values before submit
function checkstep2() {
	document.step2.submit();
}

// buy-step3 - check which payment methot that has been selected
function paymethod() {
    if(document.pay.paytype.checked) {
        pay.action='https://tpv2.4b.es/simulador/teargral.exe';
        pay.submit();
    } else {
        pay.action='buy-step4.php';
        pay.submit();
    }
}

// whois - check Whois information - step 1
function checkwhois1() {
    if (whois.domain.value == '') {
        alert('You have not entered a domain name');
        return 0;
    }
    whois.submit();
}

// whois - check Whois information - step 2
function checkwhois2() {
    if (whois.domain.value == '') {
        alert('You have not entered a domain name');
        return 0;
    }
    whois.submit();
}

// ua/domain_edit - display form fields for editing
function DomainEdit() {
    document.all['OwnerShow'].style.display='none';
    document.all['HandleOwnerEdit'].style.display='';
    document.all['HandleAdminShow'].style.display='none';
    document.all['HandleAdminEdit'].style.display='';
    document.all['HandleTechShow'].style.display='none';
    document.all['HandleTechEdit'].style.display='';
    document.all['HandleBillShow'].style.display='none';
    document.all['HandleBillEdit'].style.display='';
    document.all['EditButton'].style.display='none';
    document.all['SaveButton'].style.display='';

    for(i = 1; i <= domainedit.NScount.value; i++) {
        todo = "document.all['NSshow" + i + "'].style.display='none'";
        eval(todo);
        todo = "document.all['NSedit" + i + "'].style.display=''";
        eval(todo);
    }
}

// us/domain_edit - Show Handle select popup window
function showHandlePopup(poph, hinfo) {
    document.domainedit.popuphandle.value=poph;
    document.all['HandlePopup'].style.visibility='visible';
}

// us/domain_edit - Hide Handle select popup window
function hideHandlePopup() {
    document.all['HandlePopup'].style.visibility='hidden';
}

// us/domain_edit - Change selected Handle in twin select box
function handleSelected(h) {

    if (h == 'H') {
        document.handleform.handleN.selectedIndex = document.handleform.handleH.selectedIndex;
    }
    if (h == 'N') {
        document.handleform.handleH.selectedIndex = document.handleform.handleN.selectedIndex;
    }
    
    //document.domainedit.handleR.options[document.domainedit.handleR.selectedIndex].value
}

// us/domain_edit - Copy selected Handle from popup select box
function handleCopy() {

    handle = document.handleform.handleH.options[document.handleform.handleH.selectedIndex].value;

    if (document.domainedit.popuphandle.value == 'O') {
        document.domainedit.HandleOwner.value = handle;
    }
    if (document.domainedit.popuphandle.value == 'A') {
        document.domainedit.HandleAdmin.value = handle;
    }
    if (document.domainedit.popuphandle.value == 'T') {
        document.domainedit.HandleTech.value = handle;
    }
    if (document.domainedit.popuphandle.value == 'B') {
        document.domainedit.HandleBill.value = handle;
    }

    hideHandlePopup();
    
    return;
}

function checkrenewal(renewtxt) {
	some=false;
    for(i=0; i<document.renewal.elements.length; i++) {
        if (document.renewal.elements[i].type=="checkbox") {
        	if (document.renewal.elements[i].name.substring(0,5)=='renew') {
            	if (document.renewal.elements[i].checked) {
            		some=true;					
				}
            }
        }
    }
    if (some) {
    	if (confirm(renewtxt)) {
        	document.renewal.submit();
    	}
	}
}

// Logon
function dologon () {
    window.location='/ua/usermenu.php?action=logon';
}

// Logoff
function dologoff () {
    window.location='/ua/usermenu.php?action=logoff';
}




// ESNIC code
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////// VALIDACIONES DE NIF, CIF, ETC... ///////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function validarIdentificacion(tipoIdentificacion, identificacion, NIFerr, NIEerr, CIFerr) {
    if (tipoIdentificacion == "2") {
        return ValidarCIF(identificacion, CIFerr);
    } else if (tipoIdentificacion == "3") {
        return ValidarNIE(identificacion, NIEerr);
    } else if (tipoIdentificacion == "1") {
        return ValidarNIF(identificacion, NIFerr);
    }
    return true;
}

function ValidarNIF(nif, errMSG) {
    dni = nif.substring(0, nif.length - 1);
    let = nif.charAt(nif.length - 1);
    if (!isNaN(let)) {
        alert(errMSG);
        return false;
    } else {
        cadena="TRWAGMYFPDXBNJZSQVHLCKET";
        posicion = dni % 23;
        letra = cadena.substring(posicion, posicion + 1);
        if (letra != let.toUpperCase()) {
            alert(errMSG);
            return false;
        }
    }
    return true;
}

function ValidarNIE(nie, errMSG) {
    dni = nie.substring(1, nie.length - 1);
    ini = nie.charAt(0);
    let = nie.charAt(nie.length - 1);
    if (!isNaN(ini)) {
        alert(errMSG);
        return false;
    } else if (ini.toUpperCase() != 'X') {
        alert(errMSG);
        return false;
    } else {
        cadena="TRWAGMYFPDXBNJZSQVHLCKET";
        posicion = dni % 23;
        letra = cadena.substring(posicion, posicion + 1);
        if (letra != let.toUpperCase()) {
            alert(errMSG);
            return false;
        }
    }
    return true;
}

function ValidarCIF(cif, errMSG) {
    // La función recibe el CIF completo: A58818501
    var resultado = false;
    var v1 = new Array(0, 2, 4, 6, 8, 1, 3, 5, 7, 9);
    var temp = 0;
    var digitoControl = "";

    resultado = CompruebaDatosCIF(cif, errMSG);
    if (resultado)
    {
        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));
        digitoControl = cif.substr(8, 1);
        resultado = CompruebaDigitoControlCIF(temp, digitoControl, cif, errMSG);
    }
    return resultado;
}

function CompruebaDatosCIF(cif, errMSG) {
    // Comprueba la entrada de datos
    var resul = false;
    var temp = cif.toUpperCase(); // pasar a mayúsculas

    if (!/^[A-Za-z0-9]{9}$/.test(temp)) {  // Son 9 dígitos?
        alert(errMSG);
    } else if (!/^[ABCDEFGHKLMNPQS]/.test(temp)) {// Es una letra de las admitidas ?
        alert(errMSG);
    } else {
        resul = true;
    }
    return resul;
}

function CompruebaDigitoControlCIF(valorCalculado, digitoControl, cif, errMSG) {
    // Comprueba el digito de control del CIF
    var res = false;
    var letras = new Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J");
    var numeros = new Array("1", "2", "3", "4", "5", "6", "7", "8", "9", "0");
    var pos = 0;

    digitoControl = digitoControl.toUpperCase();
    pos = valorCalculado - 1;
    if (digitoControl != letras[pos] && digitoControl != numeros[pos]) {
        alert(errMSG);
    } else {
        res = true;
    }
    return res;
}


