$(document).ready(init);
	setTimeout('_gaq.push([\'_trackEvent\', \'NoBounce\', \'Over 20 seconds\'])',20000);
$(window).load(
	function() {
		defaultFontSize = parseInt(jQuery("#main, #wide").css('font-size')); //tamanho de fonte padrão dos elementos com id #main e #wide
		textZoomActions(); // aumentar e diminuir textos
		//printPreview(); // preview de impressão
		boxTabs(); // boxes with tabs
		
		if($('#gallery')[0] || $('#gallery-modal')[0])
			galleryInit(); // galeria
		

		/* +script temporário */
		if($('#news-page')[0]) {
			if($('.highlight-img')[0]) {
				var highlightImg = $('.highlight-img');
				var img = highlightImg.find('img');
				
				if(img.width() > 440)
					highlightImg.css("float","none");
				else
					highlightImg.css('width', img.width() + "px");
			}
		}
		/* end script temporário */
	}
);

function init() {
	/* +menu init */
	dropdown_init();
	/* end menu init */
	
	/* +ie6 hacks */
	if (isIe6()) {
		ieFlickerFix(); 
		over();
	}
	/* end ie6 hacks */
	
	/* +defaults */
	socialMenu();
	rels();
	_disabled('.disabled');
	htmlActions();
	numericLists();
	jsHide();

	/* end defaults */
	
	/* +pages */
	if($('#home')[0]) 
		home();
	
	if ($('#boxes.collapsible')[0])
		subHome();
	
	if($('#about-us-careers-tenders')[0]){
		
		$('.openTender').click(function(){
			//$('.tenderShow').slideUp();
			$(this).parent().next('.tenderShow').slideToggle();
		})				
		

		if(is_temp){			
			tendersTemp();
			tendersBiofuel();
			tendersConcursos();
		}else{			
			tenders();
			tendersBiofuel();
			tendersConcursos();
		}
	}
	
	environmentAndSocietyEnvironment();

	if($('.products-list')[0] || $('.products-large-list')[0]) 
		productsList();
	
	if($('#news-page')[0])
		news();
		
	faq();
	slideCarrousel();
	slideCarrousel2();
	transparency();
	/* end pages */
	
	/* +ie hacks */
	iconLinks();
	/* end ie hackes */	
	
$("a").click(function() {
	if($(this).attr('href').indexOf('.pdf') != -1 || $(this).attr('href').indexOf('.doc') != -1 || $(this).attr('href').indexOf('.xls') != -1 || $(this).attr('href').indexOf('.docx') != -1 || $(this).attr('href').indexOf('.zip') != -1 || $(this).attr('href').indexOf('.rar') != -1) {
		var $a = $(this);
		var href = $a.attr('href');
		var category = 'download';
		var event = 'click';
		var label = href;! ! !
		_gaq.push(['_trackEvent', category, event, label]);
	}
});
}


/* ***************************************** +locale / translation ******************************************* */
function locale(ref) {
	
	var t = new Array();
	
	if (lang=='pt') {
		
		t['textZoomText'] = 'Texto';
		t['textZoomTextTitle'] = 'Exibir texto no tamanho padrão';
		t['textZoomIn'] = 'Aumentar texto';
		t['textZoomOut'] = 'Diminuir texto';
		
		t['close'] = 'Fechar';
		t['open'] = 'Abrir';
		t['buttonDisabled'] = ' (botão desabilitado)';
		
		t['highlightsClose'] = 	'Fechar destaques';
		t['highlightsOpen'] = 'Abrir destaques';
		
		t['tenderFile'] = 'concurso.asp';
		t['tendersSelectYear'] = 'Selecione primeiramente o ano do concurso';
		t['tender'] = 'Concurso';
		t['selectTendersFinished'] = 'Campo para seleção do concurso finalizado';
		t['selectTendersAll'] = 'Campo para seleção do concurso';
		t['selectTenders'] = 'Selecione o concurso';
		
		t['newsUrlPath'] = '/noticias/';
		t['newsPagPath'] = 'pt/noticias/include/asp/ajax-other-news.asp'; 
		t['newsPagDetailsPath'] = 'pt/noticias/include/asp/ajax-other-news-details.asp';
		
		t['fillHighlightField'] = 'Por favor, preencha corretamente os campos destacados.';
		
		t['loading'] = 'Carregando...';

		t['accessibleInfo'] = 'Usuários que utilizam ledores de tela, o conteúdo foi carregado, continue navegando.';	
		t['seeLongDesc'] = 'Descrição detalhada da imagem';
		t['titleSeeLongDesc'] = 'Ir para a página com a descrição detalhada da imagem acima';
		
		
	}
	else {
		t['textZoomText'] = 'Text';
		t['textZoomTextTitle'] = 'Display text in default size';
		t['textZoomIn'] = 'Zoom text in';
		t['textZoomOut'] = 'Zoom text out';
		
		t['close'] = 'Close';
		t['open'] = 'Open';
		t['buttonDisabled'] = ' (button disabled)';
		
		t['highlightsClose'] = 	'Close highlights';
		t['highlightsOpen'] = 'Open highlights';
		
		t['tenderFile'] = 'contest.asp';
		t['tendersSelectYear'] = 'Please, select the year of the contest first';
		t['tender'] = 'Contest';
		t['selectTendersFinished'] = 'Completed contest selection field';
		t['selectTendersAll'] = 'Contest selection field';
		t['selectTenders'] = 'Select the contest';
		
		t['newsUrlPath'] = '/news/';
		t['newsPagPath'] = 'en/news/include/asp/ajax-other-news.asp'; 
		t['newsPagDetailsPath'] = 'en/news/include/asp/ajax-other-news-details.asp';
		
		t['fillHighlightField'] = 'Please, fill in the highlighted fields.';
		
		t['loading'] = 'Loading...';

		t['accessibleInfo'] = 'Users who use screen readers, the content has been loaded, continue browsing.';	
		t['seeLongDesc'] = 'Detailed image description';
		t['titleSeeLongDesc'] = 'Go to the page with the detailed description of the image above';
		

	}
	
	return (lang && ref) ? t[ref] : false;

}


/* ***************************************** +default ******************************************* */

function rels() { // função que atribui ações conforme o valor do atributo relationship da tag a
	
	$("a[@rel*=external]").attr("target", "_blank").click(function() {
		var $a = $(this);
		var href = $a.attr('href');
		var category = 'external-link';
		var event = 'click';
		var label = href;! ! !
		_gaq.push(['_trackEvent', category, event, label]);
	});
	
}

function _enable(selector) { // funcao para habilitar botoes (parametro seletor css)
	var el = $(selector);
	el.css({ opacity:'1', cursor:'pointer' });
	el.attr('title',el.attr('title').replace(locale('buttonDisabled'),''));	
	el.removeClass('disabled');
}

function _disabled(selector,hasEventAttached) { // funcao para desabilitar botoes (parametro seletor css)
	var el = $(selector);
	el.css({ opacity:'0.5', cursor:'default' });
	
	el.each(
		function(id) {
			var tLink = $(this); //this link
			var tLinkTitle = tLink.attr('title');
			
			if(tLink.attr('title').indexOf(locale('buttonDisabled')) == -1)
				tLink.attr('title',tLink.attr('title') + locale('buttonDisabled'));
		}
	);
	
	el.addClass('disabled');
	
	if (hasEventAttached == false) {
		el.unbind('click').bind('click',function() {
			return false;
		});
	}
}

function htmlActions() {
	$('#home #additional-highlights .header').css('cursor','pointer');
	
	/* +accessibility invisible links */
	var invLinks = $('a.invisible, a.accessible-link'); //invisible links 
	
	invLinks.bind('focus',
		function() {
			var tClass = $(this).hasClass('invisible') ? 'invisible' : 'accessible-link'; //this class
			
			if(supPositionFixed() && !isIe7()) // se o browser suportar position fixed e não for o ie7
				$(this).css({ position:'fixed', top:'-50px' }).removeClass(tClass).addClass('show-accessible-link').stop().animate({
					top:0
				});
			else
				$(this).removeClass(tClass).addClass('show-accessible-link');
				
			
		}
	);
	
	invLinks.bind('blur',
		function() {
			var tClass = $(this).hasClass('invisible') ? 'invisible' : 'accessible-link'; //this class
			if(supPositionFixed() && !isIe7()) // se o browser suportar position fixed e não for o ie7
				$(this).stop().animate({ top:'-50px' }, 
					function() {
						$(this).removeClass('show-accessible-link').addClass(tClass).css({ position:'absolute', top:'-9999px' });
					}
				);
			else
				$(this).removeClass('show-accessible-link').addClass(tClass);
		}
	);

	
	$('a[href="http://www2.petrobras.com.br/minisite/refinarias/petrosix/portugues/index.asp"]').click(
		function() {
			newWindow($(this).attr('href'), 'petrosix', 695, 459, 0, true);
			
			return false;
		}
	);
	
	$('a[href="http://www2.petrobras.com.br/minisite/refinarias/petrosix/ingles/index.asp"]').click(
		function() {
			newWindow($(this).attr('href'), 'petrosix', 695, 459, 0, true);
			
			return false;
		}
	);
	
	$('a[href="http://www2.petrobras.com.br/minisite/marine/port/index.html"]').click(
		function() {
			newWindow($(this).attr('href'), 'marine', 600, 406, 0, true);
			return false
		}
	);
	
	$('a[href="http://www2.petrobras.com.br/minisite/memoria/index.htm"]').click(
		function() {
			newWindow($(this).attr('href'), 'marine', 647, 386, 0, true);
			return false
		}
	);
	
	$('a[href="http://www2.petrobras.com.br/minisite/urucu/urucu.html"]').click(
		function() {
			newWindow($(this).attr('href'), 'marine', 750, 500, 0, true);
			return false
		}
	);
	
	$('a[href="http://postoscertificados.br-petrobras.com.br/index_ns.htm"]').click(
		function() {
			newWindow($(this).attr('href'), 'marine', 756, 421, 0, true);
			return false
		}
	);
	
	$('a[href="http://www.petrobras.com.br/minisite/refinarias/petrosix/portugues/index.asp"]').click(
		function() {
			newWindow($(this).attr('href'), 'marine', 693, 458, 0, true);
			return false
		}
	);
	
	$('a[href="http://www.petrobras.com.br/minisite/refinarias/petrosix/ingles/index.asp"]').click(
		function() {
			newWindow($(this).attr('href'), 'marine', 693, 458, 0, true);
			return false
		}
	);

	$('a[href="http://www.petrobras.com.br/minisite/urucu/urucu.html"]').click(
		function() {
			newWindow($(this).attr('href'), 'marine', 750, 500, 0, true);
			return false
		}
	);
	
	/* end pop-ups */
}

function numericLists() {
	var i = 1;
	$(".numeric-list .item-number").each(function() {
		$(this).prepend('<span class="number">'+ i++ +".</span> ");
	});
}

function jsHide() {
	$(".jsHide").css('display','none');
}

function resizeObject(size){
	$('#news-infograph').height(size);
}

function socialMenu(){

	/*var follow_us = $(".follow-us");
	$(">li", follow_us).mouseover(function(){
							$('.submenu', this).stop(1,1).show("fast");
						})
						.mouseleave(function(){
							$('.submenu', this).stop(1,1).hide("fast");
						});*/

	var follow_us = $(".follow-us");
	
	$(">li", follow_us).removeClass("noJs")
	                   .bind("mouseenter",function(){
							$(this).find(".submenu").stop(1,1).slideToggle("fast");
						})
						.bind("mouseleave",function(){
							$(this).find(".submenu").stop(1,1).slideToggle("fast");
						});
}

/* end defaults */

/* +win load  */
function textZoomActions() {
	
	if($('.text-actions')[0]) {
		var html = '<li class="text-size last"><a href="#" class="default-font" title="'+ locale('textZoomTextTitle') +'">'+ locale('textZoomText') +'</a><ul>';
		html += '<li class="increase-text last"><a href="#" title="'+ locale('textZoomIn') +'" class="hide_text">'+ locale('textZoomIn') + '</a></li>';
		html += '<li class="decrease-text"><a href="#" title="'+ locale('textZoomOut') + '" class="hide_text">'+ locale('textZoomOut') + '</a></li>';
		html += '</ul></li>';
	
		// create the list if it doesn't exist yet
		if (!$('#content-options ul')[0]) {
			$('#content-options .content').append("<ul>"+html+"</ul>");
		} else {
			$('#content-options .content ul').append(html);
		}
		
		rels(); //rebind
		textZoom();

	}
	$('.text-size').css('display', 'none');
	$('.text-size').eq(0).css('display', 'block');
}

function parseQueryString(queryString){
	
	var result = {};
	
	if (queryString == undefined) queryString = location.search ? location.search : '';
	if (queryString.charAt(0) == '?') queryString = queryString.substring(1);
	
	queryString = queryString.split('#')[0];
	queryString = queryString.replace('+', ' ');
	
	var queryComponents = queryString.split(/[&;]/g);
	
	for (var i = 0; i < queryComponents.length; i++){
		var keyValuePair = queryComponents[i].split('=');
		var key = decodeURIComponent(keyValuePair[0]);
		var value = decodeURIComponent(keyValuePair[1]);
		if (!result[key]) result[key] = [];
		result[key].push((keyValuePair.length == 1) ? '' : value);
	}
	
	return result;
}

/* +tabs (box com abas) */
function boxTabs() {
	if ($('.box-tabs')[0]) {
	
		var el = $('.box-tabs');
		el.find('.stripNav a:first').addClass('current');
		el.find('.panel:not(:first)').hide(1000);
		
		var links = el.find('.stripNav a');
		
		links.click(function() {
			var tLink = $(this); //this link
			var stripNav = $(this).parents('.stripNav');
			var tLinks = stripNav.find('a'); // this tabs
			var index = tLinks.index(this);
			var boxTabs = tLink.parents('.box-tabs');
			var panelContainer = tLink.parents('.box-tabs').find('.panelContainer');
			
			stripNav.removeAttr('id').attr('id','current-tab-' + parseInt(tLinks.index(this) + 1));
			stripNav.find('.current').removeClass('current');
			tLink.addClass('current');
			boxTabs.find('.panel').hide().eq(index).show();
			
			/* +accessible warning */
			$('.accessible-info').hide();
			if(!boxTabs.find('.accessible-info')[0]){
				var panelContainerIndex = parseInt($('.panelContainer').index(panelContainer)) + 1;
				$('<a href="#panels-'+ panelContainerIndex +'" class="accessible-info">'+ locale('accessibleInfo') +'</a>').insertBefore(panelContainer);
				el.find('.accessible-info').focus();
			}
			else{
				el.find('.accessible-info').show(function() { el.find('.accessible-info').focus(); });
			}
			/* end accessible warning */	
			
			textReplacement();
			
			return false;
		});
	
	}
}
/* end tabs (box com abas) */

function galleryInit() {
	var gallery = $('#gallery');
	var galleryModal = $('#gallery-modal');
	var galleryItens = $('#gallery #gallery-menu li, #gallery-modal #gallery-menu li');
	var visibleArea = gallery[0] ? "470px" : "456px";
	
	if(galleryItens.length >= 9)
		galleryMenuCarousel(visibleArea);
	else
		galleryItens.css('marginBottom','0');
		
	$('#gallery-menu-container a').bind('click', function() {	
		galleryClick($(this));
		return false;
	});
	
	/* +modal */
	if(galleryModal[0]) {
		
		var modal = $('#gallery-modal'); 
		var btnOpen = $('a[href="#gallery-modal"]');
		var modalTop = btnOpen.position().top + 'px';
		var modalLeft = Math.round($('#wrapper').width() / 2) - Math.round(modal.width() / 2) ;
		
		/* +close */
		modal.append('<a href="#" title="'+ locale('close') +'" class="close hide_text">'+ locale('close') +'</a>');
		var btnClose = $('#gallery-modal .close');
		/* end close */
		
		modal.css({position:'absolute', top:modalTop, left:modalLeft, display:'none'});
		
		btnOpen.click(
			function() {
				if (!isIe6())
					modal.fadeIn('slow', 
						function() { 
							$('#gallery-menu-container a:eq(0)').addClass('selected').css({ cursor:'default', opacity:'0.5' })
																.parent().siblings().find('a').removeClass('selected').css({ cursor:'pointer', opacity:'1' }); 
						}
					);
				else
					modal.show(
						function() { 
							$('#gallery-menu-container a:eq(0)').addClass('selected').css({ cursor:'default', opacity:'0.5' })
																.parent().siblings().find('a').removeClass('selected').css({ cursor:'pointer', opacity:'1' }); 
						}
					);
				
				
				return false;
			}
		);
		
		btnClose.click(
			function() {
				if (!isIe6())
					modal.fadeOut('slow');
				else
					modal.hide();
				
				return false
			}
		);
	
	}
	/* end modal */
	
	gallery.find('#gallery-view').show(function(){
	/*
		exibe a div gallery-view que por default tem display:none ( não carrega imagem sem javascript )
	*/
		galleryClick($('#gallery-menu-container a:eq(0)'), true);
	})
}
/* end win load  */


/**************************************** +support ***********************************************/
function textZoom() {
	
	var el = jQuery("#main, #wide");
	var currentFontSize;
	
	jQuery(".increase-text").unbind('click').bind('click', function() {
		currentFontSize = parseInt(el.css('font-size'));
		
		var fontSize = currentFontSize + 1;
		if(fontSize <= 14) {
			textZoomApply(el,fontSize);
			if($(".decrease-text a.disabled")[0]) _enable('.decrease-text a');
			textZoom();
		}
		if(fontSize == 14) _disabled($(this).find('a'),true);
		return false;
	});
	
	jQuery(".decrease-text").unbind('click').bind('click', function() {
		currentFontSize = parseInt(el.css('font-size'));
		
		var fontSize = currentFontSize - 1;
		if(fontSize >= 9) {
			textZoomApply(el,fontSize);
			if($(".increase-text a.disabled")[0]) _enable('.increase-text a');
			textZoom();
		}
		if(fontSize == 9) _disabled($(this).find('a'),true);
		return false;
	});
	
	jQuery(".text-size .default-font").unbind('click').bind('click', function() {
		currentFontSize = parseInt(el.css('font-size'));
		
		if (currentFontSize != defaultFontSize) {
			textZoomApply(el,defaultFontSize);
			if($(".increase-text a.disabled")[0]) _enable('.increase-text a');
			if($(".decrease-text a.disabled")[0]) _enable('.decrease-text a');
		}
		return false;
	});

}


function textZoomApply(el,fontSize) {
	el.css('font-size',fontSize+'px');
}


function newWindow(mypage,myname,w,h,scroll,center){ // função para abrir popup
	if(center == true) {
		var winl = (screen.width-w) / 2;
		var wint = (screen.height-h) / 2;
	}
	
	var settings ='height='+h+',';
	
	settings +='width='+w+',';
	settings +='top='+wint+',';
	settings +='left='+winl+',';
	settings +='scrollbars='+scroll+',';
	settings +='resizable=yes';
	
	var win=window.open(mypage,myname,settings);
	
	win.focus();
}

/* +Galeria Multimídia */
function galleryMenuCarousel(visibleArea) {
	
	$('div#gallery-menu #gallery-menu-content').prepend('<ul class="scroll"><li class="previous"><a href="javascript:void(0)" class="hide_text"> &lt; </a></li><li class="next"><a href="javascript:void(0)" class="hide_text"> &gt; </a></li></ul>');
	$('#gallery-modal #gallery-menu .carousel li').css('marginBottom','0');
	
	var btPrev = 'div#gallery-menu .scroll .previous a';
	var btNext = 'div#gallery-menu .scroll .next a';
	
	var carousel = $('div#gallery-menu .carousel');
	
	carousel.jMyCarousel({  
		visible: visibleArea,
		btnPrev: $(btPrev),
		btnNext: $(btNext),
		circular: false,
		vertical:false
	}); 
	
	$('div#gallery-menu .carousel').css('width', $('div#gallery-menu .carousel').width() - 4 + 'px');
	
}

function galleryClick(el, first) {
	var gallery = $('#gallery, #gallery-modal');
	var view = gallery.find('#gallery-view, #image-view');
	var loadingFocus = view.find('#gallery-view-container, #image-view-container');
	var galleryDescription = view.find('.gallery-description, .image-description'); 
	var tLink = el; //this link
	var tImg = tLink.find('img'); // this image
	
	if(!tLink.hasClass('selected')) {
		tLink.addClass('selected').css({ cursor:'default', opacity:'0.5' })
			 .parent().siblings().find('a').removeClass('selected').css({ cursor:'pointer', opacity:'1' });
		
		loadingFocus.find('div, object, img, embed').fadeOut('1000', function() {
			loadingFocus.find('.temp').remove()
						.end().addClass('loading');
			
			if(tImg.attr('longdesc') && tImg.attr('alt') == ""){
				galleryDescription.empty().addClass('loading');
				var item = tImg.attr('longdesc').split('#')
				$.get(item[0],
					function(data) {
						galleryDescription.removeClass('loading').html($('#' + item[1], data));
					}
				);
			} 
			else {
				galleryDescription.html(tImg.attr('alt'));
			}
			
			/* +carrega imagem ou gráfico */
			if(tLink.hasClass('image') || tLink.hasClass('graphic') || tLink.parents('#gallery-modal')[0]) {
				var src = tLink.attr('href');
				
				preloadImage(src, function() {
					if(!view.find('.image-details')[0])
						loadingFocus.html('<img src="" class="image-details" />');
					
					$('.image-details').attr({ src:src, alt:tImg.attr('alt'), longdesc:tImg.attr('longdesc') })
									   .css('display','none').fadeIn(
											function() { 
												loadingFocus.removeClass('loading');
												if(tImg.attr('longdesc') && tImg.attr('alt') != "") {
													loadingFocus.append('<a href="'+ tImg.attr('longdesc') +'" title="'+ locale('titleSeeLongDesc') +'" class="invisible">'+ locale('seeLongDesc')  +'</a>');
													htmlActions();
												}	
											}
										);
									   
					if(!first) {
						if(!gallery.find('.accessible-info')[0])
							$('<a href="#'+ view.attr('id') +'" class="accessible-info">'+ locale('accessibleInfo') +'</a>').insertBefore(view); 			   
						$('.accessible-info').focus();
					}
				});
			}
			/* end carrega imagem ou gráfico */
			
			/* +carrega vídeo ou áudio */
			else {
				$.get(tLink.attr('href'), { ajax:"on" },
					function(data) {
						loadingFocus.html(data)
									.css('display','none').fadeIn('slow', function(){ $(this).removeClass('loading') });
					
						if(!first) {
							if(!gallery.find('.accessible-info')[0])
								$('<a href="#'+ view.attr('id') +'" class="accessible-info">'+ locale('accessibleInfo') +'</a>').insertBefore(view); 			   
							$('.accessible-info').focus();
						}
					}
				);
			}
			/* end carrega vídeo ou audio */
		});
	}
}
/* end Galeria Multimídia */

function clickFade(anchor, fadeElement) {
	
	var showed_href;
	var animating = false;
	
	$(anchor).bind('click', function() {
		
		var link = $(this);
		var link_href = link.attr('href');
		
		if ((animating == false) && (link_href != showed_href)) {
		
			showed_href = $(this).attr('href');
			animating = true;
		
			$(fadeElement + ':visible').fadeOut("slow");
			$(link_href).fadeIn("slow", function() {
				animating = false;
			});
			
			$(this).parent().siblings(".selected").toggleClass("selected");
			$(this).parent().toggleClass("selected");
		
		}
		
		return false;
	
	});
}

function openClose(clickElement, openCloseElement, callback) { 
	$(clickElement).click(
		function() {
			$(this).unbind('click');				
						
			$(openCloseElement).slideToggle(
				function() {
					openClose(clickElement, openCloseElement,callback);
				}
			);
			
			if (typeof callback == 'function') {
				callback();
			}			
			
			return false;
		}
	);
}

function changeText(element, text, titleText) { // altera texto ou titulo de um elemento
	if(text != "")
		$(element).text(text);
	if(titleText != "")
		$(element).attr("title", titleText);
}

/* +landing pages (home das seções)  */
function subHome() { 
	if(!jaaulde.utils.cookies.get('alternative')) { // se não existir o cookie para visualizar o conteúdo alternativo...
		var pageUrl = document.location.href;
		pageUrl = pageUrl.split('/');
		var page = parseQueryString(pageUrl[pageUrl.length - 1]);
		
		function getFlashMovie(movieName) {
			var isIE = navigator.appName.indexOf("Microsoft") != -1;
			return (isIE) ? window[movieName] : document[movieName];
		}
		
		setTimeout(subHomeCloseBoxes, 1000);

		var el = $('#sections #boxes');
		var boxes = el.find('.box .content');
		
		el.hoverIntent({    
			sensitivity: 5,
			interval: 150,
			timeout: 150,
			over: function() {
				boxes.slideDown(1000);
				if(!page.alternative) getFlashMovie("flash").sendTextToFlash('close');
			},	
			out: function() {
				boxes.slideUp(1000);
				if(!page.alternative) getFlashMovie("flash").sendTextToFlash('open');
			}
		});
	}
}


function subHomeCloseBoxes() {
	$('#sections #boxes.collapsible .box .content').slideUp(1000);
}

function subHomeOpenBoxes() {
	$('#sections #boxes.collapsible .box .content').slideDown(1000);
}

/* end landing pages (home das seções)  */


String.prototype.isEmail = function() {
	var rx = new RegExp("\\w+([-+.\’]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
	var matches = rx.exec(this);
	return (matches != null && this == matches[0]);
}

//nova função para pegar o destino dos links para analytics
$('a').click(function() {
    var $a = $(this);
    var href = $a.attr('href');
    if ( (href.match(/^http/)) && (! href.match(document.domain)) ) {
		var category = 'External Link';
		var event = 'Click';
		var label = href;
    }
    });


function fbs_click() {
	u='http://www.petrobras.com.br';
	t='Eu assisti A Conquista do Pré-sal no portal da Petrobras. Assista também.';
	
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer');
	return false;
}
/* ****************************************************** end support ****************************************************** */


/* ****************************************************** pages ****************************************************** */

/* home */
function home() {
	homeAdditionalHighlights();
}

/* home-additional-highlights */
function homeAdditionalHighlights() {
	var additionalHighlights = $('#additional-highlights');  
	
	additionalHighlights.prepend('<a href="javascript:void(0)" title="'+ locale('highlightsOpen') +'" class="closed open-close hide_text">'+ locale('highlightsOpen') +'</a>');
	additionalHighlights.find('ul ul').css('display','none');
	
	openClose('#additional-highlights .open-close, #additional-highlights .header','#additional-highlights ul ul', 
		function() {
			var openCloseBtn = additionalHighlights.find('.open-close');
			
			openCloseBtn.toggleClass('closed');
			changeText('#additional-highlights .open-close', locale('highlightsClose'), locale('highlightsClose'));
			changeText('#additional-highlights .closed', locale('highlightsOpen'), locale('highlightsOpen'));
			
			/* focus no primeiro link deixa a funcionalidade acessível para leitores de tela */
			if(!openCloseBtn.hasClass('closed')) {
				if(!additionalHighlights.find('.accessible-info')[0]) {
					$('<br class="hide" />').insertAfter(openCloseBtn);
					$('<a href="#additional-highlights-list" class="accessible-info">'+ locale('accessibleInfo') +'</a>').insertAfter(openCloseBtn.next()); 
					additionalHighlights.find('.accessible-info').focus();
				}
				else	
					additionalHighlights.find('.accessible-info').show(function() { additionalHighlights.find('.accessible-info').focus(); });
				
			}
			else
				additionalHighlights.find('.accessible-info').hide();
			
			
		}
	);
}
/* end home-additional-highlights */
/* end home */

function environmentAndSocietyEnvironment() {
	if ($('#environment-and-society-environment')[0]) {	
		
		/* +tooltip */
		$('#cdas-tel').clone().appendTo('#cdas-link').attr('id','cdas-link-tel').removeClass('clear').end().remove();
	
		var link = $('#cdas-link');
		var tooltip = $('#cdas-link-tel');
		
		link.bind('mouseenter focus',function() {
			tooltip.css({ display:'block', opacity:'0' }).stop().animate({ opacity:1 });
		});
		
		link.bind('mouseleave blur',function() {
			tooltip.stop().animate({ opacity:0 },
				function() {
					$(this).css('display','none');
				}
			);
		});
		
		link.bind('click',function() {
			return false;
		});
		/* end tooltip */
	}
}

function tenders() {
	var form = $("#about-us-careers-tenders #content .simple-box form");
	var selectYears = form.find("select[@name='year']");
	var selectYearText = locale('tendersSelectYear');
	var selectTendersChooseText = form.hasClass('internal') ? locale('selectTendersAll')  :locale('selectTendersFinished');
	var selectTendersText = locale('selectTenders');
	var okBtn = form.find('.ok');
	var showOpen = form.hasClass('internal') ? true : false;
	
	form.attr('action', locale('tenderFile')).find('input[name="javascript"]').remove();
	
	if(!$('#tender')[0])
		$('<div><label class="hide" for="tendertender">'+ locale('tender') +'</label><select title="'+ selectTendersChooseText +'" id="tender" name="id"><option value="">'+ selectTendersText +'</option></select></div>').insertAfter(form.find('div:first'));
	var selectTenders = form.find("select[@name='id']");
	
	okBtn.bind('click', function() { return false; });
	selectTenders.attr({ title:selectYearText });
	
	if (selectYears.val() != "" && selectTenders.val() == "") {
		trigger();
		selectTenders.attr({ title:selectTendersChooseText});
	}
	if(selectYears.val() != "" && selectTenders.val() != "") {
		//_enable(okBtn);
		//Enable
		okBtn.css({ opacity:'1', cursor:'pointer' });
		okBtn.unbind('click');
		selectTenders.attr({ title:selectTendersChooseText });
	}
	
	selectYears.bind('change', function() {
		if($(this).val() != "") {
			selectTenders.attr({ title:selectTendersChooseText });
			trigger();
		}
		else {
			selectTenders.attr({ title:selectYearText })
						 .empty().append('<option value="">'+ selectTendersText +'</option>');	
		}
		
		_disabled(okBtn, false);
	});
	
	selectTenders.bind('change', function(){
		if($(this).val() != "") {
		//_enable(okBtn);
		//Enable
			okBtn.css({ opacity:'1', cursor:'pointer' });
			okBtn.unbind('click');
		}
		else
			_disabled(okBtn, false);
	});
	
	function trigger() {
		
		if(bio != true){
			$.ajax({
				url: 'combo.asp',
				type: 'GET',
				data: 'year='+$("select[@name='year']").val()+'&showOpen='+showOpen,
				beforeSend: function() {
					selectTenders.html('<option value="">'+ locale('loading') +'</option>');
				},
				success:function(response) {
					selectTenders.html(response);
				}
			});
		}else
		{
			$.ajax({
			url: 'combo_biofuel.asp',
			type: 'GET',
			data: 'year='+$("select[@name='year']").val()+'&showOpen='+showOpen,
			beforeSend: function() {
				selectTenders.html('<option value="">'+ locale('loading') +'</option>');
			},
			success:function(response) {
				selectTenders.html(response);
			}
		});
		}
	}
	
	if(form.hasClass('internal')) tendersInternal();
}

function tendersTemp() {
	var form = $("#about-us-careers-tenders #content .simple-box .tenders");
	var selectYears = form.find("select[@name='year']");
	var selectYearText = locale('tendersSelectYear');
	var selectTendersChooseText = form.hasClass('internal') ? locale('selectTendersAll')  :locale('selectTendersFinished');
	var selectTendersText = locale('selectTenders');
	var okBtn = form.find('.ok');
	var showOpen = form.hasClass('internal') ? true : false;
	
	form.attr('action', locale('tenderFile')).find('input[name="javascript"]').remove();
		
	if(!form.find('#tender')[0])
		$('<div><label class="hide" for="tender">'+ locale('tender') +'</label><select title="'+ selectTendersChooseText +'" id="tender" name="id"><option value="">'+ selectTendersText +'</option></select></div>').insertAfter(form.find('div:first'));
	var selectTenders = form.find("select[@name='id']");
	

	
	okBtn.bind('click', function() { return false; });
	selectTenders.attr({ title:selectYearText });

	if (selectYears.val() != "" && selectTenders.val() == "") {
		trigger();
		selectTenders.attr({ title:selectTendersChooseText});
	}
	
	if(selectYears.val() != "" && selectTenders.val() != "") {		
		//_enable(okBtn);
		//Enable
		okBtn.css({ opacity:'1', cursor:'pointer' });
		okBtn.unbind('click');		
		selectTenders.attr({ title:selectTendersChooseText });
	}
	
	selectYears.bind('change', function() {
		if($(this).val() != "") {
			selectTenders.attr({ title:selectTendersChooseText });
			trigger();
			//$(selectTenders).fadeIn();
		}
		else {
			selectTenders.attr({ title:selectYearText })
						 .empty().append('<option value="">'+ selectTendersText +'</option>');	
		}
		_disabled(okBtn, false);
	});
	
	selectTenders.bind('change', function(){
		if($(this).val() != "") {
			//_enable(okBtn);
			//Enable
			okBtn.css({ opacity:'1', cursor:'pointer' });
			okBtn.unbind('click');			
			$(okBtn).click(function(){									
				var id = form.find('#tender').val();
				var year = selectYears.val();
				var searchTender = form.find('#searchTender');
				
				$.ajax({
					url: 'show.asp',
					type: 'GET',
					data: 'year='+year+'&id='+id+'&xmlPath=include/xml/tenders.xml',
					beforeSend: function() {
						searchTender.html('Carregando...');
					},
					success:function(response) {
						searchTender.html(response);
					}
				});				
			})			
		}
		else{
			_disabled(okBtn, false);

		}
	});
	
	function trigger() {		
		$.ajax({
			url: 'combo.asp',
			type: 'GET',
			data: 'year='+$("select[@name='year']").val()+'&showOpen='+showOpen,
			beforeSend: function() {
				selectTenders.html('<option value="">'+ locale('loading') +'</option>');
			},
			success:function(response) {
				selectTenders.html(response);
			}
		});
	}
	
	//if($(selectYears).attr('value') == ''){
	//	$(selectTenders).hide();	
	//}
	

	if(form.hasClass('internal')) tendersInternal();
}

function tendersBiofuel() {
	var form = $("#about-us-careers-tenders #content .simple-box .tendersBiofuel");

	var selectYears = form.find("select[@name='year']");
	var selectYearText = locale('tendersSelectYear');
	var selectTendersChooseText = form.hasClass('internal') ? locale('selectTendersAll')  :locale('selectTendersFinished');
	var selectTendersText = locale('selectTendersBio');
	var okBtn = form.find('.ok');
	var showOpen = form.hasClass('internal') ? true : false;
	
	form.attr('action', locale('tenderFile')).find('input[name="javascript"]').remove();
	
	
	if(!form.find('#tender')[0])
		$('<div><label class="hide" for="tender">'+ locale('tender') +'</label><select title="'+ selectTendersChooseText +'" id="tender" name="id"><option value="">'+ selectTendersText +'</option></select></div>').insertAfter(form.find('div:first'));
	var selectTendersBio = form.find("select[@name='id']");
	
	okBtn.bind('click', function() { return false; });
	selectTendersBio.attr({ title:selectYearText });
	
	if (selectYears.val() != "" && selectTendersBio.val() == "") {
		trigger();
		selectTendersBio.attr({ title:selectTendersChooseText});
	}
	if(selectYears.val() != "" && selectTendersBio.val() != "") {
		//_enable(okBtn);
		//Enable
		okBtn.css({ opacity:'1', cursor:'pointer' });
		okBtn.unbind('click');
		selectTendersBio.attr({ title:selectTendersChooseText });
	}
	
	selectYears.bind('change', function() {
		if($(this).val() != "") {
			selectTenders.attr({ title:selectTendersChooseText });
			trigger();
		}
		else {
			selectTenders.attr({ title:selectYearText })
						 .empty().append('<option value="">'+ selectTendersText +'</option>');	
		}
		
		_disabled(okBtn, false);
	});
	
	selectTendersBio.bind('change', function(){
		if($(this).val() != "") {
			//_enable(okBtn);
			//Enable
			okBtn.css({ opacity:'1', cursor:'pointer' });
			okBtn.unbind('click');
			
			$(okBtn).click(function(){									
				var id = form.find('#tender').val();
				var year = selectYears.val();
				var searchTender = form.find('#searchTender');
				
				$.ajax({
					url: 'show.asp',
					type: 'GET',
					data: 'bio=1&year='+year+'&id='+id+'&xmlPath=include/xml/tenders-biofuel.xml',
					beforeSend: function() {
						searchTender.html('Carregando...');
					},
					success:function(response) {
						searchTender.html(response);
					}
				});				
			})
		}
		else
			_disabled(okBtn, false);
	});
	
	function trigger() {
		
		$.ajax({
			url: 'combo_biofuel.asp',
			type: 'GET',
			data: 'bio=1&year='+form.find("select[@name='year']").val()+'&showOpen='+showOpen,
			beforeSend: function() {
				selectTenders.html('<option value="">'+ locale('loading') +'</option>');
			},
			success:function(response) {
				selectTenders.html(response);
			}
		});
	}
	
	if(form.hasClass('internal')) tendersInternal();
}

function tendersConcursos() {
	var form = $("#about-us-careers-tenders #content .simple-box .tendersConcursos");

	var selectYears = form.find("select[@name='year']");
	var selectYearText = locale('tendersSelectYear');
	var selectTendersChooseText = form.hasClass('internal') ? locale('selectTendersAll')  :locale('selectTendersFinished');
	var selectTendersText = locale('selectTenders');
	var okBtn = form.find('.ok');
	var showOpen = form.hasClass('internal') ? true : false;
	
	form.attr('action', locale('tenderFile')).find('input[name="javascript"]').remove();
	
	
	if(!form.find('#tender')[0])
		$('<div><label class="hide" for="tender">'+ locale('tender') +'</label><select title="'+ selectTendersChooseText +'" id="tender" name="id"><option value="">'+ selectTendersText +'</option></select></div>').insertAfter(form.find('div:first'));
	var selectTenders = form.find("select[@name='id']");	
	
	okBtn.bind('click', function() { return false; });
	selectTenders.attr({ title:selectYearText });
	
	if (selectYears.val() != "" && selectTenders.val() == "") {
		trigger();
		selectTenders.attr({ title:selectTendersChooseText});
	}
	if(selectYears.val() != "" && selectTenders.val() != "") {
		//_enable(okBtn);
		//Enable
		okBtn.css({ opacity:'1', cursor:'pointer' });
		okBtn.unbind('click');
		selectTenders.attr({ title:selectTendersChooseText });
	}
	
	selectYears.bind('change', function() {
		if($(this).val() != "") {
			selectTenders.attr({ title:selectTendersChooseText });
			trigger();
			$(selectTenders).fadeIn();	
		}
		else {
			selectTenders.attr({ title:selectYearText })
						 .empty().append('<option value="">'+ selectTendersText +'</option>');	
			$(selectTenders).hide();	
						 
		}
		
		_disabled(okBtn, false);
	});
	
	selectTenders.bind('change', function(){
		if($(this).val() != "") {
			//_enable(okBtn);
			//Enable
			okBtn.css({ opacity:'1', cursor:'pointer' });
			okBtn.unbind('click');
			
			
			$(okBtn).click(function(){									
				var id = form.find('#tender').val();
				var year = selectYears.val();
				var searchTender = form.find('#searchTender');
				
				$.ajax({
					url: 'show_concursos.asp',
					type: 'GET',
					data: 'year='+year+'&id='+id+'&xmlPath=include/xml/tenders-concursos.xml',
					beforeSend: function() {
						searchTender.html('Carregando...');
					},
					success:function(response) {
						searchTender.html(response);
					}
				});				
			})
		}
		else
			_disabled(okBtn, false);
	});
	
	function trigger() {
		$.ajax({
			url: 'combo_concursos.asp',
			type: 'GET',
			data: 'year='+form.find("select[@name='year']").val()+'&showOpen='+showOpen,
			beforeSend: function() {
				selectTenders.html('<option value="">'+ locale('loading') +'</option>');
			},
			success:function(response) {
				selectTenders.html(response);
			}
		});
	}
	

	if($(selectYears).attr('value') == ''){
		$(selectTenders).hide();	
	}
	
	if(form.hasClass('internal')) tendersInternal();	
}


function tendersInternal () {
	var form = $("#about-us-careers-tenders form.internal");
	form.bind('submit', function() {

		if(bio == true)			 
		var data = 'bio=1&year='+$("select[@name='year']").val()+'&id='+$("select[@name='id']").val()+'&showOpen='+$("input[@name='showOpen']").val();
		else
		var data = 'year='+$("select[@name='year']").val()+'&id='+$("select[@name='id']").val()+'&showOpen='+$("input[@name='showOpen']").val();
		$.ajax({
			url: locale('tenderFile'),
			type: 'GET',
			data: data,
			beforeSend: function() {
				$('#show').html('').addClass('loading');
				if(!$('#tenders-main .accessible-info')[0])
					$('<a href="#show" class="accessible-info">'+ locale('loading') +'</a>').insertBefore($('#show'))
				else
					$('.accessible-info').text(locale('loading'));
				$('.accessible-info').focus(); 
				
				if($('#tenders-main .feed')[0])
					$('#tenders-main .feed').remove();
			},
			success:function(response) {
				$('#show').replaceWith($('#show', response));
				$('#tenders-main .accessible-info').text(locale('accessibleInfo'));
				$('.accessible-info').focus();
				
				if($('.feed',response)[0]) 	
					$('.feed',response).insertBefore($('#tenders-main .bottom'))			
				rels();
			}
		});

		return false;	
	});
}

var firstAccess = 0;
function productsList() {
	
	function setDefault(active) {
		
		if (!active) 
			items.addClass('unselected');
		else
			items.removeClass('unselected');
		
		items.filter('.selected').removeClass('selected').css('z-index','1');
		items.height(boxHeight);
		items.find('.details').hide();
		closeAllProducts(items);
	}


	function openDetails(el,top) {
	
		setDefault(false);
		
		// apply
		if(el.is('a'))
			recentEvent = true;
		
		if(el.is('li'))
			var item = el;
		else
			var item = el.parents('li');
		
		var details = item.find('.details');
		details.css({ position:'absolute', top:top + 'px' });
		
		// identify
		item.removeClass('unselected').addClass('selected');
		
		// fix zindex
		item.css('z-index','2');
		
		// index
		var index = items.index(item);
		
		// height
		var itemHeight = item.height();
		var detailsHeight = details.height();
		var newHeight = detailsHeight + itemHeight;
		applyHeight(index, newHeight);
		
		// fix left
		var left = (index % 3) * (boxWidth + boxMargin) * (-1);
		details.css('left',left+'px');
		
		// show
		details.show(1, 
			function() {
				if(!item.find('.accessible-info')[0])
					$('<a href="#'+ item.attr('id') +'-details" class="accessible-info">'+ locale('accessibleInfo') +'</a>').insertBefore(details);
				item.find('.accessible-info:eq(0)').focus();
				
				textReplacement();	
			}
		);
		
		// binds
		if(item.find('.box-tabs')[0])
			boxTabsAdd(item); // adiciona mais funcionalidades as tabs de produtos
		else 
			comboProducts(item);			
		
		if(el.hasClass('product')) { // quando for especificamente um produto
			var index = items.index(item);
			var productId = el.attr('id');
			var product = el;
			
			item.find('select option[value="'+ productId +'"]').attr('selected','selected');
			productShow(item, index, productId, product);
		}
		if( firstAccess != 1 && $('.products-list')[0]){
			var productUrl2 = location.href.split('#'); //id do elemento
			if(productUrl2[1]) {
				var el = $('#'+productUrl2[1]).find('.item-header a, .picture');
			}
			var prodIdent = el.parents('li').attr('id');
		}
		
		if(item.find('select')[0]) 
		// se os detalhes do produto tiver um elemento select: retirar o atributo disabled ...
			item.find('select, input.ok').attr('disabled', false)
			    .parents('form').css('display', 'block');
		// ... e aplicar display:block no form pai		
	}
	
	function applyHeight(index, height) {
		var lastInRow = getIndex(index);
		var els = items.filter(':lt('+lastInRow+')').filter(':gt('+(lastInRow-4)+')');
		els.css('height', height + "px");
	}
	
	function getIndex(index) {
		for(var i=(index+1); i < (index+4); i++) {
			if (i%3==0) {
				return i;
				break;
			}
		}
	}
	
	function comboProducts(item) {
		closeAllProducts(item);
		item.find('form').unbind('submit').bind('submit', function() {
			var index = items.index(item);
			var prodIdent = item.attr('id');
			var productId = $(this).find('select').val();
			var product = item.find('#'+productId);
			
			if(productId) {
				productShow(item, index, productId, product);
				_gaq.push(["_trackPageview", document.location.pathname + "/" + item.attr("id") + "/" + productId]);
			}
			else {
				var productOpened = false;
				item.find('.product').each(
					function(i) {
						if($(this).css('display') == 'block')
							productOpened = true;	
					}
				);
				
				closeAllProducts(item);
				if(productOpened) { // fix height bug
					var detailsHeight = item.find('.details-content').height();
					var newHeight = boxHeight + boxMargin + detailsHeight;
					applyHeight(index, newHeight);
				}
			} 
			
			return false;	
		}).find('option[value=""]').attr('selected','selected');
	}
	
	function productShow(item, index, productId, product) {
		item.parents('ul').find('.product:not(#'+productId +')').hide();
		product.show(1, function() {
			item.parents('ul').find('.product:not(#'+productId +')').hide(); // fix IE bug
			var detailsHeight = item.find('.details-content').height();
			var newHeight = boxHeight + boxMargin + detailsHeight;
			applyHeight(index, newHeight);
			textReplacement();

			if(!product.prev('.accessible-info')[0])
				$('<a href="#'+ productId +'" class="accessible-info">'+ locale('accessibleInfo') +'</a>').insertBefore(product);
			product.prev('.accessible-info').focus();	
		});
		
	}	
	
	function boxTabsAdd(item) {
		var tabs = item.find('.stripNav a');
		var index = items.index(item);
		
		tabs.click(
			function() {
				var detailsHeight = item.find('.details-content').height();
				var newHeight = boxHeight + boxMargin + detailsHeight;
				
				applyHeight(index, newHeight);
				var tabId = $(this).attr('id');
				var prodIdent2 = $(this).parents('li.item').attr('id');
			}
		);
	}
	
	function closeDetails(item, details) {
		item.removeClass('selected');
		details.hide();
		var index = items.index(item);
		applyHeight(index, boxHeight);
	}
	
	function closeAllProducts(el, callback) {
		el.find('.product').hide();
	}
	
	// get main elements
	if($('.products-list')[0]) {
		var list = $('.products-list');
		var boxWidth = 250;
		var boxHeight = 146;
		var boxMargin = 20;
	}
	
	if($('.products-large-list')[0]) {
		var list = $('.products-large-list');
		var boxWidth = 310;
		var boxHeight = 248;
		var boxMargin = 12;
	}
	
	var items = list.find('>li');
	var recentEvent = false;
	items.css({ width:boxWidth + 'px', height: boxHeight + 'px', marginRight:boxMargin + 'px', float:'left' })
         .find('.details').hide();
	
	// apply the events
	var productUrl = location.href.split('#'); //id do elemento
	if($('ul #' + productUrl[1])[0]) {
		$(window).load(
			function() {
				openDetails($('#' + productUrl[1]), boxHeight);
			}	
		);
	}
	
	list.find('.item-header a, .picture').unbind('click').bind('click', function(e) {
		// avoid double event (firefox triggers click at same time)
		setTimeout(function() {
			recentEvent = false;
		}, 500);
		
		var el = $(this);
		var item = el.parents('li');
		var details = item.find('.details');
		var nSelected = item.filter('.selected');
		
		firstAccess = 1;
		
		if (!nSelected[0]) {
			openDetails(el, boxHeight); // if the item is closed, open...
			_gaq.push(["_trackPageview", document.location.pathname + "/" + item.attr("id")]);
		} else if (!recentEvent && e.type == 'click') {
			setDefault(true); // if it is already open, and then you click, it closes. but if you press tab, is doesn't close
		}
		
		textReplacement();
		
		return false;
	});
	
	$(".arla-32").bind("click", function(e){
			// avoid double event (firefox triggers click at same time)
			setTimeout(function() {
				recentEvent = false;
			}, 500);
			
			var el = $("#arla-32");
			var item = el.parents('li');
			var details = item.find('.details');
			var nSelected = item.filter('.selected');
			
			firstAccess = 1;
			
			if (!nSelected[0]) {
				openDetails(el, boxHeight); // if the item is closed, open...
				_gaq.push(["_trackPageview", document.location.pathname + "/" + item.attr("id")]);
			} else if (!recentEvent && e.type == 'click') {
				setDefault(true); // if it is already open, and then you click, it closes. but if you press tab, is doesn't close
			}
			
			textReplacement();
			
			return false;
	})
	
	$(".diesel-s-50").bind("click", function(e){
			// avoid double event (firefox triggers click at same time)
			setTimeout(function() {
				recentEvent = false;
			}, 500);
			var el = $("#oleo-diesel");
			var item = el.parents('li');
			var details = item.find('.details');
			var nSelected = item.filter('.selected');
			
			firstAccess = 1;
			
			if (!nSelected[0]) {
				openDetails(el, boxHeight); // if the item is closed, open...
				_gaq.push(["_trackPageview", document.location.pathname + "/" + item.attr("id")]);
			} else if (!recentEvent && e.type == 'click') {
				setDefault(true); // if it is already open, and then you click, it closes. but if you press tab, is doesn't close
			}
			
			textReplacement();
			
			return false;
	})
	
	$(".diesel-s-50-en").bind("click", function(e){
			// avoid double event (firefox triggers click at same time)
			setTimeout(function() {
				recentEvent = false;
			}, 500);
			var el = $("#diesel-fuel");
			var item = el.parents('li');
			var details = item.find('.details');
			var nSelected = item.filter('.selected');
			
			firstAccess = 1;
			
			if (!nSelected[0]) {
				openDetails(el, boxHeight); // if the item is closed, open...
				_gaq.push(["_trackPageview", document.location.pathname + "/" + item.attr("id")]);
			} else if (!recentEvent && e.type == 'click') {
				setDefault(true); // if it is already open, and then you click, it closes. but if you press tab, is doesn't close
			}
			
			textReplacement();
			
			return false;
	})
	
}


function news() {
	var otherNews = $('.other-news-container');
	var pagination = $('.pagination'); 
	var ajaxTarget = $('#ajax-target');
	
	function loadOtherNews() {
		pagination = $('.pagination');
		ajaxTarget = $('#ajax-target');
		
		pagination.find('a:not(.disabled)').click(
			function() {
				var url = $(this).attr('href');
				url = new String(url);
				
				if (url.indexOf("?") != -1) 
					url = url.split("?")[1];
				
				var qString = parseQueryString(url); // query string
				ajaxTarget.empty().addClass('loading');
				
				$.get(rootUrl + newsUrl(locale('newsUrlPath')), { page:qString.page, langPath:'../../', id:otherNews.attr('id'), hiddenIds:$("#hid-ids").val() }, 
					function(data) {
						ajaxTarget.replaceWith($('#ajax-target', data)).removeClass('loading');
						loadOtherNews();
						adjustWidth();
						_disabled('.pagination .disabled');
						disabledSelectedNews();
						disabledPagination();
						
					}
				);
				
				return false;
			}
		);
	}
	
	function adjustWidth() {
		var paginationContainer = $('.pagination-container');
		
		paginationContainer.css({ width:pagination.width() + 'px', left:'50%', marginLeft:'-' + parseInt(pagination.width() / 2) + "px"  });
		otherNews.find('.content').css('padding-bottom','50px');
		pagination.parents('.pagination-container').css({ position:'absolute', bottom:'22px' });
	}
	
	
	function newsUrl(exp) {
		var url = document.location.href;
		var urlArray = url.split(exp);
		
		if(urlArray[1] == "")
			return locale('newsPagPath');
		else
			return locale('newsPagDetailsPath');
	}
	
	
	function disabledSelectedNews() {
		var item = $('.other-news-container li.selected');
		var link = item.find('a'); 	
		
		item.css({ opacity:'0.5' });
		link.css({ cursor:'default' })
			.click ( function() { return false; } )
			.attr('title',link.attr('title') + locale('buttonDisabled'));
	}
	
	function disabledPagination() {
		var link = $('.pagination a.disabled');
		
		link.css({ cursor:'default', opacity:'0.5' })
			.click( function() { return false; } );
	}
	
	adjustWidth();
	loadOtherNews();
	disabledSelectedNews();
	disabledPagination();
}

//faq
function faq(){
	var faq = $('#faq');
	
	faq.find('dd').hide();
	faq.find('dl').hide();
	
	faq.find('h3').click(function(){
		$(this).toggleClass('open');
		$(this).next('dl').slideToggle();
	}).css('cursor', 'pointer');
	faq.find('dt').click(function(){
		$(this).next('dd').slideToggle();
	}).css('cursor', 'pointer');
}

/* *** Meio Ambiente e sociedade Seleções Públicas*** */
//Carrousel
function slideCarrousel(){
	if ( jQuery.fn.jCarouselLite === undefined)
		return false;
	
	var btPrev = 'div.column .paging .previous';
	var btNext = 'div.column .paging .next';
	
	var carousel = $('.carrousel-1');
	
	carousel.jCarouselLite({  
		visible: 2,
		btnPrev: btPrev,
		btnNext: btNext,
		circular: false
	});
}
function slideCarrousel2(){
	if ( jQuery.fn.jCarouselLite === undefined)
		return false;

	var btPrev = 'div.column-right .paging .previous';
	var btNext = 'div.column-right .paging .next';
	
	var carousel = $('.carrousel-2');
	
	carousel.jCarouselLite({  
		visible: 1,
		btnPrev: btPrev,
		btnNext: btNext,
		circular: false
	}); 
}

function transparency(){
	/*if ( jQuery.$("#select-patro") === undefined)
		return false;*/
	$(".select-patro").click(function(){
		if($(this).val()!="#"){
			//alert($(this).val());
			$(this).parent().find(".ok").removeClass("disabled");
			$(this).parent().find(".ok").css("opacity","1");
		}else{
			$(this).parent().find(".ok").addClass("disabled");
			$(this).parent().find(".ok").css("opacity","0.5");
		}
	});
	/*$("#patro-transp").submit(function(){
		if( $("#select-patro").val() != "#"){
			window.open("../../../../downloads/about-us/profile/transparency/pdf/"+ $("#select-patro").val());
			return false;
		}else{
			return false;
		}
	});*/
	
	$(".patro-transp").submit(function(){	
		if( $(this).find(".select-patro").val() != "#"){
			if ($(this).find(".select-patro").val().match(/http/i)) {				
				window.open($(this).find(".select-patro").val());
			} else {
				window.open("../../../../downloads/about-us/profile/transparency/pdf/"+ $(this).find(".select-patro").val());
			}
			return false;
		}else{
			return false;
		}
	});
	
	$(".patro-transp2").submit(function(){	
		if( $(this).find(".select-patro").val() != "#"){
			if ($(this).find(".select-patro").val().match(/http/i)) {
				if($(this).find(".select-patro").hasClass("external")) {	
					$(".popup .continue").attr("href", $(this).find(".select-patro").val());
					$(".popup").fadeIn();
					return false
				}
				window.open($(this).find(".select-patro").val());
			} else {
				window.open("../../../../../downloads/about-us/profile/transparency/pdf/"+ $(this).find(".select-patro").val());
			}
			return false;
		}else{
			return false;
		}
	});
	
	$(".patro-transp3").submit(function(){	
		if( $(this).find(".select-patro").val() != "#"){
			if ($(this).find(".select-patro").val().match(/http/i)) {
				window.open($(this).find(".select-patro").val());
			} else {
				location.href = $(this).find('.select-patro').val();
			}
			return false;
		}else{
			return false;
		}
	});
	
	$(".patro-transp4").click(function(){	
		$(".popup .continue").attr("href", $(this).attr("href"));
		$(".popup").fadeIn();
		return false
	});
	
	$(".close").click(function(){
		$(".popup").fadeOut();
		return false;
	});
	$(".continue").click(function(){
		$(".popup").fadeOut();
		window.open($(this).attr("href"));
		return false;
	});
	
	$("a.captcha-list").click(function(){
		Recaptcha.reload ();
		$(".popup").fadeIn();
		$("#file").val($(this).attr("href"));
		return false;
	});
	
	$("#form-captcha").submit(function(){
		$(".popup").hide();
	});
}

$(document).ready(function(){
	$('#listToggle li div').addClass('hide');
	$('#listToggle li h3.linkToggle').click(function() {
		$(this).addClass('seta');
		if ($(this).next().is('div:visible')) {
			$(this).removeClass('seta');
			//return false;
		}
		
		//$('#listToggle li div:visible').slideToggle();
		$(this).next().slideToggle('slow');
		
		return false;
	});
	
});

function flash_tracking(path) {
	_gaq.push(['_trackPageview', path]);
}

function flash_track_event(desc, action, path) {
	_gaq.push(['_trackEvent', desc, action, path]);
}

/* ****************************************************** end pages ****************************************************** */


/* ****************************************************** +main menu ****************************************************** */

var over = function() {
	var sfEls = document.getElementsByTagName("li");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" over";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" over\\b"), "");
		}
	}
}

var dropdown_menus;
var dropdown_interval;
function dropdown_init() {
	try {
		
		// get the menus
		dropdown_menus = $('#main-menu>ul');
				
		// remove JS
		dropdown_menus.find('>li').removeClass('noJs');
		
		// focus and blur
		var menuLinks = dropdown_menus.find('a');
		menuLinks.focus( function(){dropdown_focus(this) });
		menuLinks.blur(dropdown_close);
		
		// if not IE6, apply some effects
		if (!isIe6()) dropdown_events();
	
	} catch(e){ }
}

function dropdown_events() {
	try {
		
		var lis = dropdown_menus.find('>li');
		
		lis.unbind('mouseleave').bind('mouseleave', function() {
			dropdown_close();
		}).unbind('mouseenter').bind('mouseenter', function(){
			dropdown_mouseenter($(this));
		});
	
	} catch(e){ }		
}

function dropdown_mouseenter(el) {
	try {
		
		// stop all the animations
		el.siblings('li').find('.submenu').stop(1,1);
		
		clearInterval(dropdown_interval);
		
		// hide current menu
		el.parent().find('.submenu').css("display","none");
		el.siblings('li').removeClass('focus');
		
		// hide other menu
		var otherMenu = el.parent('ul').siblings('ul');
		otherMenu.find('.submenu').stop(1,1).css("display","none");
		otherMenu.find('li').removeClass('focus');
		
		// show menu
		el.addClass('focus');
		el.children('.submenu').show(500);
		
		// rebind
		dropdown_events();
	
	} catch(e){}
}

function dropdown_focus(el) {
	try {
		clearInterval(dropdown_interval);
			
		// get lis
		var prt = $(el).parent();
		
		// select and expand the current
		prt.addClass('focus');
		
		// hide submenus
		prt.find('.submenu').css("display","none");
		
		// hide current menu
		prt.siblings('li').removeClass('focus');
		
		// hide other menu
		prt.parent('ul').siblings('ul').find('li').removeClass('focus');
		
	} 
	catch(e){}
}

function dropdown_close() {
	try {
		clearInterval(dropdown_interval);
		dropdown_interval = setInterval(function() {
			dropdown_menus.find('.focus').removeClass('focus');
			dropdown_menus.find('.submenu').stop(1,1).css("display","none");
			clearInterval(dropdown_interval);
		}, 0, null);
	}
	catch(e){}
}
/* ******************************************************  end main menu ****************************************************** */


/* ********************************************************* +plugins ************************************************************ */
$.fn.submitByCombo = function() {
	this.change(function() {
		var comboValue = $(this).val();
		if (comboValue != 0) {
			var formAction = $(this).parents('form').attr('action');
			var comboName = $(this).attr('name');
			var path = formAction+"?"+comboName+"="+comboValue;
			window.location.href = path;
			return false;
		}
	});
}


$.fn.equals = function(compareTo) {
	if (!compareTo || !compareTo.length || this.length!=compareTo.length) {
		return false;
	}
	for (var i=0; i<this.length; i++) {
		if (this[i]!==compareTo[i]) {
			return false;
		}
	}
	return true;
}

// check if the image is loaded

function preloadImage(src, callback) {
	var preloadImg = new Image();
	jQuery(preloadImg).load(callback
	).attr({ src:src });
}
/* ******************************************************* end plugins *********************************************************** */


/* ********************************************************* +sifr ************************************************************ */

function textReplacement() {
	try{
		
		var dinRegular = { 
			src: rootUrl+'include/swf/fonts/din-regular.swf' 
		};
		
		var dinBold = { 
			src: rootUrl+'include/swf/fonts/din-bold.swf' 
		};
		
		sIFR.activate(dinRegular);
		sIFR.activate(dinBold);
		
		sIFR.replace(dinRegular, { selector: '.sifr-section-title', css: '.sIFR-root { color:#035385 } a { color:#035385; text-decoration:none } a:hover { color:#035385; text-decoration:underline } a:active { text-decoration:underline }', wmode: 'transparent' });
		sIFR.replace(dinRegular, { selector: '.sifr-text', css: ['.sIFR-root { color:#5FC001; leading:-3; }', '.sIFR-root a { color:#5FC001; text-decoration:none; }', '.sIFR-root a:hover { color:#5FC001; }'], wmode: 'transparent'});
		sIFR.replace(dinRegular, { selector: '.sifr-title-3', css: ['.sIFR-root { color:#39A7EF; leading:-3; }', '.sIFR-root a { color:#5FC001; text-decoration:none; }', '.sIFR-root a:hover { color:#5FC001; }'], wmode: 'transparent'});
		sIFR.replace(dinRegular, { selector: '.sifr-title', css: '.sIFR-root { color:#297B40; leading:-4; }', wmode: 'transparent' });
		sIFR.replace(dinRegular, { selector: '.sifr-title-2', css: '.sIFR-root { color:#34749d; leading:-4; }', wmode: 'transparent' });
		sIFR.replace(dinRegular, { selector: '.sifr-text-right', css: '.sIFR-root { color:#5FC001; text-align:right; }', wmode:'transparent' });
		sIFR.replace(dinRegular, { selector: '.sifr-section-back', css: '.sIFR-root { color:#FFFFFF; }', wmode: 'transparent' });
		sIFR.replace(dinRegular, { selector: '.sifr-text-2', css: ['.sIFR-root { color:#34749D; }', 'a { text-decoration:none; }', 'a:hover { color:#34749D; font-size:12px; }'], wmode: 'transparent' });
		sIFR.replace(dinRegular, { selector: '.sifr-text-3', css: ['.sIFR-root { color:#297B40; }', 'a, a:hover, a:focus, a:active { text-decoration:none; }', 'a:hover { text-decoration:none; color:#297B40; font-size:12px; }'], wmode: 'transparent' });
		sIFR.replace(dinRegular, { selector: '.sifr-text-tooltip', css: ['.sIFR-root { color:#5FC001; leading:-3; }', '.sIFR-root a { color:#5FC001; text-decoration:none; }'], wmode: 'transparent'});
		sIFR.replace(dinBold, { selector: '.sifr-title-bold', css: '.sIFR-root { color:#006A3A; leading:-3; } a {color:#006A3A; text-decoration:none;} a:hover {color:#006A3A; text-decoration:underline;}', wmode: 'transparent' });
				
		sIFR.replace(dinBold, { selector: '.pergunta h3', css: ['.sIFR-root { color:#025284; leading:-3; }', '.sIFR-root a { color:#025284; text-decoration:none; }'], wmode: 'transparent'});
		
		sIFR.replace(dinBold, { selector: '.box-contato h3', css: ['.sIFR-root { color:#297B40; leading:-3; }', '.sIFR-root a { color:#297B40; text-decoration:none; }'], wmode: 'transparent'});
		
		
		// products list
		sIFR.replace(dinRegular, {
			selector: '.products-label',
			css: ['.sIFR-root { display:inline; color:#34749D; text-align:right; }'],
			wmode: 'transparent',
			fixWrap:true,
			onReplacement: function() {
			}
		});
		
	} catch(e){}
}

/* ********************************************************* end sifr ************************************************************ */


/* *********************************************************** +ie hacks ********************************************************* */
function supPositionFixed() {
  var isSupported = null;
  if (document.createElement) {
      var el = document.createElement("div");
      if (el && el.style) {
          el.style.width = "1px";
          el.style.height = "1px";
          el.style.position = "fixed";
          el.style.top = "10px";
          var root = document.body;
          if (root && root.appendChild && root.removeChild) {
              root.appendChild(el);
              isSupported = el.offsetTop === 10;
              root.removeChild(el);
          }
          el = null;
      }
  }
  return isSupported;
}

function iconLinks() {
	if(isIe6() || $.browser.msie && $.browser.version >= 7 && $.browser.version <= 8) { // ie (6 e 7) hack
		$('.external-link').wrapInner('<span class="external-link-text"></span>').removeClass('external-link').append('<span class="external-link">&nbsp;</span>');
		$('.doc-link').wrapInner('<span class="doc-link-text"></span>').removeClass('doc-link').append('<span class="doc-link">&nbsp;</span>');
		$('.pdf-link').wrapInner('<span class="pdf-link-text"></span>').removeClass('pdf-link').append('<span class="pdf-link ">&nbsp;</span>');
	}
}

function ieFlickerFix(){
	try {
		document.execCommand("BackgroundImageCache", false, true);

	} catch(err) {}
}

function isIe6() {
	if (typeof document.body.style.maxHeight === "undefined") return true;
	else return false;
}

function isIe7() {
	if($.browser.msie && $.browser.version.search('7') != -1) return true;
	else return false;
}

function getPath()
{
	return document.location.pathname;
}

function trackUrl(url)
{
	_gaq.push(['_trackEvent', 'external-link', 'click', url]);
	
	window.open(url);
}
/* *********************************************************** end ie hacks ********************************************************* */
