function utf8_decode ( str_data ) {
    var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0;
    str_data += '';
    while ( i < str_data.length ) {
        c1 = str_data.charCodeAt(i);
        if (c1 < 128) {
            tmp_arr[ac++] = String.fromCharCode(c1);
            i++;
        } else if ((c1 > 191) && (c1 < 224)) {
            c2 = str_data.charCodeAt(i+1);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i+1);
            c3 = str_data.charCodeAt(i+2);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }
    return tmp_arr.join('');
}

function utf8_encode (argString) {
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: sowberry
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +   improved by: Yves Sucaet
    // +   bugfixed by: Onno Marsman
    // +   bugfixed by: Ulrich
    // +   bugfixed by: Rafal Kukawski
    // *     example 1: utf8_encode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'

    if (argString === null || typeof argString === "undefined") {
        return "";
    }

    var string = (argString + ''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");
    var utftext = "",
    start, end, stringl = 0;

    start = end = 0;
    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;

        if (c1 < 128) {
            end++;
        } else if (c1 > 127 && c1 < 2048) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc !== null) {
            if (end > start) {
                utftext += string.slice(start, end);
            }
            utftext += enc;
            start = end = n + 1;
        }
    }

    if (end > start) {
        utftext += string.slice(start, stringl);
    }

    return utftext;
}


$(document).ready(function(){
    //var xTriggered = 0;
    jQuery.fn.soNumeros = function(){
        $(this).keyup(function(event){
            var val = $(".nf").val();
            var val2 = "";
            for(i = 0; i < val.length; i++){
                if(val.substr(i,1) >= 0 && val.substr(i,1) <= 9){
                    val2 += val.substr(i,1);
                }
            }
            $(this).val(val2);
        });
    }
});

function valida_cpf_cnpj(dado){
    
    dado = dado.replace(/(\.|\-|\/)/gi, "");

    var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
    
    if(dado.length != 11 && dado.length != 14){
        return false;
    }
    if(dado.length == 11){
        digitos_iguais = 1;
        if (dado.length < 11)
            return false;
        for (i = 0; i < dado.length - 1; i++)
            if (dado.charAt(i) != dado.charAt(i + 1)){
                digitos_iguais = 0;
                break;
            }
        if (!digitos_iguais){
            numeros = dado.substring(0,9);
            digitos = dado.substring(9);
            soma = 0;
            for (i = 10; i > 1; i--)
                soma += numeros.charAt(10 - i) * i;
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(0))
                return false;
            numeros = dado.substring(0,10);
            soma = 0;
            for (i = 11; i > 1; i--)
                soma += numeros.charAt(11 - i) * i;
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(1))
                return false;
            return true;
        }
        else
            return false;
    }else{
        digitos_iguais = 1;
        if (dado.length < 14 && dado.length < 15)
            return false;
        for (i = 0; i < dado.length - 1; i++)
            if (dado.charAt(i) != dado.charAt(i + 1))
            {
                digitos_iguais = 0;
                break;
            }
        if (!digitos_iguais)
        {
            tamanho = dado.length - 2
            numeros = dado.substring(0,tamanho);
            digitos = dado.substring(tamanho);
            soma = 0;
            pos = tamanho - 7;
            for (i = tamanho; i >= 1; i--)
            {
                soma += numeros.charAt(tamanho - i) * pos--;
                if (pos < 2)
                    pos = 9;
            }
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(0))
                return false;
            tamanho = tamanho + 1;
            numeros = dado.substring(0,tamanho);
            soma = 0;
            pos = tamanho - 7;
            for (i = tamanho; i >= 1; i--)
            {
                soma += numeros.charAt(tamanho - i) * pos--;
                if (pos < 2)
                    pos = 9;
            }
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(1))
                return false;
            return true;
        }
        else
            return false;
    }
}

function valida_CNPJ(cnpj){

    cnpj = cnpj.replace(".","");
    cnpj = cnpj.replace(".","");
    cnpj = cnpj.replace("/","");
    cnpj = cnpj.replace("-","");

    var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
    digitos_iguais = 1;
    if (cnpj.length < 14 && cnpj.length < 15)
        return false;
    for (i = 0; i < cnpj.length - 1; i++)
        if (cnpj.charAt(i) != cnpj.charAt(i + 1)){
            digitos_iguais = 0;
            break;
        }
    if (!digitos_iguais){
        tamanho = cnpj.length - 2
        numeros = cnpj.substring(0,tamanho);
        digitos = cnpj.substring(tamanho);
        soma = 0;
        pos = tamanho - 7;
        for (i = tamanho; i >= 1; i--)
        {
            soma += numeros.charAt(tamanho - i) * pos--;
            if (pos < 2)
                pos = 9;
        }
        resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
        if (resultado != digitos.charAt(0))
            return false;
        tamanho = tamanho + 1;
        numeros = cnpj.substring(0,tamanho);
        soma = 0;
        pos = tamanho - 7;
        for (i = tamanho; i >= 1; i--)
        {
            soma += numeros.charAt(tamanho - i) * pos--;
            if (pos < 2)
                pos = 9;
        }
        resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
        if (resultado != digitos.charAt(1))
            return false;
        return true;
    }
    else
        return false;
}



function checkMail(mail){
    var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
    if(typeof(mail) == "string"){
        if(er.test(mail)){
            return true;
        }
    }else if(typeof(mail) == "object"){
        if(er.test(mail.value)){
            return true;
        }
    }
    return false;
}

function doLoginAction(){
    var _user = $("#login-usuario").val();
    var _senha = $("#login-senha").val();
    
    $.post(LINK_BASE+'representante/login/ajax/true',{
        setor: _user,
        senha: _senha
    }, function(data){
        switch(data){
            case "OK":
                location.href=LINK_BASE+'representante';
                break;
            case "ERRO-DADOS":
                alert("Por favor preencha todos os campos");
                break;
            case "ERRO-USUARIO":
                alert("Nome de usuário inválido");
                break;
            case "ERRO-SENHA":
                alert("Senha inválida");
                break;
        }
    /*
        if(data == "ERRO"){
            alert("Nome de usuário e/ou senha incorretos.");
        }else{
            location.href=LINK_BASE='representante';
        }
        */
	});
	return false;
}

$(document).ready(function(){

    $.post(LINK_BASE+"loginBox.php",{}, function(ret){
        var html = "";
        if(ret == "true"){
            html += "<h2></h2>";
            html += '<div style="text-align: right; margin-right: 33px;">';
            html += 'Olá Representante, seja bem vindo <a href="'+LINK_BASE+'representante/">(Acessar Área Restrita)</a><a href="'+LINK_BASE+'representante/logout/">(Sair)</a>.';
            html += "</div>";
            $("#area-representante").html(html);
        }else{
            //html += '<form action="'+LINK_BASE+'representante/login" method="post">';
            html += '<h2>Espaço do Representante:</h2>';
            html += "<fieldset><label><span>Setor:</span>";
            html += '<input type="text" id="login-usuario" name="setor">';
            html += "</label><label><span>Senha:</span>";
            html += '<input type="password" id="login-senha" name="senha">';
            html += '</label>';
            html += '<input type="submit" onclick="return doLoginAction();" value="Acessar">';
            html += '</fieldset>';
            //html += '</form>';
            $("#area-representante").html(html);
        }
    });
    
    $("#descadastrar span a").fancybox();

    $("#confirmar-cadastro").click(function(){
        var _nome = $("#newsletter-nome").val();
        var _email = $("#newsletter-email").val();

        //Valida nome
        if(_nome.length == 0){
            Sexy.alert("Por favor, preencha o seu nome");
            return false;
        }

        //Valida email
        if(!checkMail(_email)){
            Sexy.alert("E-Mail inválido.\nPreencha corretamente o campo.");
            return false;
        }

        Sexy.confirm(_nome+", você confirma sua incrição em nosso sistema de newsletter com o e-mail "+_email+" e que esse e-mail é seu?",
        {
            onComplete: function(returnvalue){
                if(returnvalue){
                    $.post(LINK_BASE + "index/newsletter/ajax/true/",{
                        nome : _nome,
                        email : _email
                    }, function(data){
                        Sexy.alert(data);
                        $("#newsletter-nome").val("");
                        $("#newsletter-email").val("");
                    });
                }
            }
        }
        );

        return false;
    });

});



