﻿

var Bank = {
    checkIBAN: function(value) {
        // Devuelve si el IBAN es válido
        var tmp = '';
        var tmp2 = ''; //first operation is to extract a part of the IBAN code, which later will be transformed
        tmp = value.substr(4, value.length) + value.substr(0, 4);
        //converting letters to numbers: A=10, B=11... Z=35
        for (var i = 0; i != tmp.length; i++) {
            if (tmp.charCodeAt(i) > 64) {
                var c = tmp.charCodeAt(i) - 55;
                tmp2 += c.toString();
            } else {
                tmp2 += tmp.charAt(i);
            }
        }
        var counter = 0; //now we have to divide the huge number above to 97. The rest represents validation result
        var piece = tmp2.charAt(counter);
        var rest = 0;  //since dividing huge numbers is not possible due to Number class representation, we have to use division algorithm learned in the first years of school
        while (counter < tmp2.length) {
            if (Number(piece) > 97) { //the chunk is larger than the divider, we can divide
                rest = Number(piece) % 97;
                piece = rest.toString(); //the piece will keep the rest so we can divide again;
            } else { //the chunk is smaller than 97, we cannot divide. We'll add another piece to the chunk
                counter++;
                piece += tmp2.charAt(counter);
            }
        }
        // rest = 98 - rest; //if needed, we can return the  control code , which is the 2 digit number  after country code
        return rest; //returns the rest. If the rest is equal with 1, the IBAN account is valid
    }
};