// this needs the field names correcting for the actual ones being used...

function check_using_regex(strtotest, regexstr) {
    var re = new RegExp(regexstr);
    if (strtotest.match(re)) {
        return true;
    }
    else {
        return false;
    }
}


function check_phone(fmphone) {
    // Check PhoneNO 
    var Phone = document.getElementsByName(fmphone)[0];

    if (Phone) {
        var PhoneRegex = /(^((\(?0\d{4}\)?\s?\d{3}\s?\d{3})|(\(?0\d{3}\)?\s?\d{3}\s?\d{4})|(\(?0\d{2}\)?\s?\d{4}\s?\d{4}))(\s?#(\d{4}|\d{3}))?$)/;

        if (Phone.value == null || Phone.value == "") {
            return 'The telephone number field is incomplete';
        }
        if (check_using_regex(Phone.value, PhoneRegex) == false) {
            return 'The Telephone Number is invalid - must be a UK number with no spaces or international codes.';
        }
    }
    return '';
}

function check_phone_or_email(fmPhone, fmEmail) {
    var Phone = document.getElementsByName(fmPhone)[0];
    // Check Email
    var Emailaddr = document.getElementsByName(fmEmail)[0];

    if (Phone && Emailaddr) {
        if ((Phone.value == null || Phone.value == "") && (Emailaddr.value == null || Emailaddr.value == "")) {
            return 'You must specify either a telephone number or an email address.';
        }
        else {
            phone = check_phone(fmPhone);
            email = check_email(fmEmail);

            if (email + phone != '') {
                if (phone != '')
                    return (phone);
                if (email != '')
                    return (email);
            }
        }
    }
    return '';
}

function check_business(fmBusiness) {
    // Check Business Name 
    //  var Bname=document.getElementById(fmBusiness);
    var Bname = document.getElementsByName(fmBusiness)[0];
    if (Bname) {
        if (Bname.value == "" || Bname.value == null) {
            return 'The Business Name field is incomplete.';
        }
    }
    return '';
}

function check_fullname(fmFullname) {
    // Check Name 
    var fmFullname = document.getElementsByName(fmFullname)[0];
    if (fmFullname) {
        var FnameRegex = /(\d+)/;
        //No numerics
        if (fmFullname.value == "") {
            return 'The Name field is incomplete.';
        }
        if (check_using_regex(fmFullname.value, FnameRegex) == true) {
            return "The Name field is invalid - it can't contain numbers.";
        }
    }
    return '';
}

function check_firstname(fmFname) {
    // Check First Name 
    var Fname = document.getElementsByName(fmFname)[0];
    if (Fname) {
        var FnameRegex = /(\d+)/;
        //No numerics
        if (Fname.value == "") {
            return 'The First Name field is incomplete.';
        }
        if (check_using_regex(Fname.value, FnameRegex) == true) {
            return "The First Name field is invalid - it can't contain numbers.";
        }
    }
    return '';
}

function check_surname(fmLname) {
    // Check Surname 
    var Lname = document.getElementsByName(fmLname)[0];
    if (Lname) {
        var LnameRegex = /(\d+)/;
        //No numerics
        if (Lname.value == "") {
            return 'The Surname field is incomplete.';
        }
        if (check_using_regex(Lname.value, LnameRegex) == true) {
            return "The Surname field is invalid - it can't contain numbers.";
        }
    }
    return '';
}

function check_email(fmEmail) {
    // Check Email
    var Emailaddr = document.getElementsByName(fmEmail)[0];
    if (Emailaddr) {
        var EmailRegex = /(^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$)/;

        if (Emailaddr.value == null || Emailaddr.value == "") {
            return 'The email address field is incomplete';
        }
        if (check_using_regex(Emailaddr.value, EmailRegex) == false) {
            return 'The Email address is invalid.';
        }
    }
    if (email_final_checks(Emailaddr.value) == false) {
        return 'The Email address is invalid.';
    }
    return '';
}

function check_multiple_emails(fmEmails) {
    // Check Email
    var Emailaddr = document.getElementsByName(fmEmails)[0];
    if (Emailaddr) {


        if (Emailaddr.value.length > 300) {
            return 'The emails field is too long, maximum of 300 characters is allowed.';
        }

        // Check Emails
        var data = Emailaddr.value.replace(/ /gi, '').replace(/,/gi, ';');
        //data = Emailaddr.value.replace(/ /gi,'').replace(/'/gi,';')
        var rows = data.split(";");

        for (var i in rows) {
            var return_result = '';
            var check_for_blank = '';
            if (rows[i] != '') {
                return_result = check_multiple_email(rows[i])
                if (return_result != '') {
                    return return_result;
                }
            }
            else {
                return 'The Email field is incomplete.';
            }
        }


    }
    return '';

}




function check_multiple_email(Emailaddr) {
    // Check Email

    if (Emailaddr) {

        var EmailRegex = /(^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$)/;

        if (Emailaddr == null || Emailaddr == "") {

            return '';
        }


        if (check_using_regex(Emailaddr, EmailRegex) == false) {
            return 'The Email address is invalid.';
        }

    }
    if (email_final_checks(Emailaddr) == false) {
        return 'The Email address is invalid.';
    }
    return '';
}

function email_final_checks(strToCheck) {
    // Get number of chars that occur after @
    var AtPosition = strToCheck.indexOf("@");
    var Position = strToCheck.length - AtPosition;
    // Check position of @ is at least 5 chars before end of string
    if (Position < 6) {
        return false;
    }
    // Check for at least 1 stop after @ + 2
    if (strToCheck.indexOf(".", AtPosition + 2) == -1) {
        return false;
    }
    // Check for at least two chars before @
    if (AtPosition < 2) {
        return false;
    }
    // email format should be OK
    return true;
}

function check_postcode(fmPostCode) {
    // Check PostCode 
    var Postcode = document.getElementsByName(fmPostCode)[0];
    if (Postcode) {
        var PcodeRegex = "^[A-Za-z]{1,2}[0-9]{1,2}[A-Za-z]? ?[0-9]{1}[A-Za-z]{2}$";

        if (Postcode.value == null || Postcode.value == "") {
            return 'The Post Code field is incomplete.';
        }

        if (check_using_regex(Postcode.value, PcodeRegex) == false) {
            return 'The Post Code is invalid - must be a UK one.';
        }
    }
    return '';
}

function check_products(fmProducts) {
    var Products = document.getElementsByName(fmProducts);
    if (Products) {
        if (Products.length == 0)
            return '';

        check = false;
        for (counter = 0; counter < Products.length; counter++) {
            if (Products[counter].checked)
                check = true;
        }

        if (!check) {
            return 'You must select a product.';
        }
        return '';
    }
    return '';
}
function check_telecoms(fmTelecoms) {
    var Telecoms = document.getElementsByName(fmTelecoms);
    if (Telecoms) {
        if (Telecoms.length == 0)
            return '';

        check = false;
        for (counter = 0; counter < Telecoms.length; counter++) {
            if (Telecoms[counter].checked)
                check = true;
        }

        if (!check) {
            return 'You must select a service.';
        }
        return '';
    }
    return '';
}

function check_product(fmproduct) {
    var Product = document.getElementsByName(fmproduct)[0];
    if (Product) {
        if (Product.value == null || Product.value == "") {

            return 'You must select a product.';
        }
    }
    return '';
}

function check_supplier(fmsupplier) {
    var Supplier = document.getElementsByName(fmsupplier)[0];
    if (Supplier) {
        if (Supplier.value == null || Supplier.value == "") {
            return 'You must select a supplier.';
        }
    }
    return '';
}

function check_contract_date(fmdate) {
    var ContractDate = document.getElementsByName(fmdate)[0];
    if (ContractDate) {
        if (ContractDate.value == null || ContractDate.value == "") {
            return 'You must select your contract start date.';
        }

    }
    return '';
}

function check_contract_length(fmcontractlen) {
    var ContractLen = document.getElementsByName(fmcontractlen)[0];
    if (ContractLen) {
        if (ContractLen.value == null || ContractLen.value == "") {
            return 'You must tell us your contract term.';
        }

    }
    return '';
}

function check_price(fmprice) {
    var Price = document.getElementsByName(fmprice)[0];
    if (Price) {
        if (Price.value == null || Price.value == "") {
            return 'You must provide your price.';

        }
        if (Price.value < 1.0 || Price.value >= 20.00) {
            return 'The price you have entered is invalid.';
        }
        /*
        var isprice = /^\d+\.\d+$/;
        if (check_using_regex(Price.value, isprice)==false) 
        {
        return 'Please enter your price in numbers';
        }
        */
    }
    return '';
}

function check_address() {
    var Address1 = document.getElementsByName('psupaddr1')[0];
    if (Address1) {

        var Address1 = document.getElementsByName('psupaddr1')[0];
        // address line 2 is allowed to be empty
        var Addresstown = document.getElementsByName('psuptown')[0];
        var Addresscity = document.getElementsByName('psupcity')[0];
        // post code is validated elsewhere		

        if (Address1.value == null || Address1.value == "") {
            return 'You must provide your business address.';
        }
        if (Addresstown.value == null || Addresstown.value == "") {
            return 'You must provide your town/city.';
        }
        if (Addresscity.value == null || Addresscity.value == "") {
            return 'You must provide your county.';
        }
    }
    return '';
}

function validatePage1() {
    var msg = check_products('products');
    if (msg != '') {
        alert(msg);
        return false;
    }
    return true;
}

function validatePage2() {
    var msg = '';
    var e = check_business('pcompname');
    if (e != '') msg = msg + e + '\n';
    e = check_firstname('pfirstname');
    if (e != '') msg = msg + e + '\n';
    e = check_surname('psurname');
    if (e != '') msg = msg + e + '\n';
    if (msg != '') {
        alert(msg);
        return false;
    }
    return true;
}

function validatePage3() {
    var msg = check_phone_or_email('pphoneno', 'pemail');
    if (msg != '') {
        alert(msg);
        return false;
    }
    return true;
}

function validatePPC() {
    var msg = '';
    var e = check_business('pcompname');
    if (e != '') msg = msg + e + '\n';
    e = check_firstname('pfirstname');
    if (e != '') msg = msg + e + '\n';
    e = check_surname('psurname');
    if (e != '') msg = msg + e + '\n';
    e = check_phone_or_email('pphoneno', 'pemail');
    if (e != '') msg = msg + e + '\n';
    if (msg != '') {
        alert(msg);
        return false;
    }
    return true;
}

function validatePriceChecker() {
    var msg = '';
    var e = check_product('product');
    if (e != '') msg = msg + e + '\n';
    e = check_contract_date('pcontractdate');
    if (e != '') msg = msg + e + '\n';
    e = check_contract_length('pcontractlength');
    if (e != '') msg = msg + e + '\n';
    e = check_price('pprice');
    if (e != '') msg = msg + e + '\n';
    e = check_postcode('ppostcode');
    if (e != '') msg = msg + e + '\n';

    if (msg != '') {
        alert(msg);
        return false;
    }
    return true;
}

function check_mprn(fmmprn) {
    var Mprn = document.getElementsByName(fmmprn)[0];

    if (Mprn) {
        if (Mprn.value == null || Mprn.value == "") {
            return 'The MPRN number is incomplete.';
        }

        //    var MprnRegex=/(^((\(?0\d{4}\)?\s?\d{3}\s?\d{3})|(\(?0\d{3}\)?\s?\d{3}\s?\d{4})|(\(?0\d{2}\)?\s?\d{4}\s?\d{4}))(\s?#(\d{4}|\d{3}))?$)/;
        var MprnRegex = /^(\d{6,10}$)/;
        if (check_using_regex(Mprn.value, MprnRegex) == false) {
            return 'The MPRN number is invalid - it must be between 6 and 10 numbers.';
        }
    }
    return '';
}

function check_MPAN() {
    var Mpan_distid = document.getElementsByName('pMpanDistID')[0];
    if (Mpan_distid) {
        // first field exists so the rest should be present
        var Mpan_urn1 = document.getElementsByName('pMpanUrn1')[0];
        var Mpan_urn2 = document.getElementsByName('pMpanUrn2')[0];
        var Mpan_cd = document.getElementsByName('pMpanCD')[0];

        var mpan = Mpan_distid.options[Mpan_distid.selectedIndex].text + Mpan_urn1.value + Mpan_urn2.value + Mpan_cd.value;

        var Mpan_Profile = document.getElementsByName('pMpanProfile')[0];
        var Mpan_Mts = document.getElementsByName('pMpanMTS')[0];
        var Mpan_LL = document.getElementsByName('pMpanLL')[0];

        var fullmpan = Mpan_Profile.options[Mpan_Profile.selectedIndex].text + Mpan_Mts.value + Mpan_LL.value + mpan;

        if (fullmpan.length != 21) {
            return 'The MPAN value is incomplete.';
        }
        var primes = [3, 5, 7, 13, 17, 19, 23, 29, 31, 37, 41, 43];
        var sum = 0;
        var value = 0;

        for (i = 0; i < primes.length; i++) {
            sum = sum + (mpan.charAt(i) * primes[i]);
        }

        value = sum % 11;
        value = value % 10;

        if (value != mpan.charAt(12)) {
            return 'The MPAN value is invalid.';
        }
        return '';
    }
    return '';
}

function checkMPANorMPRN(fmproduct, fmMPRN) {
    // if product is electricity check if mpan is complete else check mprn
    var Product = document.getElementsByName(fmproduct)[0];
    if (Product) {
        // we should have already checked for a value in product
        if (Product.value == 'electricity') {
            return check_MPAN();
        }
        if (Product.value == 'gas') {
            return check_mprn(fmMPRN);
        }
    }
    return '';
}

function validatewindowchecker() {
    var result = true;
    var msg = '';
    var e = check_products('products');
    if (e != '') msg = msg + e + '\n';

    e = check_product('product');
    if (e != '') msg = msg + e + '\n';

    e = check_supplier('pCurSup');
    if (e != '') msg = msg + e + '\n';

    if (msg != '') {
        alert(msg);
        result = false;
    }
    return result;
}

function validateform() {
    var result = true;
    var msg = '';
    var e = check_products('products');
    if (e != '') msg = msg + e + '\n';

    e = check_product('product');
    if (e != '') msg = msg + e + '\n';

    e = check_telecoms('telecoms');
    if (e != '') msg = msg + e + '\n';

    e = check_supplier('pcursup');
    if (e != '') msg = msg + e + '\n';

    e = checkMPANorMPRN('product', 'pMprNo');
    if (e != '') msg = msg + e + '\n';

    e = check_fullname('pfullname');
    if (e != '') msg = msg + e + '\n';

    e = check_firstname('pfirstname');
    if (e != '') msg = msg + e + '\n';

    e = check_surname('psurname');
    if (e != '') msg = msg + e + '\n';

    e = check_business('pcompname');
    if (e != '') msg = msg + e + '\n';

    e = check_address();
    if (e != '') msg = msg + e + '\n';

    e = check_phone_or_email('pphoneno', 'pemail');
    if (e != '') msg = msg + e + '\n';

    e = check_multiple_emails('pemails');
    if (e != '') msg = msg + e + '\n';

    e = check_postcode('psuppostcode');
    if (e != '') msg = msg + e + '\n';

    if (msg != '') {
        alert(msg);
        result = false;
    }
    return result;
}

//BF 9 Nov 2010 - Terminate Letter validation
function validateTerminateLetterForm() {
    var result = true;
    var msg = '';
    var e = check_products('products');
    if (e != '') msg = msg + e + '\n';

    e = check_product('product');
    if (e != '') msg = msg + e + '\n';

    e = check_telecoms('telecoms');
    if (e != '') msg = msg + e + '\n';

    e = check_supplier('pcursup');
    if (e != '') msg = msg + e + '\n';

    e = checkMPANorMPRN('product', 'pMprNo');
    if (e != '') msg = msg + e + '\n';

    e = check_fullname('pfullname');
    if (e != '') msg = msg + e + '\n';

    e = check_firstname('pfirstname');
    if (e != '') msg = msg + e + '\n';

    e = check_surname('psurname');
    if (e != '') msg = msg + e + '\n';

    e = check_business('pcompname');
    if (e != '') msg = msg + e + '\n';

    e = check_address();
    if (e != '') msg = msg + e + '\n';

    e = check_sendflag_and_email('psendletterbyemail', 'pemail');
    if (e != '') msg = msg + e + '\n';

    e = check_postcode('psuppostcode');
    if (e != '') msg = msg + e + '\n';

    if (msg != '') {
        alert(msg);
        result = false;
    }
    return result;
}

function check_sendflag_and_email(fmSendToEmail, fmEmail) {
    var SendToEmail = document.getElementsByName(fmSendToEmail);
    var Emailaddr = document.getElementsByName(fmEmail)[0];

    if (SendToEmail[0].checked) {

        if (Emailaddr.value == null || Emailaddr.value == "") {
            return 'You must specify an email address.';
        }
        else {
            email = check_email(fmEmail);
            return (email);
        }
    }
    return '';
}
