/**
* @author tvasconcelos
*/
//Antes da renderizção do HTML
window.onunload = function () {

}

//Depois da renderização do HTML
$(document).ready(function () { 
    //if (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6) {
    //    DD_belatedPNG.fix('.png');
    //}

    $('#main table.tabela tbody tr:nth-child(even), #main .listagem ul li:nth-child(even)').addClass('alt');
    $('#main table.tabela tr > :last-child, #main #content .extratoResumido table tr:last-child').addClass('last');

    function ajuda() {
        $('.icoAjuda').hover(
			function () {$(this).append('<div class="ajuda png"><h3>Ajuda</h3><p>' + $(this).find('img').attr('alt') + '</p></div>');
			    $(this).find('.ajuda').show();
			},
			function () {
			    $(this).find('.ajuda').hide().remove();
			}
		);
    }
    ajuda();

    function abrirModal() {
        $('.openModal').click(function () {
            $('body').append('<div class="bgmodal"></div><div class="modal impressao"><iframe frameborder="0" scrolling="no" src="' + $(this).attr('href') + '"></iframe><a class="closeModal" href="#" title="Fechar">Fechar</a></div>');
            $(this).blur();
            return false;
        });
    }
    abrirModal();

    $('.closeModal,.bgmodal').live('click', function () {
        $('.modal,.bgmodal').hide();//.remove();
        return false;
    });

    $('a.media').media();
    if (Utils.objectExist('select'))
        $('select').jqf1();
    if (Utils.objectExist('input:checkbox'))
        $('input:checkbox').jqf1();
    if (Utils.objectExist('.scroll-pane'))
        $('.scroll-pane').jScrollPane({ showArrows: true, scrollbarWidth: 15 });

    if (Utils.objectExist('.calendar')) {
        $('.calendar').datepicker({
            showButtonPanel: true,
            closeText: 'Fechar',
            dayNamesMin: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'],
            monthNames: ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'],
            dateFormat: 'dd/mm/yy',
            onSelect: function (dateText, inst) {
                if ($(this).hasClass('fillSelects')) {
                    var array = dateText.split('/');
                    var day = Math.abs(array[0] - 1);
                    var month = Math.abs(array[1] - 1);
                    var year = array[2];
                    $(this).parent('li').find('.day').prev('div:first').find('ul li:eq(' + day + ') a').trigger('click');
                    $(this).parent('li').find('.month').prev('div:first').find('ul li:eq(' + month + ') a').trigger('click');
                    $(this).parent('li').find('.year').prev('div:first').find('ul li').each(function (index, object) {
                        value = $(object).find('span').text();
                        if (year == value) {
                            $(object).find('a').trigger('click');
                        }
                    });
                } else if ($(this).prev('input').length > 0) {
                    $(this).prev('input').val(dateText);
                }
            }
        });
    }


    if (Utils.objectExist('.accordion')) {
        if (Utils.objectExist('.shortSales .accordion')) {
            $('.shortSales .accordion ul li a').click(function () {
                $('.shortSales .accordion ul li div').slideUp();
                $('.shortSales .accordion ul li a').removeClass('less');
                $(this).addClass('less').next('div').slideDown();
                return false;
            });
        } else {
            var active = $('h3.active');
            index = $('.accordion h3').index(active);
            if (!Utils.objectExist('h4.active')) {
                if (index < 0)
                    index = 0;
            }
            $(".accordion").accordion({
                autoHeight: false,
                active: index,
                header: 'h3',
                changestart: function (event, ui) {
                    $(".accordion").find('.active').removeClass('active');
                }
            });
            $('.accordion h4').click(function () {
                $(".accordion").find('.active').removeClass('active')
                $(this).addClass('active')
            });
        }
    }

    if (Utils.objectExist('.carousel')) {
        $('.carousel').jcarousel({
            scroll: 4
        });
    }

    /*$('.submenu ul li').each(function(index,object){
    if($(this).text().length>20){
    $(this).addClass('lines');
    $(this).find('a').addClass('lines');
    }
    });*/

    $('input:text[title!=""]').focus(function () {
        var val = $(this).val();
        var title = $(this).attr('title');
        if (val.equals(title))
            $(this).val("");
    }).blur(function () {
        var title = $(this).attr('title');
        if (Utils.isNull($(this).val()))
            $(this).val(title);
    });

    try {
        Faq.init();
    } catch (e) { }

    try {
        Cancellation.init();
    } catch (e) { }

    try {
        Materials.init();
    } catch (e) { }

    $(".downloads tr:even").addClass("bg");

    function extratos() {
        $('input:radio', '.extrato .lista li>label').click(function () {
            $('.box', '.extrato').css('visibility', 'hidden');
            $(':input', '.extrato .box').val('').removeAttr('checked');
            $(this).parent().next('.box').css('visibility', 'visible');
        });
    }
    extratos();

    $('.btAdd a').click(function () {
        //var quantLabel = $('fieldset').find('.labelContagem').length()
        var label = $('#formTeste label.labelContagem').length + 1;
        $('fieldset .labelContagem:last').after('<label class="labelContagem">' + label + '- CPF/CNPJ:<br /> <input type="text" name="cpf_' + label + '" /><span>(Somente números)</span></label>').hide().slideDown();
        return false;
    })

    $('#ratePage').mouseover(function () {
        if (!Utils.objectExist('#frmRatePage')) {
            var form = $.create('form', { attributes: { id: 'frmRatePage'} }).appendTo('#footer .center');
            $.create('a', { attributes: { id: 'positive', href: '#' }, children: 'Gostei' }).appendTo(form);
            $.create('a', { attributes: { id: 'negative', href: '#' }, children: 'Não gostei' }).appendTo(form);
        }
        $(form).mouseleave(function () {
            $(this).remove();
        });
    });

    if (Utils.objectExist('div.vacancies')) {
        $('div.vacancies ul li a').click(function () {
            $('div.vacancies ul li div.descriptionVague').slideUp();
            $('div.vacancies ul li a').removeClass('less');
            $(this).addClass('less').next('div:first').slideDown();
            return false;
        });
    }

    if (Utils.objectExist('.bgmodal') && jQuery.browser.msie && parseInt(jQuery.browser.version) == 6) {
        var height = $('body').height();
        $('.bgmodal').height(height);
    }

    if (Utils.objectExist('.enquete .result')) {
        $('.enquete .result li span').each(function (index, object) {
            var percentage = $(object).text();
            $(object).html("&nbsp;");
            $(object).animate({
                width: Math.abs(percentage) + '%'
            }, 1500);
            $(object).after(percentage + '%');
        });
    }

    if (Utils.objectExist('ul.sf-menu')) {
        $("ul.sf-menu").superfish({
            pathClass: 'current',
            autoArrows: false
        });
        var wBody = $('body').width();
        var wMenu = $("ul.sf-menu").width();
        var calc = ((wBody - wMenu) / 2);
        $("ul.sf-menu li ul").css('left', calc + 'px');
        window.onresize = function () {
            var wBody = $('body').width();
            var wMenu = $("ul.sf-menu").width();
            var calc = ((wBody - wMenu) / 2);
            if (calc >= 0)
                $("ul.sf-menu li ul").css('left', calc + 'px');
        }
    }

    $('.checkAll,.checkNo').click(function () {
        if ($(this).hasClass('checkAll'))
            $(this).parents('div').find(':checkbox').attr('checked', 'checked');
        else if ($(this).hasClass('checkNo'))
            $(this).parents('div').find(':checkbox').removeAttr('checked');
        return false;
    });

    $('.addEmail').click(function () {
        var count = $(this).parent('div').find('input:hidden').val();
        var total = Math.abs(count) + 1;
        $(this).parent('div').find('input:hidden').val(total);
        $(this).prev().after('<input type=\"text\" name=\"email' + total + '\" value=\"\" />');
        return false;
    });

    $('a#changeAddress').click(function () {
        $(this).parents('form').find('fieldset').show().end().find('button').show().end().find('a.btnBlue').hide();
        return false;
    });

    $('.popup').click(function () {
        var url = $(this).attr('href');
        window.open(url, 'popup', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=510,height=470');
        return false;
    });
});

function calcularDimensoes() {
    $('.modal iframe', parent.document.body)
		.width($('.iframe #main').outerWidth())
		.height($('.iframe #main').outerHeight());

    $('.modal', parent.document.body).css({
        top: ($(parent.document).height() / 2) - $(this).height() / 2,
        left: ($(parent.window).width() / 2) - $(this).width() / 2
    })
}

$(document).ready(function () {
    $('.btnConsulta').click(function () {
        $(".respConsulta").show();
    });
});

//Mostra imagem selecionada na Image principal do Slide Show
function selecionaImagem(obj, msgTitulo, msgDescritivo)
{
    $("#SlideShow img:first").attr("src", $(obj).attr("src"));
    $("#Titulo").html('<strong>' + msgTitulo + ':</strong>&nbsp;' + $(obj).attr("alt"));
    $("#Descricao").html('<strong>' + msgDescritivo + ':</strong>&nbsp;' + $(obj).attr("description"));

    window.location.href = '#AncoraSlideShow';
}

var exibirInfoSom = true;
var exibirInfoVideo = true;

function somSelecionado(data, titulo, descricao, url)
{
    var tituloExibicaoSom = document.getElementById("tituloSomExibicao");

    var infoDataSom = document.getElementById("infoDataSom");
    var dataSomExibicao = document.getElementById("dataSomExibicao");
    var descritivoSomExibicao = document.getElementById("descritivoSomExibicao");
    var infoDescritivoSom = document.getElementById("infoDescritivoSom");
    var divDownloadSom = document.getElementById("divDownloadSom");

    if (exibirInfoSom) {
        tituloExibicaoSom.innerHTML = titulo;
        tituloExibicaoSom.style.display = '';

        infoDataSom.style.display = '';
        dataSomExibicao.innerHTML = data;

        infoDescritivoSom.style.display = ''
        descritivoSomExibicao.innerHTML = descricao;
        descritivoSomExibicao.style.display = '';
    }
    else {
        tituloExibicaoSom.innerHTML = '';
        tituloExibicaoSom.style.display = 'none';

        infoDataSom.style.display = 'none';
        dataSomExibicao.innerHTML = '';

        infoDescritivoSom.style.display = 'none';
        descritivoSomExibicao.innerHTML = '';
        descritivoSomExibicao.style.display = 'none';
    }

    $('#aDownloadSom').attr('href', url);
    divDownloadSom.style.display = '';

    /*jwplayer("player").setup
    (
        {
            flashplayer: $.fn.media.defaults.mp3Player, //internal player path
            file: url, //file location
            height: 62,
            width: 486,
            events:
            {
                onReady: function () { this.play(); }
            }
        }
    );*/

    /*
    var player = $('embedPlayer');
    player.attr('src', $.fn.media.defaults.mp3Player);
    player.attr('flashvars', url);
    //jwplayer('embedPlayer').play();
    jwplayer(player).play();

    var embedPlayer = document.getElementById('embedPlayer');
    embedPlayer.src = $.fn.media.defaults.mp3Player;
    embedPlayer.flashvars = "file=" + window.encodeURI(urlSom);
    jwplayer(embedPlayer).play();
    */
}

//Mostra detalhes da dica com base na dica selecionada
// a = ahref | b = div resumo | c = div detalhe
// altera também a exibição dos botões VEJA MAIS e VOLTAR
function ShowDica(a, b, c)
{
    if ($("#" + a + " span:eq(1)").css("display") == "none")
    {
        $("#" + a + " span:eq(0)").hide();
        $("#" + a + " span:eq(1)").show();
        $("#" + b).hide(1000);
        $("#" + c).show("slow");
    }
    else
    {
        $("#" + a + " span:eq(0)").show();
        $("#" + a + " span:eq(1)").hide();
        $("#" + b).show("slow");
        $("#" + c).hide(1000);
    }
}

//Mostra detalhes da dica com base na dica selecionada
// a = ahref | b = div resumo | c = div detalhe | c = DicaID
// altera também a exibição dos botões VEJA MAIS e VOLTAR
function ShowDicaExibicoes(a, b, c, d) {
    if ($("#" + a + " span:eq(1)").css("display") == "none") {
        $("#" + a + " span:eq(0)").hide();
        $("#" + a + " span:eq(1)").show();
        $("#" + b).hide(1000);
        $("#" + c).show("slow");
        $.post(window.location.href, { ClickID: d });
    }
    else {
        $("#" + a + " span:eq(0)").show();
        $("#" + a + " span:eq(1)").hide();
        $("#" + b).show("slow");
        $("#" + c).hide(1000);
    }
}

//Configurações iniciais de vídeo
$(document).ready(function ()
{
    if (exibirInfoVideo)
    {
        $("#tituloVideoExibicao").show();
        $("#infoDataVideo").show();
        $("#infoDescritivoVideo").show();
        $("#textoExibicao").show();
    }

    $("[id$=DataDeInicio]").setMask("date");
    $("[id$=DataDeFim]").setMask("date");
});

//Exibe informações do vídeo selecionado
function videoSelecionado(data, dataExt, titulo, descricao, url, exibicoes)
{
    if (exibirInfoVideo)
    {
        $("#tituloVideoExibicao").show();
        $("#tituloVideoExibicao").html(titulo);

        $("#infoDataVideo").show();
        $("#dataVideoExibicao").html(data);

        $("#infoDescritivoVideo").show();
        $("#descritivoVideoExibicao").html(descricao);

        $("#textoExibicao").show();
        $("#tituloResumoVideo").html(titulo);
        $("#dataResumoVideo").html(dataExt);
        $("#exibicoesVideo").html(exibicoes);
    }
    else
    {
        $("#tituloVideoExibicao").hide();
        $("#tituloVideoExibicao").html("");

        $("#infoDataVideo").hide();
        $("#dataVideoExibicao").html("");

        $("#infoDescritivoVideo").hide();
        $("#descritivoVideoExibicao").html("");

        $("#textoExibicao").hide();
        $("#tituloResumoVideo").html("");
        $("#dataResumoVideo").html("");
        $("#exibicoesVideo").html("");
    }
    
    /*$("[id$=playerFull]").media({
        width: 438,
        height: 322,
        src: url + "&autoplay=1&showinfo=0&fs=1&rel=0&showsearch=0",
        type: "swf"
    });*/

    $("#video").show();
    $("#movie").append("<object width='438' height='353'><param name='movie' value='" + url + "'></param><param name='allowFullScreen' value='true'></param><param name='allowscriptaccess' value='always'></param><embed src='" + url + "' type='application/x-shockwave-flash' allowscriptaccess='always' allowfullscreen='true' width='438' height='353'></embed></object>");

    document.location.href = "#ancoraReproducaoVideo";
}

//Ancora para páginas que contém o botão Topo
function GoAncora(ancora) {
    ancora = '#' + ancora;
    document.location.href = document.location.href.indexOf(ancora) > 0 ? document.location.href : '?' + ancora;
    return false;
}

function GoTop(sender) {
    sender.href = '#topo';
}

