var hostAddress = 'www.espn.com.br';

function NotNumber(e) {
	var oEvent = e? e : window.event;
	nEvent = oEvent.keyCode || oEvent.which;
	var arrPermiticao = [8,9,13,35,36,37,38,39,40,46,48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105,110,188,190];	
	for(i=0; i < arrPermiticao.length; i++)if(nEvent == arrPermiticao[i])return true;
	return false;
}

/*CLOSE MODAL*/
function closeModal() {
	/*HIDE MODAL*/
	J('.view_modal').fadeTo('fast', 0, function(){J(this).remove();});
	
	/*HIDE BACKGROUND*/
	J('.bg_modal').fadeTo('fast', 0, function() {
		J(this).remove();
		/*SHOW SELECT*/
		J('select').css('visibility', 'visible');
	});
}

// jQuery CooKie
jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{};if(value===null){value='';options.expires=-1;}var expires='';if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){var date;if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000));}else{date=options.expires;}expires='; expires='+date.toUTCString();}var path=options.path?'; path='+(options.path):'';var domain=options.domain?'; domain='+(options.domain):'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('');}else{var cookieValue=null;if(document.cookie&&document.cookie!=''){var cookies=document.cookie.split(';');for(var i=0;i<cookies.length;i++){var cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break;}}}return cookieValue;}};

// obtendo posicao do objeto
function getPosicaoElemento(obj){
	var offsetTrail = obj;
	var offsetLeft = 0;
	var offsetTop = 0;
	while (offsetTrail) {
		offsetLeft += offsetTrail.offsetLeft;
		offsetTop += offsetTrail.offsetTop;
		offsetTrail = offsetTrail.offsetParent;
	}
	if (navigator.userAgent.indexOf("Mac") != -1 && typeof document.body.leftMargin != "undefined") {
		offsetLeft += document.body.leftMargin;
		offsetTop += document.body.topMargin;
	}
	return {left:offsetLeft, top:offsetTop};
}

var leftModal = 0;
var topModal = 0;

function ajusteModal(obj,top,left){
	leftModal = getPosicaoElemento(obj).left + left;
	topModal = getPosicaoElemento(obj).top + top;
}


/*MODAL*/
function openModal(url) {
	/*CREATE ELEMENTS*/
	J('body').append(J('<img />').attr({src: "/img/fe/load.gif", width: 88, height: 78, alt: "", className: 'load'})).append(J('<div></div>').addClass('bg_modal')).append(J('<div></div>').addClass('view_modal'));

	J('.bg_modal').width(J('html')[0].scrollWidth).height(J('html')[0].scrollHeight);

	/*OPACITY*/
	J('.view_modal').css('opacity', 0);
	J('.bg_modal').css('opacity', 0);
	
	/*SELECTS HIDE*/
	J('select').css('visibility', 'hidden');

	/*SHOW BACKGROUND*/
	J('.bg_modal').fadeTo('fast', 0.5, function() {
		J('.view_modal').load(url,{nocacheattr:(new Date()).getTime()}, function() {
		
			/*REMOVE LOAD*/
			J('.load').remove();
			
			GB_getPageScrollTop = function() {
			var yScrolltop;
			if (self.pageYOffset) {
				yScrolltop = self.pageYOffset;
			} else if (document.documentElement && document.documentElement.scrollTop || document.documentElement.scrollLeft) {
				yScrolltop = document.documentElement.scrollTop;
			} else if (document.body) {
				yScrolltop = document.body.scrollTop;
			}
				return yScrolltop;
			}
			
			/*CENTRALIZE MODAL*/
			if(leftModal != 0 || topModal != 0){
				J('.view_modal').css({
						marginTop: topModal, 
						marginLeft: leftModal,
						left: 0,
						top: 0
					}
				);
				leftModal = 0;
				topModal = 0;
			} else {
				J('.view_modal').css({marginTop: parseInt(GB_getPageScrollTop() - (J('.view_modal').height()/2)), marginLeft: -parseInt(J('.view_modal').width()/2)});
			}

			/*MODAL HIDE*/
			J('.view_modal').fadeTo('fast', 1);

			/*CLOSE MODAL*/
			J("a[@rel~='modalclose']").click(function() {
				closeModal();
				return false;
			})
		});
	});
	return false;
}
	
function initModal() {
	J("a[@rel~='modal']").unbind();
	J("a[@rel~='modal']").click(function() {
		openModal(J(this).attr('href'));
		return false;
	})
	J("a[@rel~='modal']").css('visibility','visible');
}

// Strings do autocomplete
var stringTagAlias = '';
var stringTagUrl = '';

function CopyHeight() {
	var heights = [];
	for (var i = 0; i < arguments.length; i++) {
		document.getElementById(arguments[i]).style.height = '';
		heights.unshift(document.getElementById(arguments[i]).offsetHeight);
	}
	hT = heights.sort(function(a,b){ return a - b }).reverse()[0]; //ninja *[1]
	for (var i = 0; i < arguments.length; i++)
		document.getElementById(arguments[i]).style.height = hT+'px';
}

function addTagList() {
	var tag_inicial = J("#suggestionTag").val();
	
	J("#suggestionTag").focus(function(){
		J(this).css('background-color','#ffff9c');
		tag_suggestionTag = J("#suggestionTag").val();
		if(tag_suggestionTag == tag_inicial) J("#suggestionTag").val('');
	});
	
	J("#suggestionTag").hover(
		function(){J(this).css('background-color','#ffff9c');},
		function(){J(this).css('background-color','#ffffde');
	});
	
	J("#suggestionTag").blur(function(){
		J(this).css('background-color','#ffffde');
		if(J("#suggestionTag").val()=='')J("#suggestionTag").val(tag_inicial);
	});
	
	var tag_inicial = J("#suggestionTag").val();
	J("#suggestionTag").focus(function(){
		J(this).css('background-color','#ffff9c');
		tag_suggestionTag = J("#suggestionTag").val();
		if(tag_suggestionTag == tag_inicial) J("#suggestionTag").val('/');
	});
	
	J("#suggestionTag").autocomplete('/autocomplete.autocompleteByTag.ajax.logic?exibeAlias=true',{width:530,submitOnSelect:true,formSubmit:'#buscaForm'});

}

function CopyLink(text){
	var browser = navigator.appName;
	J('#'+text).focus();
	J('#'+text).select();
	copy = document.getElementById(text);
	if(browser=="Microsoft Internet Explorer"){
		Copied = copy.createTextRange();
		Copied.execCommand("Copy");
	}else{
		texto = copy.value;
		while(texto.indexOf('+')!=-1) texto = texto.replace('+','_');
		var flashcopier = 'flashcopier';
		if(!document.getElementById(flashcopier)) {
			var divholder = document.createElement('div');
			divholder.id = flashcopier;
			document.body.appendChild(divholder);
		}
		document.getElementById(flashcopier).innerHTML = '';
		var divinfo = '<embed src="/js/fe/_clipboard.swf" FlashVars="clipboard='+texto+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
		document.getElementById(flashcopier).innerHTML = divinfo;
	}
};

function popup(pagina,w,h,s) {
	if (self.screen) { 
		sw = screen.width
		sh = screen.height
		cx = (.5*sw) - (w*.5)
		cy = (.5*sh) - (h*.5)
		var  dimentions_and_such = 'width='+w+','+'height='+h+',' + 'screenX=' +cx+','+'screenY='+cy+','+'left='+cx+','+'top='+cy+',scrollbars='+s
	}
	Pop=window.open(pagina,"popacion",dimentions_and_such);
}


function clickPage(e) {
	var ev = e || window.event;
	var target = ev.target || ev.srcElement,title=target.title; 
	//FECHANDO O MENU
	if (target.className != "menu_section" && target.className != "bt_visitas_recentes" && target.id !="abre_menu_topo" && target.id !="abre_esportes_topo" && target.id !="abre_talentos_topo" && target.id !="abre_programas_topo" && target.className.indexOf("talentos_toogle") == -1){
		J('#programas ul li').removeClass('opened');
		J('.menu_section').slideUp('fast',function(){
			J('#talentos_topo').css({"padding-bottom":"0"});		
			J('#talentos_topo').height(170);
			J('a.menos_talentos').hide();
			J('a.mais_talentos').show();
			J('ul.visitas_recentes').hide();
		});
	}
}

function bar_terra(){
	J('.bar_terra').html(J('<iframe></iframe>').attr({
		src:'http://www.terra.com.br/barra50.htm',
		scrolling:'no',
		width:'778',
		height:'48'
	}));
};

// Eliminando caracteres especiais da busca
var eliminaSpecialChars = function (){
	var novaBusca = J(this).val();
	var restricao = new Array('noticia','notícia','post','espn360');
	for(i=0;i<restricao.length;i++){
		if(novaBusca.toLowerCase()==restricao[i].toLowerCase()){
			J(this).val('');
			return false;
		}
	}
	var comparacao = new RegExp("([^0-9À-úA-z !\/,$])");		
	while(comparacao.test(novaBusca))novaBusca = novaBusca.replace(/([^0-9À-úA-z !\/,$])/,'');
	if(novaBusca!=J(this).val())J(this).val(novaBusca);
}

var contKeyDown = function(event){
	var classSize = J(this).parent().find('em.chars_restantes span').attr('class');
	if(classSize!=undefined){
		var size = parseInt(classSize.replace('size',''));
	} else {
		var size = parseInt(J(this).attr('maxlength'));	
	}
	texto = J(this).val();
	if(texto.length==size){
		// teclas válidas
		var backspace = 8; var tab = 9;	var shift = 16;	var ctrl = 17; var alt = 18; var capslock = 20;
		var end = 35; var home = 36; var left = 37;	var up = 38; var right = 39; var down = 40;
		var del = 46; var f5 = 116;
		var keys = new Array(backspace,tab,shift,ctrl,alt,capslock,end,home,left,up,down,del,f5);
		for(i=0;i<keys.length; i++){ if(event.keyCode==keys[i])return true;	}
		return false;
	} else { if(texto.length>size){ J(this).val(texto.substr(0,size)); return false; } }
}

function contChar(obj){
	var classSize = J(obj).parent().find('em.chars_restantes span').attr('class');
	if(classSize!=undefined){
		var size = parseInt(classSize.replace('size',''));
	} else {
		var size = parseInt(J(obj).attr('maxlength'));	
	}
	texto = J(obj).val();
	var restantes = size - texto.length;
	if(restantes < 0){ J(obj).val(texto.substr(0,size)); restantes = 0;}
	J(obj).parent().find('em.chars_restantes span').html(''+restantes+'');	
}

function atribuindoContChars(){

	var contCharFunction = function(){
		J(this).keydown(contKeyDown);
		J(this).keyup(function(){ contChar(J(this));});
		contChar(J(this));
	}
	J('textarea.cont_chars').each(contCharFunction);
	J('input.cont_chars').each(function(){
		if(J(this).next().attr('class')!='chars_restantes'){
			maxLength = parseInt(J(this).attr('maxlength'));
			if(maxLength!=-1){
				J(this).after('<em class="chars_restantes">Máximo de '+maxLength+' caracteres  - Caracteres restantes: <span class="size'+maxLength+'"><\/span><\/em>');
				J(this).keydown(contKeyDown);
				J(this).keyup(function(){ contChar(J(this));});
				contChar(J(this));
			}		
		}
	});
	
}
var Refresh = {}
	Refresh . start = function(){}
	Refresh . stop = function(){}

J(document).ready(function(){

	addTagList();

	//Ajustando o footer
	var alturaJanela = J(window).height();
	var alturaContent = J('#content').height();
	var topo = J('#header').height();
	var footer = J('#footer').height();	
	var marginTopo = J('#topo').css('margin-top');
	if(marginTopo!='' && marginTopo != undefined){
		marginTopo = parseInt(marginTopo.replace('px',''));
		var area_header_e_footer = marginTopo + topo + footer;
		var minHeight = (alturaJanela - area_header_e_footer);
		var minHeightPX = minHeight+'px';		
		if( alturaJanela - alturaContent > area_header_e_footer){
			J('#content').css({'min-height':minHeightPX});
		}
	}
	initModal();

	J('#suggestionTag').keyup(eliminaSpecialChars);
	
	
	// VISITAS RECENTES
	J('a.bt_visitas_recentes').show().click(function(){
		if(J('ul.visitas_recentes').size()==0){
			var cookies = J.cookie('cookTagVisit');
			if (cookies){
				var jData = cookies.split("||");
				if(jData.length>0){
					J('a.bt_visitas_recentes').after('<ul class="visitas_recentes"></ul>');
					for(i=0;i<jData.length;i++){
						tagVisita = jData[i];
						J('ul.visitas_recentes').append('<li><a href="'+tagVisita+'" title="'+tagVisita+'" class="tags tag_cinza">'+tagVisita+'</a></li>');
					}
					J('ul.visitas_recentes').slideDown();					
				}			
			}
		} else {
			J('ul.visitas_recentes').slideUp(function(){
				J('ul.visitas_recentes').remove();
			});
		}
		return false;
	});
	
	
	
	// ATRIBUINDO CONTADOR DE CARACTERES RESTANTES NO TEXTAREA E INPUTS	
	atribuindoContChars();
	
	J('#buscaForm').submit(function(){
		var textoBusca = J('#suggestionTag').val();
		if(J.trim(textoBusca).toLowerCase() =='cadastro' || J.trim(textoBusca).toLowerCase() =='cadastro de usuário'){
			openModal('\/template\/fe\/cadastro_login.jsp');
			return false;
		} 
		
		if(textoBusca.toLowerCase() =='rss'){
			openModal('\/template\/fe\/rss.jsp');
			return false;
		} 		

		if(textoBusca=='') return false;
		arrUrl = stringTagUrl.split('\n');
		arrAlias = stringTagAlias.split('\n');
		for(i=0;i<arrAlias.length;i++){
			if(J.trim(textoBusca).toLowerCase()==J.trim(arrAlias[i]).toLowerCase()){
				self.location = '\/'+arrUrl[i];
				return false;
			}
		}
		
		var restrictMedia = new Array('foto','video','audio');
		for(var y=0;y<restrictMedia.length;y++){
			if(textoBusca.toLowerCase()==restrictMedia[y].toLowerCase()){
				return false;
			}
		}
		
		self.location = '\/'+textoBusca;
		return false;
	});


	
	J('#programas ul li.tags_radio a, .bt_programas').unbind();
	J('#programas ul li.tags_radio a, .bt_programas').click(function(){
		
		J('ul.visitas_recentes').hide();	
		var opened = J(this).parent('li');
		var menusection = J(this).attr('id');
		J('#programas ul li').removeClass('opened');
		menusection = menusection.replace('abre_','');
		
		if(menusection != ''|| menusection != 'undefined'){
		
			J('.menu_section').slideUp('fast');
			if(J('#'+menusection).is(":hidden")){
				
				J(opened).addClass('opened');
				J('#'+menusection).slideDown();
						
				if(menusection == 'menu_topo'){

					J.ajax({
						url: '/fe/fe.checkUserLogged.ajax.logic',
						type: "POST",
						success: function(data) {
							eval('jData='+data);
							if (jData.login){
								J('#menu_topo a[title="/newsletter"]').attr({
									href:'/cadastro/cadastro.altera.logic'
								}).removeAttr('rel');
								J('#menu_topo div.rodape ul').html('');
								J('#menu_topo div.rodape ul').append('<li><strong>Logado como:</strong></li><li><strong>'+jData.login+'</strong></li><li><a href="/cadastro/cadastro.altera.logic" title="Altetar dados">alterar dados</a> | <a href="/fe/fe.logoff.logic" title="Sair">sair</a></li>');
							}else{
								J('#menu_topo a[title="/newsletter"]').attr({
									rel:'modal'
								}).click(function(){
									openModal('/template/fe/cadastro_login.jsp');
								});
							}
						}
					});
				} else {
					if(J('#'+menusection+' p.loading').size()==1){
						if(menusection=='esportes_topo') metodoLoadingMenu = '/elementos/common.esportes.logic'; 
						if(menusection=='talentos_topo') metodoLoadingMenu = '/elementos/common.talentos.logic'; 
						if(menusection=='programas_topo') metodoLoadingMenu = '/elementos/common.programas.logic'; 
						J.ajax({
							url:metodoLoadingMenu,
							success: function(retorno){
								J('#'+menusection).html(retorno);
								if(menusection=='talentos_topo'){
									J('a.mais_talentos').click(function(){
										J('#talentos_topo').css({"padding-bottom":"30px","height":"auto"});
										J('a.mais_talentos').hide();
										J('a.menos_talentos').show();
									});
									J('a.menos_talentos').click(function(){
										J('#talentos_topo').css({"padding-bottom":"0","height":"170px"});
										J('a.menos_talentos').hide();
										J('a.mais_talentos').show();
									});								
								}
							}
						});
					}
				}			
			}else{
				J('#'+menusection).slideUp();
				J(opened).removeClass('opened');
			}
		}else{
			J('.menu_section').slideUp();
		}
		return false;			
	});
	
	/* Chamada da pop do Player */
	J('#programas ul li a[rel=radio]').click(function(){
		popup('/template/fe/radio.jsp',312,198,'no');
		return false;
	});	
	
	//Função para detectar o click e fechar os menus do topo
	if(J('.menu_section').size()>0) document.onclick = clickPage;
	
	/* Função para aumentar/Diminuir Texto em Notícias e Promoções */
	var sizeText = 13;	
	function aumentarTamanho(){
		if(sizeText<20)sizeText++;
		J("div.texto_noticia, div.texto_promo").css({ fontSize :sizeText+"px" });
		return false;
	}	
	function diminuirTamanho(){
		if(sizeText>10)sizeText--;
		J("div.texto_noticia, div.texto_promo").css({ fontSize :sizeText+"px" });
		return false;
	}
	J('div.tamanho_texto a.aumentar').click(aumentarTamanho);
	J('div.tamanho_texto a.diminuir').click(diminuirTamanho);	
	
	
	J('#respostaEnquete').submit(function(){
		popup('/elementos/enquete.confirmar.logic?'+J('#respostaEnquete').serialize(),787,667,1);
		return false;
	});	
	
	
	J('table.listagem').each(function(){
		contTR = 0;
		J(this).find('tr').each(function(){
			if(J(this).css('display')!='none'){
				contTR++;
				if(contTR%2==0){
					J(this).removeClass('odd').addClass('even');
				} else {
					J(this).removeClass('even').addClass('odd');
				}
			}
		});	
	});
});