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 clean(obj, txt){
    if (obj.value == '') {
        obj.value = txt;
    }
    else 
        if (obj.value == txt) {
            obj.value = '';
        }
}

function valida_cnpj(cnpj)
      {
	  	
		cnpj = cnpj.replace('.','');
		cnpj = cnpj.replace('.','');
		cnpj = cnpj.replace('/','');
		cnpj = cnpj.replace('-','');
      var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
      digitos_iguais = 1;
      if (cnpj.length < 14 && cnpj.length < 15)
            return false;
      for (i = 0; i < cnpj.length - 1; i++)
            if (cnpj.charAt(i) != cnpj.charAt(i + 1))
                  {
                  digitos_iguais = 0;
                  break;
                  }
      if (!digitos_iguais)
            {
            tamanho = cnpj.length - 2
            numeros = cnpj.substring(0,tamanho);
            digitos = cnpj.substring(tamanho);
            soma = 0;
            pos = tamanho - 7;
            for (i = tamanho; i >= 1; i--)
                  {
                  soma += numeros.charAt(tamanho - i) * pos--;
                  if (pos < 2)
                        pos = 9;
                  }
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(0))
                  return false;
            tamanho = tamanho + 1;
            numeros = cnpj.substring(0,tamanho);
            soma = 0;
            pos = tamanho - 7;
            for (i = tamanho; i >= 1; i--)
                  {
                  soma += numeros.charAt(tamanho - i) * pos--;
                  if (pos < 2)
                        pos = 9;
                  }
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(1))
                  return false;
            return true;
            }
      else
            return false;
      } 



// Valida cpf
function valida_cpf(cpf)
{
	  	
	cpf = cpf.replace('.','');
	cpf = cpf.replace('.','');
	cpf = cpf.replace('-','');
	
      var numeros, digitos, soma, i, resultado, digitos_iguais;
      digitos_iguais = 1;
      if (cpf.length < 11)
            return false;
      for (i = 0; i < cpf.length - 1; i++)
            if (cpf.charAt(i) != cpf.charAt(i + 1))
                  {
                  digitos_iguais = 0;
                  break;
                  }
      if (!digitos_iguais)
            {
            numeros = cpf.substring(0,9);
            digitos = cpf.substring(9);
            soma = 0;
            for (i = 10; i > 1; i--)
                  soma += numeros.charAt(10 - i) * i;
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(0))
                  return false;
            numeros = cpf.substring(0,10);
            soma = 0;
            for (i = 11; i > 1; i--)
                  soma += numeros.charAt(11 - i) * i;
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(1))
                  return false;
            return true;
            }
      else
            return false;
      }

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;
}

$(document).ready(function(){
	//limpa os campos
    $("#new-nome").focus(function(){
        valorAntigo = $(this).attr('value');
        if (valorAntigo == 'digite seu nome') {
            $('#new-nome').val("");
        }
    });
    $("#new-nome").blur(function(){
        if ($('#new-nome').val() == '') {
            $('#new-nome').val('digite seu nome');
        };
    });
	//
	$("#new-email").focus(function(){
        valorAntigo = $(this).attr('value');
        if (valorAntigo == 'digite seu email') {
            $('#new-email').val("");
        }
    });
    $("#new-email").blur(function(){
        if ($('#new-email').val() == '') {
            $('#new-email').val('digite seu email');
        };
    });
    //
////////////////////////////////////////////////////////////////////////////////////////
    // Formulario Newsletter
    $('#bt-enviar-new').click(function(event){
    	
		nome = $('#new-nome').val();
        email = $('#new-email').val();

        error = false;
        
        $('.error').hide();
		$('#error-geral').hide();
        $('#sucess-geral').hide();
		
		
		if (nome == '' || nome == 'digite seu nome') {
            //$('#error-nome').html('Nome inválido').fadeIn();
			window.alert('Nome inválido');
            error = true;
        }
		
        if (email == '' || email == 'digite seu email' || !validaEmail(email)) {
            //$('#error-email').html('E-mail inválido').fadeIn();
			window.alert('E-mail inválido');
            error = true;
        }
        
        
        if (error == false) {
   
            $.ajax({
                type: "post",
                url: "http://www.mbbugigangas.com.br/ajax.php",
                data: {
                    "action": "neswletter",
                    "email": email,
					"nome": nome
                },
                dataType: "json",
                success: function(valor){
                
                    // cadastro corretamente
                    if (valor.error == true) {
						$('#new-nome').val('digite seu nome');
                        $('#new-email').val('digite seu email');
                        //$('#sucess-geral').html(valor.msg).fadeIn();
						window.alert(valor.msg);
                        // Mostra mensagem cadastro Ok
                        
                        //$('#carregandoNew').fadeOut().remove();
                        
                    }
                    else {
                        // Mostra Errors
                        //$('#error-geral').html(valor.msg).fadeIn();
						window.alert(valor.msg);
                        //$('#carregandoNew').fadeOut().remove();
                    }
                }
            });
            
        }
        
        event.preventDefault(event);
        return false;
    });
	
   /**
     * Funcoes do carrinho de compras
     */
    // Botão add
    $(".add-carrinho").click(function(){
    
        var productIDValSplitter = (this.id).split("_");
        var productIDVal = productIDValSplitter;
        
        var productX = $("#productImageWrapID_" + productIDVal).offset().left;
        var productY = $("#productImageWrapID_" + productIDVal).offset().top;
        
        if ($("#productID_" + productIDVal).length > 0) {
            var basketX = $("#productID_" + productIDVal).offset().left;
            var basketY = $("#productID_" + productIDVal).offset().top;
            alert('if 1');
        }
        else {
            var basketX = $("#basketTitleWrap").offset().left;
            var basketY = $("#basketTitleWrap").offset().top;
        }
        
        var gotoX = basketX - productX;
        var gotoY = basketY - productY;
        
        var newImageWidth = $("#productImageWrapID_" + productIDVal).width() / 3;
        var newImageHeight = $("#productImageWrapID_" + productIDVal).height() / 3;
        
        
        $("#productImageWrapID_" + productIDVal + " img").clone().appendTo("#productImageWrapID_" + productIDVal).css({
            'display': 'none'
        }).css({
            'position': 'absolute'
        }).animate({
            opacity: 0.4
        }, 100).animate({
            opacity: 0.1,
            marginLeft: gotoX,
            marginTop: gotoY,
            width: newImageWidth,
            height: newImageHeight
        }, 1200, function(){
            $(this).remove();
            
            
            
            
            $.ajax({
                type: "POST",
                url: "http://www.mbbugigangas.com.br/ajax.php",
                data: {
                    productID: productIDVal,
                    action: "addToBasket"
                },
                dataType: "json",
                success: function(theResponse){
				
                    $(".total-carrinho").show();
                    if ($("#itt_" + productIDVal).length > 0) {
                        $("#itt_" + productIDVal).animate({
                            opacity: 0
                        }, 500);
                        $("#itt_" + productIDVal).before(theResponse.item).remove();
                        $("#itt_" + productIDVal).animate({
                            opacity: 0
                        }, 500);
                        $("#itt_" + productIDVal).animate({
                            opacity: 1
                        }, 500);
                        
                    }
                    else {
                    
                        $("#basketItemsWrap li:first").before(theResponse.item);
                        $("#basketItemsWrap li:first").hide();
                        $("#basketItemsWrap li:first").show("slow");
                        $("#notificationsLoader").empty();
                    }
                    
                    $("#carrinho-total").animate({
					
                        opacity: 0
                    }, 500);
                    $("#carrinho-total").before(theResponse.valor).remove();
                    $("#carrinho-total").animate({
                        opacity: 0
                    }, 500);
                    $("#carrinho-total").animate({
                        opacity: 1
                    }, 500);
                    
                    
                    $("#item-vazio").remove();
                }
                
            });
            
        });
        
    });
  
  
  
  
	
	// Hover tipo cadastro
	$(".hover").hover(
      function () {
        $(this).css("text-decoration",'underline');
      }, 
      function () {
        $(this).css("text-decoration",'none');
      }
    );

	// Mostra o cadastro de pessoa fisica 
	$('#fisico').click(function (){	
	
	
		$("#cep").mask("99999-999",{placeholder:" "});
	    $("#cpf").mask("999.999.999-99",{placeholder:" "});
		$("#telefone").mask("(99)9999-9999",{placeholder:" "});
		
		
		$('.form-fisica').show();
		$('.form-juridica').hide();
	});
	
	// Mostra o cadastro de pessoa Juridica 
	$('#juridica').click(function (){
		
		$("#cnpj").mask("99.999.999/9999-99",{placeholder:" "});
		$("#cep2").mask("99999-999",{placeholder:" "});	    
		$("#telefone2").mask("(99)9999-9999",{placeholder:" "});
		
		$('.form-fisica').hide();
		$('.form-juridica').show();
		
	});


	// Envia o cadastro de pessoa juridica
	$('#enviar2').click(function(event){
		
		$('.aviso').html('');
		
		var error = false;
		
		if ($('#nome2').val() == '' ) {
			$('#nome2').parents('label').children('.aviso').html('Informe o seu nome fantasia');		
			error = true;
		}	
		
		if ($('#razao').val() == '' ) {
			$('#razao').parents('label').children('.aviso').html('Informe a sua razão social');		
			error = true;
		}	
		
		if ($('#cnpj').val() == '' ) {
			$('#cnpj').parents('label').children('.aviso').html('Informe o seu cnpj');		
			error = true;
		}	
		else {
			if (!valida_cnpj($('#cnpj').val() )) {
				$('#cnpj').parents('label').children('.aviso').html('cnpj inválido');		
				error = true;
			}
		}
		
		if ($('#ie').val() == '' ) {
			$('#ie').parents('label').children('.aviso').html('Informe a sua inscrição estadual');		
			error = true;
		}	
			
	
	
		if ($('#email2').val() == '' ) {
			$('#email2').parents('label').children('.aviso').html('Informe o seu e-mail');		
			error = true;
		}	
		
		
		
		if ($('#telefone2').val() == '' ) {
			$('#telefone2').parents('label').children('.aviso').html('Informe o seu telefone');		
			error = true;
		}	
		if ($('#estado2').val() == '' ) {
			$('#estado2').parents('label').children('.aviso').html('Informe o seu estado');		
			error = true;
		}	
						
		if ($('#cidade2').val() == '' ) {
			$('#cidade2').parents('label').children('.aviso').html('Informe o seu cidade');		
			error = true;
		}	
				
		if ($('#endereco2').val() == '' ) {
			$('#endereco2').parents('label').children('.aviso').html('Informe o seu endereco');		
			error = true;
		}	
						
		if ($('#cep2').val() == '' ) {
			$('#cep2').parents('label').children('.aviso').html('Informe o seu cep');		
			error = true;
		}	

		if ($('#jur-senha').val() == '' ) {
			$('#jur-senha').parents('label').children('.aviso').html('Informe a senha');		
			error = true;
		}	
		else {
			valorSenha = $('#jur-senha').val();
			
			if (valorSenha.length < 5) {
				$('#jur-senha').parents('label').children('.aviso').html('Senha muito curta minino de 5 caracteres');		
				error = true;
			}
		}
		
		// Confirmacao da senha
		if ($('#jur-senhac').val() == '' ) {
			$('#jur-senhac').parents('label').children('.aviso').html('Confirme a senha');		
			error = true;
		}
		else {
			if ($('#jur-senhac').val() != $('#jur-senha').val()) {
				$('#jur-senhac').parents('label').children('.aviso').html('Confirmação incorreta');		
				error = true;	
			}
		}	
		
				
		if ( error == true) {
			$('#notificacao2').html('Por favor corrija os erros ');
		}
		else {
			$('#carregando2').show();
			
			var dados = $('#formulario-juridica').serialize();
			
			$.ajax({
            type: "get",
            url: "http://www.mbbugigangas.com.br/ajax.php",
            data: 'action=cad-juridica&'+dados,
            dataType: "json",
            success: function(valor){
				
				if (valor.cadastro == true) {
					$('#formulario-juridica').hide();
					
					$('#msg').html(valor.msg);
				}
				else {
					$('#formulario-juridica').hide();
					
					$('#msg').html(valor.msg);
				}
				
              event.preventDefault(event);
			return false;              
            }
			
            
        });
		}
				
			
		event.preventDefault(event);
		return false;
	});	  
    	

	// Envia mensagens de pedido
	$('#enviar-mensagem').click(function(event){
		
		$('.aviso').html('');
		
		var error = false;
		
		if ($('#mensagem').val() == '' ) {
			$('#mensagem').parents('label').children('.aviso').html('Informe a mensagem');		
			error = true;
		}	
		
		
			
		if ( error == true) {
			$('#notificacao2').html('Por favor corrija os erros ');
		}
		else {
			$('#carregando2').show();
			
			var dados = $('#form-mensagem').serialize();
			
			
			$.ajax({
            type: "get",
            url: "http://www.mbbugigangas.com.br/ajax.php",
            data: 'action=cad-mensagem&'+dados,
            dataType: "json",
            success: function(valor){				
				
				$('#carregando2').hide();
				$('#esconder').hide();	
				
				if (valor.cadastro == true) {
					$('#formulario-fisica').hide();					
					$('#msg').html(valor.msg);									
					
				}
				else {
					$('#formulario-fisica').hide();
					
					$('#msg').html(valor.msg);
				}  
				
								
              	event.preventDefault(event);
			return false;              
            }
			
            
        });
		}
				
			
		event.preventDefault(event);
		return false;
	});	  

	
	// Envia o cadastro de pessoa fisica
	$('#enviar3').click(function(event){
		
		
		$('.aviso').html('');
		
		var error = false;	
	
		if ($('#nome').val() == '' ) {
			$('#nome').parents('label').children('.aviso').html('Informe o seu nome');		
			error = true;
		}	
		
		if ($('#email').val() == '' ) {
			$('#email').parents('label').children('.aviso').html('Informe o seu e-mail');		
			error = true;
		}	
						
		if ($('#cpf').val() == '' ) {
			$('#cpf').parents('label').children('.aviso').html('Informe o seu cpf');		
			error = true;
		}
		else {
			if (!valida_cpf($('#cpf').val())){
				$('#cpf').parents('label').children('.aviso').html('cpf invalido');		
				error = true;
			}
		}
		
		if ($('#rg').val() == '' ) {
			$('#rg').parents('label').children('.aviso').html('Informe o seu rg');		
			error = true;
		}	

		if ($('#telefone').val() == '' ) {
			$('#telefone').parents('label').children('.aviso').html('Informe o seu telefone');		
			error = true;
		}	
		if ($('#estado').val() == '' ) {
			$('#estado').parents('label').children('.aviso').html('Informe o seu estado');		
			error = true;
		}	
						
		if ($('#cidade').val() == '' ) {
			$('#cidade').parents('label').children('.aviso').html('Informe o seu cidade');		
			error = true;
		}	
				
		if ($('#endereco').val() == '' ) {
			$('#endereco').parents('label').children('.aviso').html('Informe o seu endereco');		
			error = true;
		}	
						
		if ($('#cep').val() == '' ) {
			$('#cep').parents('label').children('.aviso').html('Informe o seu cep');		
			error = true;
		}	

		if ($('#fis-senha').val() == '' ) {
			$('#fis-senha').parents('label').children('.aviso').html('Informe a senha');		
			error = true;
		}	
		else {
			valorSenha = $('#fis-senha').val();
			
			if (valorSenha.length < 5) {
				$('#fis-senha').parents('label').children('.aviso').html('Senha muito curta minino de 5 caracteres');		
				error = true;
			}
		}
		
		// Confirmacao da senha
		if ($('#fis-senhac').val() == '' ) {
			$('#fis-senhac').parents('label').children('.aviso').html('Confirme a senha');		
			error = true;
		}
		else {
			if ($('#fis-senhac').val() != $('#fis-senha').val()) {
				$('#fis-senhac').parents('label').children('.aviso').html('Confirmação incorreta');		
				error = true;	
			}
		}	
		
				
		if ( error == true) {
			$('#notificacao').html('Por favor corrija os erros ');
		}
		else {
			$('#carregando2').show();
			
			var dados = $('#formulario-fisica').serialize();
			
			
			$.ajax({
            type: "get",
            url: "http://www.mbbugigangas.com.br/ajax.php",
            data: 'action=cad-fisica&'+dados,
            dataType: "json",
            success: function(valor){
               if (valor.cadastro == true) {
					$('#formulario-fisica').hide();
					
					$('#msg').html(valor.msg);
				}
				else {
					$('#formulario-fisica').hide();
					
					$('#msg').html(valor.msg);
				}  
				
				event.preventDefault(event);
		return false;           
            }
            
        });
			
			
		}
		
				
			
		
		event.preventDefault(event);
		return false;
	});
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
    // Botão Deleter do carrinho
    $(".del-carrinho").live('click', function(){
        var id = (this.id).split("_");
        id = id[1];
        
        $("#itt_" + id).remove().animate({
            opacity: 0
        }, 500);
        
        $.ajax({
            type: "POST",
            url: "http://www.mbbugigangas.com.br/ajax.php",
            data: {
                productID: id,
                action: "delToBasket"
            },
            dataType: "json",
            success: function(theResponse){
            
                $("#carrinho-total").animate({
                    opacity: 0
                }, 500);
                $("#carrinho-total").before(theResponse.valor).remove();
                $("#carrinho-total").animate({
                    opacity: 0
                }, 500);
                $("#carrinho-total").animate({
                    opacity: 1
                }, 500);
                
                if ($("#basketItemsWrap li:first").length == 0) {
                    $("#basketItemsWrap").html('<li id="item-vazio">Carrinho Vazio</li>');
                    
                    // Mensagem de error carrinho vazio 
                    //<li id="item-vazio">Carrinho Vazio</li>	
                }
                
            }
            
        });
    });
    
    
 
    // Alterar quantidade FASE 1 (Criar Campo)
    $(".alterar").click(function(event){		
        var id = (this.id).split("_");
		var id = id[1];		
		// Pego os dados        
		valor = $('#quan_'+id).val();
		
	   $.ajax({
            type: "get",
            url: "http://www.mbbugigangas.com.br/ajax.php",
            data: {
                productID: id,
                action: "atualizaQuantidade",
				quantidade: valor
            },
            dataType: "json",
            success: function(theResponse){     
			
			$("#tot_"+id).animate({
                    opacity: 0
                }, 500);
                $("#tot_"+id).before(theResponse.valorP).remove();
                $("#tot_"+id).animate({
                    opacity: 0
                }, 500);
                $("#tot_"+id).animate({
                    opacity: 1
                }, 500);
                
			
            
                $("#total-tabela").animate({
                    opacity: 0
                }, 500);
                $("#total-tabela").before(theResponse.valor).remove();
                $("#total-tabela").animate({
                    opacity: 0
                }, 500);
                $("#total-tabela").animate({
                    opacity: 1
                }, 500);
                
            }
            
        });		
		
		   	
		event.preventDefault(event);
		return false;
    });
      
	  

    // Botão Deleter da lisatgem de produtos do carrinho
    $(".del-carrinho-listar").live('click', function(event){
        var id = (this.id).split("_");
        id = id[1];
        
        $("#lis_" + id).animate({
            opacity: 0
        }, 500).remove();
        
        $.ajax({
            type: "POST",
            url: "http://www.mbbugigangas.com.br/ajax.php",
            data: {
                productID: id,
                action: "delToBasketLista"
            },
            dataType: "json",
            success: function(theResponse){          
            
                $("#total-tabela").animate({
                    opacity: 0
                }, 500);
                $("#total-tabela").before(theResponse.valor).remove();
                $("#total-tabela").animate({
                    opacity: 0
                }, 500);
                $("#total-tabela").animate({
                    opacity: 1
                }, 500);
                
            }
            
        });
		
		event.preventDefault(event);
		return false;
    });
    
    
    
    $('div.desc-content').corner();  
	
	if ($('.ligthbox a').size() >= 1) { 
		$('.ligthbox a').lightBox();
	}
	
	if ($('.not-img a').size() >= 1) { 
		$('.not-img a').lightBox(); 
    }
	
	$('a[rel*=popup]').lightBox();
	
});
