
function destaque_wide(options) { 
    //options( 1 - ON , 0 - OFF)
    options = options || {};
    
    var auto_slide = 1;
    var hover_pause = 1;
    var key_slide = 1;
    var auto_slide_seconds = options.autoSlide || 10000;
    
    var qtdItens = $('.destaque-wide li').length;
        
    $('.navegacao-destaque strong').html('1/'+qtdItens);
    
    var itemClicado = 1;
    
    
    // Mouse Over Destaque Total
    
    $('.destaque-total .chamada-destaque .bg-hover').fadeTo(0, 0.2);
    $('.navegacao-chamada > a img').fadeTo(0, 0.1);
    $('.navegacao-chamada').fadeTo(0, 0);

    $('.conteudo-destaque').mouseenter(function(){
	    $(this).find('.navegacao-chamada').stop().fadeTo(400, 1);
	    $(this).find('.bg-hover').stop().fadeTo(200, 0.5);
    }).mouseleave(function(){
	    $(this).find('.navegacao-chamada').stop().fadeTo(400, 0);
	    $(this).find('.bg-hover').stop().fadeTo(200, 0.2);
    }); 
    
    
    $('.navegacao-chamada > a').mouseenter(function(){
        $('.navegacao-chamada a img').stop().fadeTo('fast', 0.1);
        $(this).children('img').stop().fadeTo('fast', 1);
    }).mouseleave(function(){
        $('.navegacao-chamada a img').stop().fadeTo('fast', 0.1);
    }); 
    
    
    var exibeDestaque = function() {
        $('.conteudo-destaque').css('visibility','visible');
    }
    
    
    if( qtdItens == 1 ){
        $('.navegacao-chamada, .navegacao-destaque').remove();
        $('.destaque-wide').css({'left' : '0'});       
        exibeDestaque();
        return false;
    }
  
    
    //speed of auto slide(
     for (i=0; i<qtdItens; i++){
        var item = $('.destaque-wide .chamada-destaque')[i];
        $(item).attr('rel',i+1)
    }
    if( qtdItens == 2 ){
        $('.destaque-wide li:last').clone().appendTo('.destaque-wide');
    }
    $('.destaque-wide li:first').before( $('.destaque-wide li:last') );
    
    //check if auto sliding is enabled
    if(auto_slide == 1){
        var timer = setInterval("slide('right')", auto_slide_seconds); 
        $('#hidden_auto_slide_seconds').val(auto_slide_seconds);
    }
    

    //check if hover pause is enabled
    if(hover_pause === 1){
        //when hovered over the list 
        $('.destaque-wide').hover(function(){
            //stop the interval
            clearInterval(timer)
        },function(){
            //and when mouseout start it again
            timer = setInterval("slide('right')", auto_slide_seconds); 
        });

    }
    

    //check if key sliding is enabled
    if(key_slide === 1){
        //binding keypress function
        $(document).bind('keypress', function(e) {
            //keyCode for left arrow is 37 and for right it's 39 '
            if(e.keyCode == 37){
                    //initialize the slide to left function
                    slide('left');
            }else if(e.keyCode == 39){
                    //initialize the slide to right function
                    slide('right');
            }
        });
    }
    
    // Customized click
    $('.navegacao-chamada .nav-left').bind('click', function(){
        slide("left");
        return false;
    });
    $('.navegacao-chamada .nav-right').bind('click', function(){
        slide("right");
        return false;
    });
    
    slide = function(where) {
        var item_width = $('.destaque-wide li').outerWidth();
        
        var $destaqueProximo = $('.destaque-wide li:first').next().clone();
        
        if(where == 'left'){
            var left_indent = parseInt($('.destaque-wide').css('left')) + item_width;
        }else{
            var left_indent = parseInt($('.destaque-wide').css('left')) - item_width;
        }
        
        $('.destaque-wide:not(:animated)').stop().animate({'left' : left_indent},700,function(){    
            if(where == 'left'){
                if(qtdItens == 2){
                    $destaqueProximo.appendTo('.destaque-wide');
                    $('.destaque-wide li:last').before($('.destaque-wide li:first'));
                    $('.destaque-wide li:last').prev().remove();
                }else{
                    $('.destaque-wide li:first').before($('.destaque-wide li:last'));
                }
            }else{
                if(qtdItens == 2){ 
                    $destaqueProximo.appendTo('.destaque-wide');
                    $('.destaque-wide li:last').before($('.destaque-wide li:first'));
                    $('.destaque-wide li:last').prev().remove();
                }else{
                    $('.destaque-wide li:last').after($('.destaque-wide li:first'));
                }
            }
            itemClicado = $('.destaque-wide .chamada-destaque')[1];
	        marcaBullets();
            $('.destaque-wide').css({'left' : '-950px'});
        });
        
        
    }

    // BULLETS
    criaBullets = function(){
	    var tpl = '';
	    
	    //$('.navegacao-destaque strong').html(1+'/'+qtdItens)
	    for (i=0;i<qtdItens;i++){
	        tpl += "<span>&bull;</span>";	   
	    }
	    $('.nav-bullets').append(tpl);	
	    $('.nav-bullets span:first').addClass('on');
	}
	
	marcaBullets = function(){
	    var posicao = $(itemClicado).attr('rel');
	    $('.navegacao-destaque strong').html(posicao+'/'+qtdItens);
		var bulletAtual = $('.nav-bullets span')[posicao - 1];
		$('.nav-bullets span').removeClass('on');
		$(bulletAtual).addClass('on');
		try {
		    Cufon.replace('.navegacao-destaque strong', { fontFamily: 'VAGRounded Lt' });
        } catch (error) {};
	}
	
	criaBullets();   
    exibeDestaque();
};

function SliderDestaque() {
    this.qtdItens = $('.chamada-destaque-principal').length;    // quantidade inicial
    this.posicaoAtual = 1;
    this.durantePaginacao = false;  // não tenta paginar quando a página está passando
    
    if(this.qtdItens>1) {
        this.autoPaginar = true;
    	this.liAtual = 1;
    } else {
        this.autoPaginas = false;
    	this.liAtual = 0;
    }
    
    this.intervaloPaginacao = 10000;
    
    this.paginaComSetas = true
    
    $('.navegacao-chamada-principal > a img').fadeTo(0, 0.1);
    
    if (this.qtdItens > 1) {
        var ultimo = $('.chamada-destaque-principal:last').clone();
        $('.chamada-destaque-principal:first').before(ultimo);
        this.resetaMargem();
    };
    
    this.desabilitaSeVazio();
    this.setLarguraUl();
    this.conectaHoverPaginacao();
    this.conectaPaginacao();
    this.atualizaTextos();
    this.criaBullets();
    this.atualizaNumeros();
    this.conectaClickImagem();
    if (this.autoPaginar) this.conectaAutoPaginar(this.intervaloPaginacao);
    if (this.paginaComSetas) this.conectaSetas();
};

SliderDestaque.prototype.desabilitaSeVazio = function() {
    if( this.qtdItens == 1 ) {
        $('.navegacao-destaque-principal, .navegacao-chamada-principal').remove();
        $('.destaque-principal').css({'left' : '0'});
    };
};

SliderDestaque.prototype.atualizaNumeros = function() {
    $('.navegacao-destaque-principal strong').html(this.posicaoAtual + '/' + this.qtdItens);
    try {
        Cufon.replace('.navegacao-destaque-principal strong', { fontFamily: 'VAGRounded Lt' });
    } catch (err) {};
};

SliderDestaque.prototype.criaBullets = function() {
    var html = '';
    for (var i = 0; i < this.qtdItens; i++) {
        html += "<span>&bull;</span>";
    };
    $('.nav-bullets-principal').html(html);	
    $('.nav-bullets-principal span:first').addClass('on');
};
SliderDestaque.prototype.atualizaBullets = function() {
    $('.nav-bullets-principal span').each(function() { 
        $(this).removeClass('on') 
    });
    $( $('.nav-bullets-principal span')[this.posicaoAtual-1] ).addClass('on');
};

SliderDestaque.prototype.conectaHoverPaginacao = function() {
    $('.navegacao-chamada-principal > a')
        .mouseenter(function() {
            $(this).find('img').fadeTo(0, 1);
        })
        .mouseleave(function() {
            $(this).find('img').fadeTo(0, 0.1);            
        });
};

SliderDestaque.prototype.conectaPaginacao = function() {
    var that = this;
    $('.navegacao-chamada-principal .nav-right').click(function () {
        that.paginar('right');
        return false;
    });
    $('.navegacao-chamada-principal .nav-left').click(function () {
        that.paginar('left');
        return false;
    });
};

SliderDestaque.prototype.atualizaTextos = function() {
    this.atualizaTitulo();
    this.atualizaChapeu();
};
SliderDestaque.prototype.atualizaTitulo = function() {
    var li = this.getItemAtual();
    var titulo = li.find('.titulo-chamada p').html();
    var titulo_href = li.find('.titulo-chamada').attr('href');
    $('.conteudo-destaque-principal .sidebar .titulo').fadeOut(350, function() {
        $(this).html(titulo).attr('href', titulo_href);
        $(this).fadeIn(350);
    });
};
SliderDestaque.prototype.atualizaChapeu = function() {
    var li = this.getItemAtual();
    var chapeu = li.find('.chapeu-chamada').html();
    $('.conteudo-destaque-principal .sidebar .chapeu').fadeOut(300, function() {
        $(this).html(chapeu).fadeIn(300);
    });
};

SliderDestaque.prototype.paginar = function(destino) {
    
    if (this.durantePaginacao) {
        return;
    };
    this.durantePaginacao = true;
    
    if (destino == 'right') {
        var left = '-=';
        this.liAtual += 1;
    } else {
        var left = '+=';
        this.liAtual -= 1;
    };
    
    left = left + this.getLarguraLi();
    
    this.atualizaTextos();
    
    var that = this;
    $('.conteudo-destaque-principal-total ul:not(:animated)').stop().animate({'left': left}, 300, function () {
        
        if (destino == 'right') {
            $('.chamada-destaque-principal:first').remove();
            var primeiro = $('.chamada-destaque-principal:first').clone();
            $('.conteudo-destaque-principal-total ul').append(primeiro);
            that.posicaoAtual = that.posicaoAtual == that.qtdItens ? 1 : that.posicaoAtual+1;
        } else {
            $('.chamada-destaque-principal:last').remove();
            var ultimo = $('.chamada-destaque-principal:last').clone();
            ultimo.insertBefore( $('.chamada-destaque-principal:first') );
            that.posicaoAtual = that.posicaoAtual == 1 ? that.qtdItens : that.posicaoAtual-1;
        };
        that.liAtual = 1;
        that.resetaMargem();
        that.atualizaNumeros();
        that.atualizaBullets();
        that.durantePaginacao = false;
        
    });
};

SliderDestaque.prototype.setLarguraUl = function() {
    var length = $('.chamada-destaque-principal').length;
    $('.conteudo-destaque-principal-total ul').css('width', (this.getLarguraLi() * length));
};

SliderDestaque.prototype.getMargemUl = function() {
    return parseInt( $('.conteudo-destaque-principal-total ul').css('left') );
};

SliderDestaque.prototype.getLarguraLi = function() {
    return $('.chamada-destaque-principal:first').outerWidth();
};

SliderDestaque.prototype.getItemAtual = function() {
    return $($('.chamada-destaque-principal')[this.liAtual]);
};

SliderDestaque.prototype.getQuantidadeItens = function() {
    // sempre um a mais que o inicial, já que o último é colocado antes de todos
    // pra garantir uma navegação circular
    return this.qtdItens + 1;
};

SliderDestaque.prototype.resetaMargem = function() {
    $('.conteudo-destaque-principal-total ul').css('left', '-'+this.getLarguraLi()+'px');
    $('.conteudo-destaque-principal .sidebar').css('zoom', 1);  // IE 6 sux!
};

SliderDestaque.prototype.conectaClickImagem = function() {
    $('.conteudo-destaque-principal-total').click(function() {
        location.href = $('.conteudo-destaque-principal .sidebar .titulo').attr('href');
    });
};

SliderDestaque.prototype.conectaAutoPaginar = function(tempo) {
    var that = this;
    var interval = setInterval(function() { that.paginar('right') }, tempo);
    
    $('.sidebar, .conteudo-destaque-principal-total').hover(
        function() {
            clearInterval(interval);
        },
        function() {
            interval = setInterval(function() { that.paginar('right') }, tempo);
        }
    )
    
};

SliderDestaque.prototype.conectaSetas = function() {
    // keyCode para seta esquerda é 37 e para direita é 39
    var that = this;
    $(document).bind('keypress', function(e) {
        if (e.keyCode == 37){
            that.paginar('left');
        } else if(e.keyCode == 39) {
            that.paginar('right');
        };
    });
};

$(document).ready(function(){

    var corNovela = $('.cor-link').css('color');
    var corNovelaHover = $('.cor-link-hover').css('color');
    var corLinha = $('.cor-linha').css('color');
    var fundoClaro = $('.cor-fundo-claro').css('color');
    var fundoClaroHover = $('.cor-fundo-claro-hover').css('color');
	
	// mouseover titulo GERAL
	$('.conteudo-colunas .titulo-colunas').mouseenter(function(){
		$(this).parents('.conteudo-colunas .glb-grid-3').stop().animate({ "backgroundColor": fundoClaro, "borderLeftColor": corNovelaHover }, "fast", "easeInQuad");
	}).mouseleave(function(){
		$(this).parents('.conteudo-colunas .glb-grid-3').stop().animate({ "backgroundColor": "#FFF", "borderLeftColor": corLinha }, "fast", "easeInQuad");
	});

	
	// mouseover titulo COM LINK
	$('.conteudo-colunas a.titulo-colunas').mouseenter(function(){
		$('.conteudo-colunas a.titulo-colunas span').hide();
		$(this).children('span').show();
	}).mouseleave(function(){
		$(this).children('span').hide();
	});

	
	// mouse over box e coluna
	$('.borda-esquerda').fadeTo(0, 0).show();
	$('.box-destaque').mouseenter(function(){
		$(this).parents('.conteudo-colunas .glb-grid-3').stop().animate({ "backgroundColor": fundoClaro, "borderLeftColor": corNovelaHover }, "fast", "easeInQuad");
	    $(this).stop().animate({ "backgroundColor": fundoClaroHover }, "fast", "easeInQuad");
		$(this).children('.borda-esquerda').stop().fadeTo('fast', 1);
	}).mouseleave(function(){
		$(this).parents('.conteudo-colunas .glb-grid-3').stop().animate({ "backgroundColor": "#FFF", "borderLeftColor": corLinha }, "fast", "easeInQuad");
		$(this).children('.borda-esquerda').stop().fadeTo('fast', 0);
		$(this).stop().animate({ "backgroundColor": fundoClaro }, "fast", "easeInQuad", function(){
			$(this).removeAttr('style');
		});
	});

    
    // mouseover titulos destaque primario capitulo
    $('.coluna-capitulos .box-principal a.titulo').mouseenter(function(){
        $(this).css({'color': corNovelaHover});
        try {
            Cufon.replace(this, { fontFamily: 'VAGRounded Lt' }); 
        } catch (error) {};
    }).mouseleave(function(){
        $(this).css({'color': corNovela});
        try {
            Cufon.replace(this, { fontFamily: 'VAGRounded Lt' }); 
        } catch (error) {};
    });
    
	
	//fonte personalizada para chapeu em bastidores
	$('.glb-ultimo .destaque-coluna-primario .chapeu').addClass('fonte-cufon');
	
	alinhaTamanhoEixos = function(){
	    var tamColuna = $('.conteudo-colunas').height()
    	$('.conteudo-colunas .glb-grid-3').css('height',tamColuna);
	}
	window.setTimeout('alinhaTamanhoEixos()', 500);
	
});

var glb = glb || {}
glb.Delegate = function(){
    return {
        create:function(obj, method){
            if(typeof(method) != "string" || typeof(obj) != "object" || typeof(obj[method]) != "function") return null;
            return function(){
                return obj[method].apply(obj, arguments);
            }
        }
    }
}();

glb.WidgetVideos = function ($) {
    var videos = function () {};
    videos.prototype = {
		animateInfoPlayer: function(obj, acao, valAnime) {
		    $("iframe").each(function(){
                if( $(this).attr('src').indexOf( obj.midiaId ) >= 0 ){
					var $videoSimples = $(this).parent().parent().find('#video-simples');
					var $chamadaRodape = $(this).parent().parent().parent().find('.chamada-rodape');
                    
                    if( acao === 'show' ){
                    	$videoSimples.fadeIn(500, function(){
                    		$videoSimples.css('z-index', '100001');
                    		$chamadaRodape.css('z-index', '100000');
                    	});
                    }else if( acao === 'hide' ){
                    	$videoSimples.fadeOut(500, function(){
                    		$videoSimples.css('z-index', '100001');
                    		$chamadaRodape.css('z-index', '100000');
                    	});
                    }
                }
            });
		},
		onPlayPlayer: function(obj, acao) {
		    this.animateInfoPlayer(obj, "hide");
		},
		onEndPlayer: function(obj) {
		    this.animateInfoPlayer(obj, "show");
		}
	}
	
    return videos;
}(jQuery);

var Duelo = {
	
	init:function() {
	
		this.Conteudo.init();
		this.Resultado.init();
		
		this.captchaLabel = 'Preencha com o texto acima';
		this.captchaErroIncorreto = 'Os caracteres digitados est\u00e3o incorretos';
		this.captchaErro = 'N\u00e3o foi possivel computar o seu voto';
		
		this.dueloId = $('.conteudo-duelo').attr('duelo-id');
		
		$(".opcao-captcha").hide();
        $(".glb-duelo .rodape-duelo .botao-voto").unbind().click(function() { 
			Duelo.exibeLabel();
        	Duelo.confirmar($(this));
        	return false; 
        });
        $(".glb-duelo .recaptcha_reload").unbind().click(function() {
        	Duelo.reloadCaptcha();
        	return false;
        });
        var submit = function() {
        	Duelo.votar();
        	return false;
        };
		var limpaLabel = function() {
			Duelo.limpaLabel();
			return false;
		};
		var exibeLabel = function() {
			Duelo.exibeLabel();
			return false;
		};
		
        $('.glb-duelo #form-duelo').unbind().submit(submit);
        $(".glb-duelo .captcha-confirma").unbind().click(submit);
		$('#recaptcha_response_field').unbind().focus(limpaLabel).blur(exibeLabel);
   	},
	
	/* Voto */
	
	// confirmar eh quando clica em votar em seguida mostra o captcha
	confirmar:function(a) {
		var opcao = a.attr('data-id-opcao');
		var lado = a.attr('data-lado-opcao');
		$('#form-duelo #id_opcao').val(opcao);
		this.mostraCaptcha(lado);
		this.configuraLado(lado);
	},
	configuraLado: function(lado){   
	    if( lado === "esquerda" ){
	        this.ladoVotado = "esquerda";
	        this.ladoOposto = "direita";
	    }else{
	        this.ladoVotado = "direita";
	        this.ladoOposto = "esquerda";
	    }   
	},
   	votar:function() {
        $('#form-duelo').ajaxSubmit({
		  type: 'get',
		  dataType: 'jsonp',
		  success: function(data) { Duelo.votado(data) }
		});
   	},
   	votado:function(data) {

        if (this.ladoVotado === "esquerda" ) {
            $('.duelo-resultado-voto .opcao-01').css('margin-top','0').show();
            $('.duelo-resultado-voto .opcao-02').css('margin-top','200px').hide();
        } else {
            $('.duelo-resultado-voto .opcao-01').css('margin-top','200px').hide();
            $('.duelo-resultado-voto .opcao-02').css('margin-top','0').show();
        }

   		if( data.toString()=='ok' ) {
            this.Conteudo.escondeDetalhes();
    		this.Resultado.mostrar();
    		this.Resultado.getParcial();
		} else if ( data.toString()=='recaptcha invalido' ) {
			this.reloadCaptcha(function() {
				this.exibeMensagemDeErro(this.captchaErroIncorreto);
			});
		} else {
			this.exibeMensagemDeErro(this.captchaErro);
		}
	},
	
	/* Captcha */
	
	mostraCaptcha:function(lado) {
		$('.opcao-captcha').removeClass('esquerda direita');
		$('.opcao-captcha').addClass(lado).show();
		this.reloadCaptcha();
	},
	reloadCaptcha:function(callback) {
		var self = this;
		callback = (callback == undefined) ? this.exibeLabel : callback;
		this.escondeCaptchaAntes();
		RecaptchaCreate.options.callback = function() { callback.call(self) };
		RecaptchaCreate.load('form-duelo');
		this.resizeCaptcha();
	},
	escondeCaptchaAntes:function() {
		$('#recaptcha_image').css({'position':'absolute', 'z-index':'-1'});
	},
	exibeCaptchaDepois:function() {
		$('#recaptcha_image').css({'position':'relative', 'z-index':'1'});
	},
	resizeCaptcha:function() {
		var self = this;
		var achou = function() {
			return $('#recaptcha_image img').size() > 0;
		}
		var resize = function() {
			$('#recaptcha_image img').css({'width':190,'height':40});
			$('#recaptcha_image').css({'width':190,'height':40});
			self.exibeCaptchaDepois();
		}
		if( achou() ) resize();
		var thread = setInterval(function() {
			if(achou()) {
				resize();
				clearInterval(thread);
			}
		},300);
	},
	captchaPreenchido:function() {
		var val = $('#recaptcha_response_field').val();
		return (val != this.captchaLabel && val != this.captchaErroIncorreto && val != this.captchaErro && val != "");
	},
	
	/* Mensages */
   	
   	exibeMensagemDeErro:function(mensagem) {
		$('#recaptcha_response_field').addClass('erro').val(mensagem);
   	},
	exibeLabel:function() {
		if (this.captchaPreenchido()) return;
		$('#recaptcha_response_field').removeClass('erro').val(this.captchaLabel);
	},
	limpaLabel:function() {
		if (this.captchaPreenchido()) return;
		$('#recaptcha_response_field').removeClass('erro').val('');
	}
}

Duelo.Resultado = {
    
    init: function() {
        this.mostraToolTip();
        $(".botao-novo-voto").unbind().click(function() {                                        
			Duelo.Resultado.votarNovamente();
			return false;
		});
    },
    
	mostraToolTip:function() {
		$('.ferramentas-acoes a, .ferramentas-compartilhar a').tipTip().find('img').removeAttr('alt');
	},
    
    mostrar: function() {
        $('.resultado-duelo').show();
        $('.duelo-resultado-voto').show();
        $('.opcao-duelo-01, .opcao-duelo-02, .opcao-captcha').hide();
        this.mostraPersonagemVotado();
        this.transparecePersonagemPerdedor();
    },
   	mostraPersonagemVotado: function(){
   	    $('.conteudo-duelo').css('overflow','visible');
        $('.personagem[side='+ Duelo.ladoOposto +']').css('height','433px');
   	},
   	transparecePersonagemPerdedor: function() {
        $('.mascara-personagem').removeClass('mascara-personagem-'+ Duelo.ladoVotado +'').addClass('mascara-personagem-'+ Duelo.ladoOposto +'').fadeTo(0, '0.8');
   	},
   	solidificaPersonagemPerdedor: function() {
        $('.mascara-personagem').removeClass('mascara-personagem-'+ Duelo.ladoVotado +'').addClass('mascara-personagem-'+ Duelo.ladoOposto +'').hide(); 	    
   	},
    
    getParcial: function() {
        this.escondeParcial();
        $.ajax({
            url: '/duelo/' + Duelo.dueloId + '/resultado/',
            dataType: 'json',
            success: function(json, textStatus) { 
                Duelo.Resultado.preencheParcial(json);
                Duelo.Resultado.mostraParcial();
            },
            error: function(xhr, status, error) {
                alert("Desculpe, ocorreu um erro. Tente atualizar a pÃ¡gina e tentar novamente.");
            }
        });
    },
    preencheParcial: function(json) {
        var vencedor = json['vencedor'];
        var perdedor = json['perdedor'];
        
        $('.nome-resultado[data-id-opcao='+ vencedor.id +'] span').html(vencedor.porcentagem+'%').parent().addClass('vencedor-parcial');
        $('.nome-resultado[data-id-opcao='+ perdedor.id +'] span').html(perdedor.porcentagem+'%');
        
        $('.grafico-pizza').addClass('pizza-' + vencedor.lado);
        $('.grafico-pizza span').attr('class', 'pizza-'+perdedor.porcentagem_em_5);
        
    },
    limpaParcial: function() {
        $('.vencedor-parcial').removeClass('vencedor-parcial');
    },
    escondeParcial: function() {
        $('.grafico-resultado > *').css('visibility', 'hidden');
    },
    mostraParcial: function() {
        $('.grafico-resultado > *').css('visibility', 'visible');
    },
    
	votarNovamente:function(a) {
	    this.restaurar();
	},
	restaurar: function() {
	    $('.resultado-duelo').hide();
		$('.duelo-resultado-voto').hide();
		$('.opcao-captcha').hide();
		$('.opcao-duelo-01, .opcao-duelo-02').show();
		this.limpaParcial();
        Duelo.Conteudo.mostraDetalhes();
		this.solidificaPersonagemPerdedor();
		this.restauraImagemPersonagens();
	},
	restauraImagemPersonagens: function() {
        $('.conteudo-duelo').css('overflow', 'visible');
        $('.personagem[side='+ Duelo.ladoOposto +']').css('height','');
        $('.conteudo-duelo').css('overflow', '');
	}
}

Duelo.Conteudo = {
	init:function() {
		this.aplicaHoverNoThumbnail();
		this.preparaCliqueDosLinks();	
	},
   	escondeDetalhes: function(){
   	    $('.titulo-duelo').hide();
   	    $('.descricao-duelo').hide();
   	    $('#thumbnail-duelo').parent().parent().hide();
   	    //$('.detalhes-duelo').removeClass('sem-detalhes').addClass('sem-detalhes');
   	    $('.detalhes-duelo').css({'padding-top':'65px','top':'0'})
   	    if ( this.mostrandoFoto() )  this.fecharFoto();
   	    if ( this.mostrandoVideo() ) this.fecharVideo();
   	},
   	mostraDetalhes: function(){
   	    $('.titulo-duelo').show();
   	    $('.descricao-duelo').show();
   	    $('#thumbnail-duelo').parent().parent().css('display', 'block');
   	    //$('.detalhes-duelo').removeClass('sem-detalhes');
   	    $('.detalhes-duelo').removeAttr('style');
   	},
	preparaCliqueDosLinks:function() {
		var self = this;
		$('a#thumbnail-duelo').click(function() {
			self.exibirConteudo($(this));
			return false;
		});
		$('a#hover-thumbnail-duelo').click(function() {
			$('a#thumbnail-duelo').click();
			return false;
		});
		$('#popin-video a').click(function() {
			self.fecharVideo($(this));
			return false;
		});
		$('#popin-foto a').click(function() {
			self.fecharFoto($(this));
			return false;
		});
	},
	aplicaHoverNoThumbnail:function() {
		$('.detalhes-duelo div.foto a').mouseover(function() {
			$('a#hover-thumbnail-duelo').removeClass('off').addClass('on');
		}).mouseout(function() {
			$('a#hover-thumbnail-duelo').addClass('off').removeClass('on');
		});
	},
	exibirConteudo:function(a) {
		if(a.attr('data-tipo')=='V') {
			this.exibirVideo(a);
		} else {
			this.exibirFoto(a);
		}
	},
	
	mostrandoVideo:function() {
	    return $('#popin-video').css('display') == 'block';
	},
	mostrandoFoto:function() {
	    return $('#popin-foto').css('display') == 'block';
	},
	fecharVideo:function(a) {
		$('#popin-video').hide();
		this.embed.destroy();
	},
	exibirVideo:function(a) {
		var parametros = { midiaId: a.attr('data-id-video'), banda: 'N', autoStart: true, escondeFimVideo: true, escondeTrocaBanda: true };
		this.embed = new GMCEmbed(parametros);
		this.embed.attach('popin-video-player');
		$('#popin-video').show();
	},
	fecharFoto:function(a) {
	    a = (a == undefined) ? $('#popin-foto-container a') : a;
		$('#popin-foto').hide();
		$('#cortina-foto').hide();
		$('#foto-duelo').attr('src',a.attr('about:blank'));
	},
	exibirFoto:function(a) {
		var self = this;
		$('#cortina-foto').show();
		this.carregaImagem(a.attr('data-src-foto'),function(img){
			self.centralizaFoto(img);
			$('#popin-foto').show();
		});
	},
	carregaImagem:function(src,callback) {	
		var img = new Image();
		var loaded = function() {
			var carregou = function() {
				return img.width > 0 && img.height > 0;
			};
			if( carregou() ) {
				callback(img); 
			} else {
				var thread = setInterval(function() {
					if( carregou() ) {
						callback(img);
						clearInterval(thread);
					}
				},300);
			}
		}
		img.onload = loaded;
		img.src = src;
	},
	centralizaFoto:function(img) {
		var largura = img.width > 854 ? 854 : img.width;
		var altura = img.height > 412 ? 412 : img.height;
		var larguraContainer = largura + (2*33)
		var topContainer = ( 433 - altura ) / 2;
		
		$('#foto-duelo').css({ 'width': largura, 'height': altura } );
		$('#popin-foto-container').css( { 'width': larguraContainer, 'margin-top': topContainer } );
		$('#foto-duelo').attr('src',img.src);	
	}
}

var WidgetDuelo = {
    init: function(dueloId, link) {
        this.url = '/duelo/'+dueloId+'/resultado/';
        this.link = link;
        this.atualizaParcial();
        
    },
    
    atualizaParcial: function() {
        $.ajax({
            url: this.url,
            dataType: 'json',
            success: function(json){ WidgetDuelo.defineRodape(json) },
            error: function(xhr, status, error) {}
        });
    },
    defineRodape: function(json) {
    	this.status = json['status'];
        this.exibe_porcentagem = json['exibe_porcentagem']

    	if ( this.status  == 'P' && this.exibe_porcentagem == '1' ){
            this.atualizaBarra(json);
        }else if (this.status  == 'P' && this.exibe_porcentagem == '0'){
        	this.naoMostraPorcentagem();
        } else if ( this.status == 'E' ){
            this.mostraEncerrado();
        }
    },
    
    naoMostraPorcentagem: function(json) {
        $('.rodape-duelo').empty();
        htmlSemPorcentagem='<div class="participe"><a href="'+this.link+'" class="botao-participe botao"><span>participe</span></a></div>'
        $('.rodape-duelo').html(htmlSemPorcentagem);
    },
    
    atualizaBarra: function(json) {
        var vencedor = json['vencedor'];
        var perdedor = json['perdedor'];
        var barraVencedor = $('.porcentagem[data-id-opcao='+vencedor.id+'] .barra-confronto');
        var barraPerdedor = $('.porcentagem[data-id-opcao='+perdedor.id+'] .barra-confronto');
        
        barraVencedor.children('.porcentagem').html(vencedor.porcentagem+'%');
        barraPerdedor.children('.porcentagem').html(perdedor.porcentagem+'%'); 
        
        barraVencedor.addClass('barra-grande').addClass('vencedor-parcial');
        
        if (perdedor.porcentagem < 45)
            barraPerdedor.addClass('barra-pequena');
        else
            barraPerdedor.addClass('barra-grande');
        
        barraVencedor.css('width', vencedor.porcentagem+'%');
        barraPerdedor.css('width', perdedor.porcentagem+'%');
        
    },
    
    mostraEncerrado: function() {
    	$('.rodape-duelo').empty();
    	htmlEncerrado='<div class="participe-encerrado"><span>Duelo encerrado</span><a href="'+this.link+'" class="link-participe">veja o vencedor »</a></div>'
    	$('.rodape-duelo').html(htmlEncerrado);
        
    }
    
}

