function resizeThickbox(){
    var borderSize = 4,
        headerHeight = 23,
        parentDoc = $(self.parent.document.documentElement),
        contentHeight = parseInt($('#heightMarker').offset().top),
        boxHeight = contentHeight + (2 * borderSize) + headerHeight,
        finalPosition = - (boxHeight / 2);
    
    if (!$.browser.msie || $.browser.version != '6.0') {
        parentDoc.find('#TB_window').animate({marginTop: finalPosition + 'px'}, 200);
    }
    parentDoc.find('#TB_iframeContent').animate({height: boxHeight + 'px'}, 200);
    
};

$(document).ready(function() {
	// Caso esteja dentro do ThickBox de candidatura à vaga, redimensionar a caixa
	var thickBoxBody = $('body.applyToJob');
	if (thickBoxBody.length) (function(){
		setTimeout(resizeThickbox, 200);
	})();
    
    // Contêiners de erros
    var curriculumErrorsContainer = $('div.searchErrors#curriculumErrors');
    var jobOpportunityErrorsContainer = $('div.searchErrors#jobOpportunityErrors');
    
    // Erros de lado servidor
    var curriculumServerSideErrors = curriculumErrorsContainer.find('.serverSide');
    var jobOpportunityServerSideErrors = jobOpportunityErrorsContainer.find('.serverSide');
    
    
    
    // Botões para voltar na navegação
    $(".goBack,#curriculumBreadcrumbs a[href='#goBack']").click(function(event) {
        event.preventDefault(); event.stopPropagation();
		if (history && history.length > 1){
	        history.back(-1);
		}
    });
    
    // Botão para voltar na visualização de vaga
    $("body.jobOpportunityViewPage .goBack[rel='toUserHome']").unbind('click').click(function(event){
        event.preventDefault(); event.stopPropagation();
        if (history && history.length > 1){
            history.back(-1);
        }
        else {
            location.href = '/user/home.html';
        }
    });
	
	// Botões para abrir o ThickBox de candidatura a vagas
	(function(){
		var applyButtons = $('body.jobOpportunityViewPage a.sendCurriculum');
		
		// Função para abrir o ThickBox
		function applyToJob(button) {
			var width = 640,
				height = 488,
				url = button.attr('href') + '&amp;TB_iframe=true&amp;height='+height+'&amp;width='+width+'&amp;modal=false&amp;KeepThis=true',
				caption = 'Gostou desta vaga?';
				
			tb_show(caption, url, false);
			
		}
		
		// Eventos dos botões
		applyButtons.click(function(event){
			applyToJob($(this));
			
			return false;
		});
		
		// Abertura automática, caso determinado pela aplicação
		if ($(document.body).is('.autoApply')) {
			setTimeout(function(){
				applyToJob(applyButtons.eq(0));
			}, 200);
		}
	})();

	// Botões para abrir o ThickBox de envio de vagas por email
	(function(){
		var applyMailButtons = $('body.jobOpportunityViewPage li.sendMail a'),
			infoTipCookieName = "EC_MAIL_TIP_SHOWN";
		
		// Função para abrir o ThickBox
		function applyToMail(button) {
			var width = 650,
				height = 360,
				url = button.attr('href') + '&amp;TB_iframe=true&amp;height='+height+'&amp;width='+width+'&amp;modal=false&amp;KeepThis=true',
				caption = 'RECEBA GRATUITAMENTE';
				
			tb_show(caption, url, false);
			hideInfoTip();
		}
			
		// Funções do balão informativo
		function startInfoTip() {
			var alreadyShown = EMPREGOCERTO.getCookie(infoTipCookieName);
			if (alreadyShown) {
				return false;
			}
			setTimeout(showInfoTip, 1000);
			setTimeout(hideInfoTip, 6000);
			$("#jobMenu #sendMailInfo #sendMailInfoLink").click(function(){
				applyToMail(applyMailButtons.eq(0));
				return false;
			});
			document.cookie = infoTipCookieName+"=1";
			return false;
		}
		function showInfoTip() {
			$("#jobMenu #sendMailInfo").fadeIn();
		}
		function hideInfoTip() {
			$("#jobMenu #sendMailInfo").fadeOut();
		}
		
		// Eventos dos botões
		applyMailButtons.click(function(event){
			applyToMail($(this));
			
			return false;
		});
		
		// Abertura automática, caso determinado pela aplicação
		if ($(document.body).is('.autoApply')) {
			setTimeout(function(){
				applyToJob(applyButtons.eq(0));
			}, 200);
		}
		else if($(document.body).is('.jobOpportunityViewPage')) {
			startInfoTip();
		}
	})();

	// Botões para sair do ThickBox
	$('body.applyToJob .closeLink').click(function(event){
		self.parent.tb_remove();
		return false;
	});
	
	// Função para carregar o link da âncora fora do thickbox
    $.fn.loadInParent = function() {
        if (!this.is('a')) return true;
        
        this.click(function(e){
            self.parent.location.href = $(this).attr('href');
            return false;
        });
    };
	
	// Botões para voltar à tela de navegação anterior do usuário (busca, home etc)
    $('div#jobApplyActions .jumpLink, .thickBoxIframe .jumpLink,div#cannotApplyActions .cannotApplyLink, body.applyToJob').loadInParent();

    // Exibidores de navegadores (blocos de modificadores)
    $('.searchFilters .searchFilterTitle').each(function(){
        var togglerObj = $(this);
        var startsHidden = togglerObj.parent().hasClass('startsHidden');
        new SimpleSlide(togglerObj, togglerObj.nextAll('dd'), startsHidden)
            .listener(function(visible){
                if (visible) {
                    togglerObj.removeClass('closed');
                }
                else {
                    togglerObj.addClass('closed');
                }
            });
    });
    
    // Exibidores de modificadores
    $('.listToggler').each(function(){
        var togglerObj = $(this);
        new SimpleSlide(togglerObj, togglerObj.prev('dd').find('.extra'), true)
            .listener(function(visible){
                if (visible) {
                    togglerObj.html('<a href="#">- fechar op&ccedil;&otilde;es</a>');
                }
                else {
                    togglerObj.html('<a href="#">+ mais op&ccedil;&otilde;es</a>');
                }
            });
    });
    
    // Esconde/exibe detalhes de resultados de busca
    var searchResultsTable = $('.searchResults table');
    var tableWithDetails = $('caption .resultViewChange a.details');
    var tableWithoutDetails = $('caption .resultViewChange a.list');
	var jTableCurriculumButton = $('.searchResults tbody').find('td.curriculumLink a, tr.resultFooter .bigButtonAction a, td.title a, td.name a');
	
	if ($('body.searchCv').length) {
		var modePrefix = '&';
	}
	else {
		var modePrefix = '?';
	}
	
    tableWithDetails.click(function(event){
        event.preventDefault();
        searchResultsTable.removeClass('hideDetails');
        tableWithDetails.addClass('hideClick');
        tableWithoutDetails.removeClass('hideClick');
		
		//Set listMode true
		jTableCurriculumButton.attr('href',jTableCurriculumButton.attr('href').replace(modePrefix+'listMode=1',modePrefix+'listMode=0'));
    });
    tableWithoutDetails.click(function(event){
        event.preventDefault();
        searchResultsTable.addClass('hideDetails');
        tableWithoutDetails.addClass('hideClick');
        tableWithDetails.removeClass('hideClick');
		
		//Set listMode true
		if (jTableCurriculumButton.attr('href').indexOf('listMode=0') != -1){
			jTableCurriculumButton.attr('href',jTableCurriculumButton.attr('href').replace(modePrefix+'listMode=0',modePrefix+'listMode=1'));
		}else if(jTableCurriculumButton.attr('href').indexOf('listMode=1') == -1){
			jTableCurriculumButton.attr('href',jTableCurriculumButton.attr('href')+modePrefix+'listMode=1');
		}
    });
    
    // Corretor de bug de div acima de select no IE6
    //$('.advancedSearch').bgiframe();

	//persistencia para modo de exibição lista
	if (location.search.indexOf('listMode=1') != -1){
		$('caption .resultViewChange a.list').click();
	}
	
    // Quebra de lista de três colunas
    var twoColumnsList = $('.searchByWorkingAreas .listBreak.twoColumns,#workingAreasForJobNotFound .listBreak.twoColumns');
    if (twoColumnsList.length > 0) {
        ListBreak.make(2, twoColumnsList);
    }
	
	// Popup para links de feed RSS
	$('.feedLinks a').each(function(){
		$(this).popup('rss');
	});
	
});
