/*-- MENU DROPDOWN --*/
  var timeout    = 500;
  var closetimer = 0;
  var ddmenuitem = 0;
  
  function jsddm_open()
  {	jsddm_canceltimer();
  	jsddm_close();
  	ddmenuitem = $(this).find('ul').eq(0).css('visibility', 'visible');}
  
  function jsddm_close()
  {	if(ddmenuitem) ddmenuitem.css('visibility', 'hidden');}
  
  function jsddm_timer()
  {	closetimer = window.setTimeout(jsddm_close, timeout);}
  
  function jsddm_canceltimer()
  {	if(closetimer)
  	{	window.clearTimeout(closetimer);
  		closetimer = null;}}
  
  $(document).ready(function()
  {	$('#jsddm > li').bind('mouseover', jsddm_open);
  	$('#jsddm > li').bind('mouseout',  jsddm_timer);});
  
  document.onclick = jsddm_close;


$(function() {
  
  $('.telefone').mask("(99) 9999-9999");
  $('.cep').mask("99.999-999");
  $('.cpf').mask("999.999.999-99");

  /*  BOTAO NOVO EQUIPAMENTO - ORCAMENTO */
  $("#novo-equipamento").click(
    function() {
      $("#lista-orcamento li:first").clone().appendTo("#lista-orcamento").append('&nbsp;<a href="javascript:;" class="excluir" onclick="$(this).parent().remove()">x</a>');
    }
  );

  $(".excluir").click(
    function() {
      alert($(this).prev('li').html());
    }
  );
  
  
  $("#cep").blur (

    function () {
      $.getJSON(HOST+'busca_cep.php?cep='+$('#cep').val(),
            function(data){
              $('#logradouro').val(data.tipo_logradouro + ' ' + data.logradouro);
              $('#bairro').val(data.bairro);
              $('#cidade').val(data.cidade);
              $('#uf').val(data.uf);
              
            }
         );
    }
  
  )
  
  $(".pessoa").change(
    function () {
       var str = "";
        $("select option:selected").each(
          function () {
              if ($(this).text()=='Pessoa Jurídica') {
                $('#muda').html('<label style="width:50px;" class="tipo">CNPJ<span>*</span>:</label><input type="text" name="cnpj" id="documento" class="cnpj" style="width:135px">');
                $(".tipo").html('CNPJ:');
                $('#documento').unmask();
                $('#documento').mask("99.999.999/9999-99");
              }else
              if ($(this).text()=='Pessoa Física') {
                $('#muda').html('<label style="width:50px;" class="tipo">CPF<span>*</span>:</label><input type="text" name="cpf" id="documento" class="cpf" style="width:135px">');
                $(".tipo").html('CPF:');
                $('#documento').unmask();
                $('#documento').mask("999.999.999-99");
              }
          });
    });

  
  
  /*-- VALIDACAO ORCAMENTO -----------------------*/
  $('#formOrcamento').validate({
      // define regras para os campos
      rules: {
          nome: {
              required : true,
              minlength: 2
          },
          email: {
              required: true,
              email   : true
          },
          cpf: {
              cpf: true
          },
          cnpj: {
              cnpj: true
          },
          telefone: {
              required : true              
          },
          celular: {
              required : true              
          },
          operadora: {
              required : true              
          },
          cidade: {
              required : true,
              minlength: 4
          },
          cep: {
              required : true
          }
      },
      // define messages para cada campo
      messages: {
          nome : null,
          cpf : null,
          cnpj : null,
          email: null,
          telefone: null,
          celular: null,
          cidade: null,
          cep: null
      }
  });
  
  
  
  
  
  
  
  /* MENU PNEU NIVEL 1 -------------------------*/
  $(".menu-opcao-pneu").click(function () {
    $(".menu-opcao-pneu").css('background','#477323');
    $(this).css('background','#9ACF4D');    
    jGet('menu_pneu','#menu_pneu',{codigo:$(this).attr("alt")});
    return false; 
  });

  if (TIPO=='') {
    $(".menu-opcao-pneu:first").click();  
  }else{
    $(".menu-opcao-pneu[alt='"+TIPO+"']:first").click();  
  }
  
   /* MENU PNEU NIVEL 2 - MODELO -------------------------*/
  $(".menu-opcao-pneu-modelo").live("click", function(){
    $(".menu-opcao-pneu-modelo").css('color','#477323');
    $(this).css('color','#C11000');    
    jGet('pneu','#frame',{codigo:$(this).attr("alt")});
    return false; 
  });
  

  $(".product a").click(function () {
    $(".product a").css('color','#477323');
    $(this).css('color','#C11000');    
    return false; 
  });   
  
  
  
  
  

/* 
   $.getJSON("http://cep.republicavirtual.com.br/web_cep.php?cep=89160000&formato=json",
   function(data){
     alert("Data Loaded: " + data);
   });    
*/  

});

function jGet(pagina,destino,opcoes) {
  //$(destino).html('<span style="display: block; margin-left: 15px; padding: 15px; background: url(images/loading.gif) center left no-repeat; padding-left: 20px;">Carregando...</span>');
  opcoes.pg = pagina;  
  $.get(HOST+'ajax.php',
   opcoes,
   function(msg){
     $(destino).fadeOut("fast",
      function(){
        $(destino).html(msg);
        $(destino).fadeIn("fast");
      })
   }
  );
}




/* Verifica CPF e CNPJ */
function Verifica_CPF(CNUMB,obrigatorio) {
 	if((obrigatorio == 1) || (obrigatorio == 0 && CNUMB.value != "")){
    return Verify(CNUMB, 'CPF');
  }else{
    return true;
  }
}

function Verifica_CNPJ(CNUMB,obrigatorio) {
 	if((obrigatorio == 1) || (obrigatorio == 0 && CNUMB.value != "")){
    return Verify(CNUMB, 'CNPJ');
  }else{
    return true;
  }
}

function ClearStr(str, char) {
  while ((cx=str.indexOf(char))!=-1) {		
    str = str.substring(0,cx)+str.substring(cx+1);
  }
  return(str);
}

function ParseNumb(c) {
  c=ClearStr(c,'-');
  c=ClearStr(c,'/');
  c=ClearStr(c,',');
  c=ClearStr(c,'.');
  c=ClearStr(c,'(');
  c=ClearStr(c,')');
  c=ClearStr(c,' ');
  if((parseFloat(c) / c != 1)) {
    if(parseFloat(c) * c == 0) {
      return(c);
    } else {
      return(0);
    }
  } else {
    return(c);
  }
}

/* Parametros Numero e type (CPF ou CNPJ)*/
function Verify(CNUMB,CTYPE) {
  CNUMB=ParseNumb(CNUMB.value)
  if(CNUMB == 0) {
    return(false);
  }else{
    g=CNUMB.length-2;
    if(TestDigit(CNUMB,CTYPE,g)) {
      g=CNUMB.length-1;
      if(TestDigit(CNUMB,CTYPE,g)) {	
        return(true);
      }else{
        return(false);
      }
    }else{
      return(false);
    }
  }
}

function TestDigit(CNUMB,CTYPE,g) {
  var dig=0;
  var ind=2;
  for(f=g;f>0;f--) {
    dig+=parseInt(CNUMB.charAt(f-1))*ind;
    if (CTYPE=='CNPJ') { if(ind>8) {ind=2} else {ind++} }
    else { ind++ }
  }
  dig%=11;
  if(dig<2) {
    dig=0;
  }else{
    dig=11-dig;
  }
  if(dig!=parseInt(CNUMB.charAt(g))) {
    return(false);
  }else{
    return(true);
  }
}


