	function checkAvailableWidth(){
		if(document.body.clientWidth > 1000) {
			var formWidth = "auto";
			var resultWidth = "99%";
		} else {
			var formWidth = "790px";
			var resultWidth = "999px";
		}
		if(document.getElementById('mainSearchDiv')) {
			document.getElementById('mainSearchDiv').style.width = formWidth;
		} 
		if(document.getElementById('conteiner')) {
		document.getElementById('conteiner').style.width = resultWidth;
		}
		
	}
	window.onload = checkAvailableWidth;
	//window.onresize = checkAvailableWidth;

	// ONLOAD
	$(document).ready(load);

	var g_last_facet_filters = new Array();

	var orderByAtual = 'score';
	var orderAtual = 'desc';
	var perPage = '10';

	function setOrderInit(orderByIni, orderAtualIni){
		orderByAtual = orderByIni;
		orderAtual = orderAtualIni;
	}

	// Funcao LOAD
	function load(){
		
		try{
			// RESETA O FORM AO ENTRAR (SÓ NO FORM - formBusca1 é o id do form na primeira tela)
			if($('#formBusca1').length > 0 ){
				updateComboBox();
				$('#formBusca1').submit(function(){
					$('#submitButton').html('<img src=\'http://img.catho.com.br/site/geral/loading.gif\'/>');
					$('#formBusca1 input').attr("readonly",true);
					$('#formBusca1 select').attr("readonly",true);
				});
			}

			// HANDLE EVENTS ===================================
			$('input[name=perfil_id]','#mainPerfis').bind('click',selectProfile);

			// DYNAMIC LOAD =====================================================
				$("select[name=pais_id]").bind('change',LoadDynamicFields);
				$("select[name=estado_id]").bind('change',LoadDynamicFields);
				$("select[name=regiao_id]").bind('change',LoadDynamicFields);
				$("#boxPerfil input[name=perfil_id]").bind('click',LoadDynamicFields);
				$("#boxAreaNivel select[name=area_pai_id]").bind('change',LoadDynamicFields);
				$("#boxAreaNivel select[name=area_pai_id]").bind('change',changedArea);
				$("#boxAreaNivel select[name=area_id]").bind('change',changedArea);

				$('#boxAreaNivel input[type=checkbox]').bind('click',changedArea);

				// Altera Perfil
				$('#boxPerfil input[name=perfil_id]').bind('click',changeProfileName);
			// ===================================================================

			registerVagaEvents();

			// FORÇA A SELEÇÃO DO PERFIL (RADIO) - EVITA CACHE
			$('#boxPerfil input[name=perfil_id][value='+g_def_perfil+']').attr('checked','checked');
			$('#formaVisuResumida').attr('checked','checked');

			// Tipo de Busca inicial
			$('#ipt_search_type').val(g_search_type);

			// TIPS (BALOES)
			//$('.fireHelpPOP').bind('mouseover',showHelpPop);

			//$('.popHelp').bind('mouseover',hideHelpPop);

			//$('.fireHelpPOP').bind('mouseout',hideHelpPop);

			$(window).unbind('unload');
			// ==============================================================================

		}catch(err){
			debug(err);
		}

	}

	function updateComboBox(){
		// Cada SelectBox
		$('.generalClassFormComboBox').each(

			function(){

					var ck = $('#'+$(this).attr('id')+' input[type=checkbox]:checked');

					if(ck.length > 0){

						try{
							var ckH = document.getElementById($(ck[0]).attr('id'));
							var tmp = ckH.onclick;
							tmp();
						}catch(e){
							debug(e);
						}
					}
				}
			);
	}

	function showHelpPop(e){
		var pop = $('#'+$(this).attr('rel'));
		$(this).addClass('underline');
		//pop.show();
		pop.css('display','block');
	}

	function hideHelpPop(e){
		var pop = $('#'+$(this).attr('rel'));
		$(this).removeClass('underline');
		//pop.hide();
		pop.css('display','none');
	}


	// Registra os eventos dos itens da vaga (Que são recarregados via ajax)
	function registerVagaEvents(){

		if($('#dvFormasVisu').length > 0){
			// TROCA O TIPO DE VISUALIZAçÂO DA VAGA(RESUMIDA/DATALHADA)
			$('#dvFormasVisu input[name=formaVisu]').bind('click',changeVisuAll);
		}

		if($('#dvVagas').length > 0){
			$('#dvVagas .btnVerDetalhes a').bind('click',changeVisuAlone);
			$('#dvVagas .btnEsonderDetalhes a').bind('click',changeVisuAlone);
			//$('#dvVagas .resultadoItemTI a').bind('click',markAsViewed);
		}
	}

	// Mostra o Icone de envio!
	function setVagaSended(vagId){

		if(g_lg){
			$("#imgVagSended"+vagId).attr('src','http://img.catho.com.br/site/vag/icoCurV0.gif').show();
		}

	}

	//Marca a vaga como já visualizada
	function markAsViewed(vagId){

		//if(g_lg){
			//$('#vagaBox_'+vagId).addClass('jaViuVaga');
			$('#vagaBox_'+vagId).addClass('bkgRoxoClaro');
			$('#vagaBox2_'+vagId).addClass('bkgRoxoClaro');
			$('#vagaDesc_'+vagId).addClass('fundoRoxo');
			$("#imgVagViewed"+vagId).attr('src','http://img.catho.com.br/site/vag/icoVisualizado0.gif').show();
		//}
	}


	// Troca a forma de visualizacao para TODAS as VAGAS e a seta do RADIO de opção
	function changeVisuAll(visu){

		if(typeof visu =='object' || typeof visu=='undefined')
			visu = $(this).val();

		var rmClass = (visu == 'visuDetalhada') ? 'visuResumida' : 'visuDetalhada';

		$('div > .resultadoItem').removeClass(rmClass).addClass(visu);
		$('div > .resultLegend').removeClass(rmClass).addClass(visu);

	}

	// Traca a visualização apenas de uma vaga
	function changeVisuAlone(visu){

		visu = $(this).attr('rel');

		var item = $(this).parents('.resultadoItem');

		var rmClass = (visu == 'visuDetalhada') ? 'visuResumida' : 'visuDetalhada';

		item.removeClass(rmClass).addClass(visu);

		item = null;
		rmClass = null;

	}

	// Troca do Perfil
	function selectProfile(){

		$('#boxPerfil .perfilSelected').removeClass('perfilSelected');

		$(this).parents('.boxProfissionalAba').addClass('perfilSelected');

		// FECHA OUTROS PERFIS
		hideOtherProfiles();
	}

	// Alteração na area PAI!
	function changedArea(){
		// Some alerta de perfil alterado
		alertaPerfilAlterado(false);
	}

	// Exibe alerta de perfil alterado
	function alertaPerfilAlterado(show){

		if(show){
			$('.alterou_perfil').show();
		}else{
			$('.alterou_perfil').hide();
		}
	}


	function changeProfileName(){
		var profile = $(this).val();
		$('.perfilName','#boxAreaNivel').html(g_perfis[profile]);
		$('#topProfileName').html(g_perfis[profile]);

		// Exibe ou não deficiencia
		if(profile == 1){
			$('#tr_deficiencia').show();
		}else{
			$('#tr_deficiencia').hide();
			// Remove os selecionados
			selectFunc.setUnsetAll('ppdperfil_id');
		}


		// Troca o texto de perfil alterado
		if(typeof g_cw.txtChangedProfile[profile] != 'undefined')
			var txt = g_cw.txtChangedProfile[profile];
		else
			var txt = g_cw.txtChangedProfile[1];

		$('#textProfileChanged').html(txt);

		alertaPerfilAlterado(true);

		profile = null;
	}


	// Carregamento Dinamico dos Campos
	function LoadDynamicFields(fieldChaged){

		if(typeof(fieldChaged) == 'undefined' || typeof(fieldChaged) == 'object'){
			var fieldChaged = $(this).attr('name');
		}

		var invalidField = false;
		var dados='';

		var state = 'loadDynamicFields';
		var handler = makeDynamicField;
		var retType = 'json';

		switch ( fieldChaged ){

			case 'pais_id': // Mudou o Pais
				dados='pais_id='+$('#pais_id').val();
				optionsLoading('estado_id');
				optionsLoading('cidade_id');
				optionsLoading('regiao_id');
			break;

			case 'estado_id': // Mudou o Estado


//				debugTime('T1 ');

				dados='estado_id='+$('#estado_id').val();

				var regiao = $('#estado_id').val();

				/*if(regiao != '' && regiao != ''){
					dados+='&regiao_id='+regiao
				}*/

				$('#td_cidade').show();

				smobj.clear('cidade_id');
				smobj.appendText('cidade_id',g_txtLoading);
				optionsLoading('regiao_id');
			break;

			case 'regiao_id': // Mudou a regiao
				dados='estado_id='+$('#estado_id').val();
				dados+='&regiao_id='+$('#regiao_id').val();
				smobj.clear('cidade_id');
				smobj.appendText('cidade_id',g_txtLoading);
			break;


			case 'perfil_id': // Mudou a regiao
				dados='perfil_id='+$('input[name=perfil_id]:checked').val();

				optionsLoading('area_pai_id');
				optionsLoading('area_id');
				optionsLoading('nivelh_id');

			break;

			case 'area_pai_id': // Mudou a regiao
				dados='perfil_id='+$('input[name=perfil_id]:checked').val();
				dados+="&area_pai_id="+$('select[name=area_pai_id]').val();

				optionsLoading('area_id');
				optionsLoading('nivelh_id');
			break;


			default:
				invalidField = true;
			false;
		}

		dados+='&changedField='+fieldChaged+'&State='+state;
		$.ajax({
			url:'index.php',
			type: "POST",
			data: dados,
			dataType: retType,
			success: handler,
			error:handler
		});

		dados=null;
		fieldChaged = null;

	}

	// Carrega os campos dinamicos (Após chamada)
	function makeDynamicField(jsn){

		if(typeof jsn == 'object'){


			if(typeof jsn.select == 'object'){

				for(id in jsn.select){

					// DropFake
					if($('#'+id+'selectOptList').length > 0){

						$('#'+id+'selectOptList').hide();
						selectFunc.reset(id);

						selectFunc.addItemArray(jsn.select[id],id);

						$('#'+id+'selectOptList').show();

					}else{
						$("#"+id).removeOption(/./);

						if(jsn.select[id]){
							$('#'+id).addOption(jsn.select[id]);
						}

						$("#"+id).attr('disabled',false);
					}
				}

				jsn.select = null;
			}
			//



			if(typeof jsn.toogleDisplay == 'object'){

				for(id in jsn.toogleDisplay){

					if(jsn.toogleDisplay[id] == 'show')
						$("#"+id).show();
					else if(jsn.toogleDisplay[id] == 'hide')
						$("#"+id).hide();

				}
			}



			if(typeof jsn.changeInnerHtml	== 'object'){


				for(id in jsn.changeInnerHtml){

					$('#'+id).hide();
					try{
						document.getElementById(id).innerHTML = jsn.changeInnerHtml[id];
					}
					catch(e){

					}

					if(id == 'listCity'){
						smobj.register('cidade_id');
						addEventCity();
					}

					$('#'+id).show();
				}
			}


			if(typeof jsn.changeValue == 'object'){

				for(id in jsn.changeValue){

					$('#'+id).hide();
					$('#'+id).html(jsn.changeValue[id]);
					$('#'+id).show();

				}

				jsn.changeValue = null;
			}


			if(typeof jsn.selected == 'object'){

				for(id in jsn.selected){
					$('option[value='+jsn.selected[id]+']','select[name*='+id+']').attr('selected','true');
				}

				jsn.selected = null;
			}
		}

		jsn=null;

	}

	// Coloca SELECT como LOADING
	function optionsLoading(id){

		if($('#'+id+'selectOptList').length > 0){

			selectFunc.reset(id);
			selectFunc.setText(id,g_txtLoading);

		}else{
			$("#"+id).removeOption(/./);
			$("#"+id).attr('disabled',true);
			$('#'+id).addOption(0,g_txtLoading);
		}
	}

	// Mostra OUTROS PERFIS
	function showOtherProfiles(){

		if($('input[name=perfil_id]:checked').val() != '1' ){
			$('input[name=perfil_id][value=1]').click();
		}
		$('#profileHint').hide();
		$('#otherProfiles').show();


	}

	// Esconde OUTROS PERFIS
	function hideOtherProfiles(){
		$('#profileHint').show();
		$('#otherProfiles').hide();
	}



	// FACETS  ===============================
	// Limpa os facets
	function clearFacets(){
		$('.boxFacet','#dv_facet_all').html('');
	}


	// Coloca todos os facets em modo loading
	function LoadingAllFacets(){

		$('.boxFacet > ul','#dv_facet_all').each(function(){
									smobj.appendText($(this).attr('id'),g_txtLoading);
								});

		$('.boxFacet > select','#dv_facet_all').each(function(){
									optionsLoading($(this).attr('id'));
								});
								
		$('.filteredValues','#dv_facet_all').html(g_txtLoading);
		
		$('.boxBranco','#dv_facet_all').html(g_txtLoading);

		$('.boxLinha').hide();
		$('.boxLinha2').html('');

		$('.bt_facet_refine').hide();
	}

	/**
	* Monta parametros para serem enviados
	*/
	function prepareParams(params){

		var dados = '';

		if(typeof params == 'object'){

			for( x in params ){
				dados+= (dados == "" ? "" : '&');

				if( typeof params[x] == 'object'){
					dados += prepareParams(params[x]);
				}else{
					dados += x+'='+params[x];
				}
			}
		}

		return dados;
	}

	/**
	* Refina o resultado da busca por facet
	*/
	function refineResultByFacet(facet,forceReload,matriz_id,tipoFilialGrupo){		
		if(typeof facet == 'undefined'){
			facet = 'all';
		}
		
		perPageNew 	= $("#perPage").val();
		orderBy 	= $('#orderSelect').val();
		order 		= $('#orderSelect option:selected').attr('subvalue');
		
//		orderByAtual = orderBy;
//		orderAtual = order;
		pageGlobal = 0;
		arrayVagas = new Array();
		indice = 0;
		limit = 0;
		limitPlus = 0;
		LimitMinus = 0;

		var dv_facet = '#dv_facet_'+facet;

		var checked = $('input[type=checkbox]:checked',$(dv_facet));
		var selected = $('select',$(dv_facet));

		if(!(checked.length == 0 && selected.length == 0 && forceReload==false) && facet != 'palavra_chave' || (busca_parceiros==1)){

			if( !busca_parceiros ){
				busca_parceiros = 0;
			}

			if ( busca_parceiros == 1) {
				var ch = facet + '='+$('#facet_value_'+facet).val();
			}
			else {
				var ch = checked.serialize();
				var sel = selected.serialize();
			}
			params = "";

			LoadingAllFacets();

			if(ch != ''){
				params+= ch;
			}

			if(sel != ''){

				if(params!='')
					params+='&';

				params+=sel;
			}

			// Seta refinamento
			var tipoBusca = 3;
			if(document.getElementById('tipoBusca')) {
				tipoBusca = document.getElementById('tipoBusca').value;
			}
			params+='&refine=1&';
			params+='&tipoBusca='+tipoBusca;
			params+='&setOrder='+orderByAtual+'&setOrderPos='+orderAtual+'&';

			params+=$("#queryId").serialize();
			params+='&'+$("#searchId").serialize();
			
			params+= "&numPerPage="+perPageNew;
			params+= "&orderBy="+orderBy;
			params+= "&order="+order;
			params+= "&matriz_id[]="+matriz_id;
			params+= "&tipoFilialGrupo="+tipoFilialGrupo;
			
			getResultRefined(params);

			//eval("document.getElementById('dv_facet_"+facet+"').style.display='none'");

		}
		else if( facet == 'palavra_chave' ){
			var keyWordFacet = $("#"+facet+"_facet").val();
			if( keyWordFacet.length < 2 ){
				alert("Por favor, insira ao menos 2 caracteres para palavra-chave.");
				return false;
			}

			params = "";
	
			LoadingAllFacets();

                        var tipoBusca = 3;
                        if(document.getElementById('tipoBusca')) {
                                tipoBusca = document.getElementById('tipoBusca').value;
                        }
			params+= "q="+keyWordFacet;
			params+='&refine=1&';
			params+='&tipoBusca='+tipoBusca;
			params+='&setOrder='+orderByAtual+'&setOrderPos='+orderAtual+'&';
			params+=$("#queryId").serialize();
			params+='&'+$("#searchId").serialize();

			getResultRefined(params);

			//eval("document.getElementById('dv_facet_"+facet+"').style.display='none'");
		}
	}

	/**
	* Remove um determinado facet
	*/
	function redefineFacet(filter,value,matriz_id,tipoFilialGrupo){

		var param = new Array();
		if( filter == 'estado_id' ){
			param['cidade_id'] = '-1'
			param['regiao_id'] = '-1'
		}
		
		perPageNew 	= $('#perPage').val();
		orderBy 	= $('#orderSelect').val();
		order 		= $('#orderSelect option:selected').attr('subvalue');
		
		param['numPerPage'] 		= perPageNew;
		param['orderBy'] 			= orderBy;
		param['order']				= order;
		param['matriz_id[]'] 		= matriz_id;
		param['tipoFilialGrupo'] 	= tipoFilialGrupo;

		param[filter]='-1';
		param['queryId'] = $('#queryId').val();
		param['searchId'] = $('#searchId').val();
		
		
		LoadingAllFacets();
		
		getResultRefined(param);
	}


	/**
	* Faz a chamada ajax para refinar/redefinir busca!
	*/
	function getResultRefined(params){
		
//		location.href = "#result";
		$('#dv_top_buscas_salvas').hide();
		$('#dv_top_form_busca').hide();

		this.scroll(1,-1000);
		$('#loadingResult').show();

		if( !busca_parceiros ){
			busca_parceiros = 0;
		}

		if(busca_parceiros==1)
			var dados = 'State=ajaxResultadoParceiros&';
		else
			var dados = 'State=ajaxResultado&';

		if(typeof params == 'object'){
			dados+=prepareParams(params);
		}else{
			dados+=params;

		}
		
		
		var tipoBusca = 3;
                if(document.getElementById('tipoBusca')) {
                	tipoBusca = document.getElementById('tipoBusca').value;
                }
		dados+=g_debug+'&';
		dados+= '&logTipoId='+$('input[name=logTipoId]').val();
		dados+= '&tipoBusca='+tipoBusca;
		dados+= '&'+$('input[name=lastParams]').serialize();
		// Some com o link de remover todos os facets
		//		$('#lnk_remover_todos').hide();
		
		$('#ResultMAIN').css('visibility','hidden');

		$.ajax({
			url:'index.php',
			type: "POST",
			data: dados,
			dataType: 'json',
			success: function(json){
				updateResult(json);
				carregaThickbox();
			}
		});
		
		
	}
	
	function carregaThickbox(){
		tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
		imgLoader = new Image();// preload image
		imgLoader.src = tb_pathToImage;	
	}

	/**
	* Atualiza a busca de acordo com o retorno json da chamada acima (getResultRefined)
	*/

	function updateResult(json){
		
		$('#ResultMAIN').hide();
		$('#ResultMAIN').html(json.html);
		$('#ResultMAIN').show();
		
		$('#div_facets').hide();
		$('#div_facets').html(json.htmlFacets);
		$('#div_facets').show();

		$('input[name=lastParams]').val(json.lastParams);

		// Registra os eventos novamente para funcionar com o novo HTML
		registerVagaEvents();

		$('#loadingResult').hide();

		$('#ResultMAIN').css('visibility','visible');
	}

	function goToPage(page,matriz_id,tipoFilialGrupo){
		var formaVisu = $('#dvFormasVisu input[type=radio]:checked').val();
		
		getResultRefined([{
			'setOrder':			orderByAtual,
			'setOrderPos':		orderAtual,
			'page':				page,
			'pagination':		1,
			'formaVisu':		formaVisu,
			'numPerPage': 		perPage,
			'matriz_id[]': 		matriz_id,
			'tipoFilialGrupo': 	tipoFilialGrupo
		}]);
		
		pageGlobal = page;
	}
	
	function reorderResult(orderBy,order,matriz_id,tipoFilialGrupo){
		if( orderBy == orderByAtual ){
			if( orderAtual == 'asc' ){
				order = 'desc';
			}
			else{
				order = 'asc';
			}
		}
		
		var formaVisu = $('#dvFormasVisu input[type=radio]:checked').val();
		getResultRefined([{
			'setOrder': orderBy,
			'setOrderPos': order,
			'page': 1,
			'pagination': 1,
			'formaVisu': formaVisu,
			'numPerPage': perPage,
			'matriz_id[]': matriz_id,
			'tipoFilialGrupo': tipoFilialGrupo
		}]);
		
		orderByAtual = orderBy;
		orderAtual = order;
		pageGlobal = 0;
		arrayVagas = new Array();
		indice = 0;
		limit = 0;
		limitPlus = 0;
		LimitMinus = 0;
	}

    function alterPerPageResult__notLogged(perPageNew,matriz_id,tipoFilialGrupo){
    	if(perPageNew == 5 || perPageNew == 10){
            alterPerPageResult(perPageNew,matriz_id,tipoFilialGrupo);
        }
    }

	function alterPerPageResult(perPageNew,matriz_id,tipoFilialGrupo){
		//alert(matriz_id); alert(tipoFilialGrupo);
		
		perPage = perPageNew;	

                var formaVisu = $('#dvFormasVisu input[type=radio]:checked').val();
                getResultRefined([{
                        'setOrder': orderByAtual,
                        'setOrderPos': orderAtual,
                        'page': 1,
                        'pagination': 1,
                        'formaVisu': formaVisu,
                        'numPerPage': perPage,
                        'matriz_id[]': matriz_id,
                        'tipoFilialGrupo': tipoFilialGrupo
                }]);

                pageGlobal = 0;
                arrayVagas = new Array();
                indice = 0;
                limit = 0;
                limitPlus = 0;
                LimitMinus = 0;
        }

	function toogleDisplays(json){

		for(y in json){

			toogleDisplay(y,json[y]);
		}
	}


	function toogleDisplay(obj,state){

		var el = $('#'+obj);

		if(state == 'hide'){
			el.hide();
		}else{
			el.show();
		}
	}

	function removeAllFacetFilters(){

		if( g_last_facet_filters.length ){

			LoadingAllFacets();

			var params= new Array();

			for(x in g_last_facet_filters){

				var objName = g_last_facet_filters[x];
				var obvalue = -1;

				params[objName] = obvalue;
			}

			params['removeFacets'] = '1';

			getResultRefined(params);
		}

	}

	function toogleCheckChildren(){

		var a = $('input[type=checkbox]:checked',$(this));
		var b = $('input[type=checkbox]:not(:checked)',$(this));

		a.attr('checked',false).removeClass('selected');
		b.attr('checked',true).addClass('selected');

	}

		var w;
		var tipoinclusao;

	function vag(vagId, alink){
    
		if(location.href.match(/risso\.svn/)){
			var domain = 'http://www3.catho.com.br';
		}else{
			var domain = '';
		}
		
		var next = nextPrevVaga(vagId,1);
		var prev = nextPrevVaga(vagId,-1);

		// Alteração efetuada para pegar do href todos os parametros passados para a visualização da vaga - Alteração feita no projeto vagas em destaque
		if($(alink).attr("href")) {
			link = domain+$(alink).attr("href")+"&tipoinclusao="+tipoinclusao+"&nextVag="+next+"&prevVag="+prev;
		}
		else {
			link = domain+'/vag/busca/vaga.php?vag_id='+vagId+'&imgid='+vagId+"&tipoinclusao="+tipoinclusao+"&nextVag="+next+"&prevVag="+prev;
		}
        
        w = window.open(link,'popupvaga','width=620,height=500,scrollbars=1');
        w.focus();
		
        // RETIRADO para corrigir um problema quando janela já esteja aberta
		//w.opener = self;

		markAsViewed(vagId);

	}

	function comoFunciona(form){
		if( form == 1 ){
			var modelBusca = 3;
                        if(document.getElementById('tipoBusca')) {
                                modelBusca = document.getElementById('tipoBusca').value;
                        }
			if( modelBusca == 'area_nivel' ){
				modelBuscaId = '2'; 
			}	
			else if( modelBusca == 'palavra_chave' ){
				modelBuscaId = '1';
			}
			else{
				modelBuscaId = '3';
			}
			var url = "http://www3.catho.com.br/como-funciona/busca_vagas.php?typeBusca="+modelBuscaId;
		}
		else if( form == 4 ){
			var url = "http://www3.catho.com.br/como-funciona/busca_vagas.php?typeBusca=4";
		}
		else{
			var url = "http://www3.catho.com.br/como-funciona/busca_vagas.php";
		}
		window.open(url,'_blank','width=800,height=455,scrollbars=1,resizable=yes');
	}

	function verExemplos(form){
                var modelBusca = 3;
                if(document.getElementById('tipoBusca')) {
                	modelBusca = document.getElementById('tipoBusca').value;
                }
		if( modelBusca == 'area_nivel' ){
			modelBusca = '2';
		}
		else if( modelBusca == 'palavra_chave' ){
			modelBusca = '3';
		}
		else{
			modelBusca = '1';
		}

		if( modelBusca == 3 ){
			var url = "http://www3.catho.com.br/como-funciona/exemplos-busca/busca_exemplos_pc.php";
		}
		else if( modelBusca == 2 ){
			var url = "http://www3.catho.com.br/como-funciona/exemplos-busca/busca_exemplos_nivel_area.php";
		}
		else{
			var url = "http://www3.catho.com.br/como-funciona/exemplos-busca/busca_exemplos_lista-vagas.php";
		}
		window.open(url,'_blank','width=800,height=455,scrollbars=1,resizable=yes');
	}

	function debug(msg){
		if(location.href.match(/risso\.svn/)){
			alert(msg);
		}
	}

	function saveResearch(){

		var form = $('#formResearch');

		// Tira o "comente"
		$('#research_table textarea').each(focuTextAreaResearch);

		var dados = form.serialize();

		$.ajax({
		  type: "POST",
		  url: "index.php",
		  data: dados+'&State=saveResearch&teste=âãéâçá',
		  success: updateResearchContent,
		  error: updateResearchContent
		});
	}

	function updateResearchContent(content){
		$('#researchContent').hide();
		$('#researchContent').html(content);
		$('#researchContent').show();
	}

	var g_loaded_form_result = false;

	/**
	* Exibe a janela de Busca no Resultado
	*/
	function showBusca(){

		$('#mainBoxResult').hide();
		$('#boxFormFilters').hide();
		$('#boxFormResult').hide();
		$('#boxFormFiltersLoading').show();

		if(g_loaded_form_result){

			setTimeout(timeShowFormResult,50);
			return;
		}

		tmpF = function(){ $('#mainBoxResult').show(); };

		setTimeout(tmpF,50);

		var param = $('input[name=lastParams]').serialize();
		param+= '&State=formResultado';

		$.ajax({
				type: "POST",
		  		url: "index.php",
		  		data: param,
				success: showFormBusca,
				error: function (){alert('Oops. Verifique sua conexão de internet!');},
				dataType: 'html'

				}
		);
	}

	function showFormBusca(htm){

		$('#mainBoxResult').hide();
		$('#boxFormResult').html(htm);

		setTimeout(timeShowFormResult,50);

		load();
	}

	function timeShowFormResult(){
			$('#mainBoxResult').show();
			$('#boxFormResult').show();
			$('#boxFormFiltersLoading').hide();
			var t = $('#boxResult').offset().top;
			var h = $(document).height() - t + 10;

			// Pro ie poe mais
			if($.browser.msie){
				t = t-10;
			}
			var cssArg = {'top':t+'px','height':h+'px', 'visibility':'visible'}

			$('#layerHideResult').css(cssArg).show();

			g_loaded_form_result = true;
	}

	function showUsedFilters(){

		$('#mainBoxResult').hide();
		$('#boxFormFiltersLoading').show();

		var tmpF = function(){

			$('#mainBoxResult').show();
			$('#boxFormResult').hide();
			$('#boxFormFilters').show();
			$('#boxFormFiltersLoading').hide();
			var cssArg = {'top':0+'px','height':0+'px', 'visibility':'visible'}

			$('#layerHideResult').css(cssArg);
		}

		setTimeout(tmpF,50);
	}

	var timeAlert;
	var numTime=0;

	function debugTime(lbl){
		var d = new Date();

		if(typeof lbl == 'undefined')
			lbl = '';
//		$('#test').append(lbl+d.getMinutes()+':'+d.getSeconds()+':'+d.getMilliseconds()+'<br/>');
	}

// LAYER SOLICITE ATENDIMENTO
function abreLayer() {
 	$('#layerFundo').css({display: "block"});
 	$('#layerCaixa').css({visibility: "visible"});
}
function fechaLayer() {
 	$('#layerFundo').css({display: "none"});
 	$('#layerCaixa').css({visibility: "hidden"});	
}

// WRAPPER PARA A FUNÇÃO XAJAX
onBlurAlert = true;

function alertKeyWord( evt ){ 

 	if(!(false==evt)){
		if(document.all){
			var key = event.keyCode;
		}  else {
			var key = evt.which;
		}

		if(13===key){
			key = true;
		} else {
			return true;
		}

	} else {
		var key = false;
		if(false===onBlurAlert){
			return true;
		}
	}

	var formulario	= document.getElementById('formBusca1');
	var	val			= formulario.q.value;
	var perfil		= "";

	for(var i=0; i < formulario.perfil_id.length; i++){

		if(formulario.perfil_id[i].checked == true){

			switch(i){
				case 0:
					perfil="profissional";
					break;
				case 1:
					perfil="estagiario";
					break;
				default:
					perfil="operacional";
			}

			break;

		}

	}

	xajax_alertKeyWord( val, perfil, key );

	if(key){
		return false;
	}

}
// RESPONSÁVEL POR EXECUTAR UMA ALTERAÇÃO NO DISPLAY DE UM OBJETO JAVA PELO ID DO OBJETO
function display(id, acao) {
	document.getElementById(id).style.display = acao;
}

// ADICIONA EVENTO O CAMPO DE CIDADE
function addEventCity() {

	if( undefined == document.getElementById('formBusca1')['cidade_id[]']){
		return;
	}

	contador = document.getElementById('formBusca1')['cidade_id[]'].length;

	for(var i=0; i < contador; i++){

		campo = document.getElementById('formBusca1')['cidade_id[]'][i];

		if( campo.value.substring(0,1) != "0" ){

			break;

		}

	    tmpId = 'cidade_id_' + campo.value ;

		idTop = tmpId;

	    liTop = document.getElementById( idTop );

	    idBot = tmpId.replace( 'cidade_id_0', 'cidade_id_' );

		liBot = document.getElementById( idBot );

		if(window.addEventListener){

		    liTop.addEventListener( 'click',
		    	function (){

		    		ident = idTop;

		    		val = ident.replace( 'cidade_id_0', '' );

		    		cont = document.getElementById('formBusca1')['cidade_id[]'].length;

		    		for( var j=0; j < cont; j++){

		    			ckB = document.getElementById('formBusca1')['cidade_id[]'][j];

		    			if( ckB.value == val ){

							ckB.checked = !ckB.checked;

							if(ckB.checked == true){
								document.getElementById( 'cidade_id_' + ckB.value ).className = 'selected';
							} else {
								document.getElementById( 'cidade_id_' + ckB.value ).className = '';
							}

		    			}

		    		}

		    }, true);

			liBot.addEventListener( 'click',
		    	function (){

		    		ident = idBot;

		    		val = '0' + ident.replace( 'cidade_id_', '' );

		    		cont = document.getElementById('formBusca1')['cidade_id[]'].length;

		    		for( var j=0; j < cont; j++){

		    			ckB = document.getElementById('formBusca1')['cidade_id[]'][j];

		    			if( ckB.value == val ){

							ckB.checked = !ckB.checked;

							if(ckB.checked == true){
								document.getElementById( 'cidade_id_' + ckB.value ).className = 'selected';
							} else {
								document.getElementById( 'cidade_id_' + ckB.value ).className = '';
							}

		    			}

		    		}

		    }, true);
		}

		if(window.attachEvent){

			liTop.attachEvent( 'onclick',
		    	function (){

		    		ident = idTop;

		    		val = ident.replace( 'cidade_id_0', '' );

		    		cont = document.getElementById('formBusca1')['cidade_id[]'].length;

		    		for( var j=0; j < cont; j++){

		    			ckB = document.getElementById('formBusca1')['cidade_id[]'][j];

		    			if( ckB.value == val ){

							ckB.checked = !ckB.checked;

							if(ckB.checked == true){
								document.getElementById( 'cidade_id_' + ckB.value ).className = 'selected';
							} else {
								document.getElementById( 'cidade_id_' + ckB.value ).className = '';
							}

		    			}

		    		}

		    }, true);

			liBot.attachEvent( 'onclick',
		    	function (){

		    		ident = idBot;

		    		val = '0' + ident.replace( 'cidade_id_', '' );

		    		cont = document.getElementById('formBusca1')['cidade_id[]'].length;

		    		for( var j=0; j < cont; j++){

		    			ckB = document.getElementById('formBusca1')['cidade_id[]'][j];

		    			if( ckB.value == val ){

							ckB.checked = !ckB.checked;

							if(ckB.checked == true){
								document.getElementById( 'cidade_id_' + ckB.value ).className = 'selected';
							} else {
								document.getElementById( 'cidade_id_' + ckB.value ).className = '';
							}

		    			}

		    		}

		    }, true);
		}
	}

}

function vagaOver(id, vagaImgL, vagaImgR,order,orderBy) {
		if(orderBy != orderByAtual) {
				setObjClass(id,'ordenacao ativa off');
				document.getElementById(vagaImgL).setAttribute("src", "http://img.catho.com.br/site/vag/resultado/bkgDegradeAzulL.gif");
				document.getElementById(vagaImgR).setAttribute("src", "http://img.catho.com.br/site/vag/resultado/bkgDegradeAzulR.gif");


				if(orderByAtual == orderBy ){
						if( order == orderAtual && order=='desc' ){
								imgOrder = "http://img.catho.com.br/site/vag/resultado/icoSetaBranca2.gif";
						}
						else if( order == orderAtual ){
								imgOrder = "http://img.catho.com.br/site/vag/resultado/icoSetaBranca1.gif";
						}
				}
				else{
						if( order == 'asc' ){
								imgOrder = "http://img.catho.com.br/site/vag/resultado/icoSetaBranca2.gif";
						}
						else{
								imgOrder = "http://img.catho.com.br/site/vag/resultado/icoSetaBranca1.gif";
						}
				}

				$("#img_"+orderBy).attr('src',imgOrder).show();
		}
		else{
				if( orderAtual == 'asc' ){
						imgOrder = "http://img.catho.com.br/site/vag/resultado/icoSetaBranca1.gif";
				}
				else{
						imgOrder = "http://img.catho.com.br/site/vag/resultado/icoSetaBranca2.gif";
				}
				$("#img_"+orderBy).attr('src',imgOrder).show();
				var textoTemp = id.replace('Ord',"");
				textoTemp = textoTemp.replace('salario','salário');
				textoTemp = textoTemp.replace('titulo','título da vaga');
				textoTemp = textoTemp.replace('empresa','nome da empresa');
				$("#"+id).attr('title',"Alterar ordenação de "+textoTemp);
		}
}
function vagaOut(id, vagaImgL, vagaImgR,orderBy) {
		if(orderBy != orderByAtual) {
				setObjClass(id,'ordenacao inativa');
				document.getElementById(vagaImgL).setAttribute("src", "http://img.catho.com.br/site/vag/resultado/bkgDegradeAzulEscuroL.gif");
				document.getElementById(vagaImgR).setAttribute("src", "http://img.catho.com.br/site/vag/resultado/bkgDegradeAzulEscuroR.gif");
				$("#img_"+orderBy).hide();
		}
		else{
				if( orderAtual == 'asc' ){
						imgOrder = "http://img.catho.com.br/site/vag/resultado/icoSetaBranca2.gif";
				}
				else{
						imgOrder = "http://img.catho.com.br/site/vag/resultado/icoSetaBranca1.gif";
				}
				$("#img_"+orderBy).attr('src',imgOrder).show();
		}
}

function setObjClass(obj,classe){
		var objeto = document.getElementById(obj);
		if (objeto) {
			var classeAtual = objeto.getAttribute('class');
			if (!classeAtual == "") {
				objeto.removeAttribute('class');
			}
			objeto.setAttribute('class', classe);
			objeto.className = classe;
		}
}

function in_array(needle, haystack, strict) {
	var found = false, key, strict = !!strict;
	for (key in haystack) {
		if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
			found = true;
			break;
		}
	}
	return found;
}

var arrayVagas = new Array();
var indice = 0;
var limit = 0;
var limitPlus = 0;
var LimitMinus = 0;
var openFirst = 0;
var openLast = 0;
var pageGlobal = 0;

function changeNumbers( prev,next, total ){
	limit = Number(total-1);
	if( !isNaN( next ) ){
		limitPlus = (Number(next)-1)*10;
	}
	if( !isNaN( prev ) ){
		if( prev == 0 ){
			LimitMinus = 0;
		}
		else{
			LimitMinus = ((Number(prev))*10)-1;
		}
	}
}

function addVaga(vag_id){
	if( in_array(vag_id,arrayVagas) == false ){
		arrayVagas[indice] = new Array();
		arrayVagas[indice] = vag_id;
		indice++;
	}

	if(location.href.match(/risso\.svn/)){
		var domain = 'http://www3.catho.com.br';
	}else{
		var domain = '';
	}


	if( openFirst == 1 && (Number( limitPlus )-1) == indice ){
		var next   = nextPrevVaga(vag_id,-7);
		var prev   = nextPrevVaga(vag_id,-9);
		var vag_id = nextPrevVaga(vag_id,-8);

		w.location.href=domain+'/vag/busca/vaga.php?vag_id='+vag_id+'&imgid='+vag_id+"&nextVag="+next+"&prevVag="+prev;

		markAsViewed(vag_id);
		openFirst = 0;
	}
	else if( openLast == 1 && (Number( limitPlus )-1) == indice ){

		var next = nextPrevVaga(vag_id,1);
		var prev = nextPrevVaga(vag_id,-1);

		w.location.href=domain+'/vag/busca/vaga.php?vag_id='+vag_id+'&imgid='+vag_id+"&nextVag="+next+"&prevVag="+prev;
		markAsViewed(vag_id);

		openLast=0;
	}
}

function nextPrevVaga(vag_id,require){
	var vagRequire = 0;
	var indRequire = 0;
	for( var i in arrayVagas ){
		if( arrayVagas[i] == vag_id ){
			indRequire = i;
		}
	}
	var indRequireNew = (Number(indRequire)+Number(require));
	if( Number(indRequireNew) >= 0 && Number(arrayVagas[indRequireNew]) > 0 ){
	    return arrayVagas[indRequireNew];
	}
	else{
		if( require == '-1' && Number(indRequire) > 0 ){
			return "pgAnt";
		}
		else if( require == '1' && Number(indRequire) < Number(limit) ){
			return "pgNext";
		}
	}
}

function pagVag( direction ){
	if( direction == 'pgAnt' ){
		pageToGo = Number(pageGlobal);
		openLast = 1;
	}
	else if( direction == 'pgNext' ){
		pageToGo = Number(pageGlobal)+2;
		openFirst = 1;
	}
	goToPage(pageToGo);
}

/**
 * Projeto Busca de Vagas (formulários)
 * 
 * @author Guilherme Rizzo Fiuza <gfiuza@catho.com.br>
 * @since  13/04/2009
 */
function viewSelect(alvo) {
    if (alvo) {
        if (alvo.style.display == 'none' || alvo.style.display == '' || !alvo.style.display) { 
            hiddenSelect();
            alvo.style.display = 'block';
        }
        else
            hiddenSelect();
    }
}

function hiddenSelect(alvo) {
    if (alvo)
        alvo.style.display = 'none';
    else 
        $("div.comboBox > div[id^='comboBox']").css('display', 'none');
        
    if (document.getElementById('localidadeAlterada').value == 'true') {
        document.getElementById('inputsLocalidade').style.display = 'none';
        xajax_changeLocalidade(xajax.getFormValues('formBusca1',true));
        ajaxC = $("div.ajaxCarregando").html();
        document.getElementById('localidade').innerHTML = ajaxC;
    }
}

function desmarcarTodos (alvo) {
    if (alvo) {
        if (
            !(/ultimo/.test(alvo.parentNode.parentNode.parentNode.className))
        )
            localidadeAlterada('true');
            
        $('input:checkbox', alvo.parentNode.parentNode).attr({checked: false});
		$('a', alvo.parentNode.parentNode).removeClass('selected');
        changeSelectMultiplo(alvo.parentNode);
    }
}

function changeSelectUnico (alvo) {
    box = alvo.parentNode.parentNode.parentNode;
    box.parentNode.getElementsByTagName('input')[0].value   = document.getElementById(alvo.innerHTML).innerHTML;
    box.parentNode.getElementsByTagName('div')[0].innerHTML = alvo.innerHTML;
    hiddenSelect(box);
}

function changeSelectMultiplo (alvo) {
    checks = $('input:checkbox:checked', alvo);
    
	if (alvo.parentNode.className != 'areaItem' && alvo.parentNode.className != 'area txt11') {
		if (document.all) 
			selTit = alvo.parentNode.previousSibling;
		else 
			selTit = alvo.parentNode.previousSibling.previousSibling;
		
		if (checks.length > 1) 
			selTit.innerHTML = checks.length + ' selecionados';
		else {
			if (checks.parent().text()) 
				selTit.innerHTML = checks.parent().text();
			else 
				selTit.innerHTML = "Indiferente";
		}
	}
}

function alteraTituloPerfil(titulo) {
	$("#titulo_perfil").html(titulo);
	if (titulo == 'Profissional') {
		$('#ppd_values').show();
	}
	else {
		$('#ppd_values').hide();
		$('#ppd_values input[type=checkbox]').removeAttr('checked');
		$('#ppd_values a').removeClass('selected');
	}
}

function carregaPerfil (id) {

    perfil_id = id.split('_').reverse()[0];
    document.getElementById('perfil_id').value = perfil_id;
    
    $("span[id^='sperfil_id']").css('display', 'none');
    $("a[id^='aperfil_id']").css('display', 'inline');
    
    document.getElementById('aperfil_id_'+perfil_id).style.display = 'none';
    document.getElementById('sperfil_id_'+perfil_id).style.display = 'inline';
    if (document.getElementById('tipoBusca').value == 'area_nivel') {
        //$("div.area").css('display', 'none');
        xajax_carregaPerfil(xajax.getFormValues('formBusca1',true));
        ajaxC = $("div.ajaxCarregando").html();
    
        boxArea = document.getElementById('area');
        if (boxArea)
            $("div.area", document.getElementById('area')).html(ajaxC);
    
        boxNivel = document.getElementById('nivel');
        if (boxNivel)
            $("div.area", document.getElementById('nivel')).html(ajaxC);
    }

}

function carregaJsLocalidade () {

    document.getElementById('inputsLocalidade').style.display = 'block';

    $(document).bind('click', function (e) {
        with (e.target) {
            if (!(/comboBox/i.test(className)))
                if (parentNode) {
                    if (parentNode.parentNode) {
                        if (parentNode.parentNode.parentNode) {
                            if (parentNode.parentNode.parentNode.parentNode) {
                                if (
                                       !(/comboBox/i.test(e.target.parentNode.parentNode.parentNode.parentNode.className))
                                    && !(/comboBox/i.test(e.target.parentNode.parentNode.parentNode.className))
                                )
                                hiddenSelect();
                            }
                            else
                                hiddenSelect();
                        }
                        else
                            hiddenSelect();
                    }
                    else
                        hiddenSelect();
                }
                else
                    hiddenSelect();
        }
    });
    
    $('ul.selectMultiplo input:checkbox').bind('click', function (e) {
        if (
            !(/ultimo/.test(e.target.parentNode.parentNode.parentNode.parentNode.className))
			&& e.target.id.lastIndexOf('area_id') != 0
			&& e.target.id.lastIndexOf('nivelh_id') != 0
			&& e.target.id.lastIndexOf('capital') != 0
			&& e.target.id.lastIndexOf('porte_id') != 0
			&& e.target.id.lastIndexOf('ppdperfil_id') != 0
        )
			localidadeAlterada('true');
        changeSelectMultiplo(e.target.parentNode.parentNode);
    });
    
    $('ul.selectUnico a').bind('click', function (e) {
		if (!(/inputDate/.test(e.target)) && !(/faixa_sal_id/.test(e.target)))
			localidadeAlterada('true');

        changeSelectUnico(e.target);
        return false; // cancela href
    });
    
    $('img.comboBoxBotao').bind('click', function (e) {
        hiddenSelect(e.target.parentNode.parentNode);
    });

    /*$("div[id^='comboBox']").parent().bind('click', function (e) {
        viewSelect(e.target.parentNode.getElementsByTagName('div')[1]);
    });*/
	if ( !alvo ) {
		var alvo = '#localidade';
	}

	/**
	* Abre/fecha select ao clicar no comboBox
	*/
	$( 'div[id^=comboBox]' , alvo ).parent().bind( 'click' , function (e) {
		if ( e.target.parentNode == this || e.target == this) {
			var comboBox = $( 'div[id^=comboBox]' , this );
			if ( !comboBox.css('display') || comboBox.css('display') == 'none' ) {
				hiddenSelect();
				comboBox.show();
			} else {
	 			comboBox.hide();
	 			ajaxLocalidade();
			}
		}
	});

    $('a.desmarcar').bind('click', function (e) {
        desmarcarTodos(e.target);
        return false; // cancela href
    });
}

	/**
 	* Requisicao ajax para localidade
 	* @return
 	*/
	function ajaxLocalidade (){
    	if ($('#localidadeAlterada').val == 'true' ) {
        	$('#localidadeAlterada').val(false);
	        xajax_changeLocalidade( xajax.getFormValues( 'formBusca1' , true ) );
    	    $( '#localidade' ).html( $( 'div.ajaxCarregando' ).html() );
	    }
	}

	function carregaJsPerfil () {
	    if (document.getElementById('area') || document.getElementById('nivel'))
	        $("div.area").css('display', 'block');
	    
	    $("a[id^='aperfil_id']").bind('click', function (e) {
	        carregaPerfil(e.target.id);
	        return false; //cancela href
	    });
	}

	/**
	 * Aplica JS para localidade na leitura da pagina
	 */
	$(document).ready(function(){
	    if (document.getElementById('boxLocalidade')) { // se houver localidade
	        carregaJsLocalidade();
	    }
	   
		if( document.getElementById('tipoBusca') ){
		    if (!(/^lista_/.test(document.getElementById('tipoBusca').value))) { // se não for lista de vagas ou cargos
		        carregaJsPerfil();
		    }
		}
	});

function openEnvio(vag_id,acao){
	if( vag_id ){
		if( acao == 'open' ){
			$('#td_envio_'+vag_id).show();
			$('#tdEnvioButton2_'+vag_id).hide();
			$('#tdEnvioButton1_'+vag_id).hide();
			
			this.location= "#td_vag_"+vag_id;
		}
		else{
		   $('#td_envio_'+vag_id).hide();
			$('#tdEnvioButton2_'+vag_id).show();
			$('#tdEnvioButton1_'+vag_id).show();
			
			this.location= "#td_topo_vag_"+vag_id;
		}
	}
}

function sendCur( vag_id ){
	if( vag_id > 0 ){
		var formulario = eval("document.form_envio_"+vag_id);
		var questRespText = formulario.getElementsByTagName('textarea');
		var questRespInput = formulario.getElementsByTagName('input');

		var arrayResp = new Array();

		var control = 0;
	

		if( questRespInput.length > 0 ){
			for( var j=0; j < questRespInput.length; j++ ){
				if( questRespInput[j].type == 'radio' ){
					var nameInput = questRespInput[j].name;
					var fieldByName = document.getElementsByName(nameInput);
					var isChecked = 0;
					var validated = 0;
					if( arrayResp.length > 0 ){
						for(var m=0; m < arrayResp.length; m++){
							if( nameInput == arrayResp[m][0] ){
								validated = 1;
							}
						}
					}
					if( validated == 0 ){
						for( var k=0; k < fieldByName.length; k++ ){
							if( fieldByName[k].checked == true ){
								isChecked = 1;
								arrayResp[control] = new Array();
								arrayResp[control][0] = nameInput;
								arrayResp[control][1] = fieldByName[k].value;
								control++;
							}
						}
						
						if( isChecked == 0 ){
							alert("Todas as perguntas do questionario são obrigatórias.");
							fieldByName[j].focus();
							return false;
						}
					}
				}
			}
		}

		if( questRespText.length > 0 ){
			for( var i=0; i < questRespText.length; i++ ){
				if( questRespText[i].name != 'usr_carta_'+vag_id ){
					if( questRespText[i].value.length < 3 ){
						alert('Resposta invalida, especifique melhor sua resposta.');
						questRespText[i].focus();
						return false;
					}

					var content = questRespText[i].value.toLowerCase();
					if( ( (content.indexOf(' '+'cv') > 0 || content.indexOf(' '+'curriculo') > 0 || content.indexOf(' '+'currículo') > 0 || content.indexOf(' '+'curriculum') > 0 || content.indexOf(' '+'anexo') > 0 || content.indexOf(' '+'sim') > 0 || content.indexOf(' '+'não') > 0 || content.indexOf(' '+'naum') > 0 || content.indexOf(' '+'nao') > 0 || content.indexOf(' '+'combinar') > 0 ) && content.length < 15) || content == 'vide cv' || content == 'ver cv' || content == 'veja cv' || content == '' || content == 'vide currículo' || content == 'veja currículo' || content == 'ver currículo' || content == 'vide curriculum' || content == 'veja curriculum' || content == 'ver curriculum' || content == 'A/C' || content == 'a/c' || content == 'não tenho, mas tenho facilidade de aprender' || content == 'ñ tenho, mas tenho facilidade de aprender' || content == 'não tenho mas tenho facilidade de aprender' || content == 'ñ tenho mas tenho facilidade de aprender' || ( content == 'a combinar' && content.length < 14 ) || ( content == 'em anexo' && content.length < 10 ) || ( content == '...' && content.length < 6 ) || content == 'consta no currículo' || content == 'veja o currículo' || content == 'está no currículo' || content == 'vide curriculo' || content == 'veja curriculo' ||  content == 'ver curriculo' || content == 'veja o curriculo' || content == 'esta no curriculo' || ( content == 'curriculo' && content.length < 14 ) || ( content == 'currículo' && content.length < 14 ) || ( content == 'anexo' && content.length < 10 ) || ( content == 'cv' && content.length < 6 ) || ( content == 'sim' && content.length < 5 ) || ( ( content == 'não' || content == 'nao' || content == 'naum') && content.length < 6 ) ) {
						alert("Especifique melhor sua resposta.");
						questRespText[i].focus();
						return false;
					}   
					
					//reDigits = /^\d+$/;
					var re = new RegExp("[0]{5,}|[1]{5,}|[2]{5,}|[3]{5,}|[4]{5,}|[5]{5,}|[6]{5,}|[7]{5,}|[8]{5,}|[9]{5,}|[0-9]{10,}");
					if (content.match(re)){
						alert("Não utilize apenas numeros em sua resposta.");
						questRespText[i].focus();
						return false;
					}                       

					var re1 = new RegExp("[a]{4,}|[e]{4,}|[i]{4,}|[o]{4,}|[u]{4,}|[aeiou]{6}","gi");
					if (content.match(re1)){
						alert("Nao utilize apenas vogais.");
						questRespText[i].focus();
						return false;
					}                       

					var re4 = new RegExp("^[ ]{6}","gi");
					if (content.match(re4)){
						alert("Nao utilize apenas espacos."); 
						questRespText[i].focus();
						return false;
					}

					var TextoSpace = " "+content;
					var re2 = new RegExp("[b]{8,}|[c]{8,}|[d]{8,}|[f]{8,}|[g]{8,}|[h]{8,}|[j]{8,}|[k]{8,}|[l]{8,}|[m]{8,}|[n]{8,}|[p]{8,}|[q]{8,}|[r]{8,}|[s]{8,}|[t]{8,}|[v]{8,}|[w]{8,}|[x]{8,}|[y]{8,}|[z]{8,}|[b-df-hj-np-tv-z]{8,}");
					if (TextoSpace.match(re2) ){
						alert("Não utilize apenas consoantes.");
						questRespText[i].focus();
						return false;
					}

					arrayResp[control] = new Array();
					arrayResp[control][0] = questRespText[i].name;
					arrayResp[control][1] = questRespText[i].value;
					control++;

				}
			}
		}

		var cur_id = $("#usr_cur_"+vag_id).val();
		var carta  = $("#usr_carta_"+vag_id).val();


		var dados = "vag_id="+vag_id;

		for( var l in arrayResp ){
			dados += "&"+arrayResp[l][0]+"="+ajaxGlobals.url_encode(arrayResp[l][1]);
		}

		if( cur_id > 0 || cur_id.length > 0 ){
			dados += "&cur_id="+cur_id;
		}
		else{
			alert("Selecione um curriculo.");
		}
		
		if( carta.length > 2 ){
		    dados += "&carta="+carta;
        }


        $.ajax({
                url:'sendCur.php',
                type: "POST",
                data: dados,
                dataType: "html",
                success: function(qtde_envios){
                    if(qtde_envios != 2){
                        var txt = "<strong class='txt14' style='color: #FF0000;'>Seu curr&iacute;culo foi enviado ao respons&aacute;vel pela vaga!</strong>";
                    }else{
                        var txt = "<strong class='txt14' style='color: #FF0000;'>Seu curr&iacute;culo foi enviado ao respons&aacute;vel pela vaga!</strong><br />Seu curr&iacute;culo já foi enviado 2 vezes para o respons&aacute;vel por esta vaga.";
                    }
                    
                    var msg = "<img src='http://img.catho.com.br/site/vag/icoCurV0.gif' style='margin-right:5px;' />"+txt+"</strong>";
                     
                    $('#td_envio_'+vag_id).hide();
                     
                    $('#tdEnvioButton2_'+vag_id).html(msg);
                    $('#tdEnvioButton1_'+vag_id).html(msg);
                     
                    $('#tdEnvioButton2_'+vag_id).attr('align','left');
                    $('#tdEnvioButton1_'+vag_id).attr('align','left');
                    
                    $('#tdEnvioButton2_'+vag_id).show();
                    $('#tdEnvioButton1_'+vag_id).show();
                    
                    window.location= "#td_topo_vag_"+vag_id;
                },
                error: function(){
                    alert("Falha ao enviar o curriculo. Tente novamente!");
                }
        });
	}
}

function makeResearchble(word){
	var term = word.replace(/[éèêëËÊÉÈ]/g,"e");
	term = term.replace(/[àáâãäåÄÅÃÂÁÀ]/g,"a");
	term = term.replace(/[ìíîïÏÎÍÌ]/g,"i");
	term = term.replace(/[òóôõöÖÕÔÓ]/g,"o");
	term = term.replace(/[ÜÛÚÙùúûü]/g,"u");
	term = term.replace(/Ç/g,"c");
	term = term.replace(/ç/g,"c");
	term = term.toLowerCase();
	return term;
}

	function setCheckboxState(obj_id) {
		if ((/^label_/.test(obj_id))) {
			obj = $('#'+obj_id.substr(6,100));
			if (obj[0].checked) 
				obj[0].checked = false;
			else 
				obj[0].checked = true;
		}
		else
			obj = $('#'+obj_id);
		
		setSelected(obj[0]); 
	}

function setSelected(obj) {
	if ((/^area_id2/.test(obj.id)) || (/^nivelh_id2/.test(obj.id)) || (/^estado_id2/.test(obj.id)) || (/^regiao_id2/.test(obj.id)) || (/^cidade_id2/.test(obj.id))  || (/^capital2/.test(obj.id))  || (/^porte_id2/.test(obj.id)) || (/^ppdperfil_id2/.test(obj.id))) 
		if (obj.checked)
			$('#label_' + obj.id).addClass('selected');
		else
			$('#label_' + obj.id).removeClass('selected');
	//alert(obj.parentNode.parentNode+'  --- '+obj.parentNode.parentNode.parentNode);
	//alert('name:'+obj.name+'   id:'+obj.id+'   checked:'+obj.checked);
	if ((/^estado_id2/.test(obj.id)) || (/^regiao_id2/.test(obj.id)) || (/^cidade_id2/.test(obj.id))) {
		localidadeAlterada('true');
		changeSelectMultiplo(obj.parentNode.parentNode);
	}
}

function localidadeAlterada(status) {
	$('#localidadeAlterada').val(status);
	if (status == 'true') {
		$("#btnBuscarAct").hide();
		$("#btnBuscar").show();
	} else {
		$("#btnBuscar").hide();
		$("#btnBuscarAct").show();		
	}
}

function buscaPorPalavraChave(value) {
	if(value.length>1) {
		$("#palavra_chave_btnRefinar").hide();
		$("#palavra_chave_btnRefinarAct").show();
	} else {
		$("#palavra_chave_btnRefinarAct").hide();
		$("#palavra_chave_btnRefinar").show();
	}
}

function showComoFunciona(value) {
		$("#dv_como_funciona").slideToggle();
		$("#lnk_como_funciona img").toggle();
}

function mudaCarta(carta,vag_id)
{
	$("#usr_carta_"+vag_id).html(carta);
} 
