/*global.js*/
$(document).ready(function(){
    //Somente se tiver botão de favoritos

//    var sufixo = '?urlanterior=' + encodeURIComponent(document.location.toString());
//    if(document.getElementById('topo_urlretorno')){
//        $('#topo_urlretorno').val($('#topo_urlretorno').val() + sufixo);
//    }
//    if(document.getElementById('topo_urlretorno2')){
//        $('#topo_urlretorno2').val($('#topo_urlretorno2').val() + sufixo);
//    }
    if(document.getElementById('botao_favorito_id')){
        $('#link_fav').click(function(){
            $.ajax({
                type: "GET",
                url: "ajax",
                dataType: "html",
                contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                cache: false,
                data: {
                    tipo:'sf',
                    t:$("#tipo").val(),
                    ia:$("#idAlvo").val()
                },
                success: function(msg){
                    if(msg == 'OK'){
                        var btn_fav = $('#btn_favorito');
                        var link_fav = $('#link_fav');
                        $('#msg_span').hide();
                            
                        if(btn_fav.attr('src') == 'img/estrela_amarela.gif'){
                            btn_fav.attr('src', 'img/estrela_azul.gif');
                            $('#msg_span').html('Removido!');
                            $('#msg_span').fadeIn(350, function(){
                                $('#msg_span').fadeOut(350, function(){
                                    $('#msg_span').html('Adicionar aos favoritos');
                                    $('#msg_span').fadeIn(350)
                                });
                            });
                            btn_fav.attr('alt', 'Adicione aos favoritos');
                            link_fav.attr('title', 'Adicione aos favoritos');
                        }else{
                            btn_fav.attr('src', 'img/estrela_amarela.gif');
                            $('#msg_span').html('Adicionado!');
                            $('#msg_span').fadeIn(350, function(){
                                $('#msg_span').fadeOut(350, function(){
                                    $('#msg_span').html('Remover dos favoritos');
                                    $('#msg_span').fadeIn(350)
                                });
                            });
                            btn_fav.attr('alt', 'Remova dos favoritos');
                            link_fav.attr('title', 'Remova dos favoritos');
                        }
                    }
                }
            });
            return false
        });
    }
    /**
    if(document.getElementById('mec')){
        $('.tooltip').tooltip({
            indexFinal  :   9000,
            fadeIn      :   400,
            fadeOut     :   200
        });

    }

    if(document.getElementById('minhas_aulas')){
        $('.tooltip').tooltip({
            indexFinal  :   9000,
            fadeIn      :   400,
            fadeOut     :   200,
            maxWidth    :   '300%'
        });
    }
    if(document.getElementById('barra-mec')){
        $('.tooltip').tooltip({
            indexFinal  :   9000,
            fadeIn      :   400,
            fadeOut     :   200,
            maxWidth    :   '300%'
        });

    }

   */


    /**
     *  Função para direcionar o usuário à página escolhida da barra do MEC
     *  @author - Anderson Koester
     */
    $('#gov_destaque').change(function(){
        if($(this).val() != '0'){
            window.open($(this).val());
        }
    })


    /** Função do evento de mudança do tamanho da pagina.
    * Utilizada nas paginações do portal.
    * @author Rafael Antunes Torquato Araujo
    */
    $("#tamanhoDaPagina").change(function(){
        $(this).parent().submit();
    });

    /** Função para alterar o tamanho da fonte.
     * Utilizada na acessibilidade do site.
     * @desc implantada a gravação dos dados de fonte em cookies
     * @var fonte - fonte atual do conteúdo
     * @author Anderson Koester
     */
    if(document.getElementById("breadcrumb")){
        var fonte;
        if($.cookie('fonte_site')){
            fonte = $.cookie('fonte_site');
            fonte = parseFloat(fonte);
            $(".conteudo").css({
                "font-size": fonte+"em"
            });
        }else{
            fonte = 1;
        }
        $("#amais").click(function(){
            if(fonte < 1.5){
                fonte = parseFloat(fonte);
                fonte = fonte+.1;
                $.cookie('fonte_site', fonte, {
                    expires: 30
                });
                $(".conteudo").css({
                    "font-size": fonte+"em"
                });
            }
            return false;
        })
        $("#amenos").click(function(){
            if(fonte > .8){
                fonte = parseFloat(fonte);
                fonte = fonte-.1;
                $.cookie('fonte_site', fonte, {
                    expires: 30
                });
                $(".conteudo").css({
                    "font-size": fonte+"em"
                });
            }
            return false;
        })
        $("#apadrao").click(function(){
            fonte = 1;
            $.cookie('fonte_site', fonte);
            $(".conteudo").css({
                "font-size": fonte+"em"
            });
            return false;
        })
    }
    /** Função para atalhos de teclado.
     * Utilizada na acessibilidade do site.
     * @author Anderson Koester
     */
    if(document.getElementById("mec")){
        $(".conteudo").shortkeys({
            'Alt+1' : function () {
                window.location = "#menu";
            },
            'Alt+2' : function () {
                window.location = "#conteudo"
            },
            'Alt+3' : function () {
                window.location = "index.html"
            }
        })
    }

    /** Função para visualizar os atalhos de teclado.
     * Utilizada na acessibilidade do site.
     * @author Anderson Koester
     */
    if(document.getElementById("global")){
        $("#atalhos").mouseover(function(){
            $("#lista_atalhos").show();
        })
        $("#atalhos").mouseout(function(){
            $("#lista_atalhos").hide();
        })
        $("#atalhos>a").focus(function(){
            $("#lista_atalhos").show();
        })
        $("#lista_atalhos").blur(function(){
            $(this).hide();
        })
    }


    /** Função para mudar a visibilidade do elemento .hidden.
     * Utilizada na seção Meu Perfil para alterar a imagem.
     * @author Anderson Koester
     */
    $('#link_perfil_trocar_imagem').mouseover(function(){
        $('.hidden').css('visibility', 'visible');
    });
    $('#link_perfil_trocar_imagem').mouseout(function(){
        $('.hidden').css('visibility', 'hidden');
    });
    /** Função do evento de mudança do tamanho da pagina.
     * Utilizada nas paginações do portal.
     * @author Rafael Antunes Torquato Araujo
     */
    $("#tamanhoDaPagina").change(function(){
        $(this).parent().submit();
    });
    /**
     * Função que adiciona um contador automático a cada elemento que estiver com a classe contador.<br />
     * O elemento deve seguir o seguinte padrão:<br/>
     * Deve ter a classe contador, ter um span dentro do seu label,
     * o label deve ser o elemento acima do elemento que irá ter seus tamanho verificado.
     * @author Rafael Antunes Torquato Araujo
     */
    $('.contador').each(function(){
        $(this).keyup(function(){
            max = $(this).attr("max");
            tamanhoCampo = $(this).val().length;
            //Retira do valor do elemento o que foi adicionado a mais que max
            if(tamanhoCampo > max){
                $(this).val($(this).val().substr(0, tamanhoCampo - (tamanhoCampo - max)));
            }
            //Se for menor que a quantidade máxima menos 1 aparece a obs no plural
            if(tamanhoCampo < (max - 1)){
                $(this).prev().find('span').html('Restam '+(max - tamanhoCampo)+' caracteres.');
            } else if(tamanhoCampo == (max - 1)){
                $(this).prev().find('span').html('Resta 1 caractere.');
            }else if(tamanhoCampo > (max - 1)){
                $(this).prev().find('span').html('Resta 0 caractere.');
            }

            if(tamanhoCampo == 0){
                $(this).prev().find('span').html('O campo deve conter até ' + max + ' caracteres.');
            }
        })
    })
    $('[rel*="externo"]').click(function(){
        window.open($(this).attr('href'));
        return false;
    });

    //Se for a página inicial.
    var href = document.location.href.toString();
    if(href.match('index.html') != null){
        dataAtual = new Date();
        //Se for dia do professor, independente do ano e se ainda não foi exibido.
        var eDiaProfessor = dataAtual.getMonth() == 9 && verificarDia(dataAtual.getDate());
        if(eDiaProfessor){
            $('#dataComemorativa').removeClass('oculto');
            $('#linkDataComemorativa').removeClass('oculto');
        }
    }

    $('.botao_remover').click(function() {
        return confirm("Deseja remover esta aula permanentemente?");
    });
    $('.botao_remover_equipe').click(function() {
        return confirm("Deseja remover esta equipe permanentemente?");
    });

});

function verificarDia(diaMes){
    if(diaMes == 15){
        return true;
    }else if(diaMes > 15 && diaMes < 21){
        return true;
    }
    return false;
}


function listarEstatisticaRecursoEmAulaPorLetra(letra) {

    if(letra == undefined || letra == null || letra == '') {
        $('#estatisticaRecursoPorAulaListarTodos').hide();
        $('.itemEstatisticaRecurso').show();
        $('.atual').removeClass('atual');
    } else {
        $('#estatisticaRecursoPorAulaListarTodos').show();
        $('.itemEstatisticaRecurso').hide();
        $('.letra'+letra.toString().toUpperCase()).show();
        $('.atual').removeClass('atual');
        $('.letraBotao'+letra.toString().toUpperCase()).addClass('atual');
    }
}


function getShareURL( socialNetwork ){
    //initialize
    var sharedURL   =   encodeURIComponent(window.location.href);
    var title       =   getMetaValue("title");
    var mainURL     =   "";

    switch( socialNetwork ) {
        case 'twitter':
            twitterURL  = "http://twitter.com/home?status=";
            mainURL     = twitterURL + title + " - " + sharedURL;
            break;

        case 'facebook':
            facebookURL = "http://www.facebook.com/sharer.php?";
            mainURL     = facebookURL +  "u=" + sharedURL;
            break;

        case 'orkut':
            var content = "";
            content = getMetaValue("description");
            orkutURL    = "http://promote.orkut.com/preview?nt=orkut.com&";
            mainURL     = orkutURL + "tt=" + title + "&cn=" + content + "&du=" + sharedURL;
            break;
    }
    return mainURL;
}

function abrirCompartilharSocialEmail(id, tipo) {
    var url = 'enviarEmailFormulario.html?id=' + id + '&tipo=' + tipo;
    w = 420;
    h = 130;
    Shadowbox.open({
        content:    url,
        player:     "iframe",
        options :   {
            initialHeight:300,
            initialWidth:100,
            //onClose: function(){alert('OnCloseEventListener')},
            //onOpen: function(){alert('OnOpenEventListener')},
            resize: false,
            viewportPadding: 1
        },
        height:     h,
        width:      w
    });
    return false;
}

function abrirCompartilharOrkut(){
    var title = $("title").text();
    var content = $("meta[http-equiv='description']").attr("content");
    var sharedURL 	=  encodeURIComponent(window.location.href);
    var paramsPopUp = 	'width=640, height=480, toolbar=no, scrollbars=yes, status=yes';
    var orkutURL 	= "http://promote.orkut.com/preview?nt=orkut.com&";
    var mainURL 	= orkutURL + "tt=" + encodeURI(title) + "&cn=" + encodeURIComponent(content) + "&du=" + sharedURL;
    var titlePopUp  = "Compartilhar no Orkut";
    if (window.navigator.appName == "Microsoft Internet Explorer"){
        titlePopUp='';
    }
    window.open(mainURL, titlePopUp , paramsPopUp);
}
