var target;

/* onFocus('this.id','http:/* '); */
function onFocus(name,valorF) {
    var id = document.getElementById(name);
    if (id.value == '')	{
        id.value = valorF;
    }
}

/* onBlur('this.id','http:/* '); */
function onBlur(name,valorF) {
    var id = document.getElementById(name);
    if (id.value == valorF) {
        id.value = '';
    }
}

var formatoData = 'yyyy-mm-dd';
var mensagemErro = "Campos em destaque contém valores inválidos ou sem preenchimento";
var mensagemErroEmail = "E-mail inválido";

/* Validacao de formulario de contato entre outros */
(function($) {
    $.fn.validate = function(args) {
        var options = $.extend({}, $.fn.validate.defaults, args);
        var jQ = $;
        return this.each(function() {
            jQ(this).submit(function() {
                var valid=true;
                var validEmail=true;
                jQ(this).find(".validate").each(function() {
                    el = jQ(this);
                    var filtro = false;
                    if('filtro_' == el[0].name.substr(0, 7)) {
                        filtro = true;
                    }
                    el[0].setAttribute("style", "color: #000000");
                    if(el.hasClass("email")) {
                        if(!valid_required(el.val())) {
                            add_error(el,filtro);
                            valid=false;
                        }else{
                            if(!valid_email(el.val())) {
                                add_error(el,filtro);
                                validEmail=false;
                                valid=false;
                            }
                        }
                    }
                    if(el.hasClass("date")) {
                        if(!valid_required(el.val())) {
                            add_error(el,filtro);
                            valid=false;
                        }else{
                            if(!valid_date(el.val(), formatoData)) {
                                add_error(el,filtro);
                                valid=false;
                            }
                        }
                    }
                    if(el.hasClass("number")) {
                        if(!valid_required(el.val())) {
                            add_error(el,filtro);
                            valid=false;
                        }else{
                            if(!valid_number(el.val())) {
                                add_error(el,filtro);
                                valid=false;
                            }
                        }
                    }
                    if(el.hasClass("required") && !el.hasClass("checkbox")) {
                        if(!valid_required(el.val())) {
                            add_error(el,filtro);
                            valid=false;
                        }else{
                            if(el.val() == el.prev("label").text()) {
                                add_error(el,filtro);
                                valid=false;
                            }
                        }
                    }
                    if(el.hasClass("checkbox") && el.hasClass("required")) {
                        if(el.is(':checked') == false){
                            add_error2("p"+el[0].id);
                            valid=false;
                        }else{
                            $("#p"+el[0].id).attr("style", "color:#FFFFFF");
                        }
                    }
                });
                if(valid == false) {
                    if(validEmail == false) {
                        $("#mensagem_erro").html(mensagemErroEmail);
                        $("#mensagem_erro").attr("style", "color:#FF0000; font-weight:bold; font-size:16px; display: block");
                    }else{
                        $("#mensagem_erro").html(mensagemErro);
                        $("#mensagem_erro").attr("style", "color:#FF0000; font-weight:bold; font-size:16px; display: block");
                    }
                    $('html, body').animate({
                        scrollTop: $("#content").offset().top
                    }, 1500);
                    document.location.hash="mensagem_erro";
                }
                return valid;
            });
        });
    };
    /* Destaca campo com erro */
    function add_error(el,filtro) {
        if(!filtro) {
            el[0].setAttribute("style", "border: 2px solid red !important; color: #FF0000 !important; -moz-border-radius: 3px 3px 3px 3px !important");
        }
    }
    /* Destaca campo com erro */
    function add_error2(id) {
        $("#"+id).attr("style", "color: #FF0000 !important; -moz-border-radius: 3px 3px 3px 3px !important");
    }
    function valid_email(email) {
        var email_pattern  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if(email.match(email_pattern)) return true;
        if(email == '') {
            return false;
        }
        return false;
    }
    function valid_number(number) {
        var number_pattern = /^([0-9\s])+$/;
        if(number.match(number_pattern)) {
            return true;
        }
        if(number == '') {
            return true;
        }
        return false;
    }
    function valid_required(val) {
        val = $.trim(val);
        if(val.length>0) {
            return true;
        }else{
            return false;
        }
    }
    function valid_date(date_passed, date_format) {
        var date_pattern = null;
        if(date_format == "m/d/Y") date_pattern  = /(0[1-9]|1[012])+\/(0[1-9]|[12][0-9]|3[01])+\/(19|20)\d\d/;
        if(date_format == "m-d-Y") date_pattern  = /(0[1-9]|1[012])+\/(0[1-9]|[12][0-9]|3[01])+\/(19|20)\d\d/;
        if(date_format == "d/m/Y") date_pattern  = /(0[1-9]|[12][0-9]|3[01])+\/(0[1-9]|1[012])+\/(19|20)\d\d/;
        if(date_format == "d-m-Y") date_pattern  = /(0[1-9]|[12][0-9]|3[01])+\/(0[1-9]|1[012])+\/(19|20)\d\d/;
        if(date_passed.match(date_pattern)) return true;
        if(date_passed == '') {
            return true;
        }
        return false;
    }
})($);

function slideShow() {
    //Set the opacity of all images to 0
    $('#gallery a').css({
        opacity: 0.0
    });
    //Get the first image and display it (set it to full opacity)
    $('#gallery a:first').css({
        opacity: 1.0
    });
    //Set the caption background to semi-transparent
    $('#gallery .caption').css({});
    //Resize the width of the caption according to the image width
    $('#gallery .caption').css({
        width: $('#gallery a').find('img').css('width')
    });
    //Get the caption of the first image from REL attribute and display it
    $('#gallery .content').html($('#gallery a:first').find('img').attr('rel'))
    .animate({
        opacity: 1.0
    }, 400);
    //Call the gallery function to run the slideshow, 6000 = change to next image after 6 seconds
    setInterval('gallery()',6000);
}
	
function gallery() {
    //if no IMGs have the show class, grab the first image
    var current = ($('#gallery a.show')?  $('#gallery a.show') : $('#gallery a:first'));
    //Get next image, if it reached the end of the slideshow, rotate it back to the first image
    var next = ((current.next().length) ? ((current.next().hasClass('caption'))? $('#gallery a:first') :current.next()) : $('#gallery a:first'));
    //Get next image caption
    var caption = next.find('img').attr('rel');
    //Set the fade in effect for the next image, show class has higher z-index
    next.css({
        opacity: 0.0
    })
    .addClass('show')
    .animate({
        opacity: 1.0
    }, 1000);
    //Hide the current image
    current.animate({
        opacity: 0.0
    }, 1000)
    .removeClass('show');
    //Set the opacity to 0 and height to 1px
    $('#gallery .caption').animate({
        opacity: 0.0
    }, {
        queue:false,
        duration:0
    }).animate({
        height: '1px'
    }, {
        queue:true,
        duration:300
    });
    //Animate the caption, opacity to 0.7 and heigth to 100px, a slide up effect
    $('#gallery .caption').animate({
        opacity: 1.0
    },400 ).animate({
        height: '100px'
    },500 );
    //Display the content
    $('#gallery .content').html(caption);
}	


/**
 * ENVIA VOTO PARA A ENQUETE
 */
function votaEnquete(formEnquete){
    var pk = 0;
    var urlPadrao = URL_BASE+"index/ajax.votaenquete";
    var form = document.getElementById(formEnquete);
    for(i=0;i<form.length;i++){
        if(form[i].type == 'radio'){
            if(form[i].checked == true)
                pk = form[i].value;
        }
    }
    $.post(urlPadrao, {
        'pk':pk,
        'enquete':document.getElementById('enqueteId').value
    }, function(data) {
        $("#opcoesEnquete").html(data);
        $("#opcoesEnquete").removeClass('enquete');
        $("#opcoesEnquete").addClass('enquete_result');
    });
}

/*
 * BUSCA ENQUETE ATIVA
 */
function buscaEnquete(){
    jQuery.post(URL_BASE+"index/ajax.buscaenquete", {
        }, function(data) {
            return $('#enquete').html(data);
        });
}

/*
 * LIMITA A QTDE DE CARACTERES EM UM TEXTAREA
 */
function maxLength(textAreaField, limit, show) {
    var ta = document.getElementById(textAreaField);
    document.getElementById(show).innerHTML='&nbsp;&nbsp;'+(limit-ta.value.length);
    if (ta.value.length > (limit-1)) {
        ta.value = ta.value.substring(0, limit);
        alert('O limite de caracteres foi excedido!');
    }
}

/*
 * CHAMA AS FUNCOES ESPECIFICAS PARA O SITE
 */
$(document).ready (function() {
    $("#menu ul").css("display" , "none");
    $("ul li a").click(function(){
        $(this).parent().find("ul").slideToggle("slow");
        $(this).parent().find('span').toggleClass('menos');
    });
    /* Abre links com rel="external" em outro janela do navegador */
    jQuery('a[rel=external]').attr('target','_blank');
    /* Fancybox galeria de fotos e videos */
    jQuery("ul.galeria a").fancybox({
        'transitionIn'	: 'none',
        'transitionOut'	: 'none',
        'titleShow'	: true
    });
    $("#sobre").keydown(function(){
        maxLength('sobre', 570, 'faltam');
    });
    $("#sobre").keyup(function(){
        maxLength('sobre', 570, 'faltam');
    });
});

function votaBanda(banda,micro)
{
    $('#banda_'+banda).html('<div class="voto_sucesso">Processando voto...</div>');
    jQuery.post(URL_BASE+"concurso-banda/ajax.votabanda", {
        'micro':micro,
        'banda':banda
    },function(data) {
        eval('data = '+data);
        if(data.ret == 'bandaErro'){
            //$('#banda_'+banda).html('<div class="voto_erro">Você já votou nesta banda!</div>');
            $('#banda_'+banda).html('<div class="voto_erro">Você já votou, obrigado pela sua participação!</div>');
            return false;
        }
        if(data.ret == 'bandaSuce'){
            $('#banda_'+banda).html('<div class="voto_sucesso">Voto computado com sucesso, obrigado pela sua participação!</div>');
            return false;
        }
        if(data.ret == 'microErro'){
            $('#banda_'+banda).html('<div class="voto_erro">Você já votou em uma banda desta microrregião!</div>');
            return false;
        }
    });
}

/**
 * Função que realiza a votação do concurso
 * @param pk
 */
function votacao(pk) {
    jQuery.post("/fa-na-faixa/ajaxvotacao", {
        'id' : pk
    }, function(data) {
        window.location.href='/fa-na-faixa/confirmavoto';
    });
}

/**
 * Função que envia o formulário de contato do site da parte Fan na faixa. 
 */
function enviaFormContato() {
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

    if ($('#nome_completo').val() == "") {
        alert('O campo nome é de preenchimento obrigatório.');
        $('#nome_completo').focus();
        $('#nome_completo').addClass('error');
    } else if ($('#email').val() == "") {
        alert('O campo e-mail é de preenchimento obrigatório.');
        $('#email').focus();
        $('#email').addClass('error');
    } else if(reg.test($('#email').val()) == false) {
        alert('Digite um e-mail válido.');
        $('#email').focus();
        $('#email').addClass('error');
    } else if ($('#assunto').val() == "") {
        alert('O campo assunto é de preenchimento obrigatório.');
        $('#assunto').focus();
        $('#assunto').addClass('error');
    } else if ($('#mensagem').val() == "") {
        alert('O campo mensagem é de preenchimento obrigatório.');
        $('#mensagem').focus();
        $('#mensagem').addClass('error');
    } else {
        // Submit do form.
        $('#form-contato').submit();
    }
	
}

/**
 * Função que envia o formulário de cadastro do site da parte Fan na faixa. 
 */
function enviaFormcadastro() {

    if ($('#nome').val() == "") {
        alert('O campo nome é de preenchimento obrigatório.');
        $('#nome').focus();
        $('#nome').addClass('error');
		
    } else if ($('#email').val() == "") {
        alert('O campo e-mail é de preenchimento obrigatório.');
        $('#email').focus();
        $('#email').addClass('error');
		
    } else if ($('#telefone').val() == "") {
        alert('O campo telefone é de preenchimento obrigatório.');
        $('#telefone').focus();
        $('#telefone').addClass('error');
		
    } else if ($('#cidade').val() == "") {
        alert('O campo cidade é de preenchimento obrigatório.');
        $('#cidade').focus();
        $('#cidade').addClass('error');
		
    } else if ($('#data_nascimento').val() == "") {
        alert('O campo data de nascimento é de preenchimento obrigatório.');
        $('#data_nascimento').focus();
        $('#data_nascimento').addClass('error');
		
    } else if (!$('#aceite').attr('checked')) {
        alert('Marque a opção aceitando o regulamento.');
        $('#aceite').addClass('error');

    } else if ($('#captcha').val() == "") {
        alert('O campo da imagem é de preenchimento obrigatório.');
        $('#captcha').focus();
        $('#captcha').addClass('error');
		
    } else {
		
        // Submit do form.
        $('#form-votacao').submit();

    }
	
}

/**
 * Função que envia o formulário de validação de votação do site da parte Fan na faixa. 
 */
function enviaFormValidacao() {
	
    if ($('#email').val() == "") {
        alert('O campo e-mail é de preenchimento obrigatório.');
        $('#email').focus();
        $('#email').addClass('error');
		
    } else {
		
        // Submit do form.
        $('#form-votacao').submit();

    }
	
}

/**
 * Função que envia o formulário de cadastro de fanclubes 
 */
function enviaFormFanClube() {
	
    if ($('#fanclube').val() == "") {
        alert('O campo Fã Clube é de preenchimento obrigatório.');
        $('#fanclube').focus();
        $('#fanclube').addClass('error');
		
    } else if ($('#email').val() == "") {
        alert('O campo E-mail é de preenchimento obrigatório.');
        $('#email').focus();
        $('#email').addClass('error');
		
    } else if ($('#banda').val() == "") {
        alert('O campo Fã Clube é de preenchimento obrigatório.');
        $('#banda').focus();
        $('#banda').addClass('error');
		
    } else if ($('#cidade-uf').val() == "") {
        alert('O campo Cidade é de preenchimento obrigatório.');
        $('#cidade-uf').focus();
        $('#cidade-uf').addClass('error');
		
    } else if ($('#orkut').val() == "") {
        alert('O campo Orkut é de preenchimento obrigatório.');
        $('#orkut').focus();
        $('#orkut').addClass('error');
		
    }

    //else if ($('#twitter').val() == "") {
    //    alert('O campo Twitter é de preenchimento obrigatório.');
    //    $('#twitter').focus();
    //    $('#twitter').addClass('error');
    //
    //    } else if ($('#youtube').val() == "") {
    //        alert('O campo You Tube é de preenchimento obrigatório.');
    //        $('#youtube').focus();
    //        $('#youtube').addClass('error');
    //
    //    }
    else {
		
        // Submit do form.
        $('#form-fanclube').submit();

    }
	
}
