/* Functions */
var J = jQuery.noConflict();
function inputTitle(obj) {
	J(obj)
	.bind('focus',
	function() {
		if (this.value === this.getAttribute('title'))
			J(this).val('');
	})
	.bind('blur',
	function() {
		if (!this.value.length)
			J(this).val(this.getAttribute('title'));
	});
}

/*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');
	});
}


/*MODAL*/
// 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;
}

function openModal(obj) {
  	/*CREATE ELEMENTS*/
	
	J('body').append('<img src="/img/load.gif" width="88" height="78" alt="Carregando..." class="load" /><div class="bg_modal"></div><div class="view_modal"></div>');
	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(obj.attr('href'), function() {
			/*REMOVE LOAD*/
			J('.load').remove();
			
			/*CENTRALIZE MODAL*/
			if(leftModal != 0 || topModal != 0){
				J('.view_modal').css({
						marginTop: topModal, 
						marginLeft: leftModal,
						left: 0,
						top: 0
					}
				);
			} else {
				J('.view_modal').css({
						marginTop: - parseInt(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;
			})
		});
	});
}


function initModal() {
	// Gera erro na home ...

	/*
	if (J("a[@rel~='modal']")) {
		J("a[@rel~='modal']").click(function() {
			openModal(J(this));
			return false; 
		})
	}
	*/
}

J(document).ready(function(){
/*
* Trocar abas do menu do box Opçoes notícias da Home 
*/
J('.cx_result_busca ul li a').click(function() {
	J('.cx_result_busca ul li a').each(function(){
		classe = J(this).attr('class').replace('_on','');
		J(this).attr('class',classe);
	})
	classe = J(this).attr('class')+'_on';
	J(this).attr('class',classe);
	idBt = J(this).attr('id');
	J('div#container_result div.conteudo_noticias').hide();
	J('#container_'+idBt).show();
	return false;
});

});


//menu do header
var objInter;
function navShow(nav) {

if(objInter!='') clearInterval(objInter);

J('#nav_header ul li a').css('background-position','0 0');
nav = "."+nav;
var nav_sub = nav+"_sub";
var nav_subPrev;

J('#nav_header ul li ul.sub_menu').each(function(){	J(this.parentNode).css('display','none');});
J(nav_sub).css("display","inline");
J("#nav_header > ul > li").removeClass("selected");
J(nav+' a').css('background-position','0 -35px');
J(nav_sub).css("display","inline");

if (nav != ".home"){
	nav_subPrev = nav_sub;
}else{
	if (nav_subPrev != null) J(nav_subPrev).css("display","none");
	J("#nav_header > ul > li").removeClass("selected");
	J('#nav_header ul li a').css('background-position','0 0');
}

//nav+' a, '+nav_sub+' li a'
J(nav_sub).hover(
	function(){
		// executa abertura do menu normalmente
	},
	
	function(){
		if(objInter!=''){ clearInterval(objInter); }
			
		objInter = setInterval(function(){
			
			window.setTimeout(function(){
				
				J(nav_sub).css("display","none");
				J("#nav_header > ul > li").removeClass("selected");
				J('#nav_header ul li a').css('background-position','0 0');
			}, 1);
		}, 2000);
	}
);
}






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  addTicker()
@description Controla as mensagens exibidas no header do site 
@author: Leonardo Souza - leonardo.souza [at] agenciaclick [dot] com [dot] br
@version 2008-08-11 beta release
*/
var headline_count;
var headline_interval;
var old_headline = 0;
var current_headline = 0;

function addTicker() {
	function headline_rotate() {
		current_headline = (old_headline + 1) % headline_count; 
		J("p.headline:eq(" + old_headline + ")").animate({top: -205},"slow", function() {
			J(this).css('top','210px');
		});
		J("p.headline:eq(" + current_headline + ")").show().animate({top: 5},"slow");  
		old_headline = current_headline;
	}
	
	J.ajax({
		type: "GET",
		url: "../xml/ticker.xml",
		dataType: "xml",
		success: function(xml) {
			J(xml).find('noticia').each(
				function() {
					J('<p class="headline"><a href="'+J(this).find('link').text()+'">'+J(this).find('description').text()+'<\/a><\/p>').appendTo('#scrollup');
				}
			);
			headline_count = J("p.headline").length;
			J("p.headline:eq("+current_headline+")").css('top','5px');
			headline_interval = setInterval(headline_rotate,5000);
		}
	});
	
	J('#avancar').unbind().bind('click',
		function() {
			clearInterval(headline_interval);
			current_headline = (old_headline + 1) % headline_count; 
			J("p.headline:eq(" + old_headline + ")").animate({top: -205},"slow", function() {
				J(this).css('top','210px');
			});
			J("p.headline:eq(" + current_headline + ")").show().animate({top: 5},"slow");  
			old_headline = current_headline;
			headline_interval = setInterval(headline_rotate,5000);
		}
	);
	
	J('#anterior').unbind().bind('click',
		function() {
			clearInterval(headline_interval);
			current_headline = (old_headline - 1) % headline_count; 	
			if(current_headline<0) current_headline = headline_count-1;
			J("p.headline:eq(" + old_headline + ")").animate({top: +205},"slow", function() {
				J(this).css('top','-210px');
			});
			J("p.headline:eq(" + current_headline + ")").show().animate({top: 5},"slow");  
			old_headline = current_headline;
			headline_interval = setInterval(headline_rotate,5000);
		}
	);
	
	J('#parar').unbind().bind('click',
		function() {
			clearInterval(headline_interval);
		}
	);
	
	J('#parar').toggle(function(){
		J(this).css("backgroundImage", "url(/img/bt_nextA.gif)")
		J(this).attr("title", "Play");
		}, 
		function(){
		J(this).css("backgroundImage", "url(/img/bt_pause.gif)")
		J(this).attr("title", "Pause");
		headline_interval = setInterval(headline_rotate,5000);
		})

	
}


/*selecionar texto no campo */
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{
  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="../swf/_clipboard.swf" FlashVars="clipboard='+copy.value+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
  document.getElementById(flashcopier).innerHTML = divinfo;
 }

}

/*abrir e fechar filtro*/
function AbrirFiltros() {
	document.getElementById('resultados_busca').style.display='none';
	document.getElementById('link_abrir').style.display='none';
	document.getElementById('link_fechar').style.display='block';
}
function FecharFiltros(){
	document.getElementById('resultados_busca').style.display='block';
	document.getElementById('link_fechar').style.display='none';
	document.getElementById('link_abrir').style.display='block';
}

/*abrir e fechar filtro da busca */
function FecharFiltrosBusca(){
	document.getElementById('ordenar').style.display='none';
	document.getElementById('link_fechar').style.display='none';
	document.getElementById('link_abrir').style.display='block';
}
function AbrirFiltrosBusca() {
	document.getElementById('ordenar').style.display='block';
	document.getElementById('link_abrir').style.display='block';
	document.getElementById('link_fechar').style.display='none';
}

/*selecionar checkbox*/
function check_all(){
	J('#link_checar').toggle(function(){
		J("#resultados_busca input[@type='checkbox']").each(function(){
			this.checked=true;  
		});
		J(this).html('Tirar sele&ccedil;&atilde;o').attr('title','Tirar seleção')
		return false;
	},
	function(){
		J("#resultados_busca input[@type='checkbox']").each(function(){
			this.checked=false;  
		});
		J(this).html('Selecionar todos').attr('title','Selecionar todos')
		return false;
	});

};

/*Preloader imagens do menu*/
function preloadImages(){	
	var X=document;
	if(X.images){
		if(!X.p){
			X.p=new Array();
		}
		var S,p=X.p.length,G=preloadImages.arguments;
		for(S=0;S<G.length;S++){
			if(G[S].indexOf("#")!=0){
				X.p[p]=new Image;
				X.p[p++].src=G[S];
			}
		}
	}
}


// GALERIA DE FOTOS ( SEÇÂO MULTIMIDIA)
var cont = '';
var time_slide_show = null;
var velocidade;

function slide_fotos(){
	var total_thumbs = J('.outras_imagens ul li').size()-1;
	
	//zera o ícone de posição de  velocidade
	J('.bt_posicao').animate({left: '45px'});
	
	//inicia com o primeiro cara
	var init_obj = J('.outras_imagens ul li:eq(0) a');
	J('.img_selecionada img').attr({
		src: init_obj.attr('href'),
		alt: init_obj.attr('title'),
		title: init_obj.attr('title')
	});
	J('.legenda').text(init_obj.attr('title'));
	init_obj.parent().addClass('ativo');
	
	//altera imagem ao clicar no thumb
	J('.outras_imagens ul li a').click(function(){
		if(cont<total_thumbs || cont==0){
			cont++;
		}else{
			cont=0;
		};
		var h = J(this).attr('href');
		var t = J(this).attr('title');
		J(this).parent().parent().find('li').removeClass('ativo');
		J(this).parent().addClass('ativo');
		J('.img_selecionada img').fadeTo('fast', 0, function(){
			J('.img_selecionada img').attr({
				src: h,
				alt: t,
				title: t
			});
			J('.img_selecionada img').fadeTo('fast', 1);
		});
		J('.legenda').text(t);
		clearInterval(time_slide_show);
		J('#bt_play_stop').removeClass('bt_stop').addClass('bt_play');
		J('.bt_posicao').animate({left: '45px'});
		return false;
	});

	//play
	J('#bt_play_stop').click(function(){
		J('.bt_posicao').animate({left: '45px'});
		if(velocidade==undefined || velocidade == 8000 || velocidade == 1000){
			velocidade = 3000;
		};
		if(J(this).attr('class')=='bt_play'){
			J(this).removeClass('bt_play').addClass('bt_stop');
			time_slide_show = setTimeout("slide_fotos_auto("+total_thumbs+")", 1);
			time_slide_show = setInterval("slide_fotos_auto("+total_thumbs+")", velocidade);
			cont=0;
			return false;
		}else{
			J(this).removeClass('bt_stop').addClass('bt_play');
			clearInterval(time_slide_show);
			return false;
		};
	});
	
	//rewind
	J('.bt_voltar').click(function(){
		if(cont==0 || cont=='' || cont==null){
			return false;
		}else{
			clearInterval(time_slide_show);
			cont = cont-2;
			time_slide_show = setTimeout("slide_fotos_auto("+total_thumbs+")", 1);
			//time_slide_show = setInterval("slide_fotos_auto("+total_thumbs+")", velocidade);
			return false;
		};		
	});

	//forward
	J('.bt_avancar').click(function(){
		slide_fotos_auto(parseInt(total_thumbs+1));
		return false;
	});

	//diminui a velocidade
	J('.rapido').click(function(){
		clearInterval(time_slide_show);
		J('#bt_play_stop').removeClass('bt_play').addClass('bt_stop');
		velocidade = 1000;
		time_slide_show = setInterval("slide_fotos_auto("+total_thumbs+")", velocidade);
		J('.bt_posicao').animate({left: '85px'});
		return false;
	});

	//aumenta a velocidade
	J('.lento').click(function(){
		clearInterval(time_slide_show);
		J('#bt_play_stop').removeClass('bt_play').addClass('bt_stop');
		velocidade = 8000;
		time_slide_show = setInterval("slide_fotos_auto("+total_thumbs+")", velocidade);
		J('.bt_posicao').animate({left: 0});
		return false;
	});
};

function slide_fotos_auto(total){
	if(cont<total || cont==0){
		var obj = J('.outras_imagens ul li:eq('+cont+') a');
		obj.parent().parent().find('li').removeClass('ativo');
		obj.parent().addClass('ativo');
		J('.img_selecionada img').fadeTo('fast', 0, function(){
			J('.img_selecionada img').attr({
				src: obj.attr('href'),
				alt: obj.attr('title'),
				title: obj.attr('title')
			});
			J('.img_selecionada img').fadeTo('fast', 1);
		});
		J('.legenda').text(obj.attr('title'));
		cont++;
	}else{
		cont=0;
	};
};



function somente_numero(campo){  
var digits="0123456789"  
var campo_temp   
    for (var i=0;i<campo.value.length;i++){  
        campo_temp=campo.value.substring(i,i+1)   
        if (digits.indexOf(campo_temp)==-1){  
            campo.value = campo.value.substring(0,i);  
        }  
    }  
}


function selecionaDe(){ 
	J('#txt_de_dia').focus(function(){
		J('#rd_datadata').attr('checked','true');
	})
	
	J('#txt_de_dia').blur(function(){
		J('#rd_datadata').attr('checked','false');
	})
}
function widgetOutroTamanho(){ 
	J('#largura').focus(function(){
		J('#outroTamanho').attr('checked','true');
	})
	
	J('#largura').blur(function(){
		J('#outroTamanho').attr('checked','false');
	})
	
	J('#altura').focus(function(){
		J('#outroTamanho').attr('checked','true');
	})
	
	J('#altura').blur(function(){
		J('#outroTamanho').attr('checked','false');
	})
	
	J('#end').focus(function(){
		J('#outroTamanho').attr('checked','true');
	})
	
	J('#end').blur(function(){
		J('#outroTamanho').attr('checked','false');
	})	
}



//Troca automática de campo
var isNN = (navigator.appName.indexOf("Netscape")!=-1);
function autoTab(input,len, e) {
	var keyCode = (isNN) ? e.which : e.keyCode;
	var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
	if(input.value.length >= len && !containsElement(filter,keyCode)) {
		input.value = input.value.slice(0, len);
		input.form[(getIndex(input)+1) % input.form.length].focus();
	}
	function containsElement(arr, ele) {
		var found = false, index = 0;
		while(!found && index < arr.length)
			if(arr[index] == ele)
				found = true;
			else
				index++;
			return found;
	}
	function getIndex(input) {
		var index = -1, i = 0, found = false;
		while (i < input.form.length && index == -1)
		if (input.form[i] == input)index = i;
			else i++;
		return index;
	}
return true;
}


// conta e limita caracteres
function counterUpdate(opt_countedTextBox, opt_countBody, opt_maxSize) {
    var countedTextBox = opt_countedTextBox ? opt_countedTextBox : "txt_comentario";
    var countBody = opt_countBody ? opt_countBody : "countBody";
    var maxSize = opt_maxSize ? opt_maxSize : 1024;

    var field = document.getElementById(countedTextBox);

    if (field && field.value.length >= maxSize) {
            field.value = field.value.substring(0, maxSize);
    }
    var txtField = document.getElementById(countBody);
            if (txtField) { 
            txtField.innerHTML = field.value.length;
    }
}


// botao aparece depois de 15 segundos
J( document ).ready(function(){
	setTimeout(function(){
	J('#bt_jaSouAssinante').html("<img src='../img/bt_ja_assinante.jpg' alt='J&aacute; sou assinante' /> ")
	}, 15000)
});


// Show Hide
J( document ).ready(function(){
	J('#result_geral').click(function(){
		J('.result_executivos').hide() 
		J('.result_geral').show()
		J('.result_contato').hide()
		J('.result_especialidades').hide()
		J(this).addClass('selected')
		J('#result_executivos').removeClass('selected')
		J('#result_contato').removeClass('selected')
		J('#result_especialidades').removeClass('selected')
	});
	
	J('#result_contato').click(function(){
		J('.result_executivos').hide() 
		J('.result_geral').hide()
		J('.result_contato').show()
		J('.result_especialidades').hide()
		J(this).addClass('selected')
		J('#result_executivos').removeClass('selected')
		J('#result_geral').removeClass('selected')
		J('#result_especialidades').removeClass('selected')
	});
	
	J('#result_executivos').click(function(){
		J('.result_executivos').show() 
		J('.result_geral').hide()
		J('.result_contato').hide()
		J('.result_especialidades').hide()
		J(this).addClass('selected')
		J('#result_geral').removeClass('selected')
		J('#result_contato').removeClass('selected')
		J('#result_especialidades').removeClass('selected')
	});
	
	J('#result_especialidades').click(function(){
	
		J('.result_geral').hide()
			
		J('.result_executivos').hide()
		J('.result_especialidades').show() 
		J(this).addClass('selected')
		J('#result_geral').removeClass('selected')
		J('#result_executivos').removeClass('selected')
		
	});
});
