var ie6 = false;
if(navigator.userAgent.toUpperCase().indexOf('MSIE 6') > -1 || navigator.userAgent.toUpperCase().indexOf('MSIE 7') > -1 || (navigator.userAgent.toUpperCase().indexOf('SAFARI') > -1 && navigator.userAgent.toUpperCase().indexOf('CHROME') == -1))
	ie6 = true;
	
var isIphone = false;
if(navigator.userAgent.toUpperCase().indexOf('IPHONE') > -1) 
	isIphone = true;

//var regioes = ['Acre#ac','Alagoas#al','Amapá#ap','Amazonas#am','Bahia#ba','Ceará#ce','Distrito Federal#df','Espírito Santo#es','Goiás#go','Maranhão#ma','Mato Grosso#mt','Mato Grosso do Sul#ms','Minas Gerais#mg','Pará#pa','Paraíba#pb','Paraná#pr','Pernambuco#pe','Piauí#pi','Rio de Janeiro#rj','Rio Grande do Norte#rn','Rio Grande do Sul#rs','Rondônia#ro','Roraima#rr','Santa Catarina#sc','São Paulo#sp','Sergipe#se','Tocantins#to'];
var regioes = ['Acre#AC','Alagoas#AL','Amapá#AP','Amazonas#AM','Bahia#BA','Ceará#CE','Distrito Federal#DF','Espírito Santo#ES','Goiás#GO','Maranhão#MA','Mato Grosso#MT','Mato Grosso do Sul#MS','Minas Gerais#MG','Pará#PA','Paraíba#PB','Paraná#PR','Pernambuco#PE','Piauí#PI','Rio de Janeiro#RJ','Rio Grande do Norte#RN','Rio Grande do Sul#RS','Rondônia#RO','Roraima#RR','Santa Catarina#SC','São Paulo#SP','Sergipe#SE','Tocantins#TO'];

$(document).ready(function(){
	//$('input.input_ddd[name=foneArea]').numeric();
	//$('input.input_celular[name=foneNumero]').numeric();
	
	if(getCookie('siteColor') == '' || getCookie('siteColor') == undefined || getCookie('siteColor') == null)
		setCookie('siteColor','cor660099',12*365*24);

	//-- Pega a cor no cookie e define na pagina
	$('body').attr('class',getCookie('siteColor'));
	
	//-- Marca a cor atual no painel de cores
	$('#personalize_content .escolhe_cor ul li img[name='+ getCookie('siteColor') +']').parent('li').attr('class','selected');

	//-- Popula o dropdown de regioes
	for(i=0; i<regioes.length; i++){
		var liRegional = document.createElement('li');
		liRegional.setAttribute('id',regioes[i]);
		liRegional.innerHTML = regioes[i].split('#')[0];
		
		$('#ddl_regional .opener').append(liRegional);
	}
	
	if(getCookie('regional') != null && getCookie('regional') != undefined && getCookie('regional') != ''){
		//alert('regional='+getCookie('regional'))
		//-- Atribui o nome da regiao no select box
		for(r in regioes){
			if((regioes[r].split('#')[1]).toLowerCase() == getCookie('regional').toLowerCase()){
				$('#ddl_regional .ddlOpener .selected').html(regioes[r].split('#')[0]);
				break;
			}
		}
	}
	
	/**** Acões para o Dropdown ****/
		//-- Dropdown de regionalização
		$('.dropdown .ddlOpener').click(function(){
			
			//-- Se o dropdown for uma lista e está visivel, esconde ele
			if($(this).parent('ul').children('li.itens').children('.opener').css('display') == 'block'){
				$(this).parent('ul').children('li.itens').children('.opener').slideUp('fast');
				
				if(ie6)
					$('select').show();
			
			//-- Caso contrario, esconde os demais e mostra o que foi clicado
			}else{
				$('.dropdown ul li.itens ul').slideUp('fast');
				
				//-- Se o box de acesso rapido estiver aberto e for solicitado abrir o dropdown de regioes, entao é fechado o box de acesso rapido
				if($(this).parent('ul').parent('.ddl_seta').parent('.dropdown').attr('id') == 'ddl_regional')
					$('.dropdown .box_acesso_rapido').fadeOut('fast');
				
				$(this).parent('ul').children('li.itens').children('.opener').slideDown('fast');
				
				if(ie6){
					$('select').hide();
					$('.lightbox_content').find('select').show();
				}
			}
		});
		
		//-- dropdown para selects de formularios
		$('.dropdown .ddlSelect').click(function(){
			//-- Se o dropdown for uma lista e está visivel, esconde ele
			if($(this).parent('ul').children('li.itens').children('.opener').css('display') == 'block'){
				$(this).parent('ul').children('li.itens').children('.opener').slideUp('fast');
			
			//-- Caso contrario, esconde os demais e mostra o que foi clicado
			}else{
				$('.dropdown ul li.itens ul').slideUp('fast');
				$(this).parent('ul').children('li.itens').children('.opener').slideDown('fast');
			}
		});
		//-- Seleciona a opção correta no select que está invisivel.
			$('.dropdown .ddlSelect').parent('ul').find('li.itens li').click(function(){
				//-- Pega o ID do select no elemento do dropdown clicado...
				var parent_id = $(this).parents('.dropdown')[0].id.split('#')[1];
				var name = $('#' + parent_id).parent('fieldset').children('legend').html();
				var value = $(this).attr('value');
				
				//-- e seta no select invisivel
				$('#' + parent_id)[0].selectedIndex = value;
				
				$(this).parent('.opener').parent('li.itens').parent('ul').children('.ddlSelect').children('.selected').html(value != 0 ? $(this).html() : name);
				$(this).parent('.opener').slideUp('fast');
			});
		/* Lembrado que: o ID do dropdown tem que conter o id do select a ser referenciado seguido de '#' */
		
		//-- box geral
		$('.dropdown .boxOpener').click(function(){
			//-- Se o box clicado está visivel, esconde ele
			if($(this).parent('ul').parent('.ddl_seta').children('.box_acesso_rapido').css('display') == 'block'){
				$(this).parent('ul').parent('.ddl_seta').children('.box_acesso_rapido').fadeOut('fast');
				
				if(ie6)
					$('select').show();
			//-- Caso contrario, esconde os demais e mostra o que foi clicado
			}else{
				$(this).parent('ul').parent('.ddl_seta').children('.opener').find('.dropdown').find('.opener').hide();
				$(this).parent('ul').parent('.ddl_seta').children('.opener').fadeIn('fast');
				
				if(ie6){
					$('select').hide();
					$('.lightbox_content').find('select').show();
				}
			}
			
			/**
			/*	Se a posição do box estiver maior que o tamanho da janela do navegador
			/*  então seta o box de Acesso Rápido para abrir alguns pixels mais para esquerda
			/*  para evitar rolagem horizontal extra.
			**/
			if(($('.box_acesso_rapido').offset().left + $('.box_acesso_rapido').width() + 64) > $(window).width())
				$('.box_acesso_rapido').css('margin-left','-168px');
			else
				$('.box_acesso_rapido').css('margin-left','-104px');
		});
	/**** FIM - Ações para o Dropdown  ****/
	
	//-- Look and Feel de mouseover nos links em lista
	$('.dropdown li.itens li').mouseover(function(){ $(this).addClass('on'); });
	$('.dropdown li.itens li').mouseout(function(){ $(this).removeClass('on'); });
	
	
	/******* IMPORTANTE: ALTERAR ESTE TRECHO PARA REGIONALIZAR COM COOKIE GRAVADO DA REGIÃO *******/
	$('.dropdown#ddl_regional li.itens li').click(function(){
		//setCookie('regional',$(this).attr('id'),12*365*24);
		//setCookie('regional',$(this).attr('id').split('#')[1],12*365*24);
		//$(this).parent('ul').parent('li').parent('ul').find('span.selected').html($(this).html());
		var url = unescape(window.location.href);
		if(url.indexOf('regional=') == -1){
			window.location.href = (url.indexOf('?') > -1) ? url + '&regional=' + $(this).attr('id').split('#')[1] : url + '?regional=' + $(this).attr('id').split('#')[1];
		}else{
			window.location.href = (url.indexOf('&regional=') > -1) ? url.substring(0,url.indexOf('&regional=')) + url.substring(url.indexOf('&regional=') + 12) + '&regional=' + $(this).attr('id').split('#')[1] : url.substring(0,url.indexOf('?regional=')) + '?regional=' + $(this).attr('id').split('#')[1] + url.substring(url.indexOf('?regional=') + 12);
		}
		//$('#ddl_regional').find('.opener').slideUp('fast');
	});
	
	
	
	//-- Se o site estiver sendo acessado por qualquer dispositivo, que nao seja o iPhone, é verificada a posicao do mouse, para fechar os dropdowns quando ocorrer o mouseout
	if(!isIphone){
		//-- Fecha o dropdown quando aberto se ocorrer mouseout.
		$(document).mousemove( function(e) {
			mouseX = e.pageX;
			mouseY = e.pageY;
			
			var tRegion = rRegion = bRegion = lRegion = undefined;
			//-- Dropdown de Regioes
			try
			{
				tRegion = $('.dropdown#ddl_regional').find('ul').find('li.itens').offset().top - 30;
				bRegion = $('.dropdown#ddl_regional').find('ul').find('li.itens').height() + $('.dropdown#ddl_regional').find('ul').find('li.itens').offset().top + 30;
				lRegion = $('.dropdown#ddl_regional').find('ul').find('li.itens').offset().left - 30;
				rRegion = $('.dropdown#ddl_regional').find('ul').find('li.itens').width() + $('.dropdown#ddl_regional').find('ul').find('li.itens').offset().left + 30;
			
				if(lRegion != undefined && rRegion != undefined && tRegion != undefined && bRegion != undefined)
				{
					if(	mouseX < lRegion || mouseX > rRegion ||	mouseY < tRegion || mouseY > bRegion){
						if($('.dropdown#ddl_regional').find('ul').find('li.itens').find('ul').css('display') == 'block'){
							$('.dropdown#ddl_regional').find('ul').find('li.itens').find('ul').slideUp('normal');
							
							if(ie6){ $('select').show(); }
							lRegion = rRegion = tRegion = bRegion = undefined;
						}
					}
				}
				
				tRegion = $('.dropdown#ddl_vol').find('ul').find('li.itens').offset().top - 30;
				bRegion = $('.dropdown#ddl_vol').find('ul').find('li.itens').height() + $('.dropdown#ddl_vol').find('ul').find('li.itens').offset().top + 30;
				lRegion = $('.dropdown#ddl_vol').find('ul').find('li.itens').offset().left - 30;
				rRegion = $('.dropdown#ddl_vol').find('ul').find('li.itens').width() + $('.dropdown#ddl_vol').find('ul').find('li.itens').offset().left + 30;
				
				if(lRegion != undefined && rRegion != undefined && tRegion != undefined && bRegion != undefined)
				{
					if(	mouseX < lRegion || mouseX > rRegion ||	mouseY < tRegion || mouseY > bRegion){
						if($('.dropdown#ddl_vol').find('ul').find('li.itens').find('ul').css('display') == 'block'){
							$('.dropdown#ddl_vol').find('ul').find('li.itens').find('ul').slideUp('normal');
							
							if(ie6){ $('select').show(); }
							lRegion = rRegion = tRegion = bRegion = undefined;
						}
					}
				}
			}
			catch(e){}
			
			var tAcesso = rAcesso = bAcesso = lAcesso = undefined;
			//-- Dropdown de Acesso Rápido
			try
			{
				tAcesso = $('.dropdown#ddl_acesso_rapido').find('.opener').offset().top - 30;
				bAcesso = $('.dropdown#ddl_acesso_rapido').find('.opener').height() + $('.dropdown#ddl_acesso_rapido').find('.opener').offset().top + 30;
				lAcesso = $('.dropdown#ddl_acesso_rapido').find('.opener').offset().left - 30;
				rAcesso = $('.dropdown#ddl_acesso_rapido').find('.opener').width() + $('.dropdown#ddl_acesso_rapido').find('.opener').offset().left + 30;
			
				if(lAcesso != undefined && rAcesso != undefined && tAcesso != undefined && bAcesso != undefined)
				{
					if(	mouseX < lAcesso || mouseX > rAcesso ||	mouseY < tAcesso || mouseY > bAcesso){
						if($('.dropdown#ddl_acesso_rapido').find('.opener').css('display') == 'block'){
							$('.dropdown#ddl_acesso_rapido').find('.opener').fadeOut('normal');
							$('.dropdown#ddl_acesso_rapido li.itens .opener li').css('background','#eee');
							
							if(ie6){ $('select').show(); }
							lAcesso = rAcesso = tAcesso = bAcesso = undefined;
						}
					}
				}
			}
			catch(e){}
		});
	}
	
	/* Animação do menu personalizado */
	$('#personalize_content .botao .botaoContent').click(function(){
		
		var paravocePage = window.location.href;
		if (paravocePage.indexOf("/portal/para-voce.php") != -1)
		{
			_gaq.push(['_trackEvent', 'paravoce_home_customizacao', 'clique-descubra', 'home']);
		}
			
		if($(this).parents('#personalize_content').find('.content').find('.conteudo').css('display') != 'block'){
			//-- Faz uma animação caso o browser não seja IE6
			if(ie6 != true)
				$(this).parents('#personalize_content').find('.content').find('.conteudo').find('.personalize_item').css('display','none');
			
			$(this).parents('#personalize_content').find('.content').find('.conteudo').slideDown(150);
			$(this).find('p.titulo').html('fechar');
			$(this).find('.seta').addClass('on');
			
			//-- Faz uma animação caso o browser não seja IE6
			if(ie6 != true)
				$(this).parents('#personalize_content').find('.content').find('.conteudo').find('.personalize_item').fadeIn('fast');
			else
				$(this).parents('#personalize_content').find('.content').find('.conteudo').find('.personalize_item').show();
				
		}else{
			//-- Faz uma animação caso o browser não seja IE6
			if(ie6 != true)
				$(this).parents('#personalize_content').find('.content').find('.conteudo').find('.personalize_item').fadeOut('fast');
			else
				$(this).parents('#personalize_content').find('.content').find('.conteudo').find('.personalize_item').hide();
			
			$(this).parents('#personalize_content').find('.content').find('.conteudo').slideUp(300);
			//$(this).find('p.titulo').html('Eu Sou 50 Milh&otilde;es');
			$(this).find('p.titulo').html('Descubra');
			$(this).find('.seta').removeClass('on');
		}
	});
	
	/* Selecionando a cor da pagina */
	$('#personalize_content .pessoas_conectadas ul li').click(function(){
		setCookie('siteColor',$(this).find('img').attr('name'),12*365*24);
	
		//-- Se for IE6, então é feito refresh na pagina
		//if(ie6 == true){
		//	window.location.href = "";
		//}else{
			$('#personalize_content .pessoas_conectadas ul li').removeClass('selected');
			$(this).addClass('selected');
			
			if(ie6 == true) $('body,html').hide();
			else $('body').hide();
				
			$('body').attr('class',$(this).find('img').attr('name'));
			
			if(ie6 == true) $('body,html').fadeIn('slow');
			else $('body').fadeIn('slow');
		//}

	});
	
	/* Elimina a sombra no IE6 */
	if(ie6 == true){
		$('.addSombra').css('background','none');
	}
	
	$('.sombra').ready(function(){
		//-- Remove a sombras da direita se a janela estiver em um tamanho menor que (1024 + tamanho da sombra)
		if($(window).width() <= 1049)
			$('.sombra .on_right').hide();
		else
			$('.sombra .on_right').show();
	
		//-- Remove a sombras do IE6
		if(ie6 == true){
			$('.sombra .on_left').hide();
			$('.sombra .on_right').hide();
		}else{
			fnAjustaSombra();
			$('.sombra').each(function(){
				$(this).find('.on_left').css('margin-left','-35px');
				$(this).find('.on_right').css('margin-left', $(this).find('.context').width() + 16 + 'px');
			});
		}
	});
	
	//-- Remove a sombras da direita se a janela estiver em um tamanho menor que (1024 + tamanho da sombra)
	$(window).resize(function(){
		if($(window).width() <= 1049)
			$('.sombra .on_right').hide();
		else
			$('.sombra .on_right').show();
		
		
		//-- Ajusta o tamanho do lightbox e posicionamento
		if($('.lightbox').css('display') == 'block'){
			$('.lightbox .lb_background').css('width',$('.content_geral').width());
			$('.lightbox .lb_box').css('left',($(window).width() / 2) - ($('.lightbox .lb_box').width() / 2));
			$('.lightbox .lb_box').css('top',($(window).height() / 2) - ($('.lightbox .lb_box').height() / 2));
		}
	});
	
	//-- Fecha todas as categorias do menu lateral
	$('dl.lateral_categorias dl dd').hide();
	//-- Function: onClick do menu lateral para abrir as categorias
	$('dl.lateral_categorias a.menuTitulo').click(function(){
		$(this).blur();
		if($(this).parent().parent().find('dd').css('display') != 'block'){
			$(this).parent().addClass('on');
			$(this).parent().parent().find('dd').show();
		}else{
			$(this).parent().removeClass('on');
			$(this).parent().parent().find('dd').hide();
		}
		fnAjustaSombra();
	});
	
	//-- Montando o breadcrumb a partir das paginas selecionadas
	window.setTimeout(function(){
		var html = '';
		if($('.header_geral .menu li a.on').html() != null)
			html += '<a href="' + $('.header_geral .menu li a.on').attr('href') + '" >' + $('.header_geral .menu li a.on').html() + '</a>';
		
		if($('.header_geral .submenu li.on a').html() != null)
			html += ' &gt; <a href="' + $('.header_geral .submenu li.on a').attr('href') + '" >' + $('.header_geral .submenu li.on a').html() + '</a>';
			
		if($('dl.lateral_categorias h2#newSection').html() != null){
			html += ' &gt; <a href="' + $('dl.lateral_categorias h2#newSection a').attr('href') + '" >' + $('dl.lateral_categorias h2#newSection a').html() + '</a>';			
		}				
		
		if($('dl.lateral_categorias dd dt.on a').html() != null){
			html += ' &gt; <a href="' + ($('dl.lateral_categorias dd dt.on a').attr('href').indexOf('void(0)') == -1 ? $('dl.lateral_categorias dd dt.on a').attr('href') : $('.header_geral .submenu li.on a').attr('href')) + '" >' + $('dl.lateral_categorias dd dt.on a').html() + '</a>';
		}		
		
		if($('dl.lateral_categorias a.on').html() != null)
			html += ' &gt; <a href="' + $('dl.lateral_categorias a.on').attr('href') + '" >' + $('dl.lateral_categorias a.on').html() + '</a>';			
		
		if(html.length > 0)
			$('#breadcrumb_content').html(html);
		else
			$('#breadcrumb_content').parent().hide();
	},1);
	
	//-- Function: Internas de Duvidas - Show and Hide nas respostas
	$('fieldset#box_duvidas div.description > dl > dd').hide();
	$('fieldset#box_duvidas div.description > dl:first').addClass('sem_border');
	$('fieldset#box_duvidas div.description > dl > dt').click(function(){
		if($(this).parent().find('dd').css('display') == 'block'){
			$(this).removeClass('on');
			$(this).parent().find('dd').hide();
		}else{
			$(this).addClass('on');
			$('fieldset#box_duvidas div.description > dl > dd').hide();
			$(this).parent().find('dd').show();
		}
	});
	
	//-- Ao carregar a pagina, ajusta o tamanho das sombras dos conteudos
	fnAjustaSombra();
});

/***
** Função que realiza o ajax do conteudo na pagina.
** A estrutura do conteudo deve ser disponibilizada utilizando a tag fieldset.
** O parametro 'id' referencia ao id do fieldset.
***/
function fnMudaDescricao(elem, id){
	//-- Remove o blur do click
	$(elem).blur();
	
	//-- Selecione o menu clicado
	$(elem).parent().parent().find('li').removeClass('on');
	$(elem).parent().addClass('on');
	
	//-- Posiciona a seta do menu sobre o item clicado
	var left = ($(elem).offset().left - $(elem).parents('.subitens_menu').offset().left - 8) + ($(elem).width() / 2);
	$(elem).parents('.subitens_menu:first').prev().css('margin-left',left + 'px');
	
	//-- Mostra o conteudo referente ao item clicado
	$(elem).parent().parent().parent().find('fieldset').hide();
	$(elem).parent().parent().parent().find('#' + id).show();
	//-- Se houver outro submenu interno, clica no primeiro item do menu
	$(elem).parent().parent().parent().find('#' + id).find('.subitens_menu li:first a').click();
	
	fnAjustaSombra();
}

function fnAjustaSombra(){
	//-- Ajusta a altura da sombra das caixas
	$('.sombra').each(function(){
		$(this).find('.s_center').css('height',$(this).find('.moldura').height() - 200);
		$(this).find('.s_center').css('background-repeat','repeat-y');
	});
}

function fnMontaContador(numero){
	var vNumero = numero > 9999999 ? '9999999' : numero.toString();
	var array_numeros = [];
	var contadorHtml = '';
	
	var cont = 0;
	var contNumero = vNumero.length;
	for(i=0; i<7; i++){
		var num = 0;
		if((i + contNumero) >= 7){
			num = vNumero.charAt(cont);
			cont++;
		}
			
		contadorHtml += '<strong>' + num + '</strong>';
	}
	
	document.write(contadorHtml);
}

var fontSizeLevel = 0;
function fnFontSize(operador){
	if(operador == '+'){
		if(fontSizeLevel < 2){
			$('.conteudoMeio').css('font-size', parseInt($('.conteudoMeio').css('font-size')) + 2);
			fontSizeLevel++;
		}
		
	}else if(operador == '-'){
		if(fontSizeLevel > 0){
			$('.conteudoMeio').css('font-size', parseInt($('.conteudoMeio').css('font-size')) - 2);
			fontSizeLevel--;
		}
		
	}
}

function fnOpenAndClose(elemento, id){
	if($('#' + id).css('display') == 'block'){
		$(elemento).parents('dt:first').removeClass('on');
		$('#' + id).hide();
	}else{
		$(elemento).parents('dt').addClass('on');
		$('#' + id).show();
	}
}

function getCookie(c_name){
	if (document.cookie.length>0){
  		c_start=document.cookie.indexOf(c_name + "=");
  		if (c_start!=-1){
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
    		return unescape(document.cookie.substring(c_start,c_end));
    	}
  	}
	return "";
}

function setCookie(c_name,value,expiredays){
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

// Major version of Flash required
var requiredMajorVersion = 6;
// Minor version of Flash required
var requiredMinorVersion = 0;
// Revision of Flash required
var requiredRevision = 79;


function showFlashHome(getSWF,getVars,getLargura,getAltura){	
	var nome = getSWF.split('/');
	nome = nome[(nome.length - 1)];
	nome = nome.split('.swf')[0];
	
	if (AC_FL_RunContent == 0 || DetectFlashVer == 0){
		alert("This page requires AC_RunActiveContent.js.");
		
	}else{
		var hasRightVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
		if(hasRightVersion){
			AC_FL_RunContent(
				'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',
				'width', getLargura,
				'height', getAltura,
				'src', getSWF,
				'quality', 'high',
				'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
				'align', 'middle',
				'play', 'true',
				'loop', 'true',
				'scale', 'noscale',
				'wmode', 'transparent',
				'devicefont', 'false',
				'id', nome,
				'bgcolor', '#ffffff',
				'name', nome,
				'FlashVars', getVars,
				'menu', 'true',
				'allowScriptAccess','always',
				'allowFullScreen','false',
				'movie', getSWF,
				'salign', ''
			);
		}else{
			var path = getSWF.split('/');
			var imgPath = '';
			for(i=0; i < path.length-1; i++){
				imgPath += path[i] + '/';
			}
			imgPath += 'img/'+ path[path.length-1] +'.jpg';
			document.write('<img id="tvImg_'+ path[path.length-1] +'" src="' + imgPath + '" alt="" />');
		}
	}
}

function fnShowCidades(elem, id){
	$(elem).parent().parent().find('dd').hide();
	if(id != '')
		$('dd#' + id).show();
}

function in_array(needle,haystack) {
	return new RegExp('(^|\,)'+needle+'(\,|$)','gi').test(haystack);
}

/***
** Lightbox v1.0
** Author: Marcus Vinicius Corrêa
** Parameters: 	id = ID do elemento (apenas o nome do id, sem #)
**				width = largura do elemento (apenas o valor numerico)
**				height = altura do elemento (apenas o valor numerico)
**				condition = elemento ira abrir ou fechar (boolean 1 ou 0)
**				content = ID do conteudo que ira dentro do lightbox
***/
function fnLightBox(id, width, height, condition, content){
	if(ie6){
		$('select').hide();
		$('.lightbox_content').find('select').show();
	}
	
	//-- se a condition for definida como ZERO, entao o elemento com o ID selecionado sera fechado
	if(condition == 0){
		//-- esconde o box do conteudo
		$('#' + id).find('.lb_box').animate({
			opacity:0
		//-- esconde o background do lightbox
		},350).parent().find('.lb_background').delay(200).animate({
			opacity:0
		},350);
		
		//-- esconde a div principal do lightbox
		window.setTimeout(function(){
			$('#' + id).hide();
		},800);
		
		if(ie6){
			$('select').show();
		}
		
		return;
	}else if(condition == -1){
		//-- deleta o box do conteudo
		$('#' + id).remove();
		
		if(ie6){
			$('select').show();
		}
		
		return;
	}
	
	//-- se o elemento ainda nao existir na pagina, o trecho abaixo sera lido
	if($('body').find('#' + id).length == 0){
		//-- cria os elementos por javascript
		var lightbox = document.createElement('div');
		var lb_background = document.createElement('div');
		var lb_box = document.createElement('div');
		var lb_box_content = document.createElement('div');
		
		var lb_sombra = document.createElement('div');
		var lb_s_top = document.createElement('div');
		var lb_s_bottom = document.createElement('div');
		
		lightbox.setAttribute('class','lightbox');
		lightbox.className = 'lightbox';
		lightbox.setAttribute('id',id);
		
		lb_background.setAttribute('class','lb_background');
		lb_background.className = 'lb_background';
		lb_background.setAttribute('onclick','fnLightBox(\''+ id +'\',\'' + width + '\',\''+ height +'\',0,\''+ content +'\');');
		lb_background.onclick = function(){ fnLightBox(id, width, height, 0, content); };
		lightbox.appendChild(lb_background);
		
		lb_box.setAttribute('class','lb_box');
		lb_box.className = 'lb_box';
		lightbox.appendChild(lb_box);
		
		lb_box_content.setAttribute('class','lb_box_content');
		lb_box_content.className = 'lb_box_content';
		lb_box.appendChild(lb_box_content);
		
		//-- monta a estrutura do conteudo dentro do lightbox
		var box_html = '';
		box_html +=	'	<div class="bgRight">';
		box_html +=	'	<div class="bgLeft">';
		box_html +=	'		<div class="btn_fechar"><a class="lb_btn_fechar" href="javascript:void(0);" onclick="fnLightBox(\''+ id +'\',\'' + width + '\',\''+ height +'\','+ (condition == '-2' ? '-1' : '0') +',\''+ content +'\');" title="Fechar"><img src="/sys/img/2010/06/btn_fechar.gif" alt="" /> fechar</a></div>';
		box_html +=	'		<div class="lb_content"></div>';
		box_html +=	'	</div>';
		box_html +=	'	</div>';
		
		lb_box_content.innerHTML = box_html;
		
		//-- insere os elementos no corpo da pagina
		$('body').append(lightbox);
		
		//-- insere o conteudo real* que esta no html dentro do lightbox
		$('#' + id).find('.lb_content').append($('#' + content));
		$('#' + id).find('.lb_content').find('.lightbox_content').show();
		
		//--  * O que é o conteudo real?
		//-- 	Esse conteudo é uma DIV contendo um ID que sera passado como parametro ("content") nessa função.
		//--	Geralmente, esse conteudo fica alocado no arquivo da lateral direita, contendo um ID e uma classe ("lightbox_content").
		//-- 	Essa DIV ira conter todo o html que o lightbox ira mostrar na tela no momento do click.
		//--	O css dessa DIV podera ficar no css da própria área em que e encontra.
		//-- 	Essa função javascript apenas se encarrega de pegar essa DIV e jogar para dentro do lightbox, evitando ter N lightboxs diferentes.
		
	}
	
	//-- define altura e largura para o background e o box com conteudo
	$('#' + id).find('.lb_background').css('width',$('.content_geral').width() + 'px');
	$('#' + id).find('.lb_background').css('height',$(document).height() + 'px');
	$('#' + id).find('.lb_box_content').css('width',(width == 'auto' ? 'auto' : width + 'px'));
	$('#' + id).find('.lb_box_content').css('height',(height == 'auto' ? 'auto' : height + 'px'));
	$('#' + id).find('.lb_box').css('left',($(window).width() / 2) - (width / 2) + 'px');
	
	if(isNaN(height))
		$('#' + id).find('.lb_box').css('top','150px');
	else
		$('#' + id).find('.lb_box').css('top',($(window).height() / 2) - (height / 2) > 10 ? ($(window).height() / 2) - (height / 2) : 10);
	
	//-- mostra a div principal do lightbox
	$('#' + id).show();
	
	//-- faz o efeito de fadeIn no background do lightbox
	$('#' + id).find('.lb_background').css('opacity',0);
	$('#' + id).find('.lb_background').animate({
		opacity:0.7
	},350);
	
	//-- faz o efeito de fadeIn no box do conteudo
	$('#' + id).find('.lb_box').css('opacity',0);
	$('#' + id).find('.lb_box').delay(450).animate({
		opacity:1
	},350);
	
	//-- realiza o scroll para o topo da pagina
	$('html,body').animate({
		scrollTop: 0
	},200);
}

function fnLightBox_Video(id, width, height, condition, w, h, swf, variaveis){
	//-- se a condition for definida como ZERO, entao o elemento com o ID selecionado sera deletado
	if(condition == 0){
		$('#' + id).find('.lb_box').animate({
			opacity:0
		//-- esconde o background do lightbox
		},350).parent().find('.lb_background').delay(200).animate({
			opacity:0
		},350);
		
		//-- esconde a div principal do lightbox
		window.setTimeout(function(){
			$('#' + id).remove();
		},800);
		
		return;
	}
	
	//-- se o elemento ainda nao existir na pagina, o trecho abaixo sera lido
	if($('body').find('#' + id).length == 0){
		//-- cria os elementos por javascript
		var lightbox = document.createElement('div');
		var lb_background = document.createElement('div');
		var lb_box = document.createElement('div');
		var lb_box_content = document.createElement('div');
		
		var lb_sombra = document.createElement('div');
		var lb_s_top = document.createElement('div');
		var lb_s_bottom = document.createElement('div');
		
		lightbox.setAttribute('class','lightbox');
		lightbox.className = 'lightbox';
		lightbox.setAttribute('id',id);
		
		lb_background.setAttribute('class','lb_background');
		lb_background.className = 'lb_background';
		lb_background.setAttribute('onclick','fnLightBox_Video(\''+ id +'\',\'' + width + '\',\''+ height +'\',0,'+ w +','+ h +',\''+ swf +'\',\''+ variaveis +'\');');
		lb_background.onclick = function(){ fnLightBox_Video(id, width, height, 0, w, h, swf, variaveis); };
		lightbox.appendChild(lb_background);
		
		lb_box.setAttribute('class','lb_box');
		lb_box.className = 'lb_box';
		lightbox.appendChild(lb_box);
		
		lb_box_content.setAttribute('class','lb_box_content');
		lb_box_content.className = 'lb_box_content';
		lb_box.appendChild(lb_box_content);
		
		//-- monta a estrutura do conteudo dentro do lightbox
		var box_html = '';
		box_html +=	'	<div class="bgRight">';
		box_html +=	'	<div class="bgLeft">';
		box_html +=	'		<div class="btn_fechar"><a class="lb_btn_fechar" href="javascript:void(0);" onclick="fnLightBox_Video(\''+ id +'\',\'' + width + '\',\''+ height +'\',0);" title="Fechar"><img src="../sys/img/2010/06/btn_fechar.gif" alt="" /> fechar</a></div>';
		box_html +=	'		<div class="lb_content"></div>';
		
		box_html +=	'		<div class="video_content">';
		box_html +=	'		<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="'+ w +'" height="'+ h +'" id="CodeFlash" align="middle">';
		box_html +=	'		<param name="FlashVars" value="'+ variaveis +'">';
		box_html +=	'		<param name="allowScriptAccess" value="sameDomain" />';
		box_html +=	'		<param name="wmode" value="transparent" />';
		box_html +=	'		<param name="movie" value="'+ swf +'" /><param name="quality" value="hight" /><param name="bgcolor" value="#ffffff" />';
		box_html +=	'		<embed src="'+ swf +'" flashvars="'+ variaveis +'" wmode="transparent" quality="high" bgcolor="#ffffff" width="'+ w +'" height="'+ h +'" id="CodeFlash1" name="CodeFlash" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />';
		box_html +=	'		</object>';
		box_html +=	'		</div>';
		
		box_html +=	'	</div>';
		box_html +=	'	</div>';
		
		lb_box_content.innerHTML = box_html;
		
		//-- insere os elementos no corpo da pagina
		$('body').append(lightbox);
	}
	
	//-- define altura e largura para o background e o box com conteudo
	$('#' + id).find('.lb_background').css('width',$('.content_geral').width() + 'px');
	$('#' + id).find('.lb_background').css('height',$(document).height() + 'px');
	$('#' + id).find('.lb_box_content').css('width',width + 'px');
	$('#' + id).find('.lb_box_content').css('height',height + 'px');
	$('#' + id).find('.lb_box').css('left',($(window).width() / 2) - (width / 2));
	$('#' + id).find('.lb_box').css('top',($(window).height() / 2) - (height / 2) > 10 ? ($(window).height() / 2) - (height / 2) : 10);
	
	//-- mostra a div principal do lightbox
	$('#' + id).show();
	
	//-- faz o efeito de fadeIn no background do lightbox
	$('#' + id).find('.lb_background').css('opacity',0);
	$('#' + id).find('.lb_background').animate({
		opacity:0.7
	},350);
	
	//-- faz o efeito de fadeIn no box do conteudo
	$('#' + id).find('.lb_box').css('opacity',0);
	$('#' + id).find('.lb_box').delay(450).animate({
		opacity:1
	},350);
	
	//-- realiza o scroll para o topo da pagina
	$('html,body').animate({
		scrollTop: 0
	},200);
}

function fnPacotesDesconto_MudaAba(idLightbox,idAba){
	$('#'+ idLightbox +' .subitens .subitens_menu li a#' + idAba).click();
}



function xmlLoader(url){
	if(window.XMLHttpRequest) {
		var Loader = new XMLHttpRequest();
		try{
			Loader.open("GET", url ,false);
			Loader.send(null);
			return Loader.responseXML;
		}
			catch(e){
			return null;
		}
	}else if(window.ActiveXObject){
		var Loader = new ActiveXObject("Msxml2.DOMDocument.3.0");
		Loader.async = false;
		try{
			Loader.load(url);
			return Loader;
		} catch(e){
			return null;
		}
	}
}

function getParameter(pParam,pTipo){
	var wl = window.location.href;
	var params = urlDecode(wl.substring(wl.indexOf("?")+1));
	var param = params[pParam];
	
	if(param.length <= 0) return;
	
	//-- Tratando o parametro recebido, impedindo o uso de XSS
	switch(pTipo){
		case 'regional':
			var aUF = regioes;
			var vParam = param.toString().toLowerCase();
			if (in_array(vParam, aUF))
				return vParam;
			break;
			
		case 'numero':
			var numero = (parseInt(param) != undefined ? parseInt(param) : 0);
			if (!isNaN(numero))
				return numero;
			break;
			
		case 'string':
			if (param.toString().toLowerCase().indexOf('script') == -1){
				var vParam = param.replaceAll('<','&lt;').replaceAll('>','&gt;').replaceAll('/','&frasl;');
				return vParam;
			}
			break;
	}
	return '';
}

function urlDecode(string, overwrite){
    if(!string || !string.length){
        return {};
    }
    var obj = {};
    var pairs = string.split('&');
    var pair, name, value;
    var lsRegExp = /\+/g;
    for(var i = 0, len = pairs.length; i < len; i++){
        pair = pairs[i].split('=');
        name = unescape(pair[0]);
        value = unescape(pair[1]).replace(lsRegExp, " ");
        //value = decodeURIComponent(pair[1]).replace(lsRegExp, " ");
        if(overwrite !== true){
            if(typeof obj[name] == "undefined"){
                obj[name] = value;
            }else if(typeof obj[name] == "string"){
                obj[name] = [obj[name]];
                obj[name].push(value);
            }else{
                obj[name].push(value);
            }
        }else{
            obj[name] = value;
        }
    }
    return obj;
}

String.prototype.replaceAll = function(de, para){
    var str = this;
    var pos = str.indexOf(de);
    while (pos > -1){
		str = str.replace(de, para);
		pos = str.indexOf(de);
	}
    return (str);
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g, "");
}

String.prototype.ltrim = function() {
	return this.replace(/^\s+/, "");
}

String.prototype.rtrim = function() {
	return this.replace(/\s+$/, "");
}

//-- AJAX INICIO
function fnHttpRequest(file){
	var xmlHttp = getXMLHttp();
	
	xmlHttp.onreadystatechange = function(){
		if(xmlHttp.readyState == 4){
			fnHttpResponse(xmlHttp.responseText);
		}
	}
	xmlHttp.open("GET", file, true);
	xmlHttp.send(null);
}

function getXMLHttp(){
	var xmlHttp;
	
	try{
		xmlHttp = new XMLHttpRequest();
	}catch(e){
		try{
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		}catch(e){
			try{
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			}catch(e){
				alert("Your browser does not support AJAX!");
				return false;
			}
		}
	}
	return xmlHttp;
}

function fnHttpResponse(response){
	document.getElementById('faq_ajaxContent').innerHTML = response;
}
//-- AJAX FIM


function validarCPF(valor){
	var cpf = valor.replaceAll('.','').replaceAll('-','');
	if(cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" ||
	  cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" ||
	  cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" ||
	  cpf == "88888888888" || cpf == "99999999999"){
	  return false;
	}
	soma = 0;
	for(i = 0; i < 9; i++)
	 soma += parseInt(cpf.charAt(i)) * (10 - i);
	resto = 11 - (soma % 11);
	if(resto == 10 || resto == 11)
	 resto = 0;
	if(resto != parseInt(cpf.charAt(9))){
	 return false;
	}
	soma = 0;
	for(i = 0; i < 10; i ++)
	 soma += parseInt(cpf.charAt(i)) * (11 - i);
	resto = 11 - (soma % 11);
	if(resto == 10 || resto == 11)
	 resto = 0;
	if(resto != parseInt(cpf.charAt(10))){
	 return false;
	}
	return true;
}

function validarCNPJ(valor) {
	
	  var cnpj = valor.replaceAll('.','').replaceAll('-','').replaceAll('/','');
      var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
      digitos_iguais = 1;
      if (cnpj.length < 14 && cnpj.length > 15) {
            return false;
	  }
      for (i = 0; i < cnpj.length - 1; i++)
            if (cnpj.charAt(i) != cnpj.charAt(i + 1))
                  {
                  digitos_iguais = 0;
                  break;
                  }
      if (!digitos_iguais)
            {
            tamanho = cnpj.length - 2
            numeros = cnpj.substring(0,tamanho);
            digitos = cnpj.substring(tamanho);
            soma = 0;
            pos = tamanho - 7;
            for (i = tamanho; i >= 1; i--)
                  {
                  soma += numeros.charAt(tamanho - i) * pos--;
                  if (pos < 2)
                        pos = 9;
                  }
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(0)) {
                return false;
			}
            tamanho = tamanho + 1;
            numeros = cnpj.substring(0,tamanho);
            soma = 0;
            pos = tamanho - 7;
            for (i = tamanho; i >= 1; i--)
                  {
                  soma += numeros.charAt(tamanho - i) * pos--;
                  if (pos < 2)
                        pos = 9;
                  }
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(1)) {
                return false;
			}
            return true;
            }
      else {
            return false;
	  }
} //end validarCNPJ


function validarEmail(pEmail){
	var regex_email = /^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
	
	if (pEmail == null || pEmail == '')
		return false;
	
	if (regex_email.exec(pEmail))
		return true;
	
	return false;
}

function acessoMeuVivo(ddd,celular){
	if(isNaN(ddd.value) || ddd.value.length < 2){
		$(ddd).focus();
		return false;
	}else if(isNaN(celular.value) || celular.value.length < 8){
		$(celular).focus();
		return false;
	}
	
	return true;
}

function validarData(value){
	var regDate = /^((0[1-9]|[12]\d)\/(0[1-9]|1[0-2])|30\/(0[13-9]|1[0-2])|31\/(0[13578]|1[02]))\/\d{4}$/;
	if (regDate.test(value)){
		return true;
	}
	return false;
}

function removeAcento(text) {
	text = text.replace(new RegExp('[ÁÀÂÃ]','g'), 'A')
  		.replace('&Aacute;', 'A')
		.replace('&Agrave;', 'A')
		.replace('&Acirc;', 'A')
		.replace('&Atilde;', 'A')
  		.replace(new RegExp('[áàâã]','g'), 'a')
		.replace('&aacute;', 'a')
		.replace('&agrave;', 'a')
		.replace('&acirc;', 'a')
		.replace('&atilde;', 'a')
		.replace(new RegExp('[ÉÈÊ]','g'), 'E')
		.replace('&Eacute;', 'E')
		.replace('&Egrave;', 'E')
		.replace('&Ecirc;', 'E')
		.replace(new RegExp('[éèê]','g'), 'e')
		.replace('&eacute;', 'e')
		.replace('&egrave;', 'e')
		.replace('&ecirc;', 'e')
		.replace(new RegExp('[ÍÌÎ]','g'), 'I')
		.replace('&Iacute;', 'I')
		.replace('&Igrave;', 'I')
		.replace('&Icirc;', 'I')
		.replace(new RegExp('[íìî]','g'), 'i')
		.replace('&iacute;', 'i')
		.replace('&igrave;', 'i')
		.replace('&icirc;', 'i')
		.replace(new RegExp('[ÓÒÔÕ]','g'), 'O')
		.replace('&Oacute;', 'O')
		.replace('&Ograve;', 'O')
		.replace('&Ocirc;', 'O')
		.replace('&Otilde;', 'O')
		.replace(new RegExp('[óòôõ]','g'), 'o')
		.replace('&oacute;', 'o')
		.replace('&ograve;', 'o')
		.replace('&ocirc;', 'o')
		.replace('&otilde;', 'o')
		.replace(new RegExp('[ÚÙÛ]','g'), 'U')
		.replace('&Uacute;', 'U')
		.replace('&Ugrave;', 'U')
		.replace('&Ucirc;', 'U')
		.replace(new RegExp('[úùû]','g'), 'u')
		.replace('&uacute;', 'u')
		.replace('&ugrave;', 'u')
		.replace('&ucirc;', 'u')
		.replace(new RegExp('[Ç]','g'), 'C')
		.replace('&Ccedil;', 'C')
		.replace(new RegExp('[ç]','g'), 'c')
		.replace('&ccedil;', 'c');
		
  return text;
}

/* Inicio */
//Funções para as métricas do portal
function retirarAcento(objResp) {  
	 var varString = new String(objResp);  
	 var stringAcentos = new String('àâêôûãõáéíóúçüÀÂÊÔÛÃÕÁÉÍÓÚÇÜ -,');
	 var stringSemAcento = new String('aaeouaoaeioucuAAEOUAOAEIOUCU');  
		 
	 var i = new Number();  
	 var j = new Number();  
	 var cString = new String();  
	 var varRes = '';  
		 
	 for (i = 0; i < varString.length; i++) {  
		 cString = varString.substring(i, i + 1);  
		 for (j = 0; j < stringAcentos.length; j++) {  
			 if (stringAcentos.substring(j, j + 1) == cString){  
				 cString = stringSemAcento.substring(j, j + 1);  
			 }  
		 }  
		 varRes += cString;  
	 }  
	 
	 return varRes.toLowerCase();
}  


function fnMetrica(texto){
	$.post('/metrica/metrica.php?WT.ac='+texto, function(){});
}
/* Final - Métrica do HotSite */

/* google analytics */
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-23670357-1']);
  _gaq.push(['_setDomainName', '.vivo.com.br']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

