/**
 * @author Lucas Martini
 */

function showDiv(target) {
	div = document.getElementById(target);
	if (div.style.display == "block") {
		div.style.display = "none";
	} else {
		div.style.display = "block";
		div.scrollIntoView(true);
	}
}

function toggleDiv(target) {
		nome_seta = target + "_seta";
		nome_div = target + "_info";
		div = document.getElementById(nome_div);
		seta = document.getElementById(nome_seta);

		if (div.style.display == "block") {
			div.style.display = "none";
		}
		else {
			div.style.display = "table";
		}
		
		if (String(seta.src).match("seta_down")) {
			seta.src = "images/seta.jpg";
		}
		else {
			seta.src = "images/seta_down.jpg";
		}
		
		div.blur();
		seta.blur();
}

function toggleOpenDiv(target) {
		nome_seta = target + "_seta";
		nome_div = target + "_info";
		div = document.getElementById(nome_div);
		seta = document.getElementById(nome_seta);
		if (div.style.display == "none") {
			div.style.display = "block";
		}
		else {
			div.style.display = "none";
		}
		
		if (String(seta.src).match("seta_down")) {
			seta.src = "images/seta.jpg";
		}
		else {
			seta.src = "images/seta_down.jpg";
		}
		
		div.blur();
		seta.blur();
		
		document.recalc(true);	
}

function toggleDivMais(target) {
	nome_mais = target +"_mais";
	nome_div = target;
	nome_link = target +"_link";
	div = document.getElementById(nome_div);
	mais = document.getElementById(nome_mais);
	link = document.getElementById(nome_link);
	if (div.style.display == "block") {
		div.style.display = "none";
	} else {
		div.style.display = "block";
		div.scrollIntoView(true);
	}
	
	if (String(mais.src).match("mais")) {
		mais.src = "images/menos.jpg";
	} else {
		mais.src = "images/mais.jpg";
	}
	
	div.blur();
	mais.blur();
}

function redirectIn5(target){
	window.setTimeout(function(){
		location.replace(target);
	}, 3000);
}

function redirectNow(target) {
	location.replace(target);
}
function usuariosHideDivs(usr_lvl) {
	if (usr_lvl < 3) {
		div = document.getElementById('novo_usuario');
		div.style.display = "none";
	}
	
	if (usr_lvl < 2) {
		div = document.getElementById('busca_usuario');
		div.style.display = "none";
	}
	
	if (usr_lvl == 1) {
		div = document.getElementById('alterar_senha_info');
		div.style.display = "block";
	}
}

function closeMiniForms() {
	var div = document.getElementById('trans_overlay');
	try {div.style.display = "none";} catch (erro) {};
	div = document.getElementById('faturamento_form');
	try {
		div.style.display = "none";
	} 
	catch (erro) {
	};
	div = document.getElementById('contato_form');
	try {
		div.style.display = "none";
		} catch (erro) {};
	div = document.getElementById('interacao_form');
	try {	
		div.style.display = "none";
		} catch(erro){};
}

function openMiniForm(div_name) {
	var div = document.getElementById(div_name);
	div.style.display = "block";
	div = document.getElementById('trans_overlay');
	div.style.display = "block";
	
	if (String(div_name).match("contato")) {
		input = document.getElementsByName("nome_contato");
		input[0].focus();
	}
	if (String(div_name).match("faturamento")) {
		input = document.getElementsByName("tipo_faturamento");
		input[0].focus();
	}
	if (String(div_name).match("interacao")) {
		input = document.getElementsByName("resumo_interacao");
		input[0].focus();
	}
}


function insereIdioma() {
	var div = document.getElementById('idiomas_info');
	no_idiomas = document.getElementsByName('div_idioma').length + 1;
	
	var div_idioma = document.createElement('div');
	div_idioma.setAttribute('id', 'div_idioma'+no_idiomas);
	div_idioma.setAttribute('name', 'div_idioma');
	var div_umterco = document.createElement('div');
	div_umterco.setAttribute('class', 'umterco_minimo');
	div_umterco.setAttribute('className', 'umterco_minimo');
	var h2 = document.createElement('h2');
	h2.appendChild(document.createTextNode('Idioma'));
	var select1 = document.createElement('select');
	var select_name = 'idioma' + no_idiomas;
	select1.setAttribute('name', select_name);
	select1.setAttribute('className', 'selects');
	select1.setAttribute('class', 'selects');
	option = document.createElement('option');
	option.appendChild(document.createTextNode('Alemão'))
	select1.appendChild(option);
	option = document.createElement('option');
	option.appendChild(document.createTextNode('Chinês'))
	select1.appendChild(option);
	option = document.createElement('option');
	option.appendChild(document.createTextNode('Espanhol'))
	select1.appendChild(option);
	option = document.createElement('option');
	option.appendChild(document.createTextNode('Francês'))
	select1.appendChild(option);
	option = document.createElement('option');
	option.appendChild(document.createTextNode('Inglês'))
	select1.appendChild(option);
	option = document.createElement('option');
	option.appendChild(document.createTextNode('Italiano'))
	select1.appendChild(option);
	option = document.createElement('option');
	option.appendChild(document.createTextNode('Japonês'))
	select1.appendChild(option);
	option = document.createElement('option');
	option.appendChild(document.createTextNode('Russo'))
	select1.appendChild(option);
	div_umterco.appendChild(h2);
	div_umterco.appendChild(select1);

	var div_umterco2 = document.createElement('div');
	div_umterco2.setAttribute('class', 'umterco_minimo');
	div_umterco2.setAttribute('className', 'umterco_minimo');
	var h2 = document.createElement('h2');
	h2.appendChild(document.createTextNode('Nível'));
	var select2 = document.createElement('select');
	var select2_name = 'nivel_idioma' + no_idiomas;
	select2.setAttribute('name', select2_name);
	select2.setAttribute('class', 'selects');
	select2.setAttribute('className', 'selects');
	option = document.createElement('option');
	option.appendChild(document.createTextNode('Básico'))
	select2.appendChild(option);
	option = document.createElement('option');
	option.appendChild(document.createTextNode('Intermediário'))
	select2.appendChild(option);
	option = document.createElement('option');
	option.appendChild(document.createTextNode('Avançado'))
	select2.appendChild(option);
	option = document.createElement('option');
	option.appendChild(document.createTextNode('Fluente'))
	select2.appendChild(option);
	div_umterco2.appendChild(h2);
	div_umterco2.appendChild(select2);
	
	var div_umterco3 = document.createElement('div');
	div_umterco3.setAttribute('class', 'umterco_minimo');
	div_umterco3.setAttribute('className', 'umterco_minimo');
	
	div_idioma.appendChild(div_umterco);
	div_idioma.appendChild(div_umterco2);
	div_idioma.appendChild(div_umterco3);
	div.appendChild(div_idioma);
	div.scrollIntoView(true);
}


function removeIdioma(div_name) {
	div = document.getElementById('idiomas_info');
	no_idiomas = 0;
	array_divs = document.getElementsByTagName('div');
	array_idiomas = new Array();
	
	for (i = 0; i < array_divs.length;i++) {
		if (array_divs[i].getAttribute('name')== 'div_idioma') {
			array_idiomas.push(array_divs[i]);
			no_idiomas++;
		}
	}
	if (no_idiomas != 0) {	
		child = array_idiomas[array_idiomas.length-1];
		div.removeChild(child);
	}
}

function insereFormacao() {
	insert_at = document.getElementById('formacoes_info');
	if (insert_at.style.display != "block") {
		toggleDiv('formacoes');
	}
	div = document.getElementById('formacao_template');
	clone = div.cloneNode(true);
	clone.setAttribute("class", "");
	clone.setAttribute("className", "");
	insert_at.appendChild(clone);
}

function insereCurso() {
	div = document.getElementById('curso_template');
	insert_at = document.getElementById('cursos_info');
	clone = div.cloneNode(true);
	clone.setAttribute("class", "");
	clone.setAttribute("className", "");
	insert_at.appendChild(clone);
}
function insereIdioma2() {
	div = document.getElementById('idioma_template');
	insert_at = document.getElementById('idiomas_info');
	clone = div.cloneNode(true);
	clone.setAttribute("class", "");
	clone.setAttribute("className", "");
	insert_at.appendChild(clone);
}
function insereExperiencia() {
	div = document.getElementById('experiencia_template');
	insert_at = document.getElementById('experiencias_info');
	clone = div.cloneNode(true);
	clone.setAttribute("class", "");
	clone.setAttribute("className", "");
	insert_at.appendChild(clone);
}

function removeFirstClonedNode(div_name) {
	var divs=$("#"+div_name+"> .tempDiv");
	if(divs.length==0) return;
	$(divs[divs.length-1]).remove();
}
var nn = 1;
var countAutoComplete=0;
function insereFormacaoForm() {
	
	insert_at = document.getElementById('formacoes_info');
	div = document.getElementById('formacao_template');
	clone = div.cloneNode(true);
	clone.setAttribute("class","tempDiv");
	clone.setAttribute("className","tempDiv");
	clone.removeAttribute("id");
	
	insert_at.insertBefore(clone,document.getElementById('form_adiciona_formacoes'));
	var input=$(clone).find(".autocompleteHolder > input");
	$(input).attr("id","formacao_instituicao_dynamic_"+countAutoComplete);
															$(input).autocomplete(
															  "autocomplete.php",
															  {
																	delay:10,
																	minChars:2,
																	matchSubset:1,
																	matchContains:1,
																	cacheLength:10,
																	onItemSelect:selectItem,
																	onFindValue:findValue,
																	formatItem:formatItem,
																	autoFill:true
																}	
																);
	//var num=parseInt($("#formacao_counter").val());
	//$("#formacao_counter").val(num+1);
	nn++;
}
function insereCursoForm() {
	//document.getElementById('curso_template').style.display = 'table';
	insert_at = document.getElementById('cursos_info');
	div = document.getElementById('curso_template');
	
	clone = div.cloneNode(true);
	clone.setAttribute("class","tempDiv");
	clone.setAttribute("className","tempDiv");
	clone.removeAttribute("id");
	insert_at.insertBefore(clone,document.getElementById('form_adiciona_cursos'));
	//var num=parseInt($("#curso_counter").val());
	//$("#curso_counter").val(num+1);
}

function insereIdiomaForm() {
	insert_at = document.getElementById('idiomas_info');
	div = document.getElementById('idioma_template');
	clone = div.cloneNode(true);
	clone.setAttribute("class","tempDiv");
	clone.setAttribute("className","tempDiv");
	clone.removeAttribute("id");;
	insert_at.insertBefore(clone,document.getElementById('form_adiciona_idiomas'));
	//var num=parseInt($("#idioma_counter").val());
	//$("#idioma_counter").val(num+1);
}

function insereInformaticaForm() {
	insert_at = document.getElementById('informaticas_info');
	div = document.getElementById('informatica_template');
	clone = div.cloneNode(true);
	clone.setAttribute("class","tempDiv");
	clone.setAttribute("className","tempDiv");
	clone.removeAttribute("id");;
	insert_at.insertBefore(clone,document.getElementById('form_adiciona_informaticas'));
	//var num=parseInt($("#idioma_counter").val());
	//$("#idioma_counter").val(num+1);
}

function insereExperienciaForm() {
	insert_at = document.getElementById('experiencias_info');
	div = document.getElementById('experiencia_template');
	clone = div.cloneNode(true);
	clone.setAttribute("class","tempDiv");
	clone.setAttribute("className","tempDiv");
	clone.removeAttribute("id");
	insert_at.insertBefore(clone,document.getElementById('form_adiciona_experiencias'));
	//var num=parseInt($("#experiencia_counter").val());
	//$("#experiencia_counter").val(num+1);
}

function insereextra_experienciaForm() {
	insert_at = document.getElementById('extra_experiencias_info');
	div = document.getElementById('extra_experiencia_template');
	clone = div.cloneNode(true);
	clone.setAttribute("class","tempDiv");
	clone.setAttribute("className","tempDiv");
	clone.removeAttribute("id");
	insert_at.insertBefore(clone,document.getElementById('form_adiciona_extra_experiencias'));
	//var num=parseInt($("#experiencia_counter").val());
	//$("#experiencia_counter").val(num+1);
}

function removeClonedNode(div_name) {
	div = document.getElementById(div_name);
	if ((div.lastChild.nodeType != 3) && (div.lastChild.getAttribute('class') == "")) {
		div.removeChild(div.lastChild);	
	}	
}
function removeFirstClonedNode2() {
	document.getElementById('curso_template').style.display = 'none';
}
/***
*Ades 6/8/11
*/
function showHiddenContent(id){

		div = $("#"+id + "_info");
		seta =$("#"+id + "_seta");
		if (String(seta.attr("src")).match("seta_down")) {
		
			seta.attr("src","images/seta.jpg");
		}
		else {
			seta.attr("src","images/seta_down.jpg");
		}
	
		$("#"+id+"> .hidden").each(function(index) {
				if($(this).css('display')=="none"){
					$(this).show();
				}else{
					$(this).hide();
				}
			}
		)
		div.blur();
		seta.blur();
		//document.recalc(true);	

}

/* http://rticons.net
	@author  RTI Consulting
	---------------------------*/
 
// pre-submit callback 
function showRequest(formData, jqForm, options) { 
    // formData is an array; here we use $.param to convert it to a string to display it 
    // but the form plugin does this for you automatically when it submits the data 
    var queryString = $.param(formData); 
 
    // jqForm is a jQuery object encapsulating the form element.  To access the 
    // DOM element for the form do this: 
    // var formElement = jqForm[0]; 
 
    
 
    // here we could return false to prevent the form from being submitted; 
    // returning anything other than false will allow the form submit to continue 
    return true; 
} 
 
// post-submit callback 
function showResponse(responseText, statusText, xhr, $form)  { 
    // for normal html responses, the first argument to the success callback 
    // is the XMLHttpRequest object's responseText property 
 
    // if the ajaxForm method was passed an Options Object with the dataType 
    // property set to 'xml' then the first argument to the success callback 
    // is the XMLHttpRequest object's responseXML property 
 
    // if the ajaxForm method was passed an Options Object with the dataType 
    // property set to 'json' then the first argument to the success callback 
    // is the json data object returned by the server 
 
    //alert('status: ' + statusText + '\n\nresponseText: \n' + responseText); 
	if(responseText['success']){
		$windowLocation = window.location.href;
		
		var regex = /curriculo-new.php/gi;
		// console.log($windowLocation);
		var curriculoNew = regex.test($windowLocation);
        // console.log(regex.test($windowLocation));

		
		if (curriculoNew) {
		alert('Seu currículo foi cadastrado e vinculado com sucesso à vaga. Fique atento na sua caixa de e-mails e se você optou por um sistema AntiSpam para proteger sua caixa-postal de mensagens indesejadas, não esqueça de habilitar o domínio @interpersona.com.br em seu provedor de e-mail, pois nossos contatos serão feitos via e-mail.');
		setTimeout((window.location.href = "https://interpersona.websiteseguro.com/curriculo_menu.php"),2000);
		} else {
		alert('Conteúdo atualizado com sucesso!');
		}
		
		var fields={'formacoes':'formacoes_info','cursos':'cursos_info','idiomas':'idiomas_info','informaticas':'informaticas_info','experiencias':'experiencias_info', 'extra_experiencias':'extra_experiencias_info'};
		for(var x in fields){
			if(responseText['updateData'][x]!=null && responseText['updateData'][x]!= undefined && responseText['updateData'][x][1]>0){
				var lastId=responseText['updateData'][x][0];//ultimo id
				var firstId=responseText['updateData'][x][0]-( responseText['updateData'][x][1]-1);//primeiro id
				var currentId=firstId;//ID corrente
				var container=fields[x];
				$('#'+container).find('.idHolder').each(function() {
					
					if(!$(this).val() && currentId<=lastId){//<=lastId se nãoo vai pegar o elemento esqueleto
						$(this).val(currentId);
		
													
						//Criando botão de remover após adição
						var div=document.createElement('div');
						div.setAttribute('class','legendas');
						var a=document.createElement('a');
						a.setAttribute('href','#');
						a.setAttribute('onclick','remove_data(\''+x+'\','+currentId+',this)');
						img=document.createElement('img');
						img.setAttribute('src',"images/btn_remover.jpg");
						img.setAttribute('alt',"Remover");
						img.setAttribute('class',"remover_idioma_vaga");
						a.appendChild(img);
						div.appendChild(a);
						$(this.parentNode).append(div);
						//Removendo tempDiv
						if($(this.parentNode).attr('class')=='tempDiv'){
							$(this.parentNode).attr('class','');
							$(this.parentNode).attr('className','');
						}
						currentId++;
					}

				}
				);
			}
		}
	}
	else{
		//alert('Houve um erro,por favor tente novamente');
	}
}
function sendForm(concluir){

// Validador de Formacao
$("select[id^='formacao_tipo']:visible").each(function() { 
	//DEBUG alert($(this).attr('name')&&$(this).val());
	
	if ($(this).val() !== '') { 
		
		// Qual o nome da escola?
		$("input[id^='formacao_curso']:visible").each(function(){
			if ($(this).val() == '') {
				$(this).attr('class', 'inputs required');
			}
		});
		
		// Verifica qual instituicao
		$("input[id^='formacao_instituicao']:visible").each(function(){
			if ($(this).val() == '') {
				$(this).attr('class', 'inputs required');
			}
		});
		
		//Hora de ver se o usuario preencheu corretamente de quanto ate quando ele cursou
		$("select[id^='formacao_status']:visible").each(function(){
			//DEBUG alert($(this).val());
			
			// Verifica se ele colocou curso completo
			if ($(this).val() == 'Completo') {
						
						$("input[id^='formacao_termino3']:visible").each(function(){
							if ($(this).val() == '') {
								// Voce completou o curso e nao sabe o ano?
								$(this).attr('class', 'data_inputs_ano required');
							}
						});
			// Agora verifica se ele deixou em branco			
			} else if ($(this).val() == '') {
				$(this).attr('class', 'selects required');
			} else if ($(this).val() == 'Incompleto') {
			
						$("input[id^='formacao_inicio3']:visible").each(function() {
							//alert($(this).val());
							if ($(this).val() == '') {
								// Curso Incompleto? E nao sabe quando comecou?
								$(this).attr('class', 'data_inputs_ano required');
							}
						});
			}
		});	
		
	} else if ($(this).val() == '') {
	
		
	}

});


/* NAO EDITAR */
// Comeca o verificador de Curso Complementar
$("input[id^='curso_nome']:visible").each(function() { 
	//alert($(this).attr('name')&&$(this).val());
	
	if ($(this).val() !== '') { 
		
		// Qual o nome da escola?
		$("input[id^='curso_escola']:visible").each(function(){
			if ($(this).val() == '') {
				$(this).attr('class', 'inputs required');
			}
		});
		
		// Verifica se ha descricao do curso
		$("textarea[id^='curso_descricao']:visible").each(function(){
			if ($(this).val() == '') {
				$(this).attr('class', 'textareas required');
			}
		});
		
		//Hora de ver se o usuario preencheu corretamente de quanto ate quando ele cursou
		$("select[id^='curso_status']:visible").each(function(){
			//alert($(this).val());
			
			// Verifica se ele colocou curso completo
			if ($(this).val() == 'Completo') {
						
						$("input[class^='data_inputs_ano']:visible").each(function(){
							//$(this).filter(function() { return jQuery(this).is(':visible');})
							if ($(this).val() == '') {
								// Voce completou o curso e nao sabe o ano?
								$(this).attr('class', 'data_inputs_ano required');
							}
						});
			// Agora verifica se ele deixou em branco			
			} else if ($(this).val() == '') {
				$(this).attr('class', 'selects required');
			}				
		});	
		
	} else if ($(this).val() == '') {
	
		
	}

});



/*if (document.getElementById('nome').value == '') {
	document.getElementById('help_nome').innerHTML = '<span style="font-size: 10px; color: red;">O campo nome é obrigatório</span>';
}
if (document.getElementById('dtnasc').value == '') {
	document.getElementById('help_dtnasc').innerHTML = '<span style="font-size: 10px; color: red;">A data de nascimento é obrigatória</span>';
}
if (document.getElementById('nacionalidade').value == '') {
	document.getElementById('help_nacionalidade').innerHTML = '<span style="font-size: 10px; color: red;">A nacionalidade é obrigatória</span>';
}
if (document.getElementById('estado_civil').value == '') {
	document.getElementById('help_estadocivil').innerHTML = '<span style="font-size: 10px; color: red;">O estado civil é obrigatório</span>';
}
if (document.getElementById('genero').value == '') {
	document.getElementById('help_sexo').innerHTML = '<span style="font-size: 10px; color: red;">O gênero é obrigatório</span>';
}
if (document.getElementById('rg').value == '') {
	document.getElementById('help_documento').innerHTML = '<span style="font-size: 10px; color: red;">O documento é obrigatório</span>';
}*/

	var options = { 
       
        beforeSubmit:  showRequest,  // pre-submit callback 
        success:       showResponse, // post-submit callback 
		dataType:  'json'
        // other available options: 
        //url:       url         // override for form's 'action' attribute 
        //type:      type        // 'get' or 'post', override for form's 'method' attribute 
        //clearForm: true        // clear all form fields after successful submit 
        //resetForm: true        // reset the form after successful submit 
 
        // $.ajax options can be used here too, for example: 
        //timeout:   3000 
    }; 
 
    // bind form using 'ajaxForm' 
    $('#form_edita_curriculo').ajaxForm(options); 
	if($('#form_edita_curriculo').submit()) {
	
		if (concluir == true) {
			javascript:history.back();
		}
	}
	
}
function remove_data(area,id,anchor){
	var theData={'area':area,'id':id};
	
	$.ajax({
	  url: "remove_data.php",
	  data:theData,
	  dataType:'json',
	  type: "POST",
	  success: function(){
		
		var mainDiv=anchor.parentNode.parentNode;
		mainDiv.parentNode.removeChild(mainDiv);
	}
	});
}


//Helper para CSS Crossbrowser
function css_browser_selector(u){var ua=u.toLowerCase(),is=function(t){return ua.indexOf(t)>-1},g='gecko',w='webkit',s='safari',o='opera',m='mobile',h=document.documentElement,b=[(!(/opera|webtv/i.test(ua))&&/msie\s(\d)/.test(ua))?('ie ie'+RegExp.$1):is('firefox/2')?g+' ff2':is('firefox/3.5')?g+' ff3 ff3_5':is('firefox/3.6')?g+' ff3 ff3_6':is('firefox/3')?g+' ff3':is('gecko/')?g:is('opera')?o+(/version\/(\d+)/.test(ua)?' '+o+RegExp.$1:(/opera(\s|\/)(\d+)/.test(ua)?' '+o+RegExp.$2:'')):is('konqueror')?'konqueror':is('blackberry')?m+' blackberry':is('android')?m+' android':is('chrome')?w+' chrome':is('iron')?w+' iron':is('applewebkit/')?w+' '+s+(/version\/(\d+)/.test(ua)?' '+s+RegExp.$1:''):is('mozilla/')?g:'',is('j2me')?m+' j2me':is('iphone')?m+' iphone':is('ipod')?m+' ipod':is('ipad')?m+' ipad':is('mac')?'mac':is('darwin')?'mac':is('webtv')?'webtv':is('win')?'win'+(is('windows nt 6.0')?' vista':''):is('freebsd')?'freebsd':(is('x11')||is('linux'))?'linux':'','js']; c = b.join(' '); h.className += ' '+c; return c;}; css_browser_selector(navigator.userAgent);

//Script das Mascaras
(function(a){var b=(a.browser.msie?"paste":"input")+".mask",c=window.orientation!=undefined;a.mask={definitions:{9:"[0-9]",a:"[A-Za-z]","*":"[A-Za-z0-9]"},dataName:"rawMaskFn"},a.fn.extend({caret:function(a,b){if(this.length!=0){if(typeof a=="number"){b=typeof b=="number"?b:a;return this.each(function(){if(this.setSelectionRange)this.setSelectionRange(a,b);else if(this.createTextRange){var c=this.createTextRange();c.collapse(!0),c.moveEnd("character",b),c.moveStart("character",a),c.select()}})}if(this[0].setSelectionRange)a=this[0].selectionStart,b=this[0].selectionEnd;else if(document.selection&&document.selection.createRange){var c=document.selection.createRange();a=0-c.duplicate().moveStart("character",-1e5),b=a+c.text.length}return{begin:a,end:b}}},unmask:function(){return this.trigger("unmask")},mask:function(d,e){if(!d&&this.length>0){var f=a(this[0]);return f.data(a.mask.dataName)()}e=a.extend({placeholder:"_",completed:null},e);var g=a.mask.definitions,h=[],i=d.length,j=null,k=d.length;a.each(d.split(""),function(a,b){b=="?"?(k--,i=a):g[b]?(h.push(new RegExp(g[b])),j==null&&(j=h.length-1)):h.push(null)});return this.trigger("unmask").each(function(){function v(a){var b=f.val(),c=-1;for(var d=0,g=0;d<k;d++)if(h[d]){l[d]=e.placeholder;while(g++<b.length){var m=b.charAt(g-1);if(h[d].test(m)){l[d]=m,c=d;break}}if(g>b.length)break}else l[d]==b.charAt(g)&&d!=i&&(g++,c=d);if(!a&&c+1<i)f.val(""),t(0,k);else if(a||c+1>=i)u(),a||f.val(f.val().substring(0,c+1));return i?d:j}function u(){return f.val(l.join("")).val()}function t(a,b){for(var c=a;c<b&&c<k;c++)h[c]&&(l[c]=e.placeholder)}function s(a){var b=a.which,c=f.caret();if(a.ctrlKey||a.altKey||a.metaKey||b<32)return!0;if(b){c.end-c.begin!=0&&(t(c.begin,c.end),p(c.begin,c.end-1));var d=n(c.begin-1);if(d<k){var g=String.fromCharCode(b);if(h[d].test(g)){q(d),l[d]=g,u();var i=n(d);f.caret(i),e.completed&&i>=k&&e.completed.call(f)}}return!1}}function r(a){var b=a.which;if(b==8||b==46||c&&b==127){var d=f.caret(),e=d.begin,g=d.end;g-e==0&&(e=b!=46?o(e):g=n(e-1),g=b==46?n(g):g),t(e,g),p(e,g-1);return!1}if(b==27){f.val(m),f.caret(0,v());return!1}}function q(a){for(var b=a,c=e.placeholder;b<k;b++)if(h[b]){var d=n(b),f=l[b];l[b]=c;if(d<k&&h[d].test(f))c=f;else break}}function p(a,b){if(!(a<0)){for(var c=a,d=n(b);c<k;c++)if(h[c]){if(d<k&&h[c].test(l[d]))l[c]=l[d],l[d]=e.placeholder;else break;d=n(d)}u(),f.caret(Math.max(j,a))}}function o(a){while(--a>=0&&!h[a]);return a}function n(a){while(++a<=k&&!h[a]);return a}var f=a(this),l=a.map(d.split(""),function(a,b){if(a!="?")return g[a]?e.placeholder:a}),m=f.val();f.data(a.mask.dataName,function(){return a.map(l,function(a,b){return h[b]&&a!=e.placeholder?a:null}).join("")}),f.attr("readonly")||f.one("unmask",function(){f.unbind(".mask").removeData(a.mask.dataName)}).bind("focus.mask",function(){m=f.val();var b=v();u();var c=function(){b==d.length?f.caret(0,b):f.caret(b)};(a.browser.msie?c:function(){setTimeout(c,0)})()}).bind("blur.mask",function(){v(),f.val()!=m&&f.change()}).bind("keydown.mask",r).bind("keypress.mask",s).bind(b,function(){setTimeout(function(){f.caret(v(!0))},0)}),v()})}})})(jQuery)

//Mascaras diversas
jQuery(function($){
   $('input[name$="cep"]').mask("99999-999");

   $("input[name=celular]").mask("9999-9999");
   $("input[name=telefone]").mask("9999-9999");
   $("input[name=outro_telefone]").mask("9999-9999");
   
   $("input[name=ddd_cel]").mask("99");
   $("input[name=ddd_tel]").mask("99");
   $("input[name=ddd_outro]").mask("99");
   
   $("input[name=cod_cel]").mask("99");
   $("input[name=cod_tel]").mask("99");
   $("input[name=cod_outro]").mask("99");
   
});

//Mascara monetária
(function($){$.formatCurrency={};$.formatCurrency.regions=[];$.formatCurrency.regions[""]={symbol:"$",positiveFormat:"%s%n",negativeFormat:"(%s%n)",decimalSymbol:".",digitGroupSymbol:",",groupDigits:true};
$.fn.formatCurrency=function(destination,settings){if(arguments.length==1&&typeof destination!=="string"){settings=destination;destination=false
}var defaults={name:"formatCurrency",colorize:false,region:"",global:true,roundToDecimalPlace:2,eventOnDecimalsEntered:false};defaults=$.extend(defaults,$.formatCurrency.regions[""]);
settings=$.extend(defaults,settings);if(settings.region.length>0){settings=$.extend(settings,getRegionOrCulture(settings.region))}settings.regex=generateRegex(settings);
return this.each(function(){$this=$(this);var num="0";num=$this[$this.is("input, select, textarea")?"val":"html"]();if(num.search("\\(")>=0){num="-"+num
}if(num===""||(num==="-"&&settings.roundToDecimalPlace===-1)){return}if(isNaN(num)){num=num.replace(settings.regex,"");if(num===""||(num==="-"&&settings.roundToDecimalPlace===-1)){return
}if(settings.decimalSymbol!="."){num=num.replace(settings.decimalSymbol,".")}if(isNaN(num)){num="0"}}var numParts=String(num).split(".");var isPositive=(num==Math.abs(num));
var hasDecimals=(numParts.length>1);var decimals=(hasDecimals?numParts[1].toString():"0");var originalDecimals=decimals;num=Math.abs(numParts[0]);
num=isNaN(num)?0:num;if(settings.roundToDecimalPlace>=0){decimals=parseFloat("1."+decimals);decimals=decimals.toFixed(settings.roundToDecimalPlace);
if(decimals.substring(0,1)=="2"){num=Number(num)+1}decimals=decimals.substring(2)}num=String(num);if(settings.groupDigits){for(var i=0;i<Math.floor((num.length-(1+i))/3);
i++){num=num.substring(0,num.length-(4*i+3))+settings.digitGroupSymbol+num.substring(num.length-(4*i+3))}}if((hasDecimals&&settings.roundToDecimalPlace==-1)||settings.roundToDecimalPlace>0){num+=settings.decimalSymbol+decimals
}var format=isPositive?settings.positiveFormat:settings.negativeFormat;var money=format.replace(/%s/g,settings.symbol);money=money.replace(/%n/g,num);
var $destination=$([]);if(!destination){$destination=$this}else{$destination=$(destination)}$destination[$destination.is("input, select, textarea")?"val":"html"](money);
if(hasDecimals&&settings.eventOnDecimalsEntered&&originalDecimals.length>settings.roundToDecimalPlace){$destination.trigger("decimalsEntered",originalDecimals)
}if(settings.colorize){$destination.css("color",isPositive?"black":"red")}})};$.fn.toNumber=function(settings){var defaults=$.extend({name:"toNumber",region:"",global:true},$.formatCurrency.regions[""]);
settings=jQuery.extend(defaults,settings);if(settings.region.length>0){settings=$.extend(settings,getRegionOrCulture(settings.region))}settings.regex=generateRegex(settings);
return this.each(function(){var method=$(this).is("input, select, textarea")?"val":"html";$(this)[method]($(this)[method]().replace("(","(-").replace(settings.regex,""))
})};$.fn.asNumber=function(settings){var defaults=$.extend({name:"asNumber",region:"",parse:true,parseType:"Float",global:true},$.formatCurrency.regions[""]);
settings=jQuery.extend(defaults,settings);if(settings.region.length>0){settings=$.extend(settings,getRegionOrCulture(settings.region))}settings.regex=generateRegex(settings);
settings.parseType=validateParseType(settings.parseType);var method=$(this).is("input, select, textarea")?"val":"html";var num=$(this)[method]();
num=num?num:"";num=num.replace("(","(-");num=num.replace(settings.regex,"");if(!settings.parse){return num}if(num.length==0){num="0"}if(settings.decimalSymbol!="."){num=num.replace(settings.decimalSymbol,".")
}return window["parse"+settings.parseType](num)};function getRegionOrCulture(region){var regionInfo=$.formatCurrency.regions[region];if(regionInfo){return regionInfo
}else{if(/(\w+)-(\w+)/g.test(region)){var culture=region.replace(/(\w+)-(\w+)/g,"$1");return $.formatCurrency.regions[culture]}}return null}function validateParseType(parseType){switch(parseType.toLowerCase()){case"int":return"Int";
case"float":return"Float";default:throw"invalid parseType"}}function generateRegex(settings){if(settings.symbol===""){return new RegExp("[^\\d"+settings.decimalSymbol+"-]","g")
}else{var symbol=settings.symbol.replace("$","\\$").replace(".","\\.");return new RegExp(symbol+"|[^\\d"+settings.decimalSymbol+"-]","g")}}})(jQuery);

// Limitador de Characteres
(function($){ 
     $.fn.extend({  
         limit: function(limit,element) {
			
			var interval, f;
			var self = $(this);
					
			$(this).focus(function(){
				interval = window.setInterval(substring,100);
			});
			
			$(this).blur(function(){
				clearInterval(interval);
				substring();
			});
			
			substringFunction = "function substring(){ var val = $(self).val();var length = val.length;if(length > limit){$(self).val($(self).val().substring(0,limit));}";
			if(typeof element != 'undefined')
				substringFunction += "if($(element).html() != limit-length){$(element).html((limit-length<=0)?'0':limit-length);}"
				
			substringFunction += "}";
			
			eval(substringFunction);
			
			
			
			substring();
			
        } 
    });
})(jQuery);


$(document).ready(function(){

jQuery.validator.addMethod("cpf", function(value, element) {
   value = jQuery.trim(value);
    
    value = value.replace('.','');
    value = value.replace('.','');
    cpf = value.replace('-','');
    while(cpf.length < 11) cpf = "0"+ cpf;
    var expReg = /^0+$|^1+$|^2+$|^3+$|^4+$|^5+$|^6+$|^7+$|^8+$|^9+$/;
    var a = [];
    var b = new Number;
    var c = 11;
    for (i=0; i<11; i++){
        a[i] = cpf.charAt(i);
        if (i < 9) b += (a[i] * --c);
    }
    if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
    b = 0;
    c = 11;

    for (y=0; y<10; y++) b += (a[y] * c--);
    if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
    
    var retorno = true;
    if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10]) || cpf.match(expReg)) retorno = false;
    
    return this.optional(element) || retorno;

}, "Informe um CPF válido."); // Mensagem padrão 


	
    $("#form_edita_curriculo").validate({
    	ignore: ":hidden",
		success: "valid",
		errorClass: "invalid",
    	errorContainer: ".red, div#errorCallback",
    	
    	groups: {
		    nascimento: "nascimento3 nascimento2 nascimento1",
		    telefone: "cod_tel ddd_tel telefone",
		    celular: "cod_cel ddd_cel celular",
		    outro_tel: "cod_outro ddd_outro outro_telefone",
		    mudanca: "mudanca mudanca"
		    
		  },
		  errorPlacement: function(error, element) {
		     if (element.attr("name") == "nascimento3" 
		                 || element.attr("name") == "nascimento2" 
		                 || element.attr("name") == "nascimento1")
		       error.insertAfter("#dtnasc3");
		     else
		       error.insertAfter(element);
		   },
		   
		   errorPlacement: function(error, element) {
		     if (element.attr("name") == "cod_cel" 
		                 || element.attr("name") == "ddd_cel" 
		                 || element.attr("name") == "celular")
		       error.insertAfter("#celular");
		     else
		       error.insertAfter(element);
		   },
		   
		    errorPlacement: function(error, element) {
		     if (element.attr("name") == "cod_tel" 
		                 || element.attr("name") == "ddd_tel" 
		                 || element.attr("name") == "telefone")
		       error.insertAfter("#telefone");
		     else
		       error.insertAfter(element);
		   },
		   
		   errorPlacement: function(error, element) {
		     if (element.attr("name") == "mudanca" 
		                 || element.attr("name") == "mudanca")
		       error.insertAfter("#mudanca");
		     else
		       error.insertAfter(element);
		   },
		   
		   //debug:true,
		   
		   invalidHandler: function(form, validator) {
		      var errors = validator.numberOfInvalids();
		      if (errors) {
		        var message = errors == 1
		          ? "Você tem 1 campo preenchido incorretamente. Ele foi marcado."
		          : "Você tem " + errors + " campos preenchidos incorretamente. Eles foram marcados.";
		        $("div.error span").html(message);
		        $("div.error").show();
		      } else {
		        $("div.error").hide();
		      }
		    },
		    
		    rules: {
		    rg: {cpf: true},
		    nascimento1: {number: true},
		    nascimento2: {number: true},
		    nascimento3: {number: true},
		    nacionalidade: {lettersonly: true},
		    site: {url2: true}
		    },
		    
		    messages: {
		    rg: {cpf: "<p><span class='red'>informe um cpf válido.<\/span><\/p>"},
		    nascimento1: {number: "<p><span class='red'>datas somente em números.<\/span><\/p>"},
		    nascimento2: {number: "<p><span class='red'>datas somente em números.<\/span><\/p>"},
		    nascimento3: {number: "<p><span class='red'>datas somente em números.<\/span><\/p>"},
		    nacionalidade: {lettersonly: "<p><span class='red'>são permetidas somente letras.<\/span><\/p>"},
		    site: {url2: "<p><span class='red'>preencha um endereço web válido (com http://).<\/span><\/p>"}
		    }	   
		   
    });
    
    $(':text').validate({
		onfocusout: true
	});
    
});
