var http = null; 
var inCall = false;
var regexEmail = /^([\w]+)(.[\w]+)*@([\w]+)(.[\w]{2,3}){1,2}$/;
var formvalues = null;
var lastValuesDiv = null;


// - FUNCOES GENERICAS
function getObj(name) {
    return document.getElementById(name);
}

function createRequestObject() {
  var reqObj;
  var browser = navigator.appName;
  if(browser == "Microsoft Internet Explorer"){
    reqObj = new ActiveXObject("Microsoft.XMLHTTP");
    isIE = true;
  }else{
    reqObj = new XMLHttpRequest();
  }
  return reqObj;
}

function doCall(whereTo, returnTo,async){
    if (async == null)
        async = false;
        
  inCall = true;
  http = createRequestObject();
  http.open('get', noCache(whereTo), async);
  
  // DO WE HAVE A FUNCTION TO CALL ONCE CALL IS COMPLETED?
  if(returnTo.length > 0){
    eval("http.onreadystatechange = "+returnTo);
  }
  // SEND CALL
  http.send(null);
}

function noCache(uri)
{
    return uri.concat(/\?/.test(uri)?"&":"?","noCache=",(new Date).getTime(),".",Math.random()*1234567);
}

function historyReturn(value)
{
    var obj = getObj(value);
    if(obj != null && lastValuesDiv != null)
        obj.innerHTML = lastValuesDiv;
}


// - FUNCOES SISTEMA
function validateLogin()
{
    var user = getObj('user');
    var pass = getObj('pass');
    if(user == null)
        return false;
    
    if(pass == null)
        return false;

    //validar LOGIN
     if (user.value == ""){
               alert("O campo E-mail deve ser preenchido!");
               user.focus();
               return false;
     }
     
     if(!validateFieldEmail('user'))
     {
         alert ("O campo E-mail deve conter um endereco eletrônico!");
               user.focus();
               return false;
     }
     
     //validar LOGIN
     if (pass.value == ""){
               alert("O campo Senha deve ser preenchido!");
               pass.focus();
               return false;
     }
     
     return true;
}

function validateEndEntrega()
{
    var obj = getObj('endcad');
    
    if(obj != null && obj.value == 'cad')
    {
        obj = getObj('cadastro');
        if(obj != null)
        {
            obj.submit();
            return;
        }
    }
    else if(obj != null)
    {
        obj = getObj('txinicep')
        if(obj == null || obj.value == ''){
            alert('O campo cep deve ser preenchido');
            obj.focus();
            return;
        }
        
        obj = getObj('txfimcep')
        if(obj == null || obj.value == ''){
            alert('O campo cep deve ser preenchido');
            obj.focus();
            return;
        }
        
        obj = getObj('logradouro')
        if(obj == null || obj.value == ''){
            alert('O campo Rua deve ser preenchido');
            obj.focus();
            return;
        }
        
        obj = getObj('numero')
        if(obj == null || obj.value == ''){
            alert('O campo Número deve ser preenchido');
            obj.focus();
            return;
        }
        
        obj = getObj('cidade')
        if(obj == null || obj.value == ''){
            alert('O campo Cidade deve ser preenchido');
            obj.focus();
            return;
        }
        
        
        
        obj = getObj('cadastro');
        if(obj != null)
        {
            obj.submit();
            return;
        }
    }
    
    alert('Ocorreu um erro no sistema, tente novamente!');
    
}

function validateUser(){
    var response = null;
    
    if (http.readyState == 4) {
        response = http.responseText;
        if(response == 'NO')
        {
            var user = getObj('user');
            var pass = getObj('pass');
            
            alert('Usuário não cadastrado no sistema!');
            user.value = '';
            pass.value = '';
            user.focus();
        }
        else
        {
            var conteudo = getObj('carrinho');
            if(conteudo != null && response != null)
            {
                conteudo.innerHTML = response;
            }
        }
        escondeAviso();
    }
    inCall = false;
}

function goToInvoice(){
   if(validateLogin())
   {
       mostraAviso();
       obj = getObj('carrinho');
        if(obj != null)
            lastValuesDiv = obj.innerHTML;
    
       var user = getObj('user');
       var pass = getObj('pass');
       
       if(user == null && user.value != null && user.value != '')
           user = '';

       if(pass == null && pass.value != null && pass.value != '')
           pass = '';
       
       doCall("LoginServlet?act=vl&email=" + user.value +
           "&pass=" + pass.value,"validateUser", true);
   }
}

function goToCCS(act){
   if(validateLogin())
   {
       mostraAviso();
       obj = getObj('carrinho');
        if(obj != null)
            lastValuesDiv = obj.innerHTML;
    
       var user = getObj('user');
       var pass = getObj('pass');
       
       if(user == null && user.value != null && user.value != '')
           user = '';

       if(pass == null && pass.value != null && pass.value != '')
           pass = '';
       
       doCall("LoginServlet?act="+ act +"&email=" + user.value +
           "&pass=" + pass.value,"validateUser", true);
   }
}

function setCep(cepini, cepfin)
{
    var obj;
    var cep;
    
    
    obj = getObj(cepini);
    if(obj == null)
        return;
    
    cep = obj.value;
    cep += "-";
    
    obj = getObj(cepfin);
    if(obj == null)
        return;
    
    cep += obj.value;
    
    if(cep == null || cep == '' || cep == '-')
        return;
    
    mostraAviso();
    doCall("LoginServlet?act=cp&cep=" + cep,"getCep", true);
}

function URLDecode(psEncodeString) 
{
  // Create a regular expression to search all +s in the string
  var lsRegExp = /\+/g;
  // Return the decoded string
  return unescape(String(psEncodeString).replace(lsRegExp, " ")); 
}

function getCep()
{
    if (http.readyState == 4) {
        var response = http.responseText;
        if(response != null)
        {
            var values = new Array();
            var obj;
            values = response.split("|");
            
            if(values.length > 1)
            {
                var campos = new Array();
                
                campos[0] ='cep';
                campos[1] ='logradouro';
                campos[2] ='bairro';
                campos[3] ='cidade';
                campos[4] ='selEstado';
                
                for(i = 1; i < values.length; i++)
                {
                    obj = getObj(campos[i]);
                    
                    if(obj != null)
                    {
                        if(campos[i] != 'selEstado')
                        {
                            obj.value = values[i];
                        }
                        else
                        {
                            for (a = 0; a < obj.options.length; a++) {
                                if(obj.options[a].value != null && 
                                    obj.options[a].value == values[i])
                                {
                                    obj[a].selected = "1";
                                }
                            }
                        }
                    }
                }
            }
            escondeAviso();
        }
        inCall = false;
        
    }
}

function goToRegister()
{
    mostraAviso();
    obj = getObj('carrinho');
    if(obj != null)
        lastValuesDiv = obj.innerHTML;
       
    doCall("LoginServlet?act=cad&def=j","carregaConteudo", true);
}

function carregaConteudo() {
    if (http.readyState == 4) {
        var response = http.responseText;
        if(response != null)
        {
            getObj('carrinho').innerHTML = response;
        }
        inCall = false;
        escondeAviso();
    }
}
    
function registerForm(upd)
{
    var test;
    var replace;
    var persontype;
    
    persontype = getObj('radJuridica');
    
    if(persontype == null )
        persontype = 'j';
    else if(persontype.checked)
        persontype = 'j';
    else
        persontype = 'f';
    
    test = getObj('nome');
    if(test == null || test.value == '')
    {
        if(persontype == 'j')
            alert(unescape('O campo Razão Social deve ser preenchido.'));
        else
            alert('O campo Nome deve ser preenchido.');
        
        if(test != null)
            test.focus();
        return;
    }
    
    test = getObj('sobrenome');
    if(test == null || test.value == '')
    {
        if(persontype == 'j')
            alert('O campo Sobrenome deve ser preenchido.')
        else
            alert('O campo Nome Fantasia deve ser preenchido.')
        
        if(test != null)
            test.focus();
        return;
    }
    
    test = getObj('email');
    if(test == null || test.value == '')
    {
        alert('O campo email deve ser preenchido.')
        if(test != null)
            test.focus();
        return;
    }
 
    if(!validateFieldEmail('email')) 
    {
        alert('Digite um email válido no campo Email.')
        if(test != null)
            test.focus();
        return;
    } 
    
    if(upd)
    {
        test = getObj('pass');
        if(test == null || test.value == '')
        {
            alert('O campo senha deve ser preenchido.')
            if(test != null)
                test.focus();
            return;
        }


        replace = getObj('replacepass');
        if(replace == null || replace.value == '')
        {
            alert('O campo Repita a Senha deve ser preenchido.')
            if(replace != null)
                replace.focus();
            return;
        }

        if(test.value != replace.value)
        {
            alert('O campo Senha não coincide com o campo Repita a Senha.')
            
            test.value = '';
            replace.value = '';
            if(test != null)
                test.focus();
            return;
        }
        replace = null;
    }
    
    test = getObj('cnpj');
    if(test == null || test.value == '')
    {
        if(persontype == 'j')
        {
            alert('O campo CNPJ deve ser preenchido.')
        }
        else
        {
            alert('O campo CPF deve ser preenchido.')
        }
        if(test != null)
            test.focus();
        return;
    }
    else
    {
        if(persontype == 'f')
        {
            if(!validateFieldCPF('cnpj'))
            {
                alert('Insira um CPF válido no campo CPF.');

                if(test != null)
                {
                    test.value = '';
                    test.focus();
                    return;
                }
            }
        }
        else
        {
            if(!validateFieldCNPJ('cnpj'))
            {
                alert('Insira um CNPJ válido no campo CNPJ.');

                if(test != null)
                {
                    test.value = '';
                    test.focus();
                    return;
                }
            }
        }
    }


    test = getObj('ie');
    if(persontype == 'j' && test.length < 5)
    {
       
       alert('O campo Insc. Estadual deve ser preenchido.');
       if(test != null)
            test.focus();
       return;
    }


    test = getObj('numero');
    if(test == null || test.value == '')
    {
        alert('O campo Número deve ser preenchido.')
        if(test != null)
            test.focus();
        return;
    }
    
    test = getObj('telefone');
    if(test == null || test.value == '')
    {
        alert('O campo Telefone deve ser preenchido.')
        if(test != null)
            test.focus();
        return;
    }
    
    // VALIDA A ENTREGA
    validateEntrega('getReturnValidate','txinicep', 'txfimcep' );
}

 var entregaValida = '';
 
 function validateEntrega(returnTo, cep1, cep2)
 {
    if(validateCep(cep1, cep2))
    {        
        var cep = getObj(cep1).value;
        cep += getObj(cep2).value;
        doCall('ShoppingCartServlet?act=cf&cepd=' + cep , returnTo); 
    }
    else
    {
        alert('Digite um CEP válido!');
    }
 }
 
 function getReturnValidate()
 {
    var response = null;
    if (http.readyState == 4) {
        response = http.responseText;
        if(response != null)
        {
            if(response.toUpperCase().trim() == 'NO')
            {
                alert('Não entregamos nesta localidade!');
                return;
            }
            
              test = getObj('cadastro');
              if(test != null)
              {
                  test.submit();
              }
        }
        else
        {
            alert('Entre com o CEP novamente!');
        }
    }
    inCall = false;
 }
 
function setValuesRegiserForm(type)
{
    var temp;
    if(type != null && type == 'f')
    {
        temp = getObj('lnome');
        if(temp != null)
            temp.innerHTML = 'Nome*';
        
        temp = getObj('lsobrenome');
        if(temp != null)
            temp.innerHTML = 'Sobrenome*';
        
        temp = getObj('scnpj');
        if(temp != null)
        {
            var scnpj = '<label id="lcnpj" for="cnpj">CPF*</label>';
            scnpj += '<input type="text" value="" onkeyup="formatCPF(\'cnpj\');" maxlength="14" name="cnpj" id="cnpj" />';
            temp.innerHTML = scnpj;
        }
        
        temp = getObj('lie');
        if(temp != null)
            temp.innerHTML = 'RG';
    }
    else
    {
        temp = getObj('lnome');
        if(temp != null)
            temp.innerHTML = 'Razão Social*';
        
        temp = getObj('lsobrenome');
        if(temp != null)
            temp.innerHTML = 'Nome Fantasia*';
        
        temp = getObj('scnpj');
        if(temp != null)
        {
            scnpj = '<label id="lcnpj" for="cnpj">CNPJ*</label>';
            scnpj += '<input type="text" value="" onkeyup="formatCNPJ(\'cnpj\');" maxlength="18" name="cnpj" id="cnpj" />';
            temp.innerHTML = scnpj;
        }
        
        temp = getObj('lie');
        if(temp != null)
            temp.innerHTML = 'Insc. Estadual';
    }
}

function focusLength(objtest, objtofocus, objlength)
{
    if(objtest != null && objtofocus != null && objlength != null)
    {
        var objpri;
        var objfocus;

        objpri = getObj(objtest);
        if(objpri != null)
        {
            if(objpri.value.length  >= objlength)
            {
                objfocus = getObj(objtofocus);
                if(objfocus != null)
                    objfocus.focus();
            }
        }
    }
}

function actionLength(objtest, objlength, action)
{
    if(objtest != null && objlength != null)
    {
        var objpri;
        
        objpri = getObj(objtest);
        if(objpri != null)
        {
            if(objpri.value.length  == objlength)
            {
                eval(action, 1);
            }
        }
    }
}

// valida numero
function validateNumber(obj){
    
    if(obj != null)
    {
        obj = getObj(obj);
        if(obj != null)
        {
            var i;
            var cadena="";
            var s = obj.value;
            for (i = 0; i < s.length; i++){   
                var c = s.charAt(i);
                if ( isDigit(c) ){
                    cadena+=c;
                }
            }
            obj.value = cadena;
        }
    }
}

function validateNumber(obj, nullable){
    
    var out = new Array();
    
    if(nullable != null)
        out = nullable.split(' ');
    
    if(obj != null)
    {
        obj = getObj(obj);
        if(obj != null)
        {
            var i;
            var cadena="";
            var s = obj.value;
            for (i = 0; i < s.length; i++){   
                var c = s.charAt(i);
                c = c.trim();
                
                for(v = 0; v < out.length; v++)
                {
                    if(c == out[v])
                    {
                        cadena+=c;
                        continue;
                    }
                }
                
                if(isDigit(c)){
                   cadena+=c;
                }
                
            }
            obj.value = cadena;
        }
    }
}

function isDigit (c)
{
   return !isNaN(c);
}

// mascara CPF
function formatCPF(cpf)
{
    var mycpfo;
    var obj = getObj(cpf);
    
    if(obj != null)
    {
        mycpf = obj.value;
        if (mycpf != null && mycpf.length == 3) {
            mycpf = mycpf + '.';
            obj.value = mycpf;
        }
        if (mycpf != null && mycpf.length == 7) {
            mycpf = mycpf + '.';
            obj.value = mycpf;
        }
        if (mycpf != null && mycpf.length == 11) {
            mycpf = mycpf + '-';
            obj.value = mycpf;
        }
    }
}

// valida cpf
function validateCPF(cpffield) {
    if(!validateFieldCPF(cpffield))
    {
        alert('Insira um CPF válido no campo CPF.');
        var obj = getObj(cpffield);
        
        if(obj != null)
        {
            obj.value = '';
            obj.focus();
        }
    }

}

function validateFieldCPF(cpffield) {
    
    var obj = getObj(cpffield)
    if(obj != null)
    {
        var cpf = obj.value;
        var varFirstChr = cpf.charAt(0);
        var vaCharCPF = false;
        
        while(cpf.indexOf('.') != -1)
        {
            cpf = cpf.replace('.', '');
        }
        
        while(cpf.indexOf('/') != -1)
        {
            cpf = cpf.replace('/', '');
        }
        
        while(cpf.indexOf('-') != -1)
        {
            cpf = cpf.replace('-', '');
        }
        
        soma = 0;
        for (i = 0; i < 9; i++) {
            soma += (10 - i) * (eval(cpf.charAt(i)));
        }

        digito_verificador = 11 - (soma % 11);
        if ((soma % 11) < 2) digito_verificador = 0;
        if (eval(cpf.charAt(9)) != digito_verificador) {
            return false;
        }

        soma = 0;
        for (i = 0; i < 9; i++) {
            soma += (11 - i) * (eval(cpf.charAt(i)));
        }
        soma += 2 * (eval(cpf.charAt(9)));
        digito_verificador = 11 - (soma % 11);
        if ((soma % 11) < 2) digito_verificador = 0;
        if (eval(cpf.charAt(10)) != digito_verificador) {
            return false;
        }

        return true;
    }
    else{
        return false;
    }
}

// mascara CNPJ
function formatCNPJ(cnpjfield) {
    
    if(cnpjfield == null)
        return;
    
    var obj = getObj(cnpjfield);
    
    if(obj != null)
    {
        var cnpj = obj.value;

        if(cnpj.length == 2)
        {
            cnpj += '.';
            obj.value = cnpj;
        }
        
        if(cnpj.length == 6)
        {
            cnpj += '.';
            obj.value = cnpj;
        }
        
        if(cnpj.length == 10)
        {
            cnpj += '/';
            obj.value = cnpj;
        }
        
        if(cnpj.length == 15)
        {
            cnpj += '-';
            obj.value = cnpj;
        }
    }
}

// valida CNPJ
function validateCNPJ(cnpjfield) {
    if(!validateFieldCNPJ(cnpjfield))
    {
        alert('Insira um CNPJ válido no campo CNPJ.');
        var obj = getObj(cnpjfield);
        
        if(obj != null)
        {
            obj.value = '';
            obj.focus();
        }
    }

}

function validateFieldCNPJ(value) {
    /*var b = [6,5,4,3,2,9,8,7,6,5,4,3,2];
    if((c = c.replace(/[^\d]/g,"").split("")).length != 14) return false;
    for(var i = 0, n = 0; i < 12; n += c[i] * b[++i]);
    if(c[12] != (((n %= 11) < 2) ? 0 : 11 - n)) return false;
    for(var i = 0, n = 0; i <= 12; n += c[i] * b[i++]);
    if(c[13] != (((n %= 11) < 2) ? 0 : 11 - n)) return false;
    return true;*/
    var erro = new String;
    var CNPJ = getObj(value).value;
     if (CNPJ.length < 14) erro += "É necessario preencher corretamente o número do CNPJ!"; 
          //substituir os caracteres que não são números
        CNPJ = CNPJ. replace (".","");
        CNPJ = CNPJ. replace (".","");
        CNPJ = CNPJ. replace ("-","");
        CNPJ = CNPJ. replace ("/","");
        
        CNPJ = CNPJ.substr(0, 14);

        var nonNumbers = /\D/;
         if (nonNumbers.test(CNPJ)) erro += "A verificação de CNPJ suporta apenas números! \n\n"; 
         var a = [];
         var b = new Number;
         var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
         for (i=0; i<12; i++){
                 a[i] = CNPJ.charAt(i);
                 b += a[i] * c[i+1];
    }
     if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
     b = 0;
     for (y=0; y<13; y++) {
             b += (a[y] * c[y]); 
     }
     if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
     if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
             erro +="Dígito verificador com problema!";
     }
     if (erro.length > 0){
         return false;
     } 
     return true;
}

// validar email
function validateEmail(field)
{
    if(field != null)
    {
        if(!validateFieldEmail(field))
        {
            alert('Digite um email valido');
            var email = getObj(field);
            if(email != null)
            {
                email.value = '';
                email.focus();
            }
        }
    }
}

function validateFieldEmail(field)
{
    //alert(field);
    var obj = getObj(field);
    if(obj == null)
        return false;
    
    var validString = obj.value;
    if(validString != null)
    {
        if(validString.match(regexEmail))
            return true;
        else
            return false;
    }
    else
    {
        return false;
    }

}

// alterna valores do endereco de entrega
function getEnd(copy, divname, formname)
{
    var objform = getObj(formname);
    if(copy != null && copy == true)
    {
        if(objform != null)
        {
            getFormValues(objform);
            var num = objform.elements.length;
            for (var i=0; i< num; i++) {
               if (objform.elements[i] != null){
               
                    if(objform.elements[i].type == 'text')
                    {
                        objform.elements[i].value = '';
                        objform.elements[i].disabled = false;
                    }
                   
                    if(objform.elements[i].type == 'select-one')
                    {
                        objform.elements[i].selected = 'RS';
                        objform.elements[i].disabled = false;
                    }
                }
            }
        }

    }
    else if(copy != null)
    {
        if(formvalues != null && objform != null)
        {
            var num = objform.elements.length;
            var aux = '';
            for (var i=0; i< num; i++) {
               if (objform.elements[i] != null){

                    if(objform.elements[i].type == 'text')
                    {
                        aux = '';
                        if(formvalues.length >= i)
                            aux = formvalues[i];
                        
                        objform.elements[i].value = aux;
                        objform.elements[i].disabled = true;
                    }

                    if(objform.elements[i].type == 'select-one')
                    {
                        aux = 'RS';
                        if(formvalues.length >= i)
                            aux = formvalues[i];
                        
                        objform.elements[i].selected = aux;
                        objform.elements[i].disabled = true;
                    }
                }
            }
        }
    }
}

function getFormValues(objform)
{
    if(objform != null)
    {
        formvalues = new Array();
        var num = objform.elements.length;
        for (var i=0; i< num; i++) {
           if (objform.elements[i] != null){
                
                if(objform.elements[i].type == 'text')
                {
                    formvalues[i] = objform.elements[i].value;
                }
                else if(objform.elements[i].type == 'select-one')
                {
                    formvalues[i] = objform.elements[i].selected;
                }
                else
                {
                    formvalues[i] = '';
                }
            }
        }
    }
}

// funcao para selecao de pagamento
function getPayForm(idobj)
{
    var formas = new Array("boleto", "visa", "visaelectron",
    "dinners", "american", "mastercard","banricomprasavista","banricompraspredatado",
    "banricomprasparcelado","banricomprasboleto", "bradescoboleto");
    var obj = null;
    var text = null;
    var aux = null;
    
    for( i = 0; i < formas.length; i++)
    {
        obj = (document.all) ? document.all(formas[i]) : getObj(formas[i])
        if(obj != null)
        {
            if(idobj == formas[i])
            {
                setClass(formas[i], formas[i] + "-ativo ativo");
                aux = getObj(formas[i] + 'avista');
                if(aux != null)
                    aux.checked = 'checked';
            }
            else
                setClass(formas[i], formas[i]);
        }
    }
}

function setClass(objId,className) {
    document.getElementById(objId).setAttribute((document.all ? 'className': 'class'), className);
    setTimeout('document.getElementById(\''+objId+'\').setAttribute(\''+(document.all ? 'className': 'class')+'\', \''+className+'\')', 30);
}

// abre janela imagem tamanho real
function popupIMG(cod)
{
    var URL = "ImagemPopupServlet?cod=" + cod;
    
    var window_width = 640;
    var window_height = 520;
    var window_top = (screen.height-window_height)/2;
    var window_left = (screen.width-window_width)/2;
    var features = 'width='+ String(window_width) +',height='+ String(window_height);
    features  += ',location=no,scrollbars=no,menubar=no,toolbar=no,status=no';
    features  += ',directories=no,history=no,top=' + window_top + ',left=' + window_left;
    
    var j = window.open(URL,'janela1',features); 
    j.focus();
}

// submissão do fale conosco

function submitContactUs() {
    var nome = getObj('nome').value;
    var email = getObj('email').value;
    var fone = getObj('fone').value;
    var mensagem = getObj('mensagem').value;
    var captcha = getObj('captcha').value;
    var erros = "";
    
    if (nome.length <5)
        erros += "Informe um nome válido.\n";
    if (email.length <5)
        erros += "Informe um email válido.\n";
    if (fone.length < 5)
        erros += "Informe um telefone válido.\n";
    if (captcha.length !=5)
        erros += "Validação da imagem incorreta.\n";
    if (mensagem.length < 10)
        erros += "Informe a sua mensagem\n";
    
    if (erros.length > 0) {
        alert("Ocorreram erros no preenchimento dos dados:\n"+erros);
    } else {  
        var params = "nome="+nome+"&email="+email+"&fone="+fone+"&captcha="+captcha+"&mensagem="+mensagem;
        
        var ajax = getObj('ajax');
       if(ajax != null)
           ajax.style.visibility = 'visible';
        doCall("ContactUsServlet?"+params,"returnContactUs");
        
    }
}
function returnContactUs() {
    if (http.readyState == 4) {
        eval(http.responseText);
        finishAnimation();
    }
}

function returnEsqueciSenha() {
    if (http.readyState == 4) {
        eval(http.responseText);
        finishAnimation();
    }
}

function esqueciSenha() {
    
    if (validateFieldEmail('user')) {
        var email = getObj('user').value;
        doCall("EsqueciSenhaServlet?email="+email, 'returnEsqueciSenha')
    } else {
        alert('Informe um email válido no campo e-mail!');
        getObj('user').focus();
    }
}

function loginCCS()
{
    if(validateLogin())
    {
       mostraAviso(); 
        var user = getObj('user');
        var pass = getObj('pass');
       
        if(user == null && user.value != null && user.value != '')
           user = '';

        if(pass == null && pass.value != null && pass.value != '')
           pass = '';
       
	   var url = "CustomerCentralServlet?act=vl&email=" + user.value + "&pass=" + pass.value;
        doCall(url,"validateUserCCS",true);
    } 
}

function validateUserCCS(){
    var response = null;
    if (http.readyState == 4) {
        response = http.responseText;
        if(response == 'NO')
        {
            var user = getObj('user');
            var pass = getObj('pass');
            
            alert('Usuário não cadastrado no sistema!');
            user.value = '';
            pass.value = '';
            user.focus();
        }
        else
        {
            //window.location = 'CustomerCentralServlet?act=ds';
            var form = getObj('logcli');
            if(form != null)
            {
                form.submit();
            }
        }
        escondeAviso();
    }
    inCall = false;
    
}


/*
 *  INICIO DA ROTINA DE TROCA DE SENHA
 * */
function validateChangePassword()
{
    var obj;
    var atual;
    var nova;
    var novare;
    var email;
    
    obj = getObj('email')
    if(obj != null && obj.value != '')
    {
        email = obj.value;
    }
    
    obj = getObj('pass');
    if(obj == null || obj.value == '')
    {
        alert('Digite a senha atual para continuar!');
        return;
    }
    else
        atual = obj.value;
    
    obj = getObj('senha');
    if(obj == null || obj.value == '')
    {
        alert('Digite a nova senha para continuar!');
        return;
    }
    else
        nova = obj.value;
    
    obj = getObj('nsenha');
    if(obj == null || obj.value == '')
    {
        alert('Redigite a nova senha para continuar!');
        return;
    }
    else
        novare = obj.value;
    
    if(nova != novare)
    {
        alert('A senha a ser repedida não confere!');
        getObj('nsenha').value = '';
        obj.value = '';
        getObj('senha').value = '';
        obj.value = '';
        obj.focus();
        return;
    }
    
    if(atual == nova)
    {
        alert('A senha nova deve ser diferente da atual!');
        return;
    }    
    
    var ajax = getObj('ajax');
       if(ajax != null)
           ajax.style.visibility = 'visible';
       
    doCall("CustomerCentralServlet?act=cp&email=" + email +            
           "&pass=" + atual + "&senha=" + nova ,"changeLocation");

}

function changeLocation()
{
    var response = null;
    
    if (http.readyState == 4) {
        response = http.responseText;
        
        if(response.toUpperCase() != 'OK')
        {
            alert(response);
            window.location = 'CustomerCentralServlet?act=ts';
        }
        else
        {
            alert('Senha alterada com sucesso!');
            window.location = 'LogoutServlet?act=rct';
        }
        finishAnimation();
    }
    
    inCall = false;
}

/*
 *  FINAL DA ROTINA DE TROCA DE SENHA
 * */
 
/*
 *  INICIO DA ROTINA DE CALCULO DE FRETE
 * */
 
 function calculateValueFrete(idobj)
 {
    var obj = getObj(idobj);
    if(obj != null)
    {
        var frete = obj.value;
        
        var subtot = getObj('subtotal');
        
        if(subtot != null)
        {
            subtot = subtot.value;
            var total = parseFloat(subtot) + parseFloat(frete);
            var retorno = '';
            
            obj = getObj('frete');
            if(obj != null)
            {
                obj.style.color = '#000';
                retorno = toMoney(frete, 'R$ ');
                
                obj.innerHTML = retorno;
                
                obj = getObj('total');
                if(obj != null)
                {
                    retorno = toMoney(total, 'R$ ');
                    obj.innerHTML = retorno;
                }
            }
            
        }
    }
 }
 
 function toMoney(val, moeda) 
 {
       var sb = '';
       sb += moeda;
       var v = String(val);
       sb += v.substring(0, v.indexOf("."));
       var d = v.substring(v.indexOf(".")+1);
       if (d.length ==0) d = "00";
       else if(d.length ==1) d+= "0";
       else d = d.substring(0,2);
       sb += ","+d;
       return sb;
} 
 //=================================================================================
 //=================================================================================
 //=================================================================================
 //====================CALCULO DE CEP===============================================
 //=================================================================================
 //=================================================================================
 //=================================================================================
 

 
 function getValuesFrete()
 {
    if(validateCep('txiniciocep', 'txfimcep'))
    {        
        mostraAviso();
        //alert('asdfas');
        
        var obj = getObj('calcfrete');
                if(obj != null)
                    obj.innerHTML = '';
                
        var cep = getObj('txiniciocep').value;
        cep += getObj('txfimcep').value;
        doCall('ShoppingCartServlet?act=cf&cepd=' + cep , 'getReturnFrete',true); 
    }
    else
    {
        alert('Digite um CEP valido!');
    }
 }
 
String.prototype.trim = function()
{
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}
 
 function getReturnFrete()
 {
    var response = null;
    if (http.readyState == 4) {
        response = http.responseText;
        if(response != null)
        {
            if(response.toUpperCase().trim() == 'NO')
            {
                alert(unescape('Não foi possivel calcular o frete, tente novamente!'));
            }
            else
            {
                var print = '';
                var rows = new Array();
                var row  = new Array();
                var name = 'vfrete';
                var id = '';
                var text = '';
                var value = '';
                rows = response.split('|-');

                for(i = 0; i < rows.length; i++)
                {
                    row = rows[i].split('|');

                    if(row.length == 4)
                    {
                        text = row[0];
                        text += ':&nbsp;<strong>';
                        text += row[2];
                        text += '</strong>';
                        id = row[3].trim();
                        value = row[1];
                        print += getFormatedOption(name, id, text,value);
                    }
                }


                var obj = getObj('calcfrete');
                if(obj != null)
                    obj.innerHTML = print;
            }
        }
        escondeAviso();
    }
    
    inCall = false;
    
 }
 
 function validateCep(fc1, fc2)
 {
    var obj;
    
    obj = getObj(fc1);
    if(obj == null)
        return false;

    
    if(obj.value.length < 5)
        return false;
    
    obj = getObj(fc2);
    if(obj == null)
        return false;
    
    if(obj.value.length < 3)
        return false;
    
    return true;
 }
 
 /**
  * funcao para retornar os radios de opcao para frete
  * @name = nome do radio
  * @id = id do radio
  * @text = texto da label ja formatado ex.:
  *   Frete: <strong> $R 10,00</strong> 
  * @value = valor numerico do frete
  **/
 function getFormatedOption(name, id, text,value)
 {
    var valueret = '';
    
    // LABEL
    valueret += "<label>";
    
    // RADIO
    valueret += "&nbsp;&nbsp; <input onclick=\"calculateValueFrete('" + id + "')\" type=\"radio\" name=\"";
    valueret += name;
    valueret += "\" id=\"" + id + "\"";
    valueret += " value=\"";
    valueret += value;
    valueret += "\" style=\"border: 0px; width:21px;\"/>"
    valueret += "&nbsp;";
    valueret += text;
    // FECHA A LABEL
    valueret += "</label>";
    
    return valueret;
 }
 
 /*
 *  FINAL DA ROTINA DE CALCULO DE FRETE
 * */


 /*
 *  INICO DA ROTINA DE VALIDACAO DE FRETE PARA COMPRA
 * */
 
 function getCompra()
 {
    var objform = getObj('fcompras');
    var value;
    if(objform != null)
    {
        value = getFreteValue(objform);
        if(value != '')
        {
            window.location.href='LoginServlet?act=ent&idf=' + value;
            return;
        }
    }
    
    alert('Você deve escolher a opção de frete para continuar!\n' +
        'Digite seu CEP e clique em calcular!');
 }
 
 function getFreteValue(objform)
{
    if(objform != null)
    {
        fretevalue = '';
        
        var num = objform.elements.length;
        for (var i=0; i< num; i++) {
           if (objform.elements[i] != null){
                
                if(objform.elements[i].type == 'radio')
                {
                    if(objform.elements[i].checked == true ||
                        objform.elements[i].checked == 'true')
                    {
                        fretevalue = objform.elements[i].id;
                        break;
                    }
                }
            }
        }
        
        return fretevalue;
    }
}
 
 /*
 *  FINAL DA ROTINA DE VALIDACAO DE FRETE PARA COMPRA
 * */
 
 // MASCARA DATA        
 function formatDate(date)
{
    var mycpfo;
    var obj = getObj(date);
    
    if(obj != null)
    {
        mycpf = obj.value;
        if (mycpf != null && mycpf.length == 2) {
            mycpf = mycpf + '/';
            obj.value = mycpf;
        }
        if (mycpf != null && mycpf.length == 5) {
            mycpf = mycpf + '/';
            obj.value = mycpf;
        }
    }
}

 /*
 *  POP UP IMAGEM
 * */
 
 function setView(cod, title)
 {
    var obj = getObj('foto');
    var img = "<img src=\"ImagemServlet?act=gim&imgsize=c&cod="+ cod +"\" " +
                    "alt=\""+ title +"\" title=\""+title+"\" />"
    
    if(obj != null)
        obj.innerHTML = img;
 }
 
 /*
 *  POP UP IMAGEM
 * */
 
 
 /*
 *  CADASTRO OPORTUNIDADE
 * */
 
 function submitOpportunitie()
 {
    var obj;
    
    obj = getObj('nome');
    if(obj == null || obj.value == '')
    {
        alert('O campo Nome deve ser preenchido!');
        if(obj != null)
            obj.focus();
        return;
    }
     
    obj = getObj('sobrenome');
    if(obj == null || obj.value == '')
    {
        alert('O campo Sobrenome deve ser preenchido!');
        if(obj != null)
            obj.focus();
        return;
    }
    
    obj = getObj('cpf');
    if(obj == null || obj.value == '')
    {
        alert('O campo CPF deve ser preenchido!');
        if(obj != null)
            obj.focus();
        return;
    }
    else if(obj != null)
    {
       if(!validateFieldCPF('cpf'))
       {
           alert('Você deve preencher o campo CPF com um CPF válido para continuar!');
           obj.value = '';
           obj.focus();
            return;
       }
    }
    
    obj = getObj('email');
    if(obj == null || obj.value == '')
    {
        alert('O campo Email deve ser preenchido!');
        if(obj != null)
            obj.focus();
        return;
    }
    else if(obj != null)
    {
        if(!validateFieldEmail('email'))
       {
           alert('Você deve preencher o campo email com um email válido para continuar!');
           obj.value = '';
           obj.focus();
            return;
       }
    }
    
    obj = getObj('txinicep')
        if(obj == null || obj.value == ''){
            alert('O campo CEP deve ser preenchido');
            obj.focus();
            return;
        }
        
        obj = getObj('txfimcep')
        if(obj == null || obj.value == ''){
            alert('O campo CEP deve ser preenchido');
            obj.focus();
            return;
        }
        
        obj = getObj('logradouro')
        if(obj == null || obj.value == ''){
            alert('O campo Rua deve ser preenchido');
            obj.focus();
            return;
        }
        
        obj = getObj('numero')
        if(obj == null || obj.value == ''){
            alert('O campo Número deve ser preenchido');
            obj.focus();
            return;
        }
        
        obj = getObj('cidade')
        if(obj == null || obj.value == ''){
            alert('O campo Cidade deve ser preenchido');
            obj.focus();
            return;
        }
        
        obj = getObj('dtnasc')
        if(obj == null || obj.value == ''){
            alert('O campo Data de nasc. deve ser preenchido');
            obj.focus();
            return;
        }
        
        obj = getObj('dddfone_residencial')
        if(obj == null || obj.value == ''){
            alert('O campo ddd para Telefone Residencial deve ser preenchido');
            obj.focus();
            return;
        }
        
        obj = getObj('fone_residencial')
        if(obj == null || obj.value == ''){
            alert('O campo Telefone Residencial deve ser preenchido');
            obj.focus();
            return;
        }
        
        obj = getObj('fcadastro');
        if(obj != null)
            obj.submit();
        else
            alert('Não foi possivel salvar o cadastro, tente novamente!');

 }
 
 /*
 *  FINAL CADASTRO OPORTUNIDADE
 * */
 
 
/*
 *  gif ajax
 * */ 

function escondeAviso() {
       if (document.getElementById) { // DOM3 = IE5, NS6
           document.getElementById('avisomsg').style.visibility = 'hidden';
       } else {
           if (document.layers) { // Netscape 4
               document.avisomsg.visibility = 'hidden';
           } else { // IE 4
               document.all.avisomsg.style.visibility = 'hidden';
           }
       }
   }
function mostraAviso() {
   if (document.getElementById) { // DOM3 = IE5, NS6
       document.getElementById('avisomsg').style.visibility = 'visible';
   } else {
       if (document.layers) { // Netscape 4
           document.avisomsg.visibility = 'visible';
       } else { // IE 4
           document.all.avisomsg.style.visibility = 'visible';
       }
   }
} 

 
 /*
 *  fim gif ajax
 * */ 
 
 /*
  * CONSULTE / AVISE
  * */
 
 function sendContact()
 {
    var obj;
    obj = getObj('nome');
    if(obj == null || obj.value == '')
    {
        alert('Preencha o campo nome para continuar.');
        obj.focus();
        return;
    }
    
    obj = getObj('email');
    if(obj == null || obj.value == '')
    {
        alert('Preencha o campo email para continuar.');
        obj.focus();
        return;
    }
    
    if(!validateFieldEmail('email'))
    {
        alert('Preencha o campo email com um email válido para continuar.');
        obj.focus();
        return;
    }
    
    obj = getObj('frmcont')
    if(obj != null)
        obj.submit();
 }
  
/*
 * CONSULTE / AVISE
 * */
   

/*
 * VALIDA EMAIL CADASTRO
 * */
   
 var message;
 function verifyMail(idfield, idmesssage)
 {
     var obj = getObj(idfield);
     message = getObj(idmesssage);
     
     if(obj != null)
     {
        // VERIFICA O FORMATO DO EMAIL
        if(!validateFieldEmail(idfield))
        {
           var retorno = '<span class="invalidate">';
           retorno += 'Email inválido!';
           retorno += '</span>';
           
           message.innerHTML = retorno;
           return;
        }
        // VERIFICA SE JA ESTA CADASTRADO 
        doCall("LoginServlet?act=ve&email=" + obj.value ,"validateNewEmailCadastro", true);
         
     }
 }

 
 function validateNewEmailCadastro()
 {
     var response = null;
    
    if (http.readyState == 4) {
        response = http.responseText;
        message.innerHTML = response;
    }
    inCall = false;
     
 }
/*
 * VALIDA EMAIL CADASTRO
 * */
   
/*
 * CONSULTE O FRETE
 * */
/*
function agendar(idproduto) {
        var nome = document.getElementById("f_nome").value;
        var email = document.getElementById("f_email").value;
        var fone = document.getElementById("f_fone").value;
        var qtd = document.getElementById("f_qtd").value;
        
        //valida campos
        if(nome == null || nome == '')
        {
            alert('Preencha o campo nome para continuar');
            return;
        }
        
        if(email == null || email == '')
        {
            alert('Preencha o campo email para continuar');
            return;
        }
        
        if(fone == null || fone == '')
        {
            alert('Preencha o campo telefone para continuar');
            return;
        }
        
        if(qtd == null || qtd == '')
        {
            alert('Preencha o campo Quantidade para continuar');
            return;
        }
        
        document.getElementById('msgretorno').innerHTML = 'Enviando pedido...'; 
        
        doCall("ProductDetailServlet?act=av&idp="+ idproduto +
            "&nome="+nome+"&email="+email+"&fone="+fone+
            "&qtd="+qtd,"retornoAgendar", true);
}

function retornoAgendar() {
        if(http.readyState == 4) {
                eval(http.responseText);
                document.getElementById('msgretorno').innerHTML = 
                    'Pedido enviado com sucesso!<a href="javascript:hide()">[fechar]</a>'; 
        }
}*/

function show() {
        if (document.getElementById) { // DOM3 = IE5, NS6 
                document.getElementById('formaviseme').style.display = 'block'; 
        } else { 
              if (document.layers) { // Netscape 4 
                      document.formaviseme.display = 'block'; 
              } else { // IE 4 
                      document.all.formaviseme.style.display = 'block'; 
              } 
        } 
        document.getElementById("f_nome").focus();
}

function hide() {
        if (document.getElementById) { // DOM3 = IE5, NS6 
                document.getElementById('formaviseme').style.display = 'none'; 
        } else { 
                if (document.layers) { // Netscape 4 
                        document.formaviseme.display = 'none'; 
                } else { // IE 4 
                        document.all.formaviseme.style.display = 'none'; 
                } 
        } 
        document.getElementById('msgretorno').innerHTML = '';
        document.getElementById("f_nome").value = '';
        document.getElementById("f_email").value = '';
        document.getElementById("f_fone").value = '';
}

function aviseme() {
        show();
}



/*
 * CONSULTE O FRETE
 * */

/*
 * INICIO - CAPA
 * */
 
function pageLoad()
{
    //var banner = getObj('banner_capa');
    //settimeout( 'positiocionarTop(0, 400,'+ banner +', 20)', 2000);
    
    
    
    /*var banner = getObj('banner_capa');
    banner.style.display = 'block';*/
    //positiocionarTop(-378, 400,banner , 20);
    
    /*setTimeout('hideBanner()', 7000);*/
}

function hideBanner() {
        if (document.getElementById) { // DOM3 = IE5, NS6 
                document.getElementById('banner_capa').style.display = 'none'; 
        } else { 
                if (document.layers) { // Netscape 4 
                        document.banner_capa.display = 'none'; 
                } else { // IE 4 
                        document.all.banner_capa.style.display = 'none'; 
                } 
        }
}        

function positiocionarTop(inicio, fim, element, incremento)
{
    if(element != null)
    {
        inicio += incremento;

        if(inicio >= fim)
        {
            element.style.top = fim;
        }
        else
        {
            element.style.top = inicio;
            //settimeout( 'positiocionarTop('+inicio+','+ fim+','+ element +','+ incremento + ')',100);
            setTimeout(positiocionarTop(inicio,fim,element, incremento),100);
        }
    }
}

/*
 * FINAL - CAPA
 * */

function receberOferta()
{
    if (document.getElementById) { // DOM3 = IE5, NS6 
                document.getElementById('formaviseme').style.display = 'none'; 
        } else { 
                if (document.layers) { // Netscape 4 
                        document.formaviseme.display = 'none'; 
                } else { // IE 4 
                        document.all.formaviseme.style.display = 'none'; 
                } 
        } 
        
    var nome = getObj('f_nome').value;
    var mail = getObj('f_email').value;
    var fone = getObj('f_fone').value;

    getObj('msgretorno').innerHTML = 'Enviando pedido...'; 
        
    doCall("ConsultServlet?act=ro"+        
            "&nome="+nome+"&email="+mail+"&fone="+fone
            ,"receberOfertaSaved", true);
}

function receberOfertaSaved()
{
    if(http.readyState == 4) {
      eval(http.responseText);
      
      getObj('msgretorno').innerHTML = 
          'Pedido enviado com sucesso!<a href="javascript:hide()">[fechar]</a>'; 
      show();
      setTimeout('hide()',7000);
      inCall = false;
    }
}

function getGenericBanner(URL, width, height, align, valign, top, left)
{
    
    var window_width = width;
    var window_height = height;
    
    if(align == null || (align != 'center' && align != 'left' && align != 'right'))
        align = 'center';
    
    if(valign == null || (valign != 'top' && valign != 'middle' && valign != 'bottom'))
        valign = 'middle';
    
    var window_top = (screen.height-window_height)/2;
    var window_left = (screen.width-window_width)/2;
    
    if(align == 'left')
        window_left = 5;
    
    if(align == 'right')
        window_left = (screen.width-window_width) - 5;
    
    if(valign == 'top')
        window_top = 5;
    
    if(valign == 'bottom')
        window_top = (screen.height-window_height) - 5;
    
    if(isNumber(top))
        window_top = top;
    
    if(isNumber(left))
        window_left = left;
    
    
    var features = 'width='+ String(window_width) +',height='+ String(window_height);
    features  += ',location=no,scrollbars=no,menubar=no,toolbar=no,status=no';
    features  += ',directories=no,history=no,top=' + window_top + ',left=' + window_left;
    
    var j = window.open(URL,'janela1',features); 
    j.focus();  
}

function isNumber(pStr){
    var reDigits = /^d+$/; 
    if (reDigits.test(pStr)) { 
        return true; 
    } else if (pStr != null && pStr != "") {               
        return false; 
    }
}

function imprimir()
{
    document.compras.submit();
}
          