var cc_functions = Class.create({
    initialize: function(){
        this.email;
        this.textClass = ['text_interna12', 'text_interna', 'text_interna16'];
        this.textPointer = 1;
    },
    
    emailCheck: function(email){
        this.email = email;
        
        var regexmail = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i;
        
        return regexmail.test(this.email);
    },
    
    trim: function(string){
        return string.replace(/^\s+|\s+$/g, '');
    },
    
    cadastra_informativo: function(){
        var pass = true;
        var email = $F('email_news');
        var nome = $F('nome_news');
        
        if(this.trim(email).length <= 9 || this.emailCheck(email) != true){
            $('email_news').shake();
            pass = false;
        }
        
        if(this.trim(nome).length <= 2){
            $('nome_news').shake();
            pass = false;
        }
            
        if(pass != false && pass == true){
            var params = $H({'email': email, 'nome': nome}).toQueryString();
            new Ajax.Request ('backend.php?action=addBol', {
                                  method: 'get',
                                parameters: params,
                                onComplete: function(sender){
                                    var res = sender.responseText;
                                    
                                    if(res == '1')
                                        $('cc_form_newsletter').update('<span style="color:#fff;"><br /><strong>O seu cadastro foi efetuado com sucesso !</strong><br /></span> ');
                                                                                                
                                    else if(res == '0')
                                        alert('<span style="color:#fff;">Não foi possivel cadastrar seus dados, por favor tente novamente.</span>');
                                                                                                
                                    else if(res == '2')
                                        alert('<span style="color:#fff;">Este e-mail já se encontra cadastrado na nossa base de dados</span>');
                                        
                                    else
                                        $('cc_form_newsletter').update('Erro interno do servidor.');
                                }
                              });
        }
    },
    
    verif_code: function(){
        var code = $F('codigo');
        
        if(this.trim(code).length == 10){
            if(code.match(/^\w{10}$/)){
                new Ajax.Request('backend.php?action=verifCode', {
                                     method: 'get',
                                    parameters: {'code': code},
                                    onComplete: function(sender){
                                        var resposta = sender.responseText.split('-');

                                        switch(resposta[0]){
                                            case '0':
                                                alert('O código fornecido é inválido!');
                                                break;
                            
                                            case '1':
                                                window.location.href='cadastra.php?key=' + resposta[1];
                                                break;
                            
                                            case '2':
                                                alert('Este código pertence a outro usuário já em uso.');
                                                break;
                        
                                            default:
                                                alert("Erro interno do servidor. \n" + resposta[0]);
                                                break;
                                        }
                                    }
                                 });    
            }
            else
                alert('O código fornecido é inválido!');
        }
        else
            alert('O código fornecido é inválido!');
    },
    
    cadastro_site: function(){
        var nome = $('nome').value;
        var email = $('email').value;
        var dNasc = $('dNasc').value;
        var mNasc = $('mNasc').value;
        var aNasc = $('aNasc').value;
        var termos = $('termos').checked;
        var boletim = $('boletim');
        var apelido = $('apelido').value;
        var profissao = $('profissao').value;
        var numero = $('numero').value;                    
        var rua = $('rua').value;                    
        var bairro = $('bairro').value;                                        
        var complemento = $('complemento').value;                    
        var cidade = $('cidade').value;                                        
        var estado = $('estado').value;                                        
        var cep = $('cep').value;
        
        if(this.trim(nome).length <= 5){
            alert('O campo nome está preenchido incorretamente.');
            
            Field.focus('nome');
            Field.select('nome');
                        
            return false;
        }
        if(this.trim(email).length <= 9 || this.emailCheck(email) != true){
            alert('O campo e-mail está preenchido incorretamente.');
            
            Field.focus('email');
            Field.select('email');
                        
            return false;
        }
        if(this.trim(dNasc).length != 2 || this.trim(mNasc).length != 2 || this.trim(aNasc).length != 4){
            alert('A data de nascimento está preenchida incorretamente.');
            
            Field.focus('dNasc');
            Field.select('dNasc');
                        
            return false;
        }
        
        if(profissao == false){
            alert('O campo profissão está vazio, favor preencher.');
            return false;
        }                    
        
        if(numero == false){
            alert('O campo número está vazio, favor preencher.');
            return false;
        }                    
        
        if(bairro == false){
            alert('O campo bairro está vazio, favor preencher.');
            return false;
        }                        
        
        if(cidade == false){
            alert('O campo cidade está vazio, favor preencher.');
            return false;
        }                    
        
        if(estado == false){
            alert('O campo estado está vazio, favor preencher.');
            return false;
        }
        
        if(cep == false){
            alert('O campo cep está vazio, favor preencher.');
            return false;
        }
        
        if(termos == false){
            alert('Você prescisar ler e concôrdar com o termo do serviço para ativa-lo.');
            return false;
        }
        
        if(boletim == 'true'){
            if(this.trim(apelido).length != 0)
                var name = apelido;
            else
                var name = nome;
            
            new Ajax.Request('backend.php?action=addBol', {method: 'get', parameters: {'email': email, 'nome': name}});
        }
        return true;
    },
    
    favorites: function(){
        var title = 'CC2002 | Código Civil  e sua Interpretção Jurisprudencial';
        var url = 'http://www.cc2002.com.br/';
        
        if(window.sidebar)
            window.sidebar.addPanel(title, url, '');
        
        if(window.external)
            window.external.AddFavorite(url, title);
    },
    
    fonte: function(valor){
        var itens =  $$('form#form input[type="button"]');
        
        itens.each(function(elem){
                                $(elem).setStyle({fontWeight:100});
                            });
        if(valor != 'SC')                    
            $(valor).setStyle({fontWeight:'bold'});
        
    },
    
    Dados: function(estado){
        //new Ajax.Updater({success: 'aparece'}, 'estados.php', {parameters: {'estado':estado, 'numero':$('numero').value}});
        
        new Ajax.Request('estados.php', {
            parameters: {'estado':estado, 'numero':$('numero').value},
            onLoading: function(sender){
                $('aparece').update('<p id="aguarde">Aguarde, carregando documentos....</p><p><img src="_src/imgs/carregando.gif" id="carregando" alt="imagem carregando dados" /></p>');
            },
            onComplete: function(sender){
                $('aparece').update(sender.responseText);
            }
        });
        
        this.fonte(estado);
    },
    
    apresentacao: function(){
        var wheight = (typeof window.innerHeight == 'undefined' ? document.body.offsetHeight : window.document.documentElement.offsetHeight == '0' ? document.documentElement.clientHeight + window.pageYOffset : window.document.documentElement.offsetHeight);
        var wwidth = (typeof window.innerWidth == 'undefined' ? document.body.offsetWidth : window.document.documentElement.offsetWidth == '0' ? document.documentElement.clientWidth + window.pageXOffset : window.document.documentElement.offsetWidth);

        $('overflowBook').setStyle({'marginLeft': parseInt(parseInt(wwidth - 800) / 2) + 'px'});
        $('overflow').setStyle({'height':wheight + 'px'}).blindDown({duration:0.35}).appear({duration:0.35});
    },
    
    fechaLivro: function(){
        $('overflow').blindUp({duration:0.35}).fade({duration:0.4});    
    },
    
    mudaFonte: function(param){
        var sum = eval(this.textPointer + param);
        
        if(sum < 0 || sum > 2)
            return false;
            
        $$('div.' + this.textClass[this.textPointer]).each(function(elem){
            $(elem).removeClassName(cc_pages.textClass[cc_pages.textPointer]).addClassName(cc_pages.textClass[sum]);
        });
        
        this.textPointer = sum;
    },
    
    comentario: function(pagina){
        if(this.trim($('nome_coments').value).length < 3 ){
            alert('Preencha seu nome');
            $('nome_coments').shake();
                
            return false;
        }
        
        if(this.trim($('mail_comments').value).length < 9 ||  this.emailCheck($('mail_comments').value) != true){
            alert("Preencha seu e-mail.  Ele não será divulgado");
            $('mail_comments').shake();
                
            return false;
        }
        
        new Ajax.Request('backend.php?action=comentario', {
            method: 'post',
            parameters:{'nome': $('nome_coments').value, 'email':$('mail_comments').value, 'comentario':$('msg_comments').value, 'id':$('id_comments').value, 'pagina': pagina},
            onComplete: function(sender){
                if(pagina == 'jurisprudencia')
                    window.location.href = 'jurisprudencia.php?id=' + $('id_comments').value;
                else
                    window.location.href = 'destaque.php?id=' + $('id_comments').value;
            }
        });     
    },
    
    popup : function(File, Name, Width, Height)  {
        var day    =    new Date();
        var id    =    day.getTime();
        eval("page" + id + " = window.open('" + File + "', '" + Name + "', 'toolbar=0,location=0,statusbar=1,menubar=0,resizable=1,width=" + Width + ",height=" + Height + ",left = 327,top = 287');");
    },
    
    indica: function(){
        var nome = $('txtSeuNome').value;
        var email = $('txtSeuEmail').value;
        var amigo = $('txtNomeAmigo').value;
        var aemail = $('txtEmailAmigo').value;
        var msg = $('msg').value;
        
        if(this.trim(amigo).length < 3){
            alert('Preencha o nome do seu amigo.');
            return false;
        }
        
        if(this.trim(aemail).length < 9 ||  this.emailCheck(aemail) != true){
            alert('Preencha o e-mail do seu amigo.');
            return false;
        }
        
        new Ajax.Request('backend.php?action=indica', {
            parameters:{'nome': nome, 'email':email, 'msg':msg, 'amigo':amigo, 'aemail':aemail, 'pagina': window.location.href},
            onComplete: function(sender){
                alert('Página enviada com sucesso.');
                
                if($('enviarAmigo'))
                    $('enviarAmigo').hide();
                
                $('txtSeuNome').value = '';
                $('txtSeuEmail').value = '';
                $('txtNomeAmigo').value = '';
                $('txtEmailAmigo').value = '';
                $('msg').value = '';
            }    
        });
    }
});