function comboboxBusca () {
	$('#combobox-opcoes').slideToggle('slow');
}

function selOpcaoCombobox (op) {	
	valor = $(this).text();	
	$('#txt-pauta').attr('value',valor);
	$('#combobox-pauta-value').text(valor);
}

$(function(){
	
	
	// marcara de campos
	$('#cad-nascimento, #cad-casamento-data').mask("99/99/9999");
	$('#cad-telefone, #cad-celular').mask("(99) 9999 - 9999");
	$('#cad-cep').mask("99999 - 999");
	
	if($('.marcas ul').size() > 1) {
		$('.marcas ul:first').addClass('ativo').fadeIn(1300);
		setInterval(mudarElemento, 4000);
	} else {
		$('.marcas ul:first').addClass('ativo').fadeIn(1300);
	}
	
	////////////////////////////////////////////////////////////////////////////////////////
    // Limpa os campos
    // Campos lista casamento
    $('#pes-texto,#new-email,#new-nome,#log-email,#log-senha,#pes-noivo,#pes-noiva,#pes-data,#txt-pesquisar').focus(function(event){
        valorAntigo = $(this).attr('value');
        
        if (valorAntigo == "o que deseja pesquisar?" || valorAntigo == "insira seu email" || valorAntigo == "insira seu nome" || valorAntigo == "digite o nome do produto" || valorAntigo == "e-mail" || valorAntigo == 'senha' || valorAntigo == 'nome da noiva' || valorAntigo == 'nome do noivo') {
            $(this).attr('value', '');
        }
        else 
            if (valorAntigo == 'data do casamento') {
                $(this).attr('value', '');
                $(this).mask("99/99/9999");
            }
        
    }).blur(function(event){
        if ($(this).attr('value') == '') {
            $(this).attr('value', valorAntigo);
        }
        
    });
	
	
	contCarregando = 0;
	
    // Limpa os campos
	$('#txt-busca,').focus(function(event){
	valorAntigo = $(this).attr('value');

		if (valorAntigo == 'Busca por produtos' ) {
			$(this).attr('value', '');
		}

	}).blur(function(event){
	if ($(this).attr('value') == '') {
	$(this).attr('value', valorAntigo);
	}
	});
	
	
	// Click do combobox da busca (Mostra o combobox)
    $('#combobox-pauta').click(comboboxBusca);
    
	
    // Click na opção do combobox da busca (Seleciona o valor)
    $('#combobox-opcoes li').click(selOpcaoCombobox);
	
    
	// Efeito de hover do combobox da busca
    $('#combobox-opcoes li').mouseover(function(){
        $(this).css('border', '#FFFFFF solid 1px');
    }).mouseout(function(){
        $(this).css('border', 'none');
    })
  
	///////////////////////////////////////////////////////////////////////////////
    // Combobox cad-estado
    $('#campo-cad-estado').click(function(e){
        var elemento = $(this);
        var posicao = elemento.position();
        
        // Mostra as opcoes
        $('#opcoes-estado').css({
            'top': parseInt(posicao.top + 26),
            'left': parseInt(posicao.left)
        }).slideDown();
        
        // Clique na opcao
        $('#opcoes-estado li').click(function(e){
            var valor = $(this).children('.sigla').text();
            
            // Atribui os valoe selecionado
            $('#campo-cad-estado .valor').text(valor);
            $('#cad-estado').attr('value', $(this).children('.id').text());
            
            // Escondo as opcoes
            $('#opcoes-estado').slideUp();
            
            $('#campo-cad-cidade .valor').text('Carregando ...');
            
            
            var id = parseInt($(this).children('.id').text());
            
            // Lista a lista de cidades do estado selecionado
            $.ajax({
                header: {
                    "Content-Type": "text/html;  charset=ISO-8859-1"
                },
                type: "post",
                data: "acao=cidade&id=" + id,
                url: "http://www.sabongi.com.br/ajax.php",
                dataType: "html",
                success: function(valor){
                    $('#campo-cad-cidade .valor').text('Selecione a sua cidade');
                    $('#campo-cad-cidade ul').html(valor);
                    
                    e.preventDefault(e);
                    return false;
                    
                }
                
            });
            
            e.preventDefault(e);
            return false;
        });
        
        // Efeito de over da opcao
        $('#opcoes-estado li').mouseover(function(){
            $(this).css('background-color', '#868279');
            
        }).mouseout(function(){
            $(this).css('background-color', '#64615A');
        });
        
        
        e.preventDefault(e);
        return false;
        
    });
    
    ///////////////////////////////////////////////////////////////////////////////
    // Combobox cad-cidade
    $('#campo-cad-cidade').click(function(e){
        var elemento = $(this);
        var posicao = elemento.position();
        
        // Mostra as opcoes
        $('#opcoes-cidade').css({
            'top': parseInt(posicao.top + 26),
            'left': parseInt(posicao.left)
        }).slideDown();
        
        // Clique na opcao
        $('#opcoes-cidade li').click(function(e){
            var valor = $(this).children('.sigla').text();
            
            // Atribui os valoe selecionado
            $('#campo-cad-cidade .valor').text(valor);
            $('#cad-cidade').attr('value', $(this).children('.id').text());
            
            // Escondo as opcoes
            $('#opcoes-cidade').slideUp();
            
            e.preventDefault(e);
            return false;
        });
        
        // Efeito de over da opcao
        $('#opcoes-cidade li').mouseover(function(){
            $(this).css('background-color', '#868279');
            
        }).mouseout(function(){
            $(this).css('background-color', '#64615A');
        });
        
        
    });
    

    
    
    ////////////////////////////////////////////////////////////////////////////
    // Mascaras do campos    
    $("#con-telefone").mask("(99)9999-9999");
	
	
	///////////////////////////////////////////////////////////////////////////////
    // Formulario de contato
    $('#bt-enviar-contato').click(function(e){
		
        var error = false;
        
        $('.error-form').remove();
	
		// Nome
        if ($('#con-nome').val() == "") {
            mostraError($('#con-nome'));
            error = true;
        }
		
        // Valida Email
        if ($('#con-email').val() == "") {
			error = true;
			mostraError($('#con-email'));
        }
        else {
            if (validaEmail($('#con-email').val()) == false) {
				error = true;
            	mostraError($('#con-email'));
        	}
		}
        
        // Telefone
        if ($('#con-telefone').val() == "") {
            mostraError($('#con-telefone'));
            error = true;
        }
        
        // Assunto
        if ($('#con-assunto').val() == "") {
            mostraError($('#con-assunto'));
            error = true;
        }
        
        
        // Mensagem
        if ($('#con-mensagem').val() == "") {
            mostraError($('#con-mensagem'));
            error = true;
        }
        
        
        
        // Se não houver erros
        if (error == false) {
        
        
            var dados = $('#box-contato form').serialize();
            
            $.ajax({
                header: {
                    "Content-Type": "text/html;  charset=ISO-8859-1"
                },
                type: "post",
                data: "acao=contato&" + dados,
                url: "http://www.sabongi.com.br/ajax.php",
                dataType: "json",
                success: function(valor){
                
                
                    $('.mostrar').live('click', function(event){
                    
                        $('#box-contato fieldset').show();
                        $('#cadastro-ok').hide();
                        
                        event.preventDefault();
                        return false;
                    })
                    
                    if (valor.error == true) {
                        $('#box-contato fieldset').hide();
                        $('#cadastro-ok').show();
                        
                        $('#con-nome').val('');
                        $('#con-telefone').val('');
                        $('#con-assunto').val('');
                        $('#con-email').val('');
                        $('#con-mensagem').val('');
                        
                    }
                    else {
                        if (valor.msg == '') {
                            alert('Ocorreu algum erro inesperado, Por favor tente de novo ou entre em contato');
                        }
                        else {
                            alert(valor.msg);
                        }
                    }
                }
            });
        }
        
        
        e.preventDefault(e);
        return false;
    });
	
	
	 ////////////////////////////////////////////////////////////////////////////////////////
    // Enviar o Formulario de contato 
    $('#bt-enviar-ouvidoria').click(function(event){
    
    
        error = false;
        // valida Nome
        if ($('#nome').val() == "" || $('#nome').val() == "Insira seu nome (Obrigatório)") {
            $('#nome').parents('.campo').children('.avisso').text('Preencha o campo Nome');
            error = true;
        }
        else {
            $('#nome').parents('.campo').children('.avisso').text('');
        }
        
        // valida Nome
        if ($('#assunto').val() == "" || $('#assunto').val() == "Insira o assunto da mensagem (Obrigatório)") {
            $('#assunto').parents('.campo').children('.avisso').text('Preencha o campo Assunto');
            error = true;
        }
        else {
            $('#nome').parents('.campo').children('.avisso').text('');
        }
        
		  // valida Departamento
        if ($('#departamento').val() == "" || $('#departamento').val() == "Escolha um departamento") {
            $('#departamento').parents('.campo').children('.avisso').text('Selecione uma opção');
            error = true;
        }
        else {
            $('#departamento').parents('.campo').children('.avisso').text('');
        }
        
        
        
        
        // Valida Email
        if ($('#email').val() == "" || $('#email').val() == "Insira seu e-mail (Obrigatório, não será divulgado)") {
            $('#email').parents('.campo').children('.avisso').text('Preencha o campo E-mail');
            error = true;
        }
        else {
            $('#email').parents('.campo').children('.avisso').text('');
            
            if (validaEmail($('#email').val()) == false) {
                $('#email').parents('.campo').children('.avisso').text('Preencha o campo E-mail corretamente, e-mail inválido');
                error = true;
            }
        }
        
        
        // Valianuncierio		
        if ($('#comentario').val() == "" || $('#comentario').val() == "Deixe sua mensagem") {
            $('#comentario').parents('.campo').children('.avisso').text('Preencha o campo Mensagem');
            error = true;
        }
        else {
            $('#comentario').parents('.campo').children('.avisso').text('');
        }
        
        
        if (error == true) {
            return false;
        }
        else {
            dados = $('#form-comentario').serialize();
            
            $('#carregando').show();
            $('#form-comentario fieldset').hide();
            
            
            $.ajax({
                header: {
                    "Content-Type": "text/html;  charset=ISO-8859-1"
                },
                type: "get",
                data: "acao=mensagem&" + dados,
                url: "http://www.sabongi.com.br/ajax.php",
                dataType: "json",
                success: function(valor){
                    $('#carregando').html('<p class="titulo">Mensagem enviada com sucesso,Obrigado.<br /> <a href="#" class="mostra-form" title="Exibir formulário">Exibir formulário</a></p>');
                    
                    
                    if (valor.mensagem == "true") {
                        $('#nome').val('Insira seu nome (Obrigatório)');
                        $('#email').val('Insira seu e-mail (Obrigatório, não será divulgado)');
                        $('#assunto').val('Insira o assunto da mensagem (Obrigatório)');
                        $('#comentario').val('Deixe sua mesagem');
                    }
                    
                    $('.mostra-form').live('click', function(event){
                        $('#form-comentario fieldset').show();
                        $('#carregando').hide();
                        $('#carregando').html('<img src="http://www.sabongi.com.br/theme/img/carregando.gif" alt="carregando" />');
                        
                        
                        event.preventDefault(event);
                        return false;
                    });
                    
                    
                    event.preventDefault(event);
                    return false;
                }
            });
        }
        event.preventDefault(event);
        return false;
    });
	
	
	// Limpa os campos
    // Campos do formulario de contato
    $('.campo-input,#comentario,#txt-busca,#email-senha').focus(function(event){
        valorAntigo = $(this).attr('value');
        
        if (valorAntigo == "Insira seu e-mail" || valorAntigo == "Digite o que deseja pesquisar" || valorAntigo == 'Deixe sua mensagem' || valorAntigo == "Insira seu nome (Obrigatório)" || valorAntigo == "Insira seu e-mail (Obrigatório, não será divulgado)" || valorAntigo == "Insira seu telefone (Obrigatório, não será divulgado)" || valorAntigo == "Deixe seu comentário" || valorAntigo == 'Insira o assunto da mensagem (Obrigatório)') {
            $(this).attr('value', '');
        }
        
    }).blur(function(event){
        if ($(this).attr('value') == '') {
            $(this).attr('value', valorAntigo);
        }
        
    });
	
	
	////////////////////////////////////////////////////////////////////////////////
    // Botão Imprimir Popup
    $('.externo-imprimir').live('click', function(event){
    
        link = $(this).attr('href');
        abrir(link, 800, 800);
        
        event.preventDefault();
        return false;
    });
	
	
	
	//campo nome
	$("#new-nome").click(function(){
		valorAntigo = $(this).attr('value');
		if (valorAntigo == 'Preencha com seu nome'){		
        $('#new-nome').val("");
		}
    });    
    $("#new-nome").blur(function(){
        if ($('#new-nome').val() == '') {
            $('#new-nome').val('Preencha com seu nome');
        };
    });
	
	//campo email
	$("#new-email").click(function(){
		valorAntigo = $(this).attr('value');
		if (valorAntigo == 'Preencha com seu email'){		
        $('#new-email').val("");
		}
    });    
    $("#new-email").blur(function(){
        if ($('#new-email').val() == '') {
            $('#new-email').val('Preencha com seu email');
        };
    });
	
		
	////////////////////////////////////////////////////////////////////////////////////////
    // Formulario Newsletter
    $('#bt-enviar').click(function(event){
    
        email = $('#new-email').val();
        nome = $('#new-nome').val();
		
        
        error = false;
        
        $('.error').hide();
		$('#error-geral').hide();
        $('#sucess-geral').hide();
		
		if (nome == '' || nome == 'Preencha com seu nome') {
            $('#error-nome').html('Nome inválido').fadeIn();
            error = true;
        }
        
		
        if (email == '' || email == 'Preencha com seu email' || !validaEmail(email)) {
            $('#error-email').html('E-mail inválido').fadeIn();
            error = true;
        }
        
        
        if (error == false) {
        
           // $('#formulario-newsletter fieldset').append('<div id="carregandoNew"><img src="http://www.cocipa.com.br/theme/img/carregando.gif" alt="Carregando" /></div>');
            
            
            $.ajax({
                type: 'post',
                url: 'http://www.sabongi.com.br/ajax.php',
                data: {
                    'acao': 'neswletter',
                    'nome': nome,
                    'email': email
                },
                dataType: 'json',
                success: function(valor){
                
                    // cadastro corretamente
                    if (valor.error == true) {
                        $('#new-email').val('Preencha com seu email');
                        $('#new-nome').val('Preencha com seu nome');
                        $('#sucess-geral').html(valor.msg).fadeIn();
                        // Mostra mensagem cadastro Ok
                        
                        $('#carregandoNew').fadeOut().remove();
                        
                    }
                    else {
                    
                        // Mostra Errors
                        $('#error-geral').html(valor.msg).fadeIn();
                        $('#carregandoNew').fadeOut().remove();
                    }
                }
            });
            
        }
        
        event.preventDefault(event);
        return false;
    });
	
	    
    //campo nome
	$("#new-nomee").click(function(){
		valorAntigo = $(this).attr('value');
		if (valorAntigo == 'Preencha com seu nome'){		
        $('#new-nomee').val("");
		}
    });    
    $("#new-nomee").blur(function(){
        if ($('#new-nomee').val() == '') {
            $('#new-nomee').val('Preencha com seu nome');
        };
    });
	
	//campo email
	$("#new-emaill").click(function(){
		valorAntigo = $(this).attr('value');
		if (valorAntigo == 'Preencha com seu email'){		
        $('#new-emaill').val("");
		}
    });    
    $("#new-emaill").blur(function(){
        if ($('#new-emaill').val() == '') {
            $('#new-emaill').val('Preencha com seu email');
        };
    });
    
	////////////////////////////////////////////////////////////////////////////////////////
    // Formulario Newsletter
    $('#bt-enviarr').click(function(event){
    
        email = $('#new-emaill').val();
        nome = $('#new-nomee').val();
		
        
        error = false;
        
        $('.error').hide();
		$('#error-geral').hide();
        $('#sucess-geral').hide();
		
		if (nome == '' || nome == 'Preencha com seu nome') {
            $('#error-nome').html('Nome inválido').fadeIn();
            error = true;
        }
        
		
        if (email == '' || email == 'Preencha com seu email' || !validaEmail(email)) {
            $('#error-email').html('E-mail inválido').fadeIn();
            error = true;
        }
        
        
        if (error == false) {
          
            
            $.ajax({
                type: 'post',
                url: 'http://www.sabongi.com.br/ajax.php',
                data: {
                    'acao': 'neswletter',
                    'nome': nome,
                    'email': email
                },
                dataType: 'json',
                success: function(valor){
                
                    // cadastro corretamente
                    if (valor.error == true) {
                        $('#new-emaill').val('Preencha com seu email');
                        $('#new-nomee').val('Preencha com seu nome');
                        $('#sucess-geral').html(valor.msg).fadeIn();
                        // Mostra mensagem cadastro Ok
                        
                        $('#carregandoNew').fadeOut().remove();
                        
                    }
                    else {
                    
                        // Mostra Errors
                        $('#error-geral').html(valor.msg).fadeIn();
                        $('#carregandoNew').fadeOut().remove();
                    }
                }
            });
            
        }
        
        event.preventDefault(event);
        return false;
    });
	
	
	
	
	
	
	
    //////////////////////////////////////////////////////
    // adapitacoes abas
    $('#bt-imprimir').click(function(event){
        window.print();
        return true;
    });
    
    
    $('.redirect').click(function(event){
        window.location = this.href;
        //event.preventDefault(event);
        return true;
    });
    


    ////////////////////////////////////////////////////////////////////////////
    // Diminui a letra
    $('.letra-menor').live('click', function(){
        tamanhoFonte = $('#descricao').css('font-size');
        tamanhoFonte = parseInt(tamanhoFonte);
        lineH = parseInt($('#descricao').css('line-height'));
        
        
        
        if (tamanhoFonte > 10) {
            $('#descricao').css('font-size', tamanhoFonte - 2 + 'px').css('line-height', lineH - 2 + 'px');
        }
        
    });
    
    ////////////////////////////////////////////////////////////////////////////
    // Aumenta a letra
    $('.letra-maior').live('click', function(){
        tamanhoFonte = $('#descricao').css('font-size');
        tamanhoFonte = parseInt(tamanhoFonte);
        lineH = parseInt($('#descricao').css('line-height'));
        
        if (tamanhoFonte < 20) {
            $('#descricao').css('font-size', tamanhoFonte + 2 + 'px').css('line-height', lineH + 2 + 'px');
            ;
            
        }
        
    });
    
    
    
    //////////////////////////////////////////////////////////////////////////////////////////
    // Color Box	
    $('a[rel="popup"]').colorbox({
        slideshow: true
    });
	
	//////////////////////////////////////////////////////////////////////////////////////////
    // Color Box	
    $('a[rel="popup1"]').colorbox({
       rel: 'nofollow'
    });

    
    ///////////////////////////////////////////////////////////////////////////
    // Links Externos 
    $('.externo').attr('target', '_blanck');
    
    
    
    /////////////////////////////////////////////////////////////////////////
    // Mostra Formulario 
    $('.mostrar').live('click', function(event){
    
        $('#box-contato fieldset').show();
        $('#cadastro-ok').hide();
        
        event.preventDefault();
        return false;
    })
    
      
    /////////////////////////////////////////////////////////////////////////
    // Mascara Campo telefone
    $("#con-telefone").mask("(99)9999-9999");
    

	////////////////////////////////////////////////////////////////////////////////////////
    // Formulario Indique a um amigo
    $('#bt-enviar-indique').click(function(event){
    
        nomeSeu = $('#ind-seu-nome').val();
        emailSeu = $('#ind-seu-email').val();
        nomeAmigo = $('#ind-amigo-nome').val();
        emailAmigo = $('#ind-amigo-email').val();
        
        error = false;
        
        $('.error').hide();
        
        if (nomeSeu == '' || nomeSeu == 'Digite aqui seu nome') {
        
            $('#seu-nome').html('Nome inválido').fadeIn();
            error = true;
        }
        
        if (emailSeu == '' || emailSeu == 'Digite aqui seu e-mail' || !validaEmail(emailSeu)) {
            $('#seu-email').html('E-mail inválido').fadeIn();
            error = true;
            
        }
        
        if (nomeAmigo == '' || nomeAmigo == 'Digite aqui o nome do seu amigo') {
            $('#amigo-nome').html('Nome do seu amigo inválido').fadeIn();
            error = true;
        }
        
        if (emailAmigo == '' || emailAmigo == 'Digite aqui o e-mail do seu amigo' || !validaEmail(emailAmigo)) {
        
            $('#amigo-email').html('E-mail do seu amigo inválido').fadeIn();
            error = true;
        }
        
        
        
        
        
        if (error == false) {
            $('#formulario-contato fieldset').append('<div class="center" id="carregandoNew"><img src="/theme/img/carregando.gif" alt="Carregando" /></div>');
            
            
            $.ajax({
                type: 'post',
                url: 'http://www.sabongi.com.br/ajax.php',
                data: {
                    'acao': 'indique',
                    'nomeSeu': nomeSeu,
                    'emailSeu': emailSeu,
                    'nomeAmigo': nomeAmigo,
                    'emailAmigo': emailAmigo
                },
                dataType: 'json',
                success: function(valor){
                
                
                    // cadastro corretamente
                    if (valor.error == true) {
                    
                        alert(valor.msg);
                        $('#bt-fechar').click();
                        $('#carregandoNew').fadeOut().remove();
                        
                    }
                    else {
                        // Mostra Errors
                        $('#error-geral-indique').html(valor.msg).fadeIn();
                        $('#carregandoNew').fadeOut().remove();
                    }
                }
            });
            
        }
        
        
        event.preventDefault(event);
        return false;
    });
	
	//////////////////////////////////////////////////////////////////////////////////////
    // Botão Indique a um amigo
    $('#bt-indique').click(function(event){
    
        WidthO = $('body').outerWidth();
        Width = (WidthO / 2) - 400;
        
        Height = parseInt($('body').height());
        
        
        Ph = getPageScroll();
        
        $('body').append('<div id="overlay"></div>');
        
        $('#overlay').css({
            'position': 'absolute',
            'width': WidthO,
            'height': Height,
            'top': 0,
            'left': 0,
            'z-index': 555,
            'background-color': '#000000',
            'opacity': 0.75
        });
        
        $('.error').hide();
        
        $('#form-indique').css({
            'position': 'absolute',
            'z-index': 666,
            'left': Width,
            'top': Ph[0] -50
        }).show();
        
        event.preventDefault(event);
        return false;
    });
    
    
    //////////////////////////////////////////////////////////////////////////////////////
    // Botão fechar
    $('#bt-fechar').click(function(event){
    
        $('#overlay').remove();
        $('#form-indique').hide();
        
        event.preventDefault(event);
        return false;
    });
	
	////////////////////////////////////////////////////////////////////////////////////////
    // Limpa os campos
    $('#ind-seu-nome,#ind-seu-email,#ind-amigo-nome,#ind-amigo-email').focus(function(event){
        valorAntigo = $(this).attr('value');
        
        if (valorAntigo == 'Digite aqui o e-mail do seu amigo' || valorAntigo == 'Digite aqui o nome do seu amigo' || valorAntigo == 'Digite aqui seu e-mail' || valorAntigo == 'Digite aqui seu nome') {
            $(this).attr('value', '');
        }
        
    }).blur(function(event){
        if ($(this).attr('value') == '') {
            $(this).attr('value', valorAntigo);
        }
        
    });

    // Botão Fechar
    $('#fechar').live('click', function(event){
    
        $('#indique-amigo').hide();
        event.preventDefault(event);
        return false;
    });

    
	
	 ////////////////////////////////////////////////////////////////////////////////////////
    // Banner Index
    if ($('#img-destaque .item').size() > 1) {
    
        var index = 0;
        var cont = 0;
        var total = $('#img-destaque .item').size();
        var totalLink = total - 1;
        
        
        // Acresento os botoes de navegacao
        $('#img-destaque .item').each(function(){
            cont++;
            elemento = $(this);
            
            // Atribui o id do elemento
            elemento.attr('id', 'ban-' + cont);
            
            
            $('#bt-banner').append('<a class="bt-banner png" onclick="clearTimeout(bannerTempo);rotacionarBanner(this.id,' + total + ')" id="bt-' + cont + '">0' + cont + '</a>');
            
            // Posiciono o link 
            $('#bt-' + cont).css('left', (62 - (totalLink * 16)));
            totalLink = totalLink - 1;
            
            if (!(cont == total)) {
            
            }
        });
        
        rotacionarBanner("bt-1", total);
        
    }
	else {
		$('#ban-1').fadeIn();
	}

	
	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	

    // Salvar as alteracões do cadastro do usuario
    $('#bt-salvar-usuario').click(function(e){
        error = false;
        
        
        $('.error-form').remove();
        // valida Nome
        if ($('#cad-nome').val() == "") {
            mostraError($('#cad-nome'));
            error = true;
        }
        
        
        // Valida Sobrenome
        if ($('#cad-sobrenome').val() == "") {
            mostraError($('#cad-sobrenome'));
            error = true;
        }
        
        // Valida Cpf
        if ($('#cad-cpf').val() == "") {
            mostraError($('#cad-cpf'));
            error = true;
        }
        else {
            if (isCpf($('#cad-cpf').val()) == false) {
                mostraError($('#cad-cpf'));
                error = true;
            }
        }
        
        
        // Valida Rg
        if ($('#cad-rg').val() == "") {
            mostraError($('#cad-rg'));
            error = true;
        }
        
        // Valida Nascimento
        if ($('#cad-nascimento').val() == "") {
            mostraError($('#cad-nascimento'));
            error = true;
        }
        
        // Valida Sexo
        if ($('#cad-sexo').val() == "") {
            mostraError($('#campo-cad-sexo'));
            error = true;
        }
        
        // Valida telefone
        if ($('#cad-telefone').val() == "") {
            mostraError($('#cad-telefone'));
            error = true;
        }
        
        // Endereco
        if ($('#cad-endereco').val() == "") {
            mostraError($('#cad-endereco'));
            error = true;
        }
        
        // Cep
        if ($('#cad-cep').val() == "") {
            error = true;
            mostraError($('#cad-cep'));
        }
        
        // Estado
        if ($('#cad-estado').val() == "") {
            error = true;
            mostraError($('#campo-cad-estado'));
        }
        
        // cidade
        if ($('#cad-cidade').val() == "") {
            error = true;
            mostraError($('#campo-cad-cidade'));
        }
        
        
        
        // Valida Email
        if ($('#cad-email').val() == "") {
            error = true;
            mostraError($('#cad-email'));
        }
        else {
            if (validaEmail($('#cad-email').val()) == false) {
                error = true;
                mostraError($('#cad-email'));
            }
        }
        
        if ($('#cad-senha').val() != "") {
            // senha
            if ($('#cad-senha').val() == "") {
                error = true;
                mostraError($('#cad-senha'));
            }
            
            // Endereco
            if ($('#cad-csenha').val() == "") {
                error = true;
                mostraError($('#cad-csenha'));
            }
            else {
                if ($('#cad-csenha').val() != $('#cad-senha').val()) {
                    error = true;
                    mostraError($('#cad-csenha'));
                }
                
            }
            
        }
        
        // Se não houver erros
        if (error == false) {
            alteracoesForm = false;
            
            var dados = $('#form-usuario').serialize();
            
            $.ajax({
                header: {
                    "Content-Type": "text/html;  charset=ISO-8859-1"
                },
                type: "post",
                data: "acao=alterar-usuario&" + dados,
                url: "http://www.sabongi.com.br/ajax.php",
                dataType: "json",
                success: function(valor){
                
                    if (valor.error == true) {
                        alert('As alterações foram salvas com sucesso');
                    }
                    else {
                        if (valor.msg == '') {
                            alert('Ocorreu algum erro inesperado, Por favor tente de novo ou entre em contato');
                        }
                        else {
                            alert(valor.msg);
                        }
                    }
                }
            });
            
            
        }
        else {
            alert('Por Favor Corrija os erros');
        }
        
        e.preventDefault(e);
        return false;
        
    });
    
    ///////////////////////////////////
    // Salvar as alteracões do cadastro do Noivo
    $('#bt-salvar-noivo').click(function(event){
    
        var error = false;
        
        
        $('.error-form').remove();
        // valida Nome
        if ($('#cad-noivo-nome').val() == "") {
            mostraError($('#cad-noivo-nome'));
            error = true;
        }
        
        
        // Valida Sobrenome
        if ($('#cad-noivo-sobrenome').val() == "") {
            mostraError($('#cad-noivo-sobrenome'));
            error = true;
        }
        
        // Valida Email
        if ($('#cad-noivo-email').val() == "") {
            error = true;
            mostraError($('#cad-noivo-email'));
        }
        else {
            if (validaEmail($('#cad-noivo-email').val()) == false) {
                error = true;
                mostraError($('#cad-noivo-email'));
            }
        }
        
        
        
        // Se não houver erros
        if (error == false) {
            alteracoesForm = false;
            
            var dados = $('#form-noivo').serialize();
            
            $.ajax({
                header: {
                    "Content-Type": "text/html;  charset=ISO-8859-1"
                },
                type: "post",
                data: "acao=alterar-noivo&" + dados,
                url: "http://www.sabongi.com.br/ajax.php",
                dataType: "json",
                success: function(valor){
                
                    if (valor.error == true) {
                        alert('As alterações foram salvas com sucesso');
                    }
                    else {
                    
                        alert('Ocorreu algum erro inesperado, Por favor tente de novo ou entre em contato');
                        
                    }
                }
            });
            
            
        }
        else {
            alert('Por Favor Corrija os erros');
        }
        
        
        event.preventDefault(event);
        return false;
    });
    
    ///////////////////////////////////////////
    // Salvar as alteracões do cadastro de Noiva
    $('#bt-salvar-noiva').click(function(event){
    
        var error = false;
        
        $('.error-form').remove();
        // valida Nome
        if ($('#cad-noiva-nome').val() == "") {
            mostraError($('#cad-noiva-nome'));
            error = true;
        }
        
        // Valida Sobrenome
        if ($('#cad-noiva-sobrenome').val() == "") {
            mostraError($('#cad-noiva-sobrenome'));
            error = true;
        }
        
        // Valida Email
        if ($('#cad-noiva-email').val() == "") {
            error = true;
            mostraError($('#cad-noiva-email'));
        }
        else {
            if (validaEmail($('#cad-noiva-email').val()) == false) {
                error = true;
                mostraError($('#cad-noiva-email'));
            }
        }
        
        
        
        // Se não houver erros
        if (error == false) {
            alteracoesForm = false;
            
            var dados = $('#form-noiva').serialize();
            
            $.ajax({
                header: {
                    "Content-Type": "text/html;  charset=ISO-8859-1"
                },
                type: "post",
                data: "acao=alterar-noiva&" + dados,
                url: "http://www.sabongi.com.br/ajax.php",
                dataType: "json",
                success: function(valor){
                
                    if (valor.error == true) {
                        alert('As alterações foram salvas com sucesso');
                    }
                    else {
                    
                        alert('Ocorreu algum erro inesperado, Por favor tente de novo ou entre em contato');
                        
                    }
                }
            });
            
            
        }
        else {
            alert('Por Favor Corrija os erros');
        }
        
        event.preventDefault(event);
        return false;
    });
    
    /////////////////////////////////////////////////////////////////////////
    // Salvar as alteracões do cadastro de Casamento
    $('#bt-salvar-casamento').click(function(event){
        var error = false;
        
        
        $('.error-form').remove();
        
        // valida data
        if ($('#cad-casamento-data').val() == "") {
            mostraError($('#cad-casamento-data'));
            error = true;
        }
        
        
        // Valida Local
        if ($('#cad-casamento-local').val() == "") {
            mostraError($('#cad-casamento-local'));
            error = true;
        }
        
        
        // Valida Url Title
        if ($('#cad-casamento-url-title').val() == "") {
            mostraError($('#cad-casamento-url-title'));
            error = true;
        }
        
        
        // Se não houver erros
        if (error == false) {
            alteracoesForm = false;
            
            var dados = $('#form-casamento').serialize();
            
            $.ajax({
                header: {
                    "Content-Type": "text/html;  charset=ISO-8859-1"
                },
                type: "post",
                data: "acao=alterar-casamento&" + dados,
                url: "http://www.sabongi.com.br/ajax.php",
                dataType: "json",
                success: function(valor){
                
                    if (valor.error == true) {
                        alert('As alterações foram salvas com sucesso');
                    }
                    else {
                        if (valor.msg == '') {
                            alert('Ocorreu algum erro inesperado, Por favor tente de novo ou entre em contato');
                        }
                        else {
                            alert(valor.msg);
                        }
                        
                    }
                }
            });
            
        }
        else {
            alert('Por Favor Corrija os erros');
        }
        
        event.preventDefault(event);
        return false;
    });
    
    
    //=====================================================================
    // Dados do usuario
    $('#passo-1-edicao').click(function(){
        var continuar = alteracoesForm;
        
        if (continuar == false) {
            $(this).parents('#estado-edicao').children('div').addClass('opacity').css('opacity', '0.3').bind('mouseout', function(){
                $(this).css('opacity', '0.3');
            });
            $(this).removeClass('opacity').css('opacity', '0.9');
            $(this).unbind('mouseout');
            
            $('#form-cadastro fieldset').hide();
            $('#dados-pessoais').show();
        }
        else {
            alert('Houver alterações nos dados do formulário que não foram salvas. Salve as alterações para poder proseguir');
        }
        
    });
    
    
    // Dados do noivo
    $('#passo-2-edicao').click(function(event){
        var continuar = alteracoesForm;
        
        if (continuar == false) {
            $(this).parents('#estado-edicao').children('div').addClass('opacity').css('opacity', '0.3').bind('mouseout', function(){
                $(this).css('opacity', '0.3');
            });
            $(this).removeClass('opacity').css('opacity', '0.9');
            $(this).unbind('mouseout');
            
            $('#form-cadastro fieldset').hide();
            $('#dados-noivo').show();
        }
        else {
            alert('Houver alterações nos dados do formulário que não foram salvas. Salve as alterações para poder proseguir');
        }
        
        
        event.preventDefault(event);
        return false;
    });
    
    
    // dados da noiva
    $('#passo-3-edicao').click(function(){
        var continuar = alteracoesForm;
        
        if (continuar == false) {
            $(this).parents('#estado-edicao').children('div').addClass('opacity').css('opacity', '0.3').bind('mouseout', function(){
                $(this).css('opacity', '0.3');
            });
            $(this).removeClass('opacity').css('opacity', '0.9');
            $(this).unbind('mouseout');
            
            $('#form-cadastro fieldset').hide();
            
            $('#dados-noiva').show();
        }
        else {
            alert('Houver alterações nos dados do formulário que não foram salvas. Salve as alterações para poder proseguir');
        }
        
    });
    
    
    // Dados do casamento
    $('#passo-4-edicao').click(function(){
        var continuar = alteracoesForm;
        
        if (continuar == false) {
            $(this).parents('#estado-edicao').children('div').addClass('opacity').css('opacity', '0.3').bind('mouseout', function(){
                $(this).css('opacity', '0.3');
            });
            
            $(this).removeClass('opacity').css('opacity', '0.9');
            $(this).unbind('mouseout');
            
            $('#form-cadastro fieldset').hide();
            $('#dados-casamento').show();
        }
        else {
            alert('Houver alterações nos dados do formulário que não foram salvas. Salve as alterações para poder proseguir');
        }
        
    });
    
    //=====================================================================
    // Fim botoes da opcoes da edição de dados do painel
    
    ///////////////////////////////////////////////////////////////////	
    // Efeito de mousehover menu de edição de dados  do painel
    $('#estado-edicao div').mouseover(function(){
        $(this).css('opacity', '0.9');
    }).mouseout(function(){
        $(this).css('opacity', '0.3');
    });
    
    
    ///////////////////////////////////////////////////////////////////	
    // Diminui mais quantidade 
    $('.bt-remover-lista').live('click', function(event){
    
        var id = $(this).parents('tr').children('td.img').children('.id').text();
        
        elemento = $(this).parents('tr');
        
        $.ajax({
            header: {
                "Content-Type": "text/html;  charset=ISO-8859-1"
            },
            type: "post",
            data: "acao=delLista&id=" + id,
            url: "http://www.sabongi.com.br/ajax.php",
            dataType: "json",
            success: function(valor){
            
            
                if (valor.acao == true) {
                    elemento.hide();
                }
                else {
                    alert('Error! Ocorreu um erro inesperado durante a requisição. Por favor tentar novamento ou entrar em contato com o admnistrado do site');
                    
                }
            }
        });
        
        
        
        event.preventDefault(event);
        return false;
    });
    
    
    // Adiciona mais quantidade 
    $('.bt-add-quantidade').live('click', function(event){
    
        var id = $(this).parents('tr').children('td.img').children('.id').text();
        
        var quantidade = parseInt($(this).parents('td').children('.quantidadeVal').text()) + 1;
        
        $(this).parent().addClass('aki').html('<img src="/theme/img/carregando.gif" alt="Atualizando" />');
        
        container = $(this).parent('td');
        
        container = this;
        
        $.ajax({
            header: {
                "Content-Type": "text/html;  charset=ISO-8859-1"
            },
            type: "post",
            data: "acao=addQuantidade&id=" + id + "&quantidade=" + quantidade,
            url: "http://www.sabongi.com.br/ajax.php",
            dataType: "json",
            success: function(valor){
            
            
                if (valor.acao == true) {
                    $('.aki').removeClass('aki').html(valor.conteudo);
                }
                else {
                    alert('Error! Ocorreu um erro inesperado durante a requisição. Por favor tentar novamento ou entrar em contato com o admnistrado do site');
                    $('.aki').removeClass('aki').html(valor.conteudo);
                }
            }
        });
        
        event.preventDefault(event);
    });
    
    // Diminui mais quantidade 
    $('.bt-minus-quantidade').live('click', function(event){
    
        var id = $(this).parents('tr').children('td.img').children('.id').text();
        var quantidade = parseInt($(this).parents('td').children('.quantidadeVal').text()) - 1;
        
        $(this).parent().addClass('aki').html('<img src="/theme/img/carregando.gif" alt="Atualizando" />');
        
        container = $(this).parent('td');
        
        container = this;
        
        // verifico se naum e menor que zero
        if (quantidade > 0) {
        
            $.ajax({
                header: {
                    "Content-Type": "text/html;  charset=ISO-8859-1"
                },
                type: "post",
                data: "acao=minusQuantidade&id=" + id + "&quantidade=" + quantidade,
                url: "http://www.sabongi.com.br/ajax.php",
                dataType: "json",
                success: function(valor){
                
                
                    if (valor.acao == true) {
                        $('.aki').removeClass('aki').html(valor.conteudo);
                    }
                    else {
                        alert('Error! Ocorreu um erro inesperado durante a requisição. Por favor tentar novamento ou entrar em contato com o admnistrado do site');
                        $('.aki').removeClass('aki').html(valor.conteudo);
                    }
                }
            });
        }
        else {
            alert('A quantidade não pode ser menor que 1');
            
            $('.aki').removeClass('aki').html('<span class="quantidadeVal">1</span> <a href="#" title="Adicionar" class="bt-add-quantidade"><img src="/theme/img/add.png" alt="Adicionar" /></a> <a href="#" title="Retirar" class="bt-minus-quantidade"><img src="/theme/img/minus.png" alt="Diminuir" /></a>');
        }
        event.preventDefault(event);
    });
    
    
    ///////////////////////////////////////////////////////////////////////////////
    // Bt Adicionar (adicionar Produto da lista de presentes do casal )
    $('.bt-adicionar').live('click', function(e){
    
        // Id do produto
        var idProduto = $(this).attr('rel');
        var elemento = $(this);
        
        
        var error = $.ajax({
            header: {
                "Content-Type": "text/html;  charset=ISO-8859-1"
            },
            type: "post",
            data: "acao=addPresente&id=" + idProduto,
            url: "http://www.sabongi.com.br/ajax.php",
            dataType: "json",
            success: function(valor){
                if (valor.error == false) {
                    // Transformação do botão em remover
                    elemento.removeClass('bt-adicionar').addClass('bt-remover').text('remover');
                    elemento.parents('.box-produto').addClass('box-produto-ativo').removeClass('box-produto');
                    elemento.parents('#descricao-produto').attr('id', 'descricao-produto-ativo');
                }
            }
            
        });
        
        e.preventDefault(e);
        return false;
    });
    
    
    ///////////////////////////////////////////////////////////////////////////////
    // Bt Remover(remover Produto da lista de presentes do casal )
    $('.bt-remover').live('click', function(e){
    
        // Id do produto
        var idProduto = $(this).attr('rel');
        
        var elemento = $(this);
        
        var error = $.ajax({
            header: {
                "Content-Type": "text/html;  charset=ISO-8859-1"
            },
            type: "post",
            data: "acao=delPresente&id=" + idProduto,
            url: "http://www.sabongi.com.br/ajax.php",
            dataType: "json",
            success: function(valor){
                if (valor.error == false) {
                    elemento.parents('.box-produto-ativo').addClass('box-produto').removeClass('box-produto-ativo');
                    elemento.addClass('bt-adicionar').removeClass('bt-remover').text('adicionar');
                    elemento.parents('#descricao-produto-ativo').attr('id', 'descricao-produto');
                }
                
            }
            
        });
        
        
        // Transformação do botão em adicioner
        
        
        
        
        
        
        e.preventDefault(e);
        return false;
    });
    
    //////////////////////////////////
    // Passos do cadastro
    $('#estado div.opacity, #estado-edicao div.opacity').css('opacity', '0.3');
    
    ////////////////////////////////
    // Macaras 
    $("#con-telefone").mask("(99)9999-9999");
    
    
    if ($('#cad-cpf').size() > 0) {
    
        $("#cad-cpf").mask("999.999.999-99");
        $("#cad-nascimento").mask("99/99/9999");
        $("#cad-telefone").mask("(99)9999-9999");
        $("#cad-celular").mask("(99)9999-9999");
        
        $("#cad-cep").mask("99999-999");
        $("#cad-noivo-telefone").mask("(99)9999-9999");
        $("#cad-noiva-telefone").mask("(99)9999-9999");
        $('#cad-casamento-data').mask("99/99/9999");
        
    }
    
    var error = false;
    
    
    //////////////////////////////////////
    // Botao Voltar
    $('#bt-voltar1').click(function(e){
    
        $('#dados-pessoais').show();
        $('#dados-noivo').hide();
        $('#estado div').css('opacity', '0.4');
        $('#passo-1').css('opacity', '0.9');
        
        e.preventDefault(e);
        return false;
        
    });
    
    
    //////////////////////////////////////
    // Botao Voltar
    $('#bt-voltar2').click(function(e){
    
        $('#dados-noivo').show();
        $('#dados-noiva').hide();
        $('#estado div').css('opacity', '0.4');
        $('#passo-2').css('opacity', '0.9');
        
        e.preventDefault(e);
        return false;
        
    });
    
    
    //////////////////////////////////////
    // Botao Voltar
    $('#bt-voltar3').click(function(e){
    
        $('#dados-noiva').show();
        $('#dados-casamento').hide();
        $('#estado div').css('opacity', '0.4');
        $('#passo-3').css('opacity', '0.9');
        
        e.preventDefault(e);
        return false;
        
    });
    
    //////////////////////////////////
    // Botao continuar Passo 2
    $('#bt-passo2').click(function(e){
    
        error = false;
		
		
        $('.error-form,.red').remove();
		
        // valida Nome
        if ($('#cad-nome').val() == "") {
            mostraError($('#cad-nome'));
            error = true;
        }
        
        
	
		
        // Valida Sobrenome
        if ($('#cad-sobrenome').val() == "") {
            mostraError($('#cad-sobrenome'));
            error = true;
        }
		
		/*
		// Valida Email
        if ($('#cad-cpf').val() == "") {
        	mostraError($('#cad-cpf'));
            error = true;
        	alert("Teste");
		}
        
        else {
            if ( !isCpf($('#cad-cpf').val()) ) {
                mostraError($('#cad-cpf'));
                error = true;
            }
        }
        
        // Valida Rg
        if ($('#cad-rg').val() == "") {
			mostraError($('#cad-rg'));
			error = true;
        }
        */
		
        // Valida Nascimento
        if ($('#cad-nascimento').val() == "") {
            mostraError($('#cad-nascimento'));
            error = true;
        }
        
        // Valida Sexo
        if ($('#cad-sexo').val() == "") {
            mostraError($('#campo-cad-sexo'));
            error = true;
        }
        
        // Valida telefone
        if ($('#cad-telefone').val() == "") {
            mostraError($('#cad-telefone'));
            error = true;
        }
        
        // Endereco
        if ($('#cad-endereco').val() == "") {
            mostraError($('#cad-endereco'));
            error = true;
        }
		
        // Cep
        if ($('#cad-cep').val() == "") {
            error = true;
            mostraError($('#cad-cep'));
        }
        
        // Estado
        if ($('#cad-estado').val() == "") {
            error = true;
            mostraError($('#campo-cad-estado'));
        }
        
        // cidade
        if ($('#cad-cidade').val() == "") {
            error = true;
            mostraError($('#campo-cad-cidade'));
        }
		
        // Valida Email
        if ($('#cad-email').val() == "") {
            error = true;
            mostraError($('#cad-email'));
        }
		
		
		
        else {
            if (validaEmail($('#cad-email').val()) == false) {
                error = true;
                mostraError($('#cad-email'));
            }
            else {
                $.ajax({
                    header: {
                        "Content-Type": "text/html;  charset=ISO-8859-1"
                    },
                    type: "post",
                    data: "acao=verifica-email&email=" + $('#cad-email').val(),
                    url: "http://www.sabongi.com.br/ajax.php",
                    dataType: "json",
                    success: function(valor){
                    
                        if (valor.error == true) {
                            mostraError($('#cad-email'));
                            alert('Já Existe um usuário cadastro com esse e-mail');
                            error = true;
                            return true;
                        }
                        else {
                            return false;
                        }
                        
                    }
                    
                });
                
                
                
            }
            
        }
        
        
        // senha
        if ($('#cad-senha').val() == "") {
            error = true;
            mostraError($('#cad-senha'));
        }
        
        // Endereco
        if ($('#cad-csenha').val() == "") {
            error = true;
            mostraError($('#cad-csenha'));
        }
        else {
            if ($('#cad-csenha').val() != $('#cad-senha').val()) {
                error = true;
                mostraError($('#cad-csenha'));
            }
            
        }
		
		
		
		// validar check Box
		if ($('#contrato:checked').val() != "ok") {
            error++;
            $('.check').append('<span class="red"><br />É necessario aceitar os termos do contrato</span>');
        }
        
        
        // Se não houver erros
        if (error == false) {
            $('#dados-pessoais').hide();
            $('#dados-noivo').show();
            $('#estado div').css('opacity', '0.4');
            $('#passo-2').css('opacity', '0.9');
            
        }
        else {
            alert('Por Favor Corrija os erros');
        }
        
        e.preventDefault(e);
        return false;
    });
    
    // Verificar email
    $('#cad-email').blur(function(){
        idUser = 'no';
        if ($('#id-usuario').size() > 0) {
            idUser = $('#id-usuario').val();
        }
        
        $.ajax({
            header: {
                "Content-Type": "text/html;  charset=ISO-8859-1"
            },
            type: "post",
            data: "acao=verifica-email&email=" + $('#cad-email').val() + '&id-usuario=' + idUser,
            url: "http://www.sabongi.com.br/ajax.php",
            dataType: "json",
            success: function(valor){
            
                if (valor.error == true) {
                    mostraError($('#cad-email'));
                    alert('Já Existe um usuário cadastro com esse e-mail');
                    return true;
                }
                else {
                    return false;
                }
                
            }
            
        });
        
    })
    
    /////////////////////////
    // Botao continuar Passo 2
    $('#bt-passo3').click(function(e){
    
        var error = false;
        
        
        $('.error-form').remove();
        // valida Nome
        if ($('#cad-noivo-nome').val() == "") {
            mostraError($('#cad-noivo-nome'));
            error = true;
        }
        
        
        // Valida Sobrenome
        if ($('#cad-noivo-sobrenome').val() == "") {
            mostraError($('#cad-noivo-sobrenome'));
            error = true;
        }
        
        // Valida Email
        if ($('#cad-noivo-email').val() == "") {
            error = true;
            mostraError($('#cad-noivo-email'));
        }
        else {
            if (validaEmail($('#cad-noivo-email').val()) == false) {
                error = true;
                mostraError($('#cad-noivo-email'));
            }
        }
        
        
        
        // Se não houver erros
        if (error == false) {
            $('#dados-noivo').hide();
            $('#dados-noiva').show();
            $('#estado div').css('opacity', '0.4');
            $('#passo-3').css('opacity', '0.9');
            
        }
        else {
            alert('Por Favor Corrija os erros');
        }
        
        
        
        e.preventDefault(e);
        return false;
    });
    
    
    /////////////////////
    // Botao continuar Passo 4
    $('#bt-passo4').click(function(e){
    
        var error = false;
        
        
        $('.error-form').remove();
        // valida Nome
        if ($('#cad-noiva-nome').val() == "") {
            mostraError($('#cad-noiva-nome'));
            error = true;
        }
        
        
        // Valida Sobrenome
        if ($('#cad-noiva-sobrenome').val() == "") {
            mostraError($('#cad-noiva-sobrenome'));
            error = true;
        }
        
        // Valida Email
        if ($('#cad-noiva-email').val() == "") {
            error = true;
            mostraError($('#cad-noiva-email'));
        }
        else {
            if (validaEmail($('#cad-noiva-email').val()) == false) {
                error = true;
                mostraError($('#cad-noiva-email'));
            }
        }
        
        
        
        
        // Se não houver erros
        if (error == false) {
            $('#dados-noiva').hide();
            $('#dados-casamento').show();
            $('#estado div').css('opacity', '0.4');
            $('#passo-4').css('opacity', '0.9');
            
        }
        else {
            alert('Por Favor Corrija os erros');
        }
        
        
        e.preventDefault(e);
        return false;
    });
    
    
    /////////////////////////
    // Botao Salvar
    $('#bt-passo-salvar').click(function(e){
    
        var error = false;
        
        
        $('.error-form').remove();
        
        // valida data
        if ($('#cad-casamento-data').val() == "") {
            mostraError($('#cad-casamento-data'));
            error = true;
        }
        
        
        // Valida Local
        if ($('#cad-casamento-local').val() == "") {
            mostraError($('#cad-casamento-local'));
            error = true;
        }
        
        
        // Valida Url Title
        if ($('#cad-casamento-url-title').val() == "") {
            mostraError($('#cad-casamento-url-title'));
            error = true;
        }
        
        
        
        // Se não houver erros
        if (error == false) {
        
        
            var dados = $('#form-cadastro form').serialize();
            
            $.ajax({
                header: {
                    "Content-Type": "text/html;  charset=ISO-8859-1"
                },
                type: "post",
                data: "acao=cadastra&" + dados,
                url: "http://www.sabongi.com.br/ajax.php",
                dataType: "json",
                success: function(valor){
                
                    if (valor.error == true) {
                        $('#dados-casamento').hide();
                        $('#cadastro-ok').show();
                    }
                    else {
                        if (valor.msg == '') {
                            alert('Ocorreu algum erro inesperado, Por favor tente de novo ou entre em contato');
                        }
                        else {
                            alert(valor.msg);
                        }
                    }
                }
            });
        }
        else {
            alert('Por Favor Corrija os erros');
        }
        e.preventDefault(e);
        return false;
    });
    
    /////////////////////////////////
    // Combobox cad-sexo
    $('#campo-cad-sexo').click(function(e){
        var elemento = $(this);
        var posicao = elemento.position();
        
        // Mostra as opcoes
        $('#opcoes-sexo').css({
            'top': parseInt(posicao.top + 40),
            'left': parseInt(posicao.left + 5)
        }).slideDown();
        
        // Clique na opcao
        $('#opcoes-sexo li').click(function(e){
            var valor = $(this).text();
            
            // Atribui os valoe selecionado
            $('#campo-cad-sexo .valor').text(valor);
            $('#cad-sexo').attr('value', valor);
            
            // Escondo as opcoes
            $('#opcoes-sexo').slideUp();
            
            e.preventDefault(e);
            return false;
        });
        
        // Efeito de over da opcao
        $('#opcoes-sexo li').mouseover(function(){
            $(this).css('text-decoration', 'underline');
            
        }).mouseout(function(){
            $(this).css('text-decoration', 'none');
        });
        
    });
    
    
    
    
    
    ////////////////////////
    // Combobox cad-estado
    $('#campo-cad-estado').click(function(e){
        var elemento = $(this);
        var posicao = elemento.position();
        
        // Mostra as opcoes
        $('#opcoes-estado').css({
            'top': parseInt(posicao.top + 40),
            'left': parseInt(posicao.left + 5)
        }).slideDown();
        
        // Clique na opcao
        $('#opcoes-estado li').click(function(e){
            var valor = $(this).children('.sigla').text();
            
            // Atribui os valoe selecionado
            $('#campo-cad-estado .valor').text(valor);
            $('#cad-estado').attr('value', $(this).children('.id').text());
            
            // Escondo as opcoes
            $('#opcoes-estado').slideUp();
            
            $('#campo-cad-cidade .valor').text('Carregando ...');
            
            
            var id = parseInt($(this).children('.id').text());
            
            // Lista a lista de cidades do estado selecionado
            $.ajax({
                header: {
                    "Content-Type": "text/html;  charset=ISO-8859-1"
                },
                type: "post",
                data: "acao=cidade&id=" + id,
                url: "http://www.sabongi.com.br/ajax.php",
                dataType: "html",
                success: function(valor){
                    $('#campo-cad-cidade .valor').text('Selecione a sua cidade');
                    $('#campo-cad-cidade ul').html(valor);
                    
                    e.preventDefault(e);
                    return false;
                    
                }
                
            });
            
            e.preventDefault(e);
            return false;
        });
        
        // Efeito de over da opcao
        $('#opcoes-estado li').mouseover(function(){
            $(this).css('text-decoration', 'underline');
            
        }).mouseout(function(){
            $(this).css('text-decoration', 'none');
        });
        
        
        e.preventDefault(e);
        return false;
        
    });
    
    
    // Combobox cad-cidade
    $('#campo-cad-cidade').click(function(e){
        var elemento = $(this);
        var posicao = elemento.position();
        
        // Mostra as opcoes
        $('#opcoes-cidade').css({
            'top': parseInt(posicao.top + 40),
            'left': parseInt(posicao.left + 5)
        }).slideDown();
        
        // Clique na opcao
        $('#opcoes-cidade li').click(function(e){
            var valor = $(this).children('.sigla').text();
            
            // Atribui os valoe selecionado
            $('#campo-cad-cidade .valor').text(valor);
            $('#cad-cidade').attr('value', $(this).children('.id').text());
            
            // Escondo as opcoes
            $('#opcoes-cidade').slideUp();
            
            e.preventDefault(e);
            return false;
        });
        
        // Efeito de over da opcao
        $('#opcoes-cidade li').mouseover(function(){
            $(this).css('text-decoration', 'underline');
            
        }).mouseout(function(){
            $(this).css('text-decoration', 'none');
        });
        
    });
	
	
	////////////////////////////////////////////////////////////////////////////////////////////////////
	
});

// Abrir popup
function abrir(pagina, largura, altura){
    var esquerda = (screen.width - largura) / 2;
    var topo = (screen.height - altura) / 2;
    
    window.open(pagina, '', 'height=' + altura + ', width=' + largura + ', top=' + topo + ', left=' + esquerda + ', Scrollbars=YES, resizable=NO, menubar=NO');
}

function getPageScroll(){
    var xScroll, yScroll;
    if (self.pageYOffset) {
        yScroll = self.pageYOffset;
        xScroll = self.pageXOffset;
    }
    else 
        if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
            yScroll = document.documentElement.scrollTop;
            xScroll = document.documentElement.scrollLeft;
        }
        else 
            if (document.body) {// all other Explorers
                yScroll = document.body.scrollTop;
                xScroll = document.body.scrollLeft;
            }
    arrayPageScroll = new Array(xScroll, yScroll);
    return arrayPageScroll;
};

function validaEmail(mail){
    var er = RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
    if (er.test(mail) == false) {
        return false;
    }
    
    return true;
}

// Mostra a imagem que o campo esta com algum erro
function mostraError(e){
    var w = e.width();
    var posicao = e.position();
    var id = e.attr('id');
    
    
    $('.cont_txt').append('<img id="error-' + id + '" src="http://www.sabongi.com.br/theme/img/stop.gif" alt="Error" class="error-form" />');
    $('#error-' + id).css({
        'top': parseInt(posicao.top + 10),
        'left': parseInt(posicao.left + w + 25)
    });
    
}

function mostraErrorEm(e){
    var w = e.width();
    var posicao = e.position();
    var id = e.attr('id');
    
    
    $('#esqueceu-a-senha').append('<img id="error-' + id + '" src="http://www.sabongi.com.br/theme/img/stop.png" alt="Error" class="error-form" />');
    $('#error-' + id).css({
        'top': parseInt(posicao.top + 10),
        'left': parseInt(posicao.left + w + 13)
    });
    
}

// Mostra a imagem que o campo esta com algum erro
function mostraErrorNew(e){
    var w = e.width();
    var posicao = e.position();
    var id = e.attr('id');
    
    
    $('body').append('<img id="error-' + id + '" src="http://www.sabongi.com.br/theme/img/stop.png" alt="Error" class="error-form" />');
    $('#error-' + id).css({
        'top': parseInt(posicao.top + 8),
        'left': parseInt(posicao.left + w - 15)
    });
    
}



function mascaras(valor, id, mascara, evento)
{
	/////////////////////////////////////////////////////////////////////////////////
	//                             MODELO  DE MÁSCARA                              //
	//onkeyup="mascaras(this.value, this.id, '####.##.##.#######-#/#', event)"//
	/////////////////////////////////////////////////////////////////////////////////

	/////////////////////////////////////////////////////////////////////////////////
	//                         MODELO  DE MÁSCARA MONETÁRIA                        //
	//onkeyup="mascaraHellas(this.value, this.id, 'money', event)"                 //
	/////////////////////////////////////////////////////////////////////////////////
	
	
	//inicializa a variavel que vai conter o valor final
	var valorFinal = "";
	
	//verifica o que foi digitada para que seja verificado se é somente números ou não
	var tecla = evento.keyCode;	
	
	//manetem o tamanho original do campo sem retirar a máscara
	var valorOriginal = valor;
	
	//inicializa um array com todos os caracteres que serão retirado
	var arrNaoPermitidos = new Array("-", ".", "/", "\\", "|", "(", ")", ":", " ", ",");
	
	//retira qualquer máscatra que já tenho sido colocada
	for(i1=0;i1<valor.length;i1++)
	{
		for(i2=0;i2<arrNaoPermitidos.length;i2++)
		{
			if(valor.charAt(i1) == arrNaoPermitidos[i2])
			{
				valor = valor.toString().replace( arrNaoPermitidos[i2], "" );
			}	
		}	
	}	
	
	//merifica se a máscara é mometária ou uma máscara fixa
	if(mascara == "money")
	{
		//retira os zeros da frente do valor
		var temZero = true;
		while(temZero == true)
		{
			if(valor.substring(0,1) == "0")
			{
				valor = valor.substring(1,valor.length);
			}
			else
			{
				temZero = false;
			}	
		}		
		
		//verifica se foi precionado o backspae
		if(tecla == 8)
		{
			valor = valor.substring(0, valor.length);	
		}

		//faz as verificações para a formatação do valor
		if(valor.length == 1)
		{
			valorFinal = "0,0"+valor;	
		}
		else if(valor.length == 2)
		{
			valorFinal = "0,"+valor;	
		}
		else if(valor.length == 4 && valor.substr(0,2) == "00")
		{
			valorFinal = "0,"+valor.substr(2);	
		}
		else if(valor.length == 4 && valor.substr(0,1) == "0" && valor.substr(0,2) != "00")
		{
			valorFinal = valor.substr(1,1)+","+valor.substr(2);	
		}
		else if(valor.length >= 4 || valor.length == 3)
		{
			var parteInteira = valor.substr(0, (valor.length -2));
			var parteDecimal = valor.substr((valor.length -2))  
			var inteiro = "";
			var cont = 1;
			var milhar = ""; 	
			
			for(i = parteInteira.length; i>0 ; i--)
			{					
				if(cont == 4)
				{
					milhar = ".";
					cont = 2;
				}
				else
				{
					milhar = "";
					cont++;
				}	
			
				inteiro = parteInteira.substr((i-1),1)+ milhar + inteiro;
			}
			
			valorFinal = inteiro+","+parteDecimal;
		}
		else
		{
			valorFinal = "0,00";
		}	
	}
	else
	{	
		//verifica se foi precionado o backspae
		if(tecla != 8)
		{			
			//verifica se já não ultrapassou o tamanha máximo da máscara
			if(mascara.length >= valorOriginal.length)
			{			
				//loop em cima do valor do campo sem a máscara
				jaTemMascara = false;
				for(i=0;i<valor.length;i++)
				{			
					//verifica se a string já recebeu alguma máscara ou não
					if(jaTemMascara == false)
					{
						//verifica se o tipo da entrada de dados tem que ser némerica
						if(mascara.charAt(i) == "#")
						{
							//verifica se foi digitado somente números
							if(((tecla > 95) && (tecla < 106)) || ((tecla > 47) && (tecla < 58)) || tecla == 9 || tecla == 16)
							{
								//0 = 96 ou 48
								//1 = 97 ou 49
								//2 = 98 ou 50
								//3 = 99 ou 51
								//4 = 100 ou 52
								//5 = 101 ou 53
								//6 = 102 ou 54
								//7 = 103 ou 55
								//8 = 104 ou 56
								//9 = 105 ou 57
								//tecla == 9 = tab
								valorFinal = valorFinal  + valor.charAt(i);
							}
							else//se não foi digitado um número é retirado o caracter da string
							{
								valorFinal = valorOriginal.substring(0, valorOriginal.length -1);
							}					
						}
						else if(mascara.charAt(i) == "@")//verifica se o tipo da entrada é qualquer caracter
						{
							valorFinal = valorFinal  + valor.charAt(i);
						}
						else//se não for quelaquer caracter é algum elemento da máscara
						{
							//verifica se o próxima depois da máscara é númerica 
							if(mascara.charAt(i + 1) == "#")
							{
								//verifica se foi digitado somente números
								if(((tecla > 95) && (tecla < 106)) || ((tecla > 47) && (tecla < 58)) || tecla == 9 || tecla == 16)
								{
									//0 = 96 ou 48
									//1 = 97 ou 49
									//2 = 98 ou 50
									//3 = 99 ou 51
									//4 = 100 ou 52
									//5 = 101 ou 53
									//6 = 102 ou 54
									//7 = 103 ou 55
									//8 = 104 ou 56
									//9 = 105 ou 57
									//tecla == 9 = tab
									valorFinal = valorFinal + mascara.charAt(i + jaTemMascara)  + valor.charAt(i);			
									jaTemMascara = jaTemMascara + 1;	
								}
								else//se não foi digitado um número é retirado o caracter da string
								{
									valorFinal = valorOriginal.substring(0, valorOriginal.length -1);
								}
							}
							else// se não é númerico então pode ser qualuqer caracter
							{
								valorFinal = valorFinal + mascara.charAt(i + jaTemMascara)  + valor.charAt(i);			
								jaTemMascara = jaTemMascara + 1;
							}					
						}
					}
					else//else da verificação da máscara
					{
						//verifica se foi digitado somente números
						if(mascara.charAt(i + jaTemMascara) == "#")
						{
							//verifica se foi digitado somente números
							if(((tecla > 95) && (tecla < 106)) || ((tecla > 47) && (tecla < 58)) || tecla == 9 || tecla == 16)
							{
								//0 = 96 ou 48
								//1 = 97 ou 49
								//2 = 98 ou 50
								//3 = 99 ou 51
								//4 = 100 ou 52
								//5 = 101 ou 53
								//6 = 102 ou 54
								//7 = 103 ou 55
								//8 = 104 ou 56
								//9 = 105 ou 57
								//tecla == 9 = tab
								valorFinal = valorFinal  + valor.charAt(i);
							}
							else//se não foi digitado um número é retirado o caracter da string
							{
								valorFinal = valorOriginal.substring(0, valorOriginal.length -1);
							}
						}
						else if(mascara.charAt(i + jaTemMascara) == "@")//verifica se o tipo da entrada é qualquer caracter
						{
							valorFinal = valorFinal  + valor.charAt(i);
						}
						else
						{
							//verifica se foi digitado somente números
							if(mascara.charAt(i + jaTemMascara +1) == "#")
							{
								//verifica se foi digitado somente números
								if(((tecla > 95) && (tecla < 106)) || ((tecla > 47) && (tecla < 58)) || tecla == 9 || tecla == 16)
								{
									//0 = 96 ou 48
									//1 = 97 ou 49
									//2 = 98 ou 50
									//3 = 99 ou 51
									//4 = 100 ou 52
									//5 = 101 ou 53
									//6 = 102 ou 54
									//7 = 103 ou 55
									//8 = 104 ou 56
									//9 = 105 ou 57
									//tecla == 9 = tab
									valorFinal = valorFinal + mascara.charAt(i + jaTemMascara)  + valor.charAt(i);			
									jaTemMascara = jaTemMascara + 1;	
								}
								else//se não foi digitado um número é retirado o caracter da string
								{
									valorFinal = valorOriginal.substring(0, valorOriginal.length -1);
								}
							}
							else// se não é númerico então pode ser qualuqer caracter
							{
								valorFinal = valorFinal + mascara.charAt(i + jaTemMascara)  + valor.charAt(i);			
								jaTemMascara = jaTemMascara + 1;
							}							
						}	
					}//fim da verificação da máscara	
				}	
			}
			else
			{
				valorFinal = valorOriginal.substring(0, mascara.length);	
			}//final da verificação do tamanha máximo da string
		}
		else
		{
			//valorFinal = valorOriginal.substring(0, valorOriginal.length -1)
			valorFinal = valorOriginal.substring(0, valorOriginal.length);		
		}//final da verificação do backspace		
	}
	document.getElementById(id).value = valorFinal;
	
	//faz as verificações para que seja feito o tab automático
	if(mascara != "money")
	{
		
	}
}

/*
 * Mapa 
 */
//function loadMapa(lat, lng, info) {
function loadMapa(lat, lng) {
   if (GBrowserIsCompatible()) {
      
	  var map2 = new GMap2(document.getElementById("map"));
	     
      map2.setCenter(new GLatLng(lat, lng), 15);   
      //var customUI = map2.getDefaultUI();
      //customUI.controls.scalecontrol = false;
      //map2.setUI(customUI);

	  map2.addControl(new GLargeMapControl());
	 
      map2.setMapType(G_NORMAL_MAP);
      
      var point = new GPoint (lng, lat);
      var marker = new GMarker(point);
	  
	  //marker.openInfoWindowHtml(info);
	  
	  GEvent.addListener(marker, "click", function (overlay,point) {
      	//marker.openInfoWindowHtml(info);
      });
	  
      map2.addOverlay(marker);
   }
}

// Function Rotaciona banner
function rotacionarBanner(idBanner, total){


    atualElemento = $('#' + idBanner);
    atualNumero = atualElemento.attr('id');
    atualNumero = parseInt(atualNumero.replace('bt-', ''));
    atualElemento = $('#ban-' + atualNumero);
    
    $('.bt-banner').removeClass('ativo');
    
    if (atualNumero == total) {
        mostraElemento = $('#ban-1');
        $('#bt-' + total).addClass('ativo');
        atualNumero = 1;
    }
    else {
        mostraElemento = atualElemento.next();
		
		
        $('#bt-' + ( atualNumero )).addClass('ativo');
        atualNumero++;
    }
    
    $('#img-destaque .conteudo .item').css('z-index', 90).fadeOut('fast');
    mostraElemento.css('z-index', 100).fadeIn('fast');
    
    
    
    bannerTempo = setTimeout('rotacionarBanner("bt-' + atualNumero + '", ' + total + ');', 9000)
    return true;
}



$(document).ready(function(){

	$('#browsable').scrollable({circular: true}).navigator().autoscroll({interval: 9000});	

		
});

$(window).scroll(function(){				
	if($(window).scrollTop() == "0")
		$('div.scrollToTop').fadeOut('slow');
	else
		$('div.scrollToTop').fadeIn('slow');
});

$('div.scrollToTop a').live('click', function(){
	$("html, body").animate({scrollTop:0}, 'slow');
});

function mudarElemento() {
	
	if ($('.marcas ul.ativo').next().hasClass('parceiros-listas')) {	
		var elemento = $('.marcas ul.ativo').next();
	}
	else {
		var elemento = $('.marcas ul:first');
	}
	
	$('.marcas ul.ativo').fadeOut(1300).removeClass('ativo');
	elemento.fadeIn(1300).addClass('ativo');
}

