﻿// find the base path of a script
var settings = {};
settings.basePath = null;

if (!settings.basePath) {
  (function (name) {
    var scripts = document.getElementsByTagName('script');

    for (var i = scripts.length - 1; i >= 0; --i) {
      var src = scripts[i].src;
      var l = src.length;
      var length = name.length;
      if (src.substr(l - length) == name) {
        // set a global propery here
        settings.basePath = src.substr(0, l - length);

      }
    }
  })('scripts.js');
}
var root_path = settings.basePath;
root_path = root_path.replace("js/","");

// DOM ready!
$(document).ready(function() {

	$(".cpf").mask("999.999.999-99");
	$(".data").mask("99/99/9999");
	$(".telefone").mask("(99) 9999-9999");
	$(".cep").mask("99999999");
	$(".cnpj").mask("99.999.999/9999-99");

  /*
  Efeitos de aparencia
  */

	//Menu e Submenu
	$("#menu .menu-admin").click(function(){
			$(this).next(".sub-menu").slideToggle("slow");
			$(this).toggleClass("selected");
   	return false;
	event.preventDefault();
 	});

  /*
  Ajax
  */

	$(".typewatch").keyup(function () {
		var elem = $(this);
    var form = $(this).parents("form.ajax-submit");
  	typewatch(function () {
   		// executed only 500 ms after the last keyup event.
		  ajax_post(elem, form);
  	}, 300);
	});

	var typewatch = (function(){
  	var timer = 0;
  	return function(callback, ms){
    	clearTimeout (timer);
   		timer = setTimeout(callback, ms);
  	}  
	})();
	
	$(".blur").blur(function () {
		var elem = $(this);
		var form = $(this).closest("form.ajax-submit");
    ajax_post(elem, form);
	});

  $("form.ajax-submit").ajaxForm({
    dataType: 'script'
  });
  
  /*
	$("form.ajax-submit").submit(function(event) {
		var elem = null;
    var form = $(this);
		ajax_post(elem, form, true);
	  event.preventDefault();
	});
  */
	
	function ajax_post(elem, form, submit){

    // Verifica se envia o formulário ou se é validação de campo
    var url = '';

    if (submit === undefined) {
      url = root_path + "index.php/ajax/check/"+$(elem).attr("id");
		  var msg=$(elem).siblings(".msg-campo");
      // Retorna mensagem ao estado inicial
      $(msg).removeClass("erro success").text("");
    } else {
      url = $(form).attr("action");
		  var msg=$(".msg-formulario");
      // Retorna mensagem ao estado inicial
      $('.msg-campo, .msg-formulario').removeClass("erro success").text("");
    }
    
    // Exibe loader
		$(msg).addClass("loading");
    
    // Faz a requisição Ajax
		$.ajax({
		  type: "POST",
		  url: url,
		  data:form.serialize(),
		  dataType: "script",
		  error: function() { 
			  // Em caso de erro na requisição ajax
        $(msg).text("Ocorreu um erro na verificação.").addClass("erro");
		  },
		  complete: function() { 
        // Remove o loader
			  $(msg).removeClass("loading");
		  }
		});
  };
	
	//Toggle do value da busca do header
	$(function() {
 		 // VALUE DA BUSCA
  		$("#busca").focus(function () {
      		if ($(this).val() == "O que está procurando?") $(this).val("");
  		})
  		.blur(function(){
  			if ($(this).val() == "") $(this).val("O que está procurando?");
  		});
 	});

 	//Fancybox
	$("#mapa-localizacao").fancybox();
	
	  //Carregar Bairro de Acordo com a Cidade
  $("#cidade").change(function(event){
		$.get(root_path + 'index.php/painel/lista_bairros/'+$(this).val(),function(response) {
        eval(response); 
    });   
  });

  // Banner Topo 
		jQuery('#publicidadeTopo a').data('anima', true);
		var element = '#publicidadeTopo a';
		jQuery(element + ":first").show();
		var delay = false;
		var temp = setInterval(function() {
			if (delay == false && jQuery('#publicidadeTopo a').data('anima')) {
				rotate(element, 'next');
				jQuery('#publicidadeTopo').data('anima', true);
				var position = jQuery("#publicidadeTopo a:visible").index();
			}
			delay = false;
		},10000);
		function rotate(element, direction) {	
			if (direction == 'next') {
				if (jQuery(element + ':visible').next(element).size() > 0) {
					jQuery(element + ':visible').hide().next(element).fadeIn();
				} else {
					jQuery(element).hide().filter(":first").fadeIn();
				}
			} else if (direction == 'prev') {
				if (jQuery(element + ':visible').prev(element).size() > 0) {
					jQuery(element + ':visible').hide().prev(element).fadeIn();
				} else {
					jQuery(element).hide().filter(":last").fadeIn();
				}
			}
		}
  
  $(".menu-alterar").live('click',function(event){
    event.preventDefault();
    var form = $(this).closest('form.form-banners');
    $.ajax({
      type: "POST",
      url: $(this).attr("href"),
      dataType: "script",
		  data:form.serialize(),
      error: function() { 
        alert("Ocorreu um erro no processamento de sua solicitação. Por favor tente novamente mais tarde ou entre em contato.");
      }
    });
  });

  $(".menu-excluir").live('click',function(event){
    event.preventDefault();
    if (confirm("Confirma a exclusão?")) {
      $.ajax({
        type: "POST",
        cache: false,        
        url: $(this).attr("href"),
        dataType: "script",
        error: function() { 
          alert("Ocorreu um erro no processamento de sua solicitação. Por favor tente novamente mais tarde ou entre em contato.");
        }
      });
    }
  });

});

