$(document).ready(function(){

  /*
    ----
      BORDAS ARREDONDADAS
    ----
  */
  
  // 4px
  DD_roundies.addRule('a.botao, a.botao_call, form button, #topo .importadora', '4px', true);
  
  
  /*
    ----
      AJUSTES GERAIS
    ----
  */
  
  // Label de busca
  $('form#frmbusca input').focus(function() {
    if (this.value == this.defaultValue){
    this.value = '';
    $(this).addClass('ativo');
    }
      if(this.value != this.defaultValue){
      this.select();
    }
  });
  $('form#frmbusca input').blur(function() {
    if ($.trim(this.value) == ''){
      this.value = (this.defaultValue ? this.defaultValue : '');
      $(this).removeAttr('class');
    }
  });
  
  
  var search = new Array();
  var count = 0;
  $.ajax({
  	url: "/ajax/busca.php",
  	dataType: "json",
  	async: false,
  	success: function (result)
  	{
	  $.each (result, function (index, val) {
		  if (val != null && val != undefined && val != "")
		  {
			  search[count] = val;
			  count ++;
		  }
	  });
  	}
  });

  $("#busca").autocomplete(search, {
		minChars: 0,
		max: 12,
		autoFill: true,
		mustMatch: true,
		matchContains: false,
		scrollHeight: 200
  });

  /*
    ----
      AJUSTES ESPECIFICOS
    ----
  */
  
//PAGINA INICIAL
  
  // Banners
  $('#home #banner .mascara').before('<a class="seguinte" href="#" title="Seguinte">Seguinte</a> <a class="anterior" href="#" title="Anterior">Anterior</a>');
  $('#home #banner a.anterior').addClass('inativo');
  
  limiteBanners = 2 //scroll maximo
  indiceBanners = 0 //scroll inicial
  
  $('#home #banner a.seguinte').click(function(){
    indiceBanners += 1;
    
    if(indiceBanners <= limiteBanners){
      $('#home #banner .mascara ul').animate({ marginLeft: '-=852px', marginRight: '-=852px' }, 300);
      $('#home #banner a.anterior').removeClass('inativo');
    }
    if (indiceBanners >= limiteBanners) {
      indiceBanners = limiteBanners;
      $('#home #banner a.seguinte').addClass('inativo');
      $('#home #banner a.anterior').removeClass('inativo');
    }
    
    return false;
  });
  
  $('#home #banner a.anterior').click(function(){
    if(indiceBanners > 0){
      indiceBanners -= 1;
      $('#home #banner .mascara ul').animate({ marginLeft: '+=852px', marginRight: '+=852px' }, 300);
      $('#home #banner a.seguinte').removeClass('inativo');
    }
    if (indiceBanners == 0) {
      indiceBanners = 0;
      $('#home #banner a.anterior').addClass('inativo');
      $('#home #banner a.seguinte').removeClass('inativo');
    }
    
    return false;
  });
  
    
    // Legenda da imagem
    $('#home #banner .mascara ul li').hover(function(){
      $('img', $(this)).animate({opacity: '.7'}, 300);
    }, function(){
      $('img', $(this)).animate({opacity: '1'}, 300);
    });
    
  
   // PRODUTOS
      
      // Filtros
      $('#produtos #coluna1 form fieldset ul li a').click(function(){
        if($(this).hasClass('ativo')){
          $(this).removeAttr('class');
        } else {
          $(this).addClass('ativo');
        }
      })
      
      // Preview do produto    
      $('#produtos #coluna2 ul#catalogo li').hover(function(){
        $('img:last-child', $(this)).animate({opacity: '.8'}, 300);
        
        e = $(this); // define o elemento hover
        abreZoom = setTimeout(function(){ jQuery('img.grande', e).show(); }, 1000); // define uma variavel com a funcao do timeout
        abreZoom(); // executa a funcao
      }, function(){
        $('img:last-child', $(this)).animate({opacity: '1'}, 300);
        
        $('img.grande', $(this)).hide();
        clearTimeout(abreZoom); // elimina o timeout
      })
    
      
    // PRODUTO
    
      // Galeria
      $('#produtos #coluna2 .hproduct .galeria ul li:first a').addClass('ativo');
      $('#produtos #coluna2 .hproduct .galeria ul li a').click(function(){
        var imagem = $('#produtos #coluna2 .hproduct .galeria img.photo'); // imagem padrão
        var legenda = $('img', $(this)).attr('alt'); // alt da thumb
        var enderecoImagem = $(this).attr('href'); // href do link clicado
        
        imagem.attr('src', enderecoImagem); // definindo o src da imagem
        imagem.attr('alt', legenda); // definindo o alt da imagem
        
        $('#produtos #coluna2 .hproduct .galeria .legenda').hide(); // esconde todas as legendas para ampliar fotos
        $('#produtos #coluna2 .hproduct .galeria .legenda[href="' + enderecoImagem + '"]').show(); // monstra a legenda da imagem selecionada
        
        $('#produtos #coluna2 .hproduct .galeria ul li a').removeAttr('class');	
        $(this).addClass('ativo');
        
        return false;
      });
    
    
    // REVENDAS

    
      // Exibicao
      $('#revendas #coluna2 .exibicao a, #lista .botao').click(function(){
        tipoExibicao = $(this).attr('href');
        
        $('#revendas #coluna2 .visualizacao').hide();
        
        $('#revendas #coluna2 '+ tipoExibicao).show();
        
        return false;
      });
      
      $('#estado').change(function () {

			$("#cidade").ajaxStart(function () {
				$(this).empty().html("Carregando..").attr("disabled", "disabled");
			});
			
			$.ajax({
				url: '/admin/ajax/cidades-listar-por-estado.php',
				type: 'post',
				data: 'uf_uid=' + $(this).val(),
				success: function(html)
				{
					$('#cidade').removeAttr("disabled");
					$('#cidade').empty().html(html);
				}
			});
		});
      
      $("#dimensoes").change(function() {
    	 
    	  $("#frmBuscaDetalhada").submit();
    	  
      });
	  
	  // Contato com Revenda
		$('a[name=modal]').click(function(e) {
			e.preventDefault();
			
			var id = $(this).attr('href');
			
			var maskHeight = $(document).height();
			var maskWidth = $(window).width();
			
			$('#mask').css({'width':maskWidth,'height':maskHeight});
			
			$('#mask').fadeIn(1000);
			$('#mask').fadeTo("slow",0.8);
			
			var winH = $(window).height();
			var winW = $(window).width();
			$(id).css('top',  '-250px');
			$(id).css('left', '10%');
			$(id).fadeIn(2000);
			$('html, body').animate({scrollTop: $(id)}, 1000);
			});
			
			$('.window .close').click(function (e) {
			e.preventDefault();
			$('#mask, .window, .return').hide();
			});
			
			$('#mask').click(function () {
			$(this).hide();
			$('.window').hide();
		});
		// Validação Contato com Revenda
		$('.btn_envia_contato').click(function(event){
			event.preventDefault();	
			beforeSend:
			$('.window strong').hide();	
			$('.window input,.window textarea').css('border','1px solid #999');	
			
			var formAtivo = $(this).attr('name');
	

			var hasError = false;
   		 	var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; 
			var email = $('#'+formAtivo).find("#email").val();
			var nome = $('#'+formAtivo).find("#nome").val();
			var cidade = $('#'+formAtivo).find("#city").val();
			var assunto = $('#'+formAtivo).find("#assunto").val();
			var msg = $('#'+formAtivo).find("#msg").val();
			var email_revenda = $('#'+formAtivo).find("#email_revenda").val();
			
			if(nome == '') {
				$('#'+formAtivo).find('label[for=nome]').append('<strong> Digite seu nome.</strong>');
				$('#'+formAtivo).find('input[name=nome]').css('border','1px solid #990000');
			  	hasError = true;
			}
			if(email == '') {
				$('#'+formAtivo).find('label[for=email]').append('<strong> Digite seu e-mail.</strong>');
				$('#'+formAtivo).find('input[name=email]').css('border','1px solid #990000');
			  	hasError = true;
			}		 
			else if(!emailReg.test(email)) {
			  	$('#'+formAtivo).find("#email").after(' <strong> Digite um e-mail válido.</strong>');
				$('#'+formAtivo).find('input[name=email]').css('border','1px solid #990000');
			 	hasError = true;
			}
			if(cidade == '') {
				$('#'+formAtivo).find('label[for=city]').append('<strong> Digite sua cidade.</strong>');	
				$('#'+formAtivo).find('input[name=city]').css('border','1px solid #990000');			
			  	hasError = true;
			}
			if(assunto == '') {
				$('#'+formAtivo).find('label[for=assunto]').append('<strong> Digite o assunto.</strong>');		
				$('#'+formAtivo).find('input[name=assunto]').css('border','1px solid #990000');	
			  	hasError = true;
			}	
			if(msg == '') {
				$('#'+formAtivo).find('label[for=msg]').append('<strong> Digite sua mensagem.</strong>');			
				$('#'+formAtivo).find('textarea[name=msg]').css('border','1px solid #990000');	
			  	hasError = true;
			}
					 
			 	if(hasError == true) { return true; }			
			
			if(nome && email && cidade && msg && assunto){	
			//envia formulário
			$.post('../persistence/EnviaContatoRevenda.php',{nome: nome, email:email, assunto:assunto, msg: msg, cidade:cidade, email_revenda:email_revenda}, function(retorna){
			complete:
					$('.window form,.btn_envia_contato').slideUp();
					$('.return').slideDown().html(retorna);
				});	
			}
		});
	  
  
});
