$(document).ready(function() {
    if ($.browser.msie && ($.browser.version < 7)) { $("body").addClass("ie"); }
    $("div.youtube a[href^='http://www.youtube.com']").each(function() {
        $w = $(this).parent().width();
        $h = $(this).parent().height();
        $(this).flash({ width: $w, height: $h, wmode: 'opaque' }, { version: 9 },
	        function(htmlOptions) {
	            htmlOptions.src = $(this).attr('href');
	            $(this).html($.fn.flash.transform(htmlOptions));
	        }
	    ).removeAttr("href");
    });
    $(".formCadastro").each(function() {
        $(this).validate({ errorContainer: $(".mensagemError"), errorLabelContainer: $(".msgError"),
            submitHandler: function() {
                $.ajax({
                    type: 'POST',
                    data: $(".formCadastro").serialize(),
                    dataType: "json",
                    url: '/Site/CadastroDeAtividadePost.ashx',
                    success: function(json) {
                        if (json.msg == "OK") {
                            $(".sucessCadastro").fadeIn();
                            $(".form").fadeOut();
                        } else if (json.msg == "EXISTE") {
                            $(".msgExisteEmailCpf").fadeIn();
                        } else {
                            $(".msgError").fadeIn();
                        }
                    }
                });
            }
        });

    });

    $(".msgExisteEmailCpf").hide();
    if ($("#Id").val() != "") {
        $(".deslogado").hide();
        $(".logado").fadeIn();
    }

    $(".formDeslogado").validate({ errorContainer: $(".mensagemError"), errorLabelContainer: $(".msgError"),
        submitHandler: function() {
            $.ajax({
                type: 'POST',
                data: $(".formDeslogado").serialize(),
                dataType: "json",
                url: '/Site/ValidaLogin.ashx',
                success: function(json) {
                    if (json.msg == "OK") {
                        $(".deslogado").hide();
                        $(".logado").fadeIn();
                        window.location = "cadastroDeAtividade.aspx";
                    } else {
                        $(".msgError").fadeIn();
                        alert("Email e senha inexistente.");
                    }
                }
            });
        }
    });

    $(".formEsqueciSenha").validate({ errorContainer: $(".mensagemError"), errorLabelContainer: $(".msgError"),
        submitHandler: function() {
            $.ajax({
                type: 'POST',
                data: $(".formEsqueciSenha").serialize(),
                dataType: "json",
                url: '/Site/EnviaEmail.ashx',
                success: function(json) {
                    if (json.msg == "OK") {
                        $(".contentSenha").hide();
                        $(".sucessEsqueciSenha").fadeIn();
                    } else {
                        $(".msgError").fadeIn;
                    }
                }
            });
        }
    });

    $("a.esqueciSenha").click(function() {
        $(".deslogado").hide();
        $(".esqueciSenha").fadeIn();
    });

    $("a.btnFazerLogin").click(function() {
        $(".esqueciSenha").hide();
        $(".deslogado").fadeIn();
    });

    $("a.btnDeslogar").click(function() {
        $.ajax({
            cache: false,
            dataType: "json",
            url: '/Site/Logout.ashx',
            success: function(json) {
                if (json.msg == "OK") {
                    $(".logado").hide();
                    $(".deslogado").fadeIn();
                    window.location = "Index.aspx";
                }
            }
        });
    });


    $("textarea.maxlength").maxlength({
        'feedback': '.charsLeft small'
    });


    $(".dadosAtividade .item:last").each(function() {
        $number = $(this).find("input").attr("id").split("[")[1].split("]")[0];
    });

    $("a.btnAddAtividade").live("click", function() {
        $number++;
        $size = $(".dadosAtividade .item").size();
        $clone = $(".dadosAtividade .item:last").clone();
        $(".dadosAtividade").append($clone);
        $(".dadosAtividade .item:last").find("input, select, textarea").val("").removeClass("error");
        if ($size == 1) {
            //$(".dadosAtividade .item:last").prepend('<h3>Dados da Atividade</h3>');
        }
        $(".dadosAtividade .item:last").find("input, select, textarea").each(function() {
            $val = $(this).attr("name");
            $val = $val.replace(/([0-9+])/gi, $number);
            $(this).attr({ id: $val, name: $val });
            if ($size >= 1) {
                $(".dadosAtividade .item:last h3").html('Dados da Atividade ' + ($number + 1));
            }
        });

        $(".dadosAtividade .item:last").find("a.btnExcluir2").each(function() {
            $(this).attr("id", "");
        });
        $(".dadosAtividade .item:last").find("a.btnSalvar2").each(function() {
            $(this).attr("id", "");
        });

        $("textarea.maxlength").maxlength({
            'feedback': '.dadosAtividade .item:last .charsLeft small'
        });
        return false;
    });

    $(".dadosAtividade .item .btnExcluir, .dadosAtividade .item .btnExcluir2").live("click", function() {
        $size = $(".dadosAtividade .item").size();
        if ($size > 1) {

            $id = $(this).attr("id");

            $(this).parent().remove();


            if ($id != "") {
                $.ajax({
                    type: 'POST',
                    dataType: "json",
                    url: '/Site/DeletaAtividadePost.ashx?idAtividade=' + $id,
                    success: function(json) {
                        if (json.msg == "OK") {

                        } else {

                        }
                    }
                });
            }
        }
        return false;
    });

//função para salvar uma unica atividade *** INCOMPLETA ***
    /*$(".dadosAtividade .item .btnExcluir, .dadosAtividade .item .btnSalvar2").live("click", function() {
        $size = $(".dadosAtividade .item").size();
        if ($size > 1) {

            $id = $(this).attr("id");
            $num = $(this).attr("rel");
            
            if ($id != "") {
                $.ajax({
                    type: 'POST',
                    dataType: "json",
                    url: '/Site/SalvaAtividadePost.ashx?idAtividade=' + $id,
                    success: function(json) {
                        if (json.msg == "OK") {
                            alert("Atividade salva");
                        } else {

                        }
                    }
                });
            }
        }
        return false;
    });*/

    $("input.cpf").blur(function() {
        var cpf = $(this).val();
        exp = /\.|\-/g
        cpf = cpf.toString().replace(exp, "");
        if (cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999") {
            $(this).val("");
            alert('CPF Invalido!');
            return false;
        }
        add = 0;
        for (i = 0; i < 9; i++) {
            add += parseInt(cpf.charAt(i)) * (10 - i);
        }
        rev = 11 - (add % 11);

        if (rev == 10 || rev == 11)
            rev = 0;

        if (rev != parseInt(cpf.charAt(9))) {
            $(this).val("");
            alert('CPF Invalido!');
            return false;
        }
        add = 0;
        for (i = 0; i < 10; i++)
            add += parseInt(cpf.charAt(i)) * (11 - i);

        rev = 11 - (add % 11);
        if (rev == 10 || rev == 11)
            rev = 0;

        if (rev != parseInt(cpf.charAt(10))) {
            $(this).val("");
            alert('CPF Invalido!');
            return false;
        }
        return true;
    });

    /*Google Analytics*/
    $("a.btnComunidade").click(function() {
        pageTracker._trackPageview('/G1/semanaglobal.ning.com');
    });

    $("a.btnCadastreAtividade").click(function() {
        pageTracker._trackPageview('/CadastroAtividade_Home');
    });

    $("a.btnBuscar").click(function() {
        pageTracker._trackPageview('/Busca_Home');
    });

    $("a.btnCadastrarAtividade").click(function() {
        pageTracker._trackPageview('/CadastroAtividade_Agenda');
    });

    $("a.btnBuscar61x25").click(function() {
        pageTracker._trackPageview('/Busca_Agenda');
    });

    $("a.btnFiltrar").click(function() {
        pageTracker._trackPageview('/BuscaFiltro_Agenda');
    });

    $("a.first").click(function() {
        pageTracker._trackPageview('/Resultado_1');
    });

    $("a.prev").click(function() {
        pageTracker._trackPageview('/Resultado_Voltar');
    });

    $("a.next").click(function() {
        pageTracker._trackPageview('/Resultado_Ir');
    });

    $("a.last").click(function() {
        pageTracker._trackPageview('/Resultado_Ultimo');
    });

    $("a.btnExcluir").click(function() {
        pageTracker._trackPageview('/CadastroAtividade_Excluir');
    });

    $("a.btnAddAtividade").click(function() {
        pageTracker._trackPageview('/CadastroAtividade_Adicionar');
    });

    $("a.btnCadastrar").click(function() {
        pageTracker._trackPageview('/CadastroAtividade_Cadastrar');
    });

    $("a.btnInstitutoEndeavor").click(function() {
        pageTracker._trackPageview('/G1/endeavor.org.br');
    });

    $("a.btnTwitter").click(function() {
        pageTracker._trackPageview('/G1/twitter.com/endeavorbrasil');
    });

    $("a.btnBlog").click(function() {
        pageTracker._trackPageview('/G1/institutoendeavor.wordpress.com');
    });

    $("a.btnYoutube").click(function() {
        pageTracker._trackPageview('/G1/youtube.com/botaprafazer');
    });

    $("a.btnFlickr").click(function() {
        pageTracker._trackPageview('/G1/flickr.com/photos/endeavorbrasil');
    });

    $("a.btnBancoReal").click(function() {
        pageTracker._trackPageview('/G1/gruposantanderbrasil.com.br');
    });

    $("a.btnNatura").click(function() {
        pageTracker._trackPageview('/G1/natura.net');
    });

    $("a.btnSebrae").click(function() {
        pageTracker._trackPageview('/G1/sebrae.com.br');
    });

    $("a.btnMakeYour").click(function() {
        pageTracker._trackPageview('/G1/makeyourmark.org.uk');
    });

    $("a.btnKauffman").click(function() {
        pageTracker._trackPageview('/G1/kauffman.org');
    });

    $("a.btnCadastreAtividade206x33").click(function() {
        pageTracker._trackPageview('/comoParticipar_CadastroAtividade');
    });

    $("a.btnConhecaExemplos").click(function() {
        pageTracker._trackPageview('/comoParticipar_ConhecaSemana');
    });

    $("a.btnConfiraAgenda").click(function() {
        pageTracker._trackPageview('/comoParticipar_ConfiraAgenda');
    });

    $("a.btnMaisDepoimentos").click(function() {
        pageTracker._trackPageview('/comoParticipar_MaisDepoimentos');
    });

    $("a.btnParticipe").click(function() {
        pageTracker._trackPageview('/comoParticipar_Participe');
    });

    $("a.btnConhecaSemana").click(function() {
        pageTracker._trackPageview('/comoParticipar_Conheca_Semana');
    });

    $("input.ddd").mask("999");
    $("input.tel").mask("9999-9999");
    $("input.nasc").mask("99/99/9999");
    $("input.cpf").mask("999.999.999-99");
    $("input.cep").mask("99999-999");
    $("input.cnpj").mask("99.999.999/9999-99");
    $("input.hint").hint();
    $(".fix").ifixpng();
});

/* HINT */
/**
* @author Remy Sharp
* @url http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/
*/
(function ($) {

$.fn.hint = function (blurClass) {
  if (!blurClass) { 
    blurClass = 'blur';
  }
    
  return this.each(function () {
    // get jQuery version of 'this'
    var $input = $(this),
    
    // capture the rest of the variable to allow for reuse
      title = $input.attr('title'),
      $form = $(this.form),
      $win = $(window);

    function remove() {
      if ($input.val() === title && $input.hasClass(blurClass)) {
        $input.val('').removeClass(blurClass);
      }
    }

    // only apply logic if the element has the attribute
    if (title) { 
      // on blur, set value to title attr if text is blank
      $input.blur(function () {
        if (this.value === '') {
          $input.val(title).addClass(blurClass);
        }
      }).focus(remove).blur(); // now change all inputs to title
      
      // clear the pre-defined text when form is submitted
      $form.submit(remove);
      $win.unload(remove); // handles Firefox's autocomplete
    }
  });
};

})(jQuery);

/* HINT */


/*
 *
 * NOVO METODO PARA O JQUERY VALIDATE
 * VALIDA CNPJ COM 14 OU 15 DIGITOS
 * A VALIDAÇÃO É FEITA COM OU SEM OS CARACTERES SEPARADORES, PONTO, HIFEN, BARRA
 *
 * ESTE MÉTODO FOI ADAPTADO POR:
 * 
 * Shiguenori Suguiura Junior <junior@dothcom.net>
 * 
 * http://blog.shiguenori.com
 * http://www.dothcom.net
 * 
 */
jQuery.validator.addMethod("cnpj", function(cnpj, element) {
   // DEIXA APENAS OS NÚMEROS
   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;
      return true;
   }
   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;
      return true;
   }
}, "Informe um CNPJ válido."); // Mensagem padrão 
 