﻿function AreaConteudo(a,b,bs) {
    this.area = a;
    this.btn = b;
    this.btnSel = bs;
}

function TemplateSlider(a,s){
    this.area = a;
    this.slider = s;
    this.onMoveHandler = null;
    this.onMoveResultHandler = null;
    this.percOnMove = 0;
    this.lockByUser = false;
    
    if(a == null || s == null) { return; }
    
    this.horizontal = (parseInt(template.getStyle(a,'width')) > parseInt(template.getStyle(a, 'height')) ? true : false);
    this.max = parseInt( this.horizontal? template.getStyle(a, 'width') : template.getStyle(a, 'height') );
    
    if (!this.max) {
        this.max = 0;
    }
        
    //verifica as dimensões do slider
    this.difSlider = Math.floor(parseInt( this.horizontal? template.getStyle(s, 'width') : template.getStyle(s, 'height') )/2);
                

    //verifica a posição da área de slider referente ao iframe do visualizador
    this.posAreaX = parseInt(template.getStyle(a, 'left'));
    this.posAreaY = parseInt(template.getStyle(a, 'top'));

    var objPai = a.offsetParent;
    while(objPai != null) {
        if (objPai.style != null) {
            if(template.getStyle(objPai, 'left') != null && template.getStyle(objPai, 'left') != '' && parseInt(template.getStyle(objPai, 'left')) > 0 )
            { this.posAreaX += parseInt(template.getStyle(objPai, 'left')); }
            if(template.getStyle(objPai, 'top') != null && template.getStyle(objPai, 'top') != '' && parseInt(template.getStyle(objPai, 'top')) > 0 ) 
                { this.posAreaY += parseInt(template.getStyle(objPai, 'top')); }
        }
        trace(objPai.id + ' (' + objPai.type + ') -> Slider: ' + this.posAreaX +' x '+ this.posAreaY);
        
        objPai = objPai.offsetParent;
    }
}



var template = {

    SHOWING_VOLUME_TIME: 2000,

    document: null,
    body: null,
    webPath: '',

    TituloTransmissao: null,
    AreaVideo: null,
    BtnArrastarVideo: null,

    Legenda: null,
    RelogioVideo: null,
    Informacao: null,
    BtnTelaCheia: null,

    BtnMudo: null,
    BtnMudo_Sel: null,

    sliderAudio: null,
    sliderVideo: null,

    BtnPlay: null,
    BtnPlay_Sel: null,
    BtnAdiantar: null,
    BtnRetroceder: null,

    Banner_1: null,
    Banner_2: null,
    Banner_3: null,

    slides: null,
    arquivosAuxiliares: null,
    infoTransmissao: null,
    enquetes: null,
    ajuda: null,

    chat: null,
    Chat_Mensagens: null,
    Chat_Entrada: null,
    Chat_BtnEnviar: null,

    Multimidia_Area: null,

    interacaoMultimidia: null,
    indices: null,
    reverChat: null,

    anotacao: null,
    anotacoes_Entrada: null,
    anotacoes_Aviso: null,

    duvidas: null,
    Duvidas_Entrada: null,
    Duvidas_BtnEnviar: null,

    Credito_Area: null,
    Credito_Minutos: null,
    Credito_Acessos: null,

    configuracao: null,
    // Configuracao_Velocidade: null,

    agrupamentos: null,
    tabList: null,


    init: function () {

        trace('DEBUG: getting objects from iframe...');
        if (!template.getHTMLobjects()) { return false; }
        trace('getting objects from iframe...ok');

        trace('DEBUG: template visual activation...');
        template.visualActivation();
        trace('DEBUG: template visual activation...ok');

        trace('DEBUG: template content activation...');
        template.contentActivation();
        trace('DEBUG: template content activation...ok');

        trace('DEBUG: template function activation...');
        template.functionActivation();
        trace('DEBUG: template function activation...ok');

        return true;
    },


    // pega o estilo computado (prop) de um objeto
    getStyle: function (obj, prop) {
        return obj.currentStyle // cross browser thingy
		    ? obj.currentStyle[prop]
		    : template.document.defaultView.getComputedStyle(obj, null).getPropertyValue(prop);
    },


    getHTMLobjects: function () {

        try {
            template.document = visualizador.IframeTemplate.contentWindow.document;
            template.body = template.document.body;
        } catch (e) { return false; }

        template.agrupamentos = new Array();
        template.tabList = new Array();

        template.TituloTransmissao = template.document.getElementById('WebCasters_TituloTransmissao');
        template.AreaVideo = template.document.getElementById('WebCasters_AreaVideo');
        template.BtnArrastarVideo = template.document.getElementById('WebCasters_BtnArrastarVideo');

        template.Legenda = template.document.getElementById('WebCasters_Legenda');
        template.RelogioVideo = template.document.getElementById('WebCasters_RelogioVideo');
        template.Informacao = template.document.getElementById('WebCasters_Informacao');
        template.BtnTelaCheia = template.document.getElementById('WebCasters_BtnTelaCheia');

        template.BtnMudo = template.document.getElementById('WebCasters_BtnMudo');
        template.BtnMudo_Sel = template.document.getElementById('WebCasters_BtnMudo_Sel');

        template.sliderAudio = new TemplateSlider(template.document.getElementById('WebCasters_AreaSliderAudio')
                                                 , template.document.getElementById('WebCasters_SliderAudio'));

        template.sliderVideo = new TemplateSlider(template.document.getElementById('WebCasters_AreaSliderVideo')
                                                 , template.document.getElementById('WebCasters_SliderVideo'));

        template.BtnPlay = template.document.getElementById('WebCasters_BtnPlay');
        template.BtnPlay_Sel = template.document.getElementById('WebCasters_BtnPlay_Sel');

        template.BtnAdiantar = template.document.getElementById('WebCasters_BtnAdiantar');
        template.BtnRetroceder = template.document.getElementById('WebCasters_BtnRetroceder');

        template.Banner_1 = template.document.getElementById('WebCasters_Banner_1');
        template.Banner_2 = template.document.getElementById('WebCasters_Banner_2');
        template.Banner_3 = template.document.getElementById('WebCasters_Banner_3');

        template.slides = new AreaConteudo(template.document.getElementById('WebCasters_Slides_Area')
                                           , template.document.getElementById('WebCasters_Slides_Btn')
                                           , template.document.getElementById('WebCasters_Slides_Btn_Sel'));
        template.groupArea(template.slides);

        template.arquivosAuxiliares = new AreaConteudo(template.document.getElementById('WebCasters_ArquivosAuxiliares_Area')
                                                       , template.document.getElementById('WebCasters_ArquivosAuxiliares_Btn')
                                                       , template.document.getElementById('WebCasters_ArquivosAuxiliares_Btn_Sel'));
        template.groupArea(template.arquivosAuxiliares);

        template.infoTransmissao = new AreaConteudo(template.document.getElementById('WebCasters_InfoTransmissao_Area')
                                                   , template.document.getElementById('WebCasters_InfoTransmissao_Btn')
                                                   , template.document.getElementById('WebCasters_InfoTransmissao_Btn_Sel'));
        template.groupArea(template.infoTransmissao);

        template.enquetes = new AreaConteudo(template.document.getElementById('WebCasters_Enquetes_Area')
                                            , template.document.getElementById('WebCasters_Enquetes_Btn')
                                            , template.document.getElementById('WebCasters_Enquetes_Btn_Sel'));
        template.groupArea(template.enquetes);

        template.ajuda = new AreaConteudo(template.document.getElementById('WebCasters_Ajuda_Area')
                                            , template.document.getElementById('WebCasters_Ajuda_Btn')
                                            , template.document.getElementById('WebCasters_Ajuda_Btn_Sel'));
        template.groupArea(template.ajuda);

        template.Chat_Mensagens = template.document.getElementById('WebCasters_Chat_Mensagens');
        template.Chat_Entrada = template.document.getElementById('WebCasters_Chat_Entrada');
        template.Chat_BtnEnviar = template.document.getElementById('WebCasters_Chat_BtnEnviar');
        template.chat = new AreaConteudo(template.document.getElementById('WebCasters_Chat_Area')
                                        , template.document.getElementById('WebCasters_Chat_Btn')
                                        , template.document.getElementById('WebCasters_Chat_Btn_Sel'));
        template.groupArea(template.chat);


        template.Multimidia_Area = template.document.getElementById('WebCasters_InteracaoMultimidia_Area');

        template.interacaoMultimidia = new AreaConteudo(template.document.getElementById('WebCasters_InteracaoMultimidia_Area')
                                                        , template.document.getElementById('WebCasters_InteracaoMultimidia_Btn')
                                                        , template.document.getElementById('WebCasters_InteracaoMultimidia_Btn_Sel'));
        template.groupArea(template.interacaoMultimidia);


        template.indices = new AreaConteudo(template.document.getElementById('WebCasters_Indices_Area')
                                            , template.document.getElementById('WebCasters_Indices_Btn')
                                            , template.document.getElementById('WebCasters_Indices_Btn_Sel'));
        template.groupArea(template.indices);

        template.reverChat = new AreaConteudo(template.document.getElementById('WebCasters_ReverChat_Area')
                                             , template.document.getElementById('WebCasters_ReverChat_Btn')
                                             , template.document.getElementById('WebCasters_ReverChat_Btn_Sel'));
        template.groupArea(template.reverChat);

        template.anotacoes_Entrada = template.document.getElementById('WebCasters_Anotacoes_Entrada');
        template.anotacoes_Aviso = template.document.getElementById('WebCasters_Anotacoes_Aviso');
        template.anotacao = new AreaConteudo(template.document.getElementById('WebCasters_Anotacoes_Area')
                                             , template.document.getElementById('WebCasters_Anotacoes_Btn')
                                             , template.document.getElementById('WebCasters_Anotacoes_Btn_Sel'));
        template.groupArea(template.anotacao);

        template.Duvidas_Entrada = template.document.getElementById('WebCasters_Duvidas_Entrada');
        template.Duvidas_BtnEnviar = template.document.getElementById('WebCasters_Duvidas_BtnEnviar');
        template.duvidas = new AreaConteudo(template.document.getElementById('WebCasters_Duvidas_Area')
                                           , template.document.getElementById('WebCasters_Duvidas_Btn')
                                           , template.document.getElementById('WebCasters_Duvidas_Btn_Sel'));
        template.groupArea(template.duvidas);

        template.Credito_Area = template.document.getElementById('WebCasters_Credito_Area');
        template.Credito_Minutos = template.document.getElementById('WebCasters_Credito_Minutos');
        template.Credito_Acessos = template.document.getElementById('WebCasters_Credito_Acessos');

        // template.Configuracao_Velocidade = template.document.getElementById('WebCasters_Configuracao_Velocidade');
        // template.configuracao = new AreaConteudo(template.document.getElementById('WebCasters_Configuracao_Area')
        //                                        , template.document.getElementById('WebCasters_Configuracao_Btn')
        //                                        , template.document.getElementById('WebCasters_Configuracao_Btn_Sel'));
        // template.groupArea(template.configuracao);
        template.configuracao = template.document.getElementById('WebCasters_Configuracao_Btn');

        try {
            template.document.getElementById('WebCasters_Configuracao_Btn_Sel').style.display = "none";
            template.document.getElementById('WebCasters_Configuracao_Area').style.display = "none";
        } catch (e) { }



        return true;
    },

    groupArea: function (ac) {
        template.tabList.push(ac);
        if ((ac.area != null) && (ac.area.getAttribute('agrupamento') != null)) {

            var n = ac.area.getAttribute('agrupamento');
            //se ainda não existir esse agrupamento, adiciona ele na matriz como uma array
            if (template.agrupamentos[n] == null) { template.agrupamentos[n] = new Array(); }
            //agrupa a área de conteúdo na última posição do grupo
            template.agrupamentos[n].push(ac);
            trace(n + ' : ' + ac.area.id);

        }
    },

    visualActivation: function () {
        //título da janela
        if (template.document.title.trim() != '') {
            document.title = template.document.title;
            trace('using template\'s window title');
        }
        else {
            document.title = visualizador.Cliente.Nome;
            //document.title = visualizador.Cliente.Nome + " - " + visualizador.Transmissao.Nome;
            trace('using client\'s name as title');
        }

        //Dimensão do visualizador
        var screenh = parseInt(template.getStyle(template.body, 'height'));
        var screenw = parseInt(template.getStyle(template.body, 'width'));

        if ((screenh > 0) && (screenw > 0)) {

            ResizeToInner(screenw, screenh);

            visualizador.IframeTemplate.style.width = screenw + 'px';
            visualizador.IframeTemplate.style.height = screenh + 'px';

            config.setScreenSize(screenw + 'px', screenh + 'px');

            trace('resize browser to ' + screenw + 'px X ' + screenh + 'px');
        } else {

            visualizador.IframeTemplate.style.width = '100%';
            visualizador.IframeTemplate.style.height = '100%';

            config.setScreenSize('100%', '100%');

            trace('resize browser to 100% X 100%');
        }

        //cor de fundo
        template.body.style.backgroundColor = visualizador.PadraoTransmissao.CorFundo;
        trace('using transmission\'s default backgroundColor');

        //imagem de fundo
        if ((template.getStyle(template.body, 'backgroundImage') == '' ||
           template.getStyle(template.body, 'backgroundImage') == 'none' ||
           template.getStyle(template.body, 'backgroundImage') == null)
           && visualizador.PadraoTransmissao.ArquivoFundo != '') {

            template.body.style.backgroundImage = 'url(' + visualizador.PadraoTransmissao.ArquivoFundo + ')';

        }

        if ((template.getStyle(template.body, 'backgroundRepeat') == '' ||
           template.getStyle(template.body, 'backgroundRepeat') == 'none' ||
           template.getStyle(template.body, 'backgroundRepeat') == null)) {
            template.body.style.backgroundRepeat = 'repeat';

        }


        // copia as perfumarias do corpo do tamplate para a página externa
        document.body.style.backgroundColor = template.body.style.backgroundColor;
        document.body.style.backgroundImage = template.body.style.backgroundImage;
        document.body.style.backgroundRepeat = template.body.style.backgroundRepeat;


        //título da transmissão
        if (template.TituloTransmissao != null) {
            template.TituloTransmissao.innerHTML = visualizador.Transmissao.Nome.htmlEncode();
            template.TituloTransmissao.style.color = visualizador.PadraoTransmissao.CorTitulo;
        }

        //posicionamento do vídeo
        if (template.AreaVideo != null &&
           template.getStyle(template.AreaVideo, 'visibility') != 'hidden' &&
           template.getStyle(template.AreaVideo, 'display') != 'none') {

            wcplayer.move(parseInt(template.getStyle(template.AreaVideo, 'left')),
                          parseInt(template.getStyle(template.AreaVideo, 'top')));

            wcplayer.resize(parseInt(template.getStyle(template.AreaVideo, 'width')),
                            parseInt(template.getStyle(template.AreaVideo, 'height')));
        }
        else { trace('Area Video hidden or not found'); wcplayer.resize(0, 0); }

        //legenda atual
        template.setLegenda(visualizador.Transmissao.LegendaAtual);

        if (template.Legenda != null) {

            trace('legenda original color: "' + template.getStyle(template.Legenda, 'color') + '"');

            if (template.getStyle(template.Legenda, 'color') == '') {

                template.Legenda.style.color = visualizador.PadraoTransmissao.CorLegenda;

                trace('legenda new color: "' + template.getStyle(template.Legenda, 'color') + '" (' + visualizador.PadraoTransmissao.CorLegenda + ')');
            }
        }





        //informação
        template.setInformacao('');

        //relógio 
        template.setRelogioVideo();


        //banners
        template.loadBanner(template.Banner_1,
                            visualizador.PadraoTransmissao.ArquivoBanner1,
                            visualizador.PadraoTransmissao.LinkBanner1);
        template.loadBanner(template.Banner_2,
                            visualizador.PadraoTransmissao.ArquivoBanner2,
                            visualizador.PadraoTransmissao.LinkBanner2);
        template.loadBanner(template.Banner_3,
                            visualizador.PadraoTransmissao.ArquivoBanner3,
                            visualizador.PadraoTransmissao.LinkBanner3);

        //slider de audio                    
        template.visualPositionSlider(wcplayer.volume(), template.sliderAudio);

        //slider de video
        template.visualPositionSlider(wcplayer.current(), template.sliderVideo);

        template.checkControlsVisibility();
    },

    controlsVisibility: true,

    checkControlsVisibility: function () {
        var visibility = template.controlsVisibility ? 'visible' : 'hidden';

        SetVisibilityIfExists(template.BtnPlay, visibility);
        SetVisibilityIfExists(template.BtnPlay_Sel, visibility);
        SetVisibilityIfExists(template.BtnAdiantar, visibility);
        SetVisibilityIfExists(template.BtnRetroceder, visibility);

        SetVisibilityIfExists(template.RelogioVideo, visibility);

        SetVisibilityIfExists(template.BtnMudo, visibility);
        SetVisibilityIfExists(template.BtnMudo_Sel, visibility);

        SetVisibilityIfExists(template.BtnTelaCheia, visibility);

        if (template.sliderAudio != null) {
            SetVisibilityIfExists(template.sliderAudio.area, visibility);
        }

        if (template.sliderVideo != null) {
            SetVisibilityIfExists(template.sliderVideo.area, visibility);
        }

    },

    contentActivation: function () {
        if (template.ajuda.area != null && template.ajuda.area.innerHTML.trim().length == 0) {
            template.ajuda.area.innerHTML = visualizador.getHTMLAjuda();
        }

        if (template.arquivosAuxiliares.area != null) {
            template.arquivosAuxiliares.area.innerHTML = visualizador.getHTMLArquivosAuxiliares();
        }

        template.infoTransmissaoClick();

        template.loadSlide();

        template.loadUserCredit();

        template.loadIndices();

    },



    loadUserCredit: function () {
        var minuto = 0;
        var acesso = 0;

        if (visualizador.Credito != null) {
            minuto = visualizador.Transmissao.AoVivo ? visualizador.Credito.MinutosAoVivo : visualizador.Credito.MinutosOnDemand;
            acesso = visualizador.Transmissao.AoVivo ? visualizador.Credito.QtdAcessosAoVivo : visualizador.Credito.QtdAcessosOnDemand;
        }

        if (minuto > 60) {
            var mn = minuto % 60;
            var hr = Math.floor(minuto / 60);

            hr = (hr < 10) ? '0' + hr : '' + hr;
            mn = (mn < 10) ? '0' + mn : '' + mn;

            minuto = hr + ':' + mn;
        }

        if (template.Credito_Minutos != null) { template.Credito_Minutos.innerHTML = minuto + ''; }
        if (template.Credito_Acessos != null) { template.Credito_Acessos.innerHTML = acesso + ''; }
    },

    loadSlide: function () {

        if (template.slides.area == null) { return; }

        if (visualizador.Transmissao.SlideAtual == '') {
            template.slides.area.innerHTML = '<br/><br/><br/><center><b>Aguarde slides...</b></center>';
        }
        else {
            template.loadErrorSlideCount = 0;

            var html = '<img src="' + visualizador.Transmissao.SlideAtual + '" ';
            html += ' width=100% height=100% ';
            //html += ' onclick=window.open("'+ visualizador.Transmissao.SlideAtual +'","_blank"); ';
            html += ' oncontextmenu="return false;" ';
            html += ' onerror=parent.template.loadErrorSlide(); ';
            //html += ' style=cursor:pointer; ';
            html += ' />';

            template.slides.area.innerHTML = html;
        }
    },

    loadErrorSlideCount: 0,

    loadErrorSlide: function () {

        trace('load slide error: ' + visualizador.Transmissao.SlideAtual);

        var oldPath = visualizador.pathSlidesList[visualizador.idxPathSlides];
        visualizador.idxPathSlides++;
        if (visualizador.idxPathSlides == visualizador.pathSlidesList.length) { visualizador.idxPathSlides = 0; }
        var newPath = visualizador.pathSlidesList[visualizador.idxPathSlides];

        template.loadErrorSlideCount++;
        if (template.loadErrorSlideCount == visualizador.pathSlidesList.length) {
            template.slides.area.innerHTML = '<br/><br/><br/><center><b>Não foi possível carregar esse slide.</b></center>';
        } else {
            visualizador.Transmissao.SlideAtual = visualizador.Transmissao.SlideAtual.replace(oldPath, newPath);

            var html = '<img src="' + visualizador.Transmissao.SlideAtual + '" ';
            html += ' width=100% height=100% ';
            html += ' onclick=window.open("' + visualizador.Transmissao.SlideAtual + '","_blank"); ';
            html += ' onerror=parent.template.loadErrorSlide(); ';
            html += ' style=cursor:pointer; />';

            template.slides.area.innerHTML = html;
        }
    },

    tabAddEvent: function (ac) {
        if (ac.btn != null)
        { simpleAddEvent(ac.btn, 'click', function () { template.btnClick(ac); }); }
        if (ac.btnSel != null)
        { simpleAddEvent(ac.btnSel, 'click', function () { template.btnSelClick(ac); }); }
    },

    functionActivation: function () {
        trace('adding events to tabs');
        template.tabAddEvent(template.slides);
        template.tabAddEvent(template.arquivosAuxiliares);
        template.tabAddEvent(template.infoTransmissao);
        template.tabAddEvent(template.enquetes);
        template.tabAddEvent(template.ajuda);
        template.tabAddEvent(template.chat);
        template.tabAddEvent(template.interacaoMultimidia);
        template.tabAddEvent(template.indices);
        template.tabAddEvent(template.anotacao);
        template.tabAddEvent(template.reverChat);
        template.tabAddEvent(template.duvidas);
        // template.tabAddEvent(template.configuracao);

        if (template.configuracao != null) {
            simpleAddEvent(template.configuracao, 'click', config.show);
        }

        //arruma o estado inicial - desseleciona todos que não estão agrupados e seleciona o primeiro de cada grupo
        var grpSel = new Array();
        for (var i = 0; i < template.tabList.length; i++) {

            var ac = template.tabList[i];

            if (ac.area != null) {

                var tstate = visualizador.lstTabsState[ac.area.id];
                if (tstate == null) {

                    var n = ac.area.getAttribute('agrupamento')
                    if (n == null) { template.btnSelClick(ac); }
                    else {
                        if (!grpSel.contains(n)) {
                            template.btnClick(ac);
                            grpSel.push(n);
                        }
                    }

                } else {
                    if (tstate) { template.btnClick(ac); }
                    else { template.btnSelClick(ac); }
                }
            }
        }

        //Seleciona as abas que o template define como selecionadas
        for (var i = 0; i < template.tabList.length; i++) {
            var ac = template.tabList[i];
            if (ac.area != null && ac.area.getAttribute('selecionado') != null) { template.btnClick(ac); }
        }

        if (visualizador.Transmissao.TipoChat == 0) { template.disableTab(template.chat); }

        if (visualizador.Transmissao.AoVivo) {
            template.ativarChat();

        } else {
            template.verificaChatOD();

        }

        if (template.anotacoes_Entrada != null) {
            anotacao.ativarInterface(template.anotacoes_Entrada, template.anotacoes_Aviso);
        }

        // ativa a lista de enquetes
        if (template.enquetes.area != null) {
            gerenciadorEnquete.ativarInterface(template.enquetes.area, template.enquetes.area.getAttribute('listaTodasEnquetes') != null);
        }

        if (!visualizador.Transmissao.HabilitaInteracaoMultimidia) { template.disableTab(template.interacaoMultimidia); }

        if (!visualizador.Transmissao.HabilitaReverChat) { template.disableTab(template.reverChat); }

        if (template.Credito_Area != null) {
            if (visualizador.Transmissao.ConsumirMinutosPacotes) { template.Credito_Area.style.visibility = 'visible'; }
            else { template.Credito_Area.style.visibility = 'hidden'; }
        }

        if (template.sliderAudio != null) {
            template.sliderAddFunction(template.sliderAudio, template.sliderAudioUserMove, null);
        }
        if (template.sliderVideo != null) {
            template.sliderAddFunction(template.sliderVideo, template.sliderVideoUserMove, template.sliderVideoUserResult);
        }

        if (template.BtnMudo != null) {
            simpleAddEvent(template.BtnMudo, 'click',
                function () {
                    trace('template.BtnMudo.onClick()');
                    template.muteOnClick();
                }
            );
        }
        if (template.BtnMudo_Sel != null) {
            simpleAddEvent(template.BtnMudo_Sel, 'click',
                function () {
                    trace('template.BtnMudo_Sel.onClick()');
                    template.muteOffClick();
                }
            );
        }

        if (wcplayer.mute()) { template.muteOnClick(); }
        else { template.muteOffClick(); }

        if (template.BtnTelaCheia != null) {
            simpleAddEvent(template.BtnTelaCheia, 'click',
                function () {
                    trace('template.BtnTelaCheia.onClick()');
                    template.telaCheiaClick();
                }
            );
        }

        if (template.BtnArrastarVideo != null) {
            template.BtnArrastarVideo.style.zIndex = '2147483647';
            simpleAddEvent(template.BtnArrastarVideo, 'mousedown', template.onMouseDownVideoMove);
            simpleAddEvent(template.BtnArrastarVideo, 'mousedown', function () { return false; });
            simpleAddEvent(template.BtnArrastarVideo, 'selectstart', function () { return false; });
        }

        if (template.BtnPlay != null) {
            simpleAddEvent(template.BtnPlay, 'click',
                function () {
                    trace('template.BtnPlay.onClick()');
                    wcplayer.play();
                }
            );
        }

        if (template.BtnPlay_Sel != null) {
            simpleAddEvent(template.BtnPlay_Sel, 'click',
                function () {
                    if (visualizador.Transmissao.AoVivo) {
                        trace('template.BtnPlay_Sel.onClick(stop)');
                        wcplayer.stop();
                    } else {
                        trace('template.BtnPlay_Sel.onClick(pause)');
                        wcplayer.pause();
                    }
                }
            );
        }

        if (template.BtnAdiantar != null) {
            simpleAddEvent(template.BtnAdiantar, 'click',
                function () {
                    trace('template.BtnAdiantar.onClick()');
                    wcplayer.current(wcplayer.current() + 60000);
                }
            );
        }

        if (template.BtnRetroceder != null) {
            simpleAddEvent(template.BtnRetroceder, 'click',
                function () {
                    trace('template.BtnRetroceder.onClick()');
                    wcplayer.current(wcplayer.current() - 60000);
                }
            );
        }

        if (template.Duvidas_BtnEnviar != null) {
            simpleAddEvent(template.Duvidas_BtnEnviar, 'click',
                function () {
                    trace('template.Duvidas_BtnEnviar.onClick()');
                    template.enviarDuvidaClick();
                }
            );
        }

        template.btnPlayVisualState();
    },

    ChatOdDisponivel: false,

    verificaChatOD: function () {

        if (template.reverChat.area == null && template.Chat_Mensagens != null) {

            trace("chat.verificaChatOD - disponível.");
            template.ChatOdDisponivel = true; // chat OD Habilitavel

            template.ativarChat();
            return;
        }

        if (template.reverChat.area != null && template.Chat_Mensagens != null) {
            // aqui, está cagado
            trace("chat.verificaChatOD - ERRO: O template tem tanto rever chat, quanto chat.");
            // nada será feito
            template.ChatOdDisponivel = false;
            return;
        }

        trace("chat.verificaChatOD - indisponível.");

        template.ChatOdDisponivel = false;
        // aqui, o template não tem chat OD, mas tem ReverChat
        chat.ativarInterface(template.reverChat.area, null, null);


    },

    ativarChat: function () {

        chat.ativarInterface(template.Chat_Mensagens, template.Chat_Entrada, template.Chat_BtnEnviar);
        multimidia.ativarInterface(template.Multimidia_Area);

        if (template.Chat_Entrada != null) {
            simpleAddEvent(template.Chat_Entrada, 'keyup', template.onKeyUpChatEntrada);
        }

    },

    enviarDuvidaClick: function () {

        if (template.Duvidas_Entrada == null || template.Duvidas_Entrada.value == null) { return; }

        var txt = template.Duvidas_Entrada.value.trim();

        if (template.Duvidas_Entrada.value == 'Enviada com Sucesso!') { return; }

        if (txt.length < 5) {
            alert('Digite uma questão com no mínimo 5 caracteres');
            template.Duvidas_Entrada.focus();
            return;
        }

        var res = verificaSessao(WCAjax.Duvidas_EnviaDuvida(visualizador.Transmissao.Codigo, txt));

        if (res) { template.Duvidas_Entrada.value = 'Enviada com Sucesso!'; }
        else { alert('Ocorreu um problema ao enviar a sua mensagem. Esta transmissão pode estar configurada para não receber mensagens.'); }

    },

    onKeyUpChatEntrada: function () {

        if (template.Chat_Entrada == null) { return; }

        if (template.Chat_Entrada.value.length > 500) {

            template.Chat_Entrada.value = template.Chat_Entrada.value.substr(0, 500);
        }
    },

    btnPlayVisualState: function () {

        var notPlaying = !(wcplayer.CurrentState() == wcplayer.WM_STATE_STOPPED
                            || wcplayer.CurrentState() == wcplayer.WM_STATE_PAUSED
                            || wcplayer.CurrentState() == wcplayer.WM_STATE_CLOSED);

        if (template.controlsVisibility == false) {
            return;
        }

        if (template.BtnPlay != null) { template.BtnPlay.style.visibility = (notPlaying ? 'hidden' : 'visible'); }
        if (template.BtnPlay_Sel != null) { template.BtnPlay_Sel.style.visibility = (notPlaying ? 'visible' : 'hidden'); }

    },

    telaCheiaClick: function () { wcplayer.fullscreen(); },

    palestranteClick: function (cod) {
        if (template.infoTransmissao.area != null) {
            template.infoTransmissao.area.innerHTML = visualizador.getHTMLPalestrante(cod);
        }
    },

    infoTransmissaoClick: function () {
        if (template.infoTransmissao.area != null) {
            template.infoTransmissao.area.innerHTML = visualizador.getHTMLInfoTransmissao();
        }
    },



    muteOnClick: function () {
        wcplayer.mute(true);
        template.setInformacao('mudo', template.SHOWING_VOLUME_TIME);

        if (template.controlsVisibility == false) {
            return;
        }

        SetVisibilityIfExists(template.BtnMudo_Sel, 'visible');
        SetVisibilityIfExists(template.BtnMudo, 'hidden');
    },

    muteOffClick: function () {

        wcplayer.mute(false);
        template.setInformacao('volume: ' + wcplayer.volume() + '%', template.SHOWING_VOLUME_TIME);

        if (template.controlsVisibility == false) {
            return;
        }

        SetVisibilityIfExists(template.BtnMudo_Sel, 'hidden');
        SetVisibilityIfExists(template.BtnMudo, 'visible');
    },




    sliderAddFunction: function (st, handler, rhandler) {
        if (st.area != null && st.slider != null) {
            st.onMoveHandler = handler;
            st.onMoveResultHandler = rhandler;

            simpleAddEvent(st.area, 'click', function (event) { template.onSliderClick(event, st); });
            simpleAddEvent(st.slider, 'mousedown', function () { template.onMouseDownSlider(st); });
            simpleAddEvent(st.slider, 'mousedown', function () { return false; });
            simpleAddEvent(st.slider, 'selectstart', function () { return false; });
        }
    },

    onMouseDownVideoMove: function (event) {
        trace('onMouseDownArrastarVideo()');

        template.BtnArrastarVideo.difPosMouseX = event.clientX - parseInt(template.getStyle(template.BtnArrastarVideo, 'left'));
        template.BtnArrastarVideo.difPosMouseY = event.clientY - parseInt(template.getStyle(template.BtnArrastarVideo, 'top'));

        simpleAddEvent(template.document, 'mousemove', template.mainDragVideoMoveHandler);
        simpleAddEvent(template.document, 'mouseup', template.stopDragVideoMoveHandler);
    },

    onSliderClick: function (event, st) {
        template._ActualSliderTemplate = st;
        template.sliderHandlerMove(st, event);
        if (typeof st.onMoveResultHandler == 'function') {
            st.onMoveResultHandler();
        }
        template._ActualSliderTemplate = null;
    },

    onMouseDownSlider: function (st) {
        trace('onMouseDownSlider() from ' + (st.slider != null ? st.slider.id : 'unknown'));

        st.lockByUser = true;

        template._ActualSliderTemplate = st;
        simpleAddEvent(template.document, 'mousemove', template.mainDragSliderHandler);
        simpleAddEvent(template.document, 'mouseup', template.stopDragSliderHandler);
    },

    stopDragVideoMoveHandler: function () {
        trace('stopDragVideoMoveHandler()');
        simpleRemoveEvent(template.document, 'mousemove', template.mainDragVideoMoveHandler);
        simpleRemoveEvent(template.document, 'mouseup', template.stopDragVideoMoveHandler);
        template.body.focus();
    },

    stopDragSliderHandler: function () {
        trace('stopDragSliderHandler()');

        template._ActualSliderTemplate.lockByUser = false;
        if (template._ActualSliderTemplate.onMoveResultHandler != null) {
            template._ActualSliderTemplate.onMoveResultHandler();
        }
        template._ActualSliderTemplate = null;

        simpleRemoveEvent(template.document, 'mousemove', template.mainDragSliderHandler);
        simpleRemoveEvent(template.document, 'mouseup', template.stopDragSliderHandler);
        template.body.focus();
    },

    mainDragVideoMoveHandler: function (event) {
        template.BtnArrastarVideo.style.left = (event.clientX - template.BtnArrastarVideo.difPosMouseX) + 'px';
        template.BtnArrastarVideo.style.top = (event.clientY - template.BtnArrastarVideo.difPosMouseY) + 'px';

        wcplayer.move(event.clientX - template.BtnArrastarVideo.difPosMouseX - wcplayer.width(),
                      event.clientY - template.BtnArrastarVideo.difPosMouseY);
    },

    mainDragSliderHandler: function (event) {
        var st = template._ActualSliderTemplate;
        if (st == null || st.area == null || st.slider == null) { return; }

        template.sliderHandlerMove(st, event);

    },

    sliderHandlerMove: function (st, event) {

        var mousex = event.clientX;
        var mousey = event.clientY;

        //Posiciona o slider de acordo com a orientação e a posição do mouse
        var perc = 0;
        if (st.horizontal) {

            if (mousex - st.difSlider < st.posAreaX) { st.slider.style.left = '0px'; }
            else if (mousex - st.difSlider > st.posAreaX + st.max) { st.slider.style.left = st.max + 'px'; }
            else { st.slider.style.left = (mousex - st.posAreaX - st.difSlider) + 'px'; }

            perc = Math.floor(100 * parseInt(template.getStyle(st.slider, 'left')) / st.max)

        } else {

            if (mousey - st.difSlider < st.posAreaY) { st.slider.style.top = '0px'; }
            else if (mousey - st.difSlider > st.posAreaY + st.max) { st.slider.style.top = st.max + 'px'; }
            else { st.slider.style.top = (mousey - st.posAreaY - st.difSlider) + 'px'; }

            perc = Math.floor(100 * (st.max - parseInt(template.getStyle(st.slider, 'top'))) / st.max);
        }

        st.percOnMove = perc;
        st.onMoveHandler(perc);

    },

    visualPositionSlider: function (perc, st) {

        //Posiciona o slider de acordo com a porcentagem
        if (!st) { return; }

        if (st.lockByUser) { return; }

        if (st.area == null || st.slider == null) { return; }

        if (perc < 1 || !perc) {
            perc = 0;
        }

        if (st.horizontal) {
            st.slider.style.left = Math.floor(perc * (st.max / 100)) + 'px';
        }
        else {
            st.slider.style.top = Math.floor((100 - perc) * (st.max / 100)) + 'px';
        }
    },

    sliderAudioUserMove: function (perc) {
        if (wcplayer.mute()) { template.muteOffClick(); }

        if (perc < 1 || !perc) {
            perc = 0;
        }

        wcplayer.volume(perc);

        template.setInformacao('volume: ' + perc + '%', template.SHOWING_VOLUME_TIME);
    },

    setAudioSliderPosition: function () {
        template.visualPositionSlider(wcplayer.volume(), template.sliderAudio);
    },


    sliderVideoUserMove: function (perc) {
        if (template.RelogioVideo == null) { return; }

        var current = Math.floor(visualizador.Transmissao.Duracao * perc / 100);

        template.RelogioVideo.innerHTML = template._mstotime(current) + ' / ' + template._mstotime(visualizador.Transmissao.Duracao);

        template.setInformacao('procurando...');
    },

    sliderVideoUserResult: function (st) {

        wcplayer.currentTotalPercent(template._ActualSliderTemplate.percOnMove);
    },

    disableTab: function (ac) {
        if (ac.area != null) {
            ac.area.style.visibility = 'hidden';
            ac.area.style.display = 'none';
        }
        if (ac.btn != null) {
            ac.btn.style.visibility = 'hidden';
            ac.btn.style.display = 'none';
        }
        if (ac.btnSel != null) {
            ac.btnSel.style.visibility = 'hidden';
            ac.btnSel.style.display = 'none';
        }
    },

    btnClick: function (ac) {
        if ((ac.area != null) && (ac.area.getAttribute('agrupamento') != null)) {
            var n = ac.area.getAttribute('agrupamento');

            for (var i = 0; i < template.agrupamentos[n].length; i++) {
                if (template.agrupamentos[n][i] == ac) { continue; }
                if (template.agrupamentos[n][i].area != null) {
                    template.agrupamentos[n][i].area.style.visibility = 'hidden';
                    visualizador.lstTabsState[template.agrupamentos[n][i].area.id] = false;
                }
                if (template.agrupamentos[n][i].btn != null) { template.agrupamentos[n][i].btn.style.visibility = 'visible'; }
                if (template.agrupamentos[n][i].btnSel != null) { template.agrupamentos[n][i].btnSel.style.visibility = 'hidden'; }
            }
        }

        if (ac.area != null) {
            ac.area.style.visibility = 'visible';
            visualizador.lstTabsState[ac.area.id] = true;
        }
        if (ac.btn != null) { ac.btn.style.visibility = 'hidden'; }
        if (ac.btnSel != null) { ac.btnSel.style.visibility = 'visible'; }
    },

    btnSelClick: function (ac) {
        //se não fazer parte de um agrupamento, desaparece com a área
        if ((ac.area != null) && (ac.area.getAttribute('agrupamento') == null)) {
            if (ac.area != null) { ac.area.style.visibility = 'hidden'; }
            if (ac.btn != null) { ac.btn.style.visibility = 'visible'; }
            if (ac.btnSel != null) { ac.btnSel.style.visibility = 'hidden'; }
            visualizador.lstTabsState[ac.area.id] = false;
        }
    },

    loadBanner: function (obj, path, link) {
        if (obj == null) { return; }

        if (path != '') {
            if (path.toLowerCase().endsWith('.swf')) {
                //Flash
                var sb = new StringBuilder();
                sb.append('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="100%" height="100%">');
                sb.append('  <param name="movie" value="' + path + '" />');
                sb.append('  <param name="quality" value="high"/>');
                sb.append('  <embed src="' + path + '" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="100%" height="100%">');
                sb.append('</object>');
                obj.innerHTML = sb.toString();
            }
            //Imagem
            else { obj.style.backgroundImage = 'url(' + path + ')'; }
        }

        if (link != '') {
            if (!link.toLowerCase().startsWith('http://')) { link = 'http://' + link; }
            simpleAddEvent(obj, 'click', function () { window.open(link); });
            obj.style.cursor = 'pointer';
        } else { obj.style.cursor = 'default'; }
    },

    setRelogioVideo: function (current, total) {
        if (template.RelogioVideo == null) { return; }
        if (template.sliderVideo.lockByUser) { return; }

        if (current != null && total != null) {
            template.RelogioVideo.innerHTML = template._mstotime(current) + ' / ' + template._mstotime(total);

        } else {
            template.RelogioVideo.innerHTML = '';
        }
    },

    setSliderVideoPosition: function () {

        template.visualPositionSlider(wcplayer.currentTotalPercent(), template.sliderVideo);
    },

    _mstotime: function (ms) {
        var sec = Math.floor(ms / 1000);

        var hou = Math.floor(sec / (60 * 60));
        var min = Math.floor((sec - hou * 60 * 60) / 60);
        sec = sec % 60;

        if (hou > 0) {
            return (hou < 10 ? '0' + hou : hou) + ':' +
                   (min < 10 ? '0' + min : min) + ':' +
                   (sec < 10 ? '0' + sec : sec);

        } else {

            return (min < 10 ? '0' + min : min) + ':' +
                   (sec < 10 ? '0' + sec : sec);

        }
    },

    setInformacao: function (informacao, showTime) {
        if (template.Informacao == null) { return; }

        template.Informacao.innerHTML = informacao.htmlEncode();

        if (showTime != null) {
            setTimeout(function () { template._setInformacaoHide(informacao); }, showTime);
        }
    },

    _setInformacaoHide: function (text) {
        if (template.Informacao == null) { return; }

        if (template.Informacao.innerHTML == text) { template.Informacao.innerHTML = ''; }
    },

    setLegenda: function (legenda) {
        visualizador.Transmissao.LegendaAtual = legenda;
        if (template.Legenda != null)
        { template.Legenda.innerHTML = visualizador.Transmissao.LegendaAtual.htmlEncode(); }
    },


    loadIndices: function () {
        if (visualizador.Transmissao.AoVivo) { return; }
        if (template.indices.area == null) { return; }

        var tb = visualizador.Indices;

        var sb = new StringBuilder();

        //iteração dos indices
        for (var i = 0; i < tb.rows.length; i++) {

            var row = tb.rows[i];

            sb.append('<div id=' + row.ObjId + ' class=' + row.CSS + ' onclick=parent.streamManager.SetFileByIndex(' + i + ') >');

            sb.append('<span style=float:left; >' + row.Nome + '</span>');

            sb.append('<span style=float:right; >');
            sb.append(i == 0 ? '&nbsp' : template._mstotime(row.OffSetTotal));
            sb.append('</span>');

            sb.append('</div><br/>');
        }

        template.indices.area.innerHTML = sb.toString();
        template.indicesSetSelection();
    },

    indicesSetSelection: function () {
        if (visualizador.Transmissao.AoVivo) { return; }
        if (template.indices.area == null) { return; }

        var current = wcplayer.currentTotal();

        var tb = visualizador.Indices;

        //iteração dos indices
        for (var i = 0; i < tb.rows.length; i++) {

            var obj = template.document.getElementById(tb.rows[i].ObjId);

            if (obj == null) { continue; }

            if (tb.rows[i].OffSetTotal > current) {
                obj.className = tb.rows[i].CSS;
            } else {
                obj.className = tb.rows[i].CSSSEL;
            }
        }
    }

}

