
function FormataValorMysql(obj,tammax,teclapres) {
	var tecla = teclapres.keyCode;
	vr = obj.value;
	vr = vr.replace( /\D/g, '' );
	tam = vr.length;

//	if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }

//	if (tecla == 8 ){	tam = tam - 1 ; }
		
//	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
		if ( tam <= 2 ){ 
	 		obj.value = vr ; 	}
	 	if ( (tam > 2) && (tam <= 5) ){
	 		obj.value = vr.substr( 0, tam - 2 ) + '.' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 6) && (tam <= 8) ){
	 		obj.value = vr.substr( 0, tam - 5 ) + ',' + vr.substr( tam - 5, 3 ) + '.' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 9) && (tam <= 11) ){
	 		obj.value = vr.substr( 0, tam - 8 ) + ',' + vr.substr( tam - 8, 3 ) + ',' + vr.substr( tam - 5, 3 ) + '.' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 12) && (tam <= 14) ){
	 		obj.value = vr.substr( 0, tam - 11 ) + ',' + vr.substr( tam - 11, 3 ) + ',' + vr.substr( tam - 8, 3 ) + ',' + vr.substr( tam - 5, 3 ) + '.' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 15) && (tam <= 17) ){
	 		obj.value = vr.substr( 0, tam - 14 ) + ',' + vr.substr( tam - 14, 3 ) + ',' + vr.substr( tam - 11, 3 ) + ',' + vr.substr( tam - 8, 3 ) + ',' + vr.substr( tam - 5, 3 ) + '.' + vr.substr( tam - 2, tam ) ;}
//	}		
}

function formatoData( string ) {
	v=string;
	v=v.replace(/\D/g,"") //Remove tudo o que não é dígito
	v=v.replace(/(\d{2})(\d)/,"$1/$2");
	v=v.replace(/(\d{2})(\d)/,"$1/$2");
	return v;
}

function formatoMesAno( string ) {
	v=string;
	v=v.replace(/\D/g,"") //Remove tudo o que não é dígito
	v=v.replace(/(\d{2})(\d)/,"$1/$2") //Coloca um ponto entre o sexto e o sétimo dígitos
	return v;
}

//--->Função para a formatação dos campos...<---
function Mascara(tipo, campo, teclaPress) {
	if (window.event) {
		var tecla = teclaPress.keyCode;
	} else {
		tecla = teclaPress.which;
	}

	var s = new String(campo.value);
	// Remove todos os caracteres à seguir: ( ) / - . e espaço, para tratar a
	// string denovo.
	s = s.replace(/(\.|\(|\)|\/|\-| )+/g, '');

	tam = s.length + 1;

	if (tecla != 9 && tecla != 8) {
		switch (tipo) {
		case 'CPF':
			v = $(campo).val();
			v=formatoCPF(v);
			$(campo).val(v);
			break;

		case 'CNPJ':
			v = $(campo).val();
			v=formatoCNPJ(v);
			$(campo).val(v);
			break;
		case 'TEL':
			v = $(campo).val();
			$(campo).val( formatoTel(v) );
			break;
		case 'DATA':
			v = $(campo).val();
			$(campo).val(formatoData(v));
			break;
		case 'MES_ANO':
			v = $(campo).val();
			$(campo).val(formatoMesAno(v));
			break;
		case 'CEP':
			if (tam > 5 && tam < 7)
				campo.value = s.substr(0, 5) + '-' + s.substr(5, tam);
			break;
		case 'NUM_REALP':
			if ( tam > 3 ) {
				s = s.substr(0, tam-3) + '.' + s.substr(tam-3, tam);
				campo.value = s;
			}
			break;
		case 'PLACA':
			v = $(campo).val();
			$(campo).val(formatoPlaca(v));
			break;
		}
	}
}

function in_array( what, where ){
	for(var i=0;i<where.length;i++){
		if(what == where[i]){
			return true;
		}
	}
	return false;
}

//--->Função para verificar se o valor digitado é número...<---
function verificaKeyNumero( key ) {
	return (key > 47 && key < 58) // teclado normal
	|| (key > 95 && key < 106); // teclado numerico
}
//--->Função para verificar se o valor digitado é letra...<---
function verificaKeyLetra( key ) {
	return (key > 64 && key < 91); // teclado numerico
}
function verificaKeyPonto( key ) {
	// 190, 194: "."
	return key == 190 || key == 194 ;
}
function verificaKeySpace( key ) {
	// 32: space
	return key == 32;
}
function verificaKeyVirgula( key ) {
	// 188: ","
	return key == 188;
}
function verificaKeyEspecial( key ) {
	/*
	 * 8: backspace
	 * 9: tab
	 * 13: enter
	 * 16: shift
	 * 18: alt
	 * 20: capslock
	 * 27: esc
	 * 35: end
	 * 36: home
	 * 37..40: direcionais
	 * 45: insert
	 * 46: delete
	 * 91: win
	 * 93: menu de contexto
	 * 112..123: f1..f12
	 * 144: numlock
	 */
	if ( key == true ) return true; // para os casos de ctrl+x, ctrl+c, etc.
	var keysValidas = [ 8, 9, 13, 14, 16, 18, 20, 27, 35, 36, 37, 38, 39, 40, 45, 46, 91, 93, 112, 116, 144 ];
	return in_array( key, keysValidas );
}
function pegaKey( event ) {
	var ctrl = event.ctrlKey || event.metaKey;
	if (ctrl) { 
		return true;
	}
	var key = event.keyCode;
	if ( key == "undefined" || key == 0 ) {
		if (window.event) {
			// IE
			key = event.keyCode;
		} else if (event.which) {
			// netscape
			key = event.which;
		}
	}
	return key;
}

function alfanum(element) {
	var padrao = new RegExp("([^0-9A-Za-z]+)");
	$(element).val($(element).val().replace(padrao,''));
}
// chamando da seguinte forma: <input [...] onkeypress="return digitos(event, this);">
// o campo aceita somente números.
function digitos(event) {
	var key = pegaKey(event);
	return verificaKeyNumero(key) || verificaKeyEspecial(key);
}

//--->Função para verificar se o valor digitado é número ou ponto...<---
//chamando da seguinte forma: <input [...] onkeypress="return digitosP(event);">
//o campo aceita somente números e ponto
function digitosP(event) {
	var key = pegaKey(event);
	return verificaKeyNumero(key) || verificaKeyEspecial(key) || verificaKeyPonto(key);
}

function maiusculas( campo ) {
	$(campo).val( $(campo).val().toUpperCase() );
}

function alerta( elemento, msg, titulo ) {
	$(elemento).append('<div id="dialog" title="'+titulo+'"><p><span>'+msg+'</span></p></div>');
	$('#dialog').dialog({
			resizable: false,
			width: 450,
			modal: true,
			buttons: {
				'OK': function() {
					$(this).dialog('close');
					$('#dialog').remove();
				}
			}
	});
}

function Valida( tipo, campo ) {
    if ( $(campo).val() != "" ) {
    	var valor = $(campo).val();
        $(campo).append( "<div id='loading_field'><img src='img/ajax-loader.gif'/> Pesquisando dados...</div>");
        $.getJSON("../services/valida.php?q="+valor+"&tipo="+tipo+"&",{id: $(this).val(), ajax: 'true'}, function(j){
          if ( j.valido != 'true' ) {
        	  alerta(campo, tipo+' inválido.', 'Atenção');
          }
          $("#loading_field").remove();
        });
    }
}

$().ready(function() {
	
	$('.withtipsy_opaco').tipsy({ html: true, gravity: 'n', opacity: 1 });
	$('.withtipsy_ne').tipsy({ html: true, gravity: 'ne', fade: true, delayOut: 300 });
	$('.withtipsy_n').tipsy({ html: true, gravity: 'n' });
	$('.withtipsy_erro').tipsy({ html: true, gravity: 'sw' });
	$('#form_dimas .withtipsy_input').tipsy({ html: true, gravity: 'nw', fade: true, trigger: 'focus' });
	$('#form_busca .withtipsy_input').tipsy({ html: true, gravity: 's', fade: true, trigger: 'focus' });
	$('select.withtipsy_input').tipsy({ html: true, gravity: 'sw', fade: true, delayOut: 300 });
	$('.withtipsy_input[type=file]').tipsy({ html: true, gravity: 'n', fade: true, delayOut: 300 });


	/* Brazilian initialisation for the jQuery UI date picker plugin. */
	$.datepicker.regional['pt-BR'] = {
		yearRange: '1900:2100',
		closeText: 'Fechar',
		prevText: '&#x3c;Anterior',
		nextText: 'Pr&oacute;ximo&#x3e;',
		currentText: 'Hoje',
		monthNames: ['Janeiro','Fevereiro','Mar&ccedil;o','Abril','Maio','Junho',
		'Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
		monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun',
		'Jul','Ago','Set','Out','Nov','Dez'],
		dayNames: ['Domingo','Segunda-feira','Ter&ccedil;a-feira','Quarta-feira','Quinta-feira','Sexta-feira','Sabado'],
		dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sab'],
		dayNamesMin: ['Dom','Seg','Ter','Qua','Qui','Sex','Sab'],
		weekHeader: 'Sm',
		dateFormat: 'dd/mm/yy',
		firstDay: 0,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: '',
		showOtherMonths: true
	};
	$.datepicker.setDefaults($.datepicker.regional['pt-BR']);
	
	$('.campodata, .campodatah, .campodataz, .campodatal').datepicker({
		changeMonth: true,
		changeYear: true,
		showOtherMonths: true,
		selectOtherMonths: true,
		autoResize: false,
		buttonImageOnly: true,
		showOn: 'both',
		buttonImage: '../img/jqueryui/calendar.png'
	});

	// Removi o código de MultiDatas
	
//	$('.campodata').mask('99/99/9999'); // comentado pois campos desse tipo usam datepicker
	$('.campodatahora').mask('99/99/9999 99:99:99');
	$('.campocpf').mask('999.999.999-99');
	$('.campocnpj').mask('99.999.999/9999-99');
	$('.campotelefone').mask('(99) 9999-9999');
	$('.campocep').mask('99999-999');
	$('.campomes_ano').mask('99/9999');
	
	$('div.error').effect("shake", { times:2, direction: "right", distance: 20 }, 100);

})

