	/**
 * @projectDescription arquivo javascript principal do site Petrobras
 */

/**
 * @classDescription Default classe padrão do framework
 */
var Default = function() {
    /**
    * @method rels executa ações nos links conforme o valor do atributo rel
    */
    this.rels = function() {
        $("a[rel*=external]").attr("target", "_blank");
    }

    /**
    * @method printPreview verifica se a página é preview de impressao, se ela for abre a janela de impressão
    */
    this.printPreview = function() {
        var url = window.location.href;
        
        if (url.search('Imprimir') != -1)
            window.print();
    }

    /**
    * @method parseQueryString retorna um objeto com os valores das variáveis de url
    * @param {String} queryString url com as variáveis
    * @return objeto com as variáveis de url
    */
    this.parseQueryString = function(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;
    }

    /**
     * @method notSupMaxPropert o browser n�o suporta max-height?
     * @return boolean true se ele n�o suportar, false se ele suportar
     */
    this.notSupMaxPropert = function() {
        if (typeof document.body.style.maxHeight === "undefined") return true;
        else return false;
    }
}

/**
 * @classDescription Site classe com os elementos básicos que será herdada pelas demais classes do projeto
 * @constructor
 */
var Site = function() {
	this.structure = {
		html: $('html'),
		header: $('#header'),
		nav: $('#nav'),
		content: $('#content'),
		main: $('#main', '#content'),
		footer: $('#footer')
	}
	
	/*
	 * adiciona o id js para a tag html para o funcionamento correto de alguns javascripts como, por exemplo,
	 * o menu
	 */
	this.structure.html.attr('id', 'js');
}

/**
 * @classDescription SiteUi(Site User Interface) controla a interface do site
 * @constructor
 */
var SiteUI = function(section) {
    var siteClass = this;
	var structure = this.structure;
	
	/**
	 * @method menu controla o menu principal do site
	 */
	this.menu = function() {
		var li = structure.nav.find('#menu > li'),
			item;
		
		li.unbind('mouseenter').bind('mouseenter',
			function(){
				li.children('.submenu').stop(1, 1);
				
				$(this).addClass('over')
					   .siblings().children('.submenu').hide()
					   .end().end().children('.submenu').show('normal');
			}
		).find('a').bind('focus',
			function() {
				// li pai do link que recebeu o foco
				item = $(this).closest('li.item'); 
				
				item.addClass('focus')
					.siblings().removeClass('focus').children('.submenu').stop(1, 1).hide()
					.end().end().children('.submenu').stop(1, 1).show('normal');
			}
		);
		
		li.unbind('mouseleave').bind('mouseleave',
			function(){
				li.children('.submenu').stop(1, 1);
				
				$(this).removeClass('over')
				       .children('.submenu').hide();
			}
		).find('a').bind('blur',
			function() {
				// li pai do link que recebeu o foco
				item = $(this).closest('li.item'); 
				
				item.removeClass('focus');
				
				setTimeout(function() {
					if(!item.hasClass('focus'))
						item.children('.submenu').stop(1, 1).hide();
				}, 100);	
			}
		);
	}
	
	/**
	 * @method textSize controla os botões de aumentar e diminuir texto do site
	 */
	this.textSize = function() {
		var fontSizeValue,
			increase = structure.content.find('.increase-text'),
			decrease = structure.content.find('.decrease-text');
		
		// o elemento main por padrão ficará com 12px
		structure.main.css('font-size', '12px');
		
		increase.bind('click',
			function() {
				// se o tamanho de fonte do elemento #main for menor que 15...
				if(structure.main.css('font-size').replace('px','') < 15) {
					
					/* 
					 * aumenta 1px o tamanho da fonte do elemento #main, consequentemente aumentará de todo o resto pois estão com tamanhos 
					 * de fonte declarados em "em"
					 */
					structure.main.css('font-size', parseInt(structure.main.css('font-size').replace('px','')) + 1 + 'px');
					
					if(structure.main.css('font-size') == '15px')
						$(this).css('opacity', 0.5);
					
					decrease.css('opacity', 1);	
				}
			}
		);
		
		decrease.bind('click',
			function() {
				if(structure.main.css('font-size').replace('px','') > 10) {
					
					/* 
					 * diminui 1px o tamanho da fonte do elemento #main, consequentemente diminuirá de todo o resto pois estão com tamanhos 
					 * de fonte declarados em "em"
					 */
					structure.main.css('font-size', parseInt(structure.main.css('font-size').replace('px','')) - 1 + 'px');				
					
					if(structure.main.css('font-size') == '10px')
						$(this).css('opacity', 0.5);
						
					increase.css('opacity', 1);	
				}
			}
		);
		
		structure.content.find('.default-font').bind('click',
			function() {
				structure.main.css('font-size', '12px');

				increase.css('opacity', 1);	
				decrease.css('opacity', 1);	
			}
		);
	}

}


/**
 * @classDescription SiteForms controla todos os formulários do projeto
 */
var SiteForms = function() {

    /**
     * @method setInputFocus Função para inputs que começam com um valor default, por exemplo campos de busca que tem o texto "Busca" dentro do próprio input. Quando o campo busca estiver vazio volta o texto que está dentro do atributo title ( que deve ser o mesmo do atributo "value" default)
     * @param {Object} input elemento input
     *
     */
    this.setInputFocus = function(input) {
        input.focus(function() {
            var elm = $(this);
            if (elm.val() == elm.attr("title")) {
                elm.val('').removeClass('empty');
            }
        }).blur(function() {
            var elm = $(this);
            if ($.trim(elm.val()) == "") {
                elm.val(elm.attr("title")).addClass('empty');
            }
        }).addClass('empty');
    }
}

		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;
		}
		

		//verifica se o flash foi carregado
		function isLoaded(e) {
	        if (e.success) {
	            $(".alt").css('display', 'none');
				//insere botão para desativar o flash
				$('#'+e.id).before('<a href="#lalala" class="invisible lkn-access">Ver conteúdo alternativo</a>');
				
				
				
				/* end accessibility invisible links */
				/* Botão de acessibilidade no header do site */
				//$('.btnAccessible').hide();
				$('.lkn-access').toggle(
					function() {
						$('object[id ^= "flash-"]').css('display', 'none');
						$('div[class $= "alt"]').css('display', 'block');
						return false;
					},
					function() {
						$('object[id ^= "flash-"]').css('display', 'block');
						$('div[class $= "alt"]').css('display', 'none');
						return false;
					}
				).click(function(){return false;});
				/* end Botão de acessibilidade no header do site */
	        }
	        else {
	            //alert("e.success ERRO = " + e.success); 
	            $(".btnAccessible").css('display', 'none');
	        }
	    }



		
		
/**
* Função que abre-fecha as abas dos ícones de mídias sociais do header principal
*/
function socialMenu() {
    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");
		});
}


/**
 * tarefas executadas para todo o portal, por isso não foram divididas em arquivos referentes à página ou seção
 */
 
 
/**
 * Abrir detalhes do produto

 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');
		tracker("/"+locale('trackerPrefix')+"/produtos/"+trackPath+prodIdent+"/acesso"); 
	}
	
	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 getIndex(index) {
	for(var i=(index+1); i < (index+4); i++) {
		if (i%3==0) {
			return i;
			break;
		}
	}
}
	
$(document).ready(
    function() {
		$('a').click(function() {
			if($(this).attr("target") == '_blank') {
				var $a = $(this);
				var href = $a.attr('href');
				var category = 'external-link';
				var event = 'click';
				var label = href;
				_gaq.push(['_trackEvent', category, event, label]);
			}
		});

		$('a.pdf').click(function() {
			var $a = $(this);
			var href = $a.attr('href');
			var category = 'download';
			var event = 'click';
			var label = href;
			_gaq.push(['_trackEvent', category, event, label]);
		});		
	
        /**
        * @extends
        */
        SiteUI.prototype = new Site();
       
        // instantiated classes
        var df = new Default();
        df.rels();
        df.printPreview();

        var siteUI = new SiteUI();
        siteUI.menu();
        siteUI.textSize();

        // cufon
        Cufon.replace('.cufon-dinr', {
            fontFamily: 'din-regular'
        });

        Cufon.replace('.cufon-dinb', {
            fontFamily: 'din-bold'
        });
	
        Cufon.now();

        /* +Magazine header*/
        var btnMagazine = $(".btn-magazine");
        $("a", btnMagazine).bind("mouseenter", function() {
            $(this).next(".submenu").slideToggle("fast"); 		   

            $(this).addClass("selected");
        }).bind("mouseleave", function() {
            $(this).next(".submenu").stop(1, 1).hide();
            $(this).removeClass("selected");
        });
        /* end Magazine header*/
		
		/* +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()){
						$(this).css({ position:'fixed', top:'0', left:'50%' }).removeClass(tClass).addClass('show-accessible-link');
					}
					else {
						$(this).removeClass(tClass).addClass('show-accessible-link');
					}
					
				});
				invLinks.bind('blur', function() {
					var tClass = $(this).hasClass('accessible-link') ? 'invisible' : 'accessible-link'; //this class
					if(supPositionFixed()){
						$(this).removeClass('show-accessible-link').addClass(tClass).css({ left:'-9999px' });
					}
					else {
						$(this).removeClass('show-accessible-link').addClass(tClass);
					}
				});	
				
		if (!$('#sidebar-submenu').length){
			$('#access-sidebar').removeClass('invisible');
			$('#access-sidebar').css('display','none');
			}
		
		
	
		/* +Magazine header
        var btnWorld = $(".bt-world");
        $("a", btnWorld).bind("mouseenter", function() {
            $(this).next(".submenu-flags").show();
            $(this).addClass("selected");
        }).bind("mouseleave", function() {
            $(this).next(".submenu-flags").hide();
            $(this).removeClass("selected");
        });
        end Magazine header*/

		
		/* +Flags on top*/
        
        $("#world").mouseenter(
        function () {
                $(".submenu-flags").slideToggle("fast"); // addClass("show") // .stop(1, 1);
                }
        );
        
        $("#world, .submenu-flags").mouseleave(
        function () {
                $(".submenu-flags").hide();
                }
        );
        
        /* end Flags on top*/
        socialMenu();
	
		if($("ul.products-list li").length) {
			$("ul.products-list li .item-header, ul.products-list li a.picture").click(function(){
				if($(this).hasClass("item-header")) {
					$(this).parent().find("a.picture").click();
					window.location = $(this).parent().find("a.picture").attr("href");
					return true;
				}
				
				var item = $(this).parent();
				// get main elements
				var list = $('.products-list');				
				var items = list.find('>li');
				var boxWidth = 240;
				var boxHeight = 168;
				var boxMargin = 10;
				
				$("ul.products-list li").css('background','none');
				$("ul.products-list li div.bottom").css('display','block');
				items.css('margin-bottom', '0px');
				
				if(!item.hasClass("selected")) {
					items.css('z-index','1');
					items.height(boxHeight);
					items.find('.details').hide();
					item.css('background','#FCFCFC');
					item.find('div.bottom').css('display','none');
					item.find('div.main').css('background-position', '0px '+ (item.find('.details').height() - 23) + 'px');
					
					if((items.last().attr('id') == item.attr('id')) && item.hasClass('first')) {
						item.css('margin-bottom', item.height() + 'px');
					}
					
					var details = item.find('.details');
					details.css({ position:'absolute'/*, top:top + 'px'*/ });
					
					// fix zindex
					item.css('z-index','2');
					
					// index
					var index = items.index(item);
					
					// height
					var newHeight = details.height() + item.height() - 40;
					
					var browser = navigator.appName
					var ver = navigator.appVersion
					var thestart = parseFloat(ver.indexOf("MSIE"))+1
					var brow_ver = parseFloat(ver.substring(thestart+4,thestart+7))
					if ((browser=="Microsoft Internet Explorer") && (brow_ver == 6))
					{
						newHeight = details.height() + item.height() - 20;
						if((items.last().attr('id') == item.attr('id')) && item.hasClass('first')) {
							item.css("padding-bottom", (details.height()-50) + "px");
						}
					}
					
					var lastInRow = getIndex(index);
					var els = items.filter(':lt('+lastInRow+')').filter(':gt('+(lastInRow-3)+')');

					els.css('height', newHeight + "px");
					
					var left = (index % 3) * (boxWidth + boxMargin) * (-1);
					details.css('left',left+'px');
					
					$("ul.products-list li a img, ul.products-list li h2").fadeTo(0, 0.5);
					item.find('a img').fadeTo(0, 1);
					item.find('h2').fadeTo(0, 1);
					
					details.show();
					items.removeClass("selected");
					item.addClass("selected");
					
				} else {
					$("ul.products-list li a img, ul.products-list li h2").fadeTo(0, 1);
					items.removeClass("selected");
					items.css('z-index','1');
					items.height(boxHeight);
					items.find('.details').hide();
					item.css('background','none');

				}
			});			
			
			var productUrl = location.href.split('#'); //id do elemento
			if($('ul #' + productUrl[1])[0]) {
				$(window).load(
					function() {
						var clickLocation = productUrl[1].slice(0, productUrl[1].length - 8);
						$('ul.products-list #' + clickLocation + ' .item-header').click();
					}
				);
			}

		}
		
		/* Verifica se a página tem algum elemento select, pois na versão do firefox 3.0.03- tem-se conflitos com a classe clearfix setada para todos os elementos que circundam o select */
		var content = $('div#content');
		var contentInt = $('div.grid-8');
		
		if( $('#main select').length ){
			if( ($('body .products, div.country-careers-opportunities, div.country-procurement').length) && (!$.browser.msie) ){
				content.removeClass('clearfix');
				contentInt.removeClass('clearfix');
				if($('body .products').length){
					contentInt.find('.clearfix').removeClass('clearfix');
					$('div.grid-8 .products-list').addClass('clear');
					$('div.grid-8').find('.quest-bar').addClass('clear');
				}
			}
		}	
			$("#quotes .alt").css('display', 'block'); //lista com cores alternadas
		
    }
	

);

		
