﻿/// <reference path="../jquery-1.5.1.js"/>
function soNumero(event) {
    var iKey = KeyStroke(event);
    return ((iKey > 47 && iKey < 58) || iKey == 0 || iKey == 8 || iKey == 13);
}

function soCaracter(event) {
    var iKey = KeyStroke(event);
    return ((iKey >= 97 && iKey <= 122) || (iKey >= 65 && iKey <= 90) || iKey == 0 || iKey == 8 || iKey == 13 || iKey == 32 || iKey == 199 || iKey == 89 || iKey == 231);
}

function soNumSinal(iKeyPerm, event) {
    var iKey = KeyStroke(event);
    return ((iKey > 47 && iKey < 58) || (iKey == 0 || iKey == 8 || iKey == 13 || iKey == 44 || iKey == iKeyPerm));
}

function soNumSinalsemVirgula(iKeyPerm, event) {
    var iKey = KeyStroke(event);
    return ((iKey > 47 && iKey < 58) || (iKey == 0 || iKey == 8 || iKey == 13 || iKey == iKeyPerm));
}

function soNaoSinal(iKeyPerm, event) {
    return !(KeyStroke(event) == iKeyPerm);
}

$('.sem-caracter-especial-mantem-espacos').live('blur', function (e) {
    var ctrl = $(this);
    ctrl.val(ctrl.val().RemoveDiacritics());
    if (ctrl.val().replace(/[^a-zA-Z ]+/g, '').length != ctrl.val().length)
        ctrl.val('');
});

function KeyStroke(event) {
    var ikey = 0;
    if (event.which == undefined) {
        ikey = window.event.keyCode;
    }
    else {
        ikey = event.which;
    }
    return ikey;
}

function KeyIns(event, iKey) {
    if (event.which == undefined) {
        window.event.keyCode = iKey;
    }
    else {
        event.keyCode = iKey;
    }
}

function ValidatePhoneNumber(phoneNumber, phType) {
    var reg = null;

    switch (phType) {
        case PhoneType.Comercial:
        case PhoneType.Residencial:
            reg = /^[0-5]/;
            break;

        case PhoneType.Celular:
            reg = /^[6-9]/;
            break;

        default:
            return false;
    }

    return reg.test(phoneNumber);
}

function validCPF_CNPJ(theCPF) {

    theCPF = trim(fnlmpCNPJ(theCPF));

    theCPF = theCPF.replace(/[^0-9]/g, '');

    if (theCPF == "") {
        return (false);
    }
    if (((theCPF.length == 11) && (theCPF == 11111111111) || (theCPF == 22222222222) || (theCPF == 33333333333) || (theCPF == 44444444444) || (theCPF == 55555555555) || (theCPF == 66666666666) || (theCPF == 77777777777) || (theCPF == 88888888888) || (theCPF == 99999999999) || (theCPF == 00000000000))) {
        return (false);
    }


    if (!((theCPF.length == 11) || (theCPF.length == 14))) {
        return (false);
    }

    var checkOK = "0123456789";
    var checkStr = theCPF;
    var allValid = true;
    var allNum = "";
    for (i = 0; i < checkStr.length; i++) {
        ch = checkStr.charAt(i);
        for (j = 0; j < checkOK.length; j++)
            if (ch == checkOK.charAt(j))
                break;
        if (j == checkOK.length) {
            allValid = false;
            break;
        }
        allNum += ch;
    }

    if (!allValid) {
        return (false);
    }

    var chkVal = allNum;
    var prsVal = parseFloat(allNum);
    if (chkVal != "" && !(prsVal > "0")) {
        return (false);
    }

    if (theCPF.length == 11) {
        var tot = 0;

        for (i = 2; i <= 10; i++)
            tot += i * parseFloat(checkStr.charAt(10 - i));

        if ((tot * 10 % 11 % 10) != parseFloat(checkStr.charAt(9))) {
            return (false);
        }

        tot = 0;

        for (i = 2; i <= 11; i++)
            tot += i * parseFloat(checkStr.charAt(11 - i));

        if ((tot * 10 % 11 % 10) != parseFloat(checkStr.charAt(10))) {
            return (false);
        }
    }
    else {
        var tot = 0;
        var peso = 2;

        for (i = 0; i <= 11; i++) {
            tot += peso * parseFloat(checkStr.charAt(11 - i));
            peso++;
            if (peso == 10) {
                peso = 2;
            }
        }

        if ((tot * 10 % 11 % 10) != parseFloat(checkStr.charAt(12))) {
            return (false);
        }

        tot = 0;
        peso = 2;

        for (i = 0; i <= 12; i++) {
            tot += peso * parseFloat(checkStr.charAt(12 - i));
            peso++;
            if (peso == 10) {
                peso = 2;
            }
        }

        if ((tot * 10 % 11 % 10) != parseFloat(checkStr.charAt(13))) {
            return (false);
        }
    }
    return (true);
}

function MascaraCPF_CNPJ(inputCPF_CNPJ, event) {
    if (inputCPF_CNPJ.value.length > 14)
        return fnMascaraCNPJ(inputCPF_CNPJ, event);
    else
        return fnMascaraCPF(inputCPF_CNPJ, event);
}

function fnlmpCNPJ(strCNPJ) {
    strResult = '';
    for (iCont = 0; iCont < strCNPJ.length; iCont++) {
        if (strCNPJ.charAt(iCont) != '.' && strCNPJ.charAt(iCont) != '-' && strCNPJ.charAt(iCont) != '/') {
            strResult += strCNPJ.charAt(iCont);
        }
    }
    return strResult;
}

function fnMascaraCNPJ(sCNPJ, event) {
    valor = '';
    valor = trim(fnlmpCNPJ(sCNPJ.value));
    Key = KeyStroke(event);
    if (valor.length > 0 && ((Key >= 48 && Key <= 57) || (Key >= 96 && Key <= 105))) {
        mask = '';
        if (valor.length > 0) {
            mask = valor;
            if (valor.length >= 2)
                mask = valor.substring(0, 2) + '.' + valor.substring(2, 5);
            if (valor.length >= 5)
                mask = valor.substring(0, 2) + '.' + valor.substring(2, 5) + '.' + valor.substring(5, 8);
            if (valor.length >= 8)
                mask = valor.substring(0, 2) + '.' + valor.substring(2, 5) + '.' + valor.substring(5, 8) + '/' + valor.substring(8, 12);
            if (valor.length >= 12)
                mask = valor.substring(0, 2) + '.' + valor.substring(2, 5) + '.' + valor.substring(5, 8) + '/' + valor.substring(8, 12) + '-' + valor.substring(12, 14);
        }
        sCNPJ.value = mask;
    }
}

function MascaraCEP(sender, event) {
    valor = sender.value;
    valor = valor.replace("-", "");

    Key = KeyStroke(event);

    if (valor.length > 0 && ((Key >= 48 && Key <= 57) || (Key >= 96 && Key <= 105))) {
        mask = '';
        if (valor.length > 0) {
            mask = valor;
            if (valor.length >= 5)
                mask = valor.substring(0, 5) + '-' + valor.substr(5, 3);
        }
        sender.value = mask;
    }
}

function fnMascaraCPF(sCPF, event) {
    valor = '';
    valor = trim(fnlmpCPF(sCPF.value));
    Key = KeyStroke(event);
    if (valor.length > 0 && ((Key >= 48 && Key <= 57) || (Key >= 96 && Key <= 105))) {
        mask = '';
        if (valor.length > 0) {
            mask = valor;
            if (valor.length >= 3)
                mask = valor.substring(0, 3) + '.' + valor.substring(3, 6);
            if (valor.length >= 6)
                mask = valor.substring(0, 3) + '.' + valor.substring(3, 6) + '.' + valor.substring(6, 9);
            if (valor.length >= 9)
                mask = valor.substring(0, 3) + '.' + valor.substring(3, 6) + '.' + valor.substring(6, 9) + '-' + valor.substring(9, 11);
        }
        sCPF.value = mask;
    }
}

function fnlmpCPF(strCPF) {
    strResult = '';
    for (iCont = 0; iCont < strCPF.length; iCont++) {
        if (strCPF.charAt(iCont) != '.' && strCPF.charAt(iCont) != '-') {
            strResult += strCPF.charAt(iCont);
        }
    }
    return strResult;
}

function fnMascaraCEP(sCEP, event) {
    valor = '';
    valor = trim(fnlmpCEP(sCEP.value));
    Key = KeyStroke(event);
    if (valor.length > 0 && ((Key >= 48 && Key <= 57) || (Key >= 96 && Key <= 105))) {
        mask = '';
        if (valor.length > 0) {
            mask = valor;
            if (valor.length >= 5)
                mask = valor.substring(0, 5) + '-' + valor.substring(5, 8);
        }
        sCEP.value = mask;
    }
}

function fnlmpCEP(strCEP) {
    strResult = '';
    for (iCont = 0; iCont < strCEP.length; iCont++) {
        if (strCEP.charAt(iCont) != '-') {
            strResult += strCEP.charAt(iCont);
        }
    }
    return strResult;
}
function adjustDate(ObjText) {
    valor = '';
    valor = trim(ObjText.value);
    valor = lmpStr(valor, '/');
    iDia = 0;
    iMes = 0;
    iAno = 0;
    mask = '';
    var today = new Date();
    var today_year = today.getFullYear();
    var today_mes = today.getMonth();
    var today_dia = today.getDay();

    if (trim(valor).length != 0) {
        if (valor.length >= 1) {
            iDia = parseFloat(valor.substring(0, 2));
            if (iDia < 01) { iDia = 01 }
            if (iDia > 31) { iDia = 31 }
        }
        else {
            iDia = today_dia;
        }
        if (valor.length >= 3) {
            iMes = parseFloat(valor.substring(2, 4));
            if (iMes < 01) { iMes = 01 }
            if (iMes > 12) { iMes = 12 }

        }
        else {
            iMes = today_mes + 1;
        }
        if (valor.length > 4) {
            iAno = parseFloat(valor.substring(4, 8));
            if (iAno < 100) { iAno = iAno + 2000 }
        }
        else {
            iAno = today_year;
        }

        if (iAno < 1500 || iAno > 2500)
            iAno = today_year;

        ObjText.value = '';

        //
        //Validacao de dias por mes
        //
        if (iMes == 4 && iDia > 30) { iDia = 30 }
        if (iMes == 6 && iDia > 30) { iDia = 30 }
        if (iMes == 9 && iDia > 30) { iDia = 30 }
        if (iMes == 11 && iDia > 30) { iDia = 30 }
        if (iMes == 2 && iDia > 29) { iDia = 29 }

        //
        //Bissexto
        //
        if (iMes == 2 && iDia >= 28) {
            iBiSexto = iAno / 4;
            iDia = iBiSexto.toString().length == 3 ? 29 : 28;
        }

        //
        //Dia
        //
        var iDiaToString = iDia.toString();
        ObjText.value += (iDiaToString.length < 2 ? '0' : '') + iDiaToString + '/';

        //
        //Mes e Ano
        //
        var iMesToString = iMes.toString();
        ObjText.value += (iMesToString.length < 2 ? '0' : '') + iMesToString + '/' + iAno.toString();
    }
}
function MascData(ObjText, event) {
    valor = '';
    valor = trim(ObjText.value);
    valor = lmpStr(valor, '/');
    iKey = KeyStroke(event);
    strDia = '';
    strMes = '';

    if (valor.length > 0 && ((iKey >= 48 && iKey <= 57) || (iKey >= 96 && iKey <= 105))) {
        mask = '';
        if (valor.length > 0 && valor.length <= 2) {
            mask = valor;
            if (valor.length == 2) {
                if (parseFloat(valor.substring(0, 2)) > 31) {
                    mask = '31';
                }
            }
        }
        if (valor.length > 2 && valor.length <= 4) {
            if (parseFloat(valor.substring(0, 2)) > 31)
            { strDia = '31' }

            else
            { strDia = valor.substring(0, 2) }

            if (valor.length == 4) {
                var valorSubString = valor.substring(2, 4);
                if (parseFloat(valorSubString) > 12) {
                    strMes = '12'
                }
                else {
                    strMes = valorSubString
                }
            }
            else {
                strMes = valor.substring(2, 4);
            }
            mask = mask + strDia + '/' + strMes;
        }
        if (valor.length > 4) {
            if (parseFloat(valor.substring(0, 2)) > 31)
            { strDia = '31' }

            else
            { strDia = valor.substring(0, 2) }

            if (valor.length > 4) {
                if (parseFloat(valor.substring(2, 4)) > 12)
                { strMes = '12' }

                else
                { strMes = valor.substring(2, 4) }
            }
            else {
                strMes = valor.substring(2, 4);
            }
            mask = mask + strDia + '/' + strMes + '/' + valor.substring(4, 8);
        }
        ObjText.value = mask;
    }
}

function trim(str) {
    return (str == undefined || str == null) ? "" : ltrim(rtrim(str));
}
function lmpStr(strVal, StrCar) {

    strResult = '';
    for (iCont = 0; iCont < strVal.length; iCont++) {
        if (strVal.charAt(iCont) != StrCar) {
            strResult += strVal.charAt(iCont);
        }
    }
    return strResult;
}
function ltrim(str) {
    l = new Number(str.length);
    if (l > 0) {
        while (str.charAt(0) == " " || str.charAt(0) == "\t")
            str = str.substr(1, l - 1);
    }
    return str;
}

function rtrim(str) {
    l = new Number(str.length);
    if (l > 0) {
        while (str.charAt(l - 1) == " " || str.charAt(l - 1) == "\t") {
            str = str.substr(0, l - 1);
            l = str.length;
        }
    }
    return str;
}

String.prototype.RemoveDiacritics = function () {
    var Acentos = "áàãââÁÀÃÂéêÉÊíÍóõôÓÔÕúüÚÜçÇabcdefghijklmnopqrstuvxwyzABCDEFGHIJKLMNOPQRSTUVXWYZñòîÎìÌèÈ";
    var Traducao = "aaaaaAAAAeeEEiIoooOOOuuUUcCabcdefghijklmnopqrstuvxwyzABCDEFGHIJKLMNOPQRSTUVXWYZnoiIiIeE";
    var Posic, Carac;
    var TempLog = "";
    var value = this;

    for (var i = 0, len = this.length; i < len; i++) {

        Carac = value.charAt(i);
        Posic = Acentos.indexOf(Carac);

        TempLog += Posic > -1 ? Traducao.charAt(Posic) : Carac;
    }

    return TempLog;
}

String.prototype.replaceAll = function (OldValue, NewValue) {
    var returnValue = this;
    while (returnValue.indexOf(OldValue) >= 0) {
        returnValue = returnValue.replace(OldValue, NewValue);
    }
    return returnValue.toString();
};

function isEmail(Email) {
    if (Email != null && Email != undefined)
        Email = Email.replaceAll(" ", "");

    var emailDetector = new RegExp(/^[\d\w_.-]+@([\d\w_-]+\.){1,}[\w\d]+$/);
    return emailDetector.test(Email);
}

function ValidaCartaoCredito(inNumber, type) {

    var total = 0;
    var tmp = 0;
    var number = "";

    // Verificacao de numeros na string inNumber
    for (i = 0, len = inNumber.length; i < len; i++) {
        var inNumberCharAt = inNumber.charAt(i);
        if (inNumberCharAt >= "0" && inNumberCharAt <= "9")
            number += inNumberCharAt;
        else
            return false
    }

    // Se numero for curto demais para qualquer tipo
    if (number.length < 13)
        return false;

    first = "" + number.charAt(0);
    second = "" + number.charAt(1);
    third = "" + number.charAt(2);
    firstTwo = first + second;
    firstFour = firstTwo + third + number.charAt(3);

    // MASTERCARD
    if (type == "MC") {//"Credicard/MasterCard"
        if (first != "5" || second < "1" || second > "5")
            return false;
        if (number.length != 16)
            return false;
    }

    // MASTERCARD Submarino
    if (type == "MS") {//"MasterCard Submarino"
        if (number.substring(0, 4).indexOf("5324") == -1)
            return false;
        if (number.length != 16)
            return false;
    }

    //AURA
    else if (type == "AU" || type == "submarino") {
        if (checkCCAura(number) != 0 || number.substring(6, 8).indexOf("18") == -1 || number.substring(0, 6).indexOf("507860") == -1)
            return false;
    }

    // Hipercard
    else if (type == "GE") {
        if (number.length == 19) {
            if ((number.substring(0, 6) != "384100") ||
                ((number.substr(6, 1) != '1') &&
                (number.substr(6, 1) != '4') &&
                (number.substr(6, 1) != '6'))) {
                return false;
            }
            else {
                return true;
            }
        }
        else if (number.length == 16) {
            if (number.substring(0, 6) == "606282")
                return true;
            else
                return false;
        }
        else {
            return false;
        }
    }

    // VISA
    else if (type == "VI") { //"Visa"
        if (first != "4")
            return false;
        if (number.length != 13 && number.length != 16)
            return false;
    }
    // AMERICAN EXPRESS
    else if (type == "AX") { //"American Express"
        if (first != "3" || (second != "4" && second != "7"))
            return false;
        if (number.length != 15)
            return false;
    }
    // DINERS
    else if (type == "DI") { //"Diners"
        if (firstTwo != "36" && firstTwo != "38" && (firstTwo != "30" || (third < "0" || third > "5")))
            return false;
        if (number.length != 14)
            return false;
    }
    // JCB CARDS
    else if (type == "JCB Cards") {
        if (firstFour != "2131" && firstFour != "1800" && (first != "3"))
            return false;
        if (number.length != 16 && first == "3")
            return false;
        if (number.length != 15 && first != "3")
            return false;
    }

    // Fazendo o check sum
    for (loc = number.length - 2; loc >= 0; loc -= 2) {
        total += 1 * number.charAt(loc + 1);
        tmp = number.charAt(loc) * 2;
        if (tmp > 9)
            total += 1;
        total += tmp % 10;
    }
    if (number.length % 2 > 0)
        total += 1 * number.charAt(0);

    return (total % 10 == 0);
}

function checkCCAura(ccnumber) {
    var re;
    re = / /gi;

    ccnumber = ccnumber.replace(re, '');

    if (ccnumber.charAt(0) == '0')
        ccnumber = ccnumber.substr(1, ccnumber.length);

    ccprefix = '507860';

    prefixvalid = false;
    lengthvalid = false;

    if (ccnumber.indexOf(ccprefix) == 0)
        prefixvalid = true;

    if (ccnumber.length == 19)
        lengthvalid = true;

    var result = 0;
    if (!prefixvalid)
        result += 1;

    if (!lengthvalid)
        result += 2;

    qsum = 0;

    for (var x = 0; x < ccnumber.length; x++) {
        ch = ccnumber.substr(ccnumber.length - x - 1, 1);
        if (x % 2 != 0) {
            sum = 2 * parseFloat(ch, 10);
            qsum += (sum % 10);
            if (sum > 9)
                qsum += 1;
        }
        else
            qsum += parseFloat(ch, 10);
    }

    if (qsum % 10 != 0)
        result += 4;

    return result;
}

function isCCInternational(CCNumber) {
    return false;
    if (BinCCInternacional != undefined)
        for (var i = 0, len = BinCCInternacional.length; i < len; i++) {
            var itemLen = BinCCInternacional[i].toString().length;
            if (CCNumber.length < itemLen)
                return false;
            else if (BinCCInternacional[i] == CCNumber.substring(0, itemLen))
                return true;
        }

    return false;
}

function VerificaCodigoSeguranca(codSeg, type) {
    var retorno = true;

    if (type == 'VI') { retorno = codSeg.length <= 3 }
    if (type == 'MC') { retorno = codSeg.length <= 3 }
    if (type == 'MS') { retorno = codSeg.length <= 3 }
    if (type == 'AX') { retorno = codSeg.length == 4 }
    if (type == 'DI') { retorno = codSeg.length <= 3 }
    if (type == 'AU') { retorno = codSeg.length == 0 }
    if (type == 'GE') { retorno = codSeg.length <= 3 }

    return retorno;
}

function CalculaIdade(birthDay, birthMonth, birthYear, todayDay, todayMonth, todayYear) {
    //today_date = new Date();
    today_year = todayYear; //  today_date.getFullYear();
    today_month = todayMonth; //  today_date.getMonth();
    today_day = todayDay; //  today_date.getDate();
    age = today_year - birthYear;
    if (today_month < (birthMonth - 1)) {
        age--;
    }
    if (((birthMonth - 1) == today_month) && (today_day < birthDay)) {
        age--;
    }
    return age;
}

function setDateRegionalString(DateString) {
    var oDate;
    if (DateString && DateString.indexOf("/") >= 0) {
        var dateStringSplit = DateString.split("/");
        if (dateStringSplit.length == 3) {
            var Day = dateStringSplit[0];
            var Month = dateStringSplit[1] - 1;
            var Year = dateStringSplit[2];
            oDate = new Date();
            oDate.setFullYear(Year, Month, Day);
        }
    }
    return oDate;
}
