//---------------------------------------------
// As variveis abaixo ficariam externas
// ao arquivo JS, para permitir a configurao
// diretamente no cdigo HTML, sem que seja
// necessria a alterao dentro do arquivo
// JS
//---------------------------------------------

// Esta varivel contm a primeira linha a ser apresentada caso aparea um erro
var strHeaderErro = 'Ocorreram os seguintes erros:\n\n';

// Esta varivel contm a ltima linha a ser apresentada caso aparea um erro
var strBottomErro = '\nPor favor, corrija-os e tente novamente';

//---------------------------------------------
// As variveis abaixo ficariam internas
// ao arquivo JS
//---------------------------------------------

// Dados fixos da validao de data
var dtCh= "/";
var minYear=1900;
var maxYear=2100;


//Varivel global de controle de checkboxes
var strCheckboxes = '';


function Validacao(objForm, pErro, pFocus) {



	//------------------------------------------------------
	// Validaes que devemos considerar:
	// 
	//  Text
	//		CPF
	//		CGC
	//		
	//	Select
	//		Valor <> ''
	//------------------------------------------------------
	//	Mscaras que devemos considerar:
	//		
	//	Text
	//		Data
	//		Telefone
	//		Valores
	//		CEP
	//		Somente nmeros
	//------------------------------------------------------
	// Controles que devemos adicionar:
	//
	//	Containers
	//	Drop-down c/ n relacionamentos
	//	Controle adio de novo / seleo de antigo (JP)
	//	Data c/ calendrio (JP)
	//  Validao de senha
	//------------------------------------------------------
	//	No  interessante fazer validaes diretamente 
	//	orientadas  checkbox caso estas sejam repetidas
	//	(listagens). Melhor colocar um campo hidden 
	//	orientando esta validao.
	//------------------------------------------------------

	// Esta varivel contm as mensagens de erro

	var strErro = (!pErro?'':pErro);

	// Esta varivel contm o campo para focus

	var strCampo = (!pFocus?'':pFocus);
	
	// Esta varivel contm os nomes de checkboxes j validadas

	strCheckboxes = '';

	for(var i=0;i<=objForm.elements.length-1;i++)	{
	
		//alert(objForm.elements[i] + '-' + objForm.elements[i].name);

		objElemento		= objForm.elements[i];
		strTipo			= objElemento.type;
		strNome			= objElemento.getAttribute("nome");
	
		if(objForm.elements[i].getAttribute("validacao")) {
			if(objForm.elements[i].getAttribute("validacao").indexOf(",")>0) {
					strValidacao = objForm.elements[i].getAttribute("validacao").split(",");
					for (var j=0; j<strValidacao.length; j++) {
						strtmpErro = ValidaObjeto(objElemento,strTipo,strValidacao[j]);
						if (strtmpErro.length > 0) {
							strErro += strtmpErro;
							if (strTipo != 'checkbox' && strTipo != 'radio' && strTipo != 'hidden' && strCampo == '') strCampo = objElemento.name;
						}
					}
			} else {
				strValidacao	= objForm.elements[i].getAttribute("validacao")
				strtmpErro = ValidaObjeto(objElemento,strTipo,strValidacao);
				if (strtmpErro.length > 0) {
					strErro += strtmpErro;
					if (strTipo != 'checkbox' && strTipo != 'radio' && strTipo != 'hidden' && strCampo == '') {strCampo = objElemento.name;}
				} 
			}
		}
	}


	if (strErro.length > 0) {
		alert(strHeaderErro + strErro + strBottomErro);
		//if (strCampo != '') eval(objForm.name+'.'+strCampo+'.focus();');

		return false;
	}
	
	return true;
}



function ValidaObjeto(objeto, tipo, validacao) {

	var tmpErro = '';

	switch (tipo) {
	case 'text': {
		switch (validacao) {
			case 'numero': {
				if (isNaN(objeto.value) || isEmpty(objeto.value)) tmpErro += ' - O campo \'' + objeto.getAttribute("nome") + '\' deve conter um número \n';
				break;
				}
			case 'email': {
				if (isEmpty(objeto.value)) {
					tmpErro += ' - O campo \'' + objeto.getAttribute("nome") + '\' deve conter um e-mail válido \n';
				} else {
					if (!isEmail(objeto.value)) tmpErro += ' - O campo \'' + objeto.getAttribute("nome") + '\' contém um e-mail inválido \n';
				} 
				break;
				}
			case 'email2': {
				if ( (!isEmpty(objeto.value)) && (!isEmail(objeto.value))) tmpErro += ' - O campo \'' + objeto.getAttribute("nome") + '\' contém um e-mail inválido \n';
				break;
				}
			case 'cpf': {
				if (!validaCPF(objeto.value)) tmpErro += ' - O campo \'' + objeto.getAttribute("nome") + '\' contém um CPF inválido \n';
				break;
				}
			case 'ddmmyyyy2': {
				// Validao dd/mm/yyyy
				if (!isDate(objeto.value)) tmpErro += ' - O campo \'' + objeto.getAttribute("nome") + '\' deve ser preenchido com uma data no formato DD/MM/AAAA \n';
				break;
				}
			case 'maiorde16': {
				// Validao para verificar se o usurio tem mais de 16 anos
				if ((DateDiff('d',new Date(FormataMMDDYYYY(objeto.value)),new Date())/365.25) < 16) tmpErro += ' - Você precisa ter 16 anos ou mais para se cadastrar \n';
				break;
				}
			case 'hhmm': {
				// Validao dd/mm/yyyy
				if (!isHour(objeto.value)) tmpErro += ' - O campo \'' + objeto.getAttribute("nome") + '\' deve ser preenchido com uma hora no formato HH:MM \n';
				break;
				}
			case 'ddmmyyyy': { // Implementao feita por Rafael (rever para uso, pois esta situao pode existir)
				// Validao dd/mm/yyyy
				if (objeto.value.length > 0) {
				 if (!isDate(objeto.value)) tmpErro += ' - O campo \'' + objeto.getAttribute("nome") + '\' deve ser preenchido com uma data no formato DD/MM/AAAA \n';
				} else {
				 tmpErro += ' - O campo \'' + objeto.getAttribute("nome") + '\' deve ser preenchido com uma data no formato DD/MM/AAAA \n';
				}
				break;
				}
			//case 'ddmmyyyy3': { // Implementao feita por Rafael (rever para uso, pois esta situao pode existir)
				// Validao dd/mm/yyyy
				//mdata1 = objeto.value.substr(3,2) + '/' + objeto.value.substr(0,2) + '/' + objeto.value.substr(6,4);
			//	mdata2 = objeto.value.substr(3,2) + '/' + objeto.value.substr(0,2) + '/' + objeto.value.substr(6,4);
			
				//data1 = new Date(mdata1);
				//data2 = new Date(mdata2);
			
				//if (data2 < data1) tmpErro += ' - Erros nas data so!!! \n';
				//break;
				//}
			case 'preenchido': {
				// Validao preenchido
				if (isEmpty(objeto.value)) tmpErro += ' - O campo \'' + objeto.getAttribute("nome") + '\'  de preenchimento obrigatório \n';
				break;
				}
			break;
			}
		break;
		}
	case 'file' : {
	    switch (validacao) {
		    case 'preenchido' : {
			    if (objeto.value.length < 1) tmpErro += ' - Selecione um arquivo para o campo \'' + objeto.getAttribute("nome") + '\'\n';
				break;
			}
			case 'extensao' : {
			  var tamanho = objeto.value.length;
			  var extensao = objeto.value.substr(tamanho-3,tamanho);
			  if (objeto.value != 0) {
			   if ((extensao != 'jpg') && (extensao != 'JPG')) tmpErro += ' - Selecione um arquivo com extensão JPG para o campo \'' + objeto.getAttribute("nome") + '\'\n';
			   break;
			  }
			}
			
			case 'extensao_arquivo_obrigatorio' : {
			  var tamanho = objeto.value.length;
			  var extensao = objeto.value.substr(tamanho-3,tamanho);
			  if (objeto.value != 0) {
			   if ((extensao == 'exe') || (extensao == 'EXE')) tmpErro += ' - No  permitida a publicao de arquivos executveis. Escolha arquivos com outra extensão para o campo \'' + objeto.getAttribute("nome") + '\'\n';
			   break;
			  } else {
			  	tmpErro += ' - Selecione um arquivo para o campo \'' + objeto.getAttribute("nome") + '\'\n';
			  }
			}
			
			case 'extensao_arquivo' : {
			  var tamanho = objeto.value.length;
			  var extensao = objeto.value.substr(tamanho-3,tamanho);
			  if (objeto.value != 0) {
			   if ((extensao == 'exe') || (extensao == 'EXE')) tmpErro += ' - No  permitida a publicao de arquivos executveis. Escolha arquivos com outra extensão para o campo \'' + objeto.getAttribute("nome") + '\'\n';
			   break;
			  }
			}
			
			break;
		}
		break;
	}


	case 'select-one': {
		switch (validacao) {
			case 'selecionado': {
				if ((objeto.value=='') || (objeto.value=='NULL')) tmpErro += ' - O campo \'' + objeto.getAttribute("nome") + '\' deve conter um valor selecionado \n';
				break;
				}
			break;
			}
		break;
		}
	case 'password': {
		switch (validacao) {
			case 'preenchido': {
				// Validao preenchido
				if (isEmpty(objeto.value)) tmpErro += ' - O campo \'' + objeto.getAttribute("nome") + '\'  de preenchimento obrigatório \n';
				break;
				}
			break;
			}
		break;
		}
	case 'textarea': {
		switch (validacao) {
			case 'preenchido': {
				// Validao preenchido
				if (objeto.value < 1) tmpErro += ' - O campo \'' + objeto.getAttribute("nome") + '\'  de preenchimento orbigatório \n';
				break;
				}
			break;
			}
		break;
		}
	case 'checkbox': {
		switch (validacao) {
			case 'marcado': {
				// Validao marcado
				if(strCheckboxes.indexOf('|' + objeto.getAttribute("nome") + '|') < 0) {
					if (!isAnyChecked(objeto)) {
						tmpErro += ' - Você deve selecionar ao menos um campo \'' + objeto.getAttribute("nome") + '\' \n';
						strCheckboxes += '|'+ objeto.getAttribute("nome") + '|';
						break;
						}
					break;
					}
				break;
				}
			break;
			}
		break;
		}
	case 'radio': {
		switch (validacao) {
			case 'marcado': {
				// Validao marcado
					if (!isRadioSelected(objeto)) {
						tmpErro += ' - Você deve selecionar ao menos um valor para o campo \'' + objeto.getAttribute("nome") + '\' \n';
						break;
						}
				break;
				}
			break;
			}
		break;
		}
	case 'hidden': {
		switch (validacao) {
			case 'supdata': {
				// Algum selecionado
				var data_inicial;
				var data_final;
				var monta_data_ini;
				var monta_data_fim;
				monta_data_ini = eval(objeto.form.name+'.'+objeto.supdata+'Inicial').value.substr(3,2) + '/' + eval(objeto.form.name+'.'+objeto.supdata+'Inicial').value.substr(0,2) + '/' + eval(objeto.form.name+'.'+objeto.supdata+'Inicial').value.substr(6,4);
				monta_data_fim = eval(objeto.form.name+'.'+objeto.supdata+'Final').value.substr(3,2) + '/' + eval(objeto.form.name+'.'+objeto.supdata+'Final').value.substr(0,2) + '/' + eval(objeto.form.name+'.'+objeto.supdata+'Final').value.substr(6,4);
				data_inicial = new Date(monta_data_ini);
				data_final   = new Date(monta_data_fim);

				if (data_final < data_inicial)  { 
				  tmpErro += '- A Data Final não pode ser inferior a Data Inicial.\n';
				  break;
				}
				break;
			}
			case 'newold': {
				// Algum selecionado
				if( (eval(objeto.form.name+'.opt'+objeto.newold+'[0]').checked == true && eval(objeto.form.name+'.'+objeto.newold+'_1').value == 0) || (eval(objeto.form.name+'.opt'+objeto.newold+'[1]').checked == true && isEmpty(eval(objeto.form.name+'.'+objeto.newold+'_2').value)) ) {
					tmpErro += ' - Você deve selecionar ou digitar um valor para o campo \'' + objeto.getAttribute("nome") + '\' \n';
					break;
					}
				break;
				}
			case 'newold2': {
				// Algum selecionado
				if( (eval(objeto.form.name+'.'+objeto.newold+'[0]').checked == true && isEmpty(eval(objeto.form.name+'.'+objeto.valida1).value)) || (eval(objeto.form.name+'.'+objeto.newold+'[1]').checked == true && isEmpty(eval(objeto.form.name+'.'+objeto.valida2).value)) ) {
					tmpErro += ' - Você deve selecionar ou digitar um valor para o campo \'' + objeto.getAttribute("nome") + '\' \n';
					break;
					}
				break;
				}
			case 'senha': {
				// Testando se senhas conferem
				if ( ((eval(objeto.form.name+'.str'+objeto.senha).value.length) > 0) && ((eval(objeto.form.name+'.str'+objeto.senha+'2').value.length) > 0)) {
				 if ((eval(objeto.form.name+'.str'+objeto.senha).value+'') != (eval(objeto.form.name+'.str'+objeto.senha+'2').value+'')) {
				  tmpErro += ' - A Confirmação de senha não confere \n';
				  break;
				 }
				}
				break;
				}
			break;
			}
		break;
		}
	}

	return(tmpErro);
}

function trim(inputString) {
	if (typeof inputString != "string") { return inputString; }
	var retValue = inputString;
	var ch = retValue.substring(0, 1);
	while (ch == " ") { 
		retValue = retValue.substring(1, retValue.length);
		ch = retValue.substring(0, 1);
	}
	ch = retValue.substring(retValue.length-1, retValue.length);
	while (ch == " ") { 
		retValue = retValue.substring(0, retValue.length-1);
		ch = retValue.substring(retValue.length-1, retValue.length);
	}
	while (retValue.indexOf("  ") != -1) { 
		retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); 
	}
	return retValue; 
} 



// -------------------------------
// Funes para validao de hora
// -------------------------------
 function isHour(Hora)
   {
   var hm = -1;
   var hora = Array(2);
   var ch = Hora.charAt(0); 
   for(i=0; i < Hora.length && (( ch >= '0' && ch <= '9' ) || ( ch == ':' && i != 0 ) ); ){
    hora[++hm] = '';
    if(ch!=':' && i != 0) return false;
    if(i != 0 ) ch = Hora.charAt(++i);
    if(ch=='0') ch = Hora.charAt(++i);
    while( ch >= '0' && ch <= '9' ){
     hora[hm] += ch;
     ch = Hora.charAt(++i);
    } 
   }
   if(ch!='') return false;
   if(hora[0] == '' || isNaN(hora[0]) || parseInt(hora[0]) < 0 || parseInt(hora[0]) > 23) return false;
   if(hora[1] == '' || isNaN(hora[1]) || parseInt(hora[1]) < 0 || parseInt(hora[1]) > 59) return false;
   return true;
  }



//------------------------------------------
// Funes de validao de checkbox
//------------------------------------------

function isAnyChecked(objeto){
	var fn_form = objeto.form;
	var fn_name = objeto.name;

	for(var i=0;i<fn_form.elements.length-1;i++) {
		if (fn_form.elements[i].type == 'checkbox' && fn_form.elements[i].name == fn_name) {
			if(fn_form.elements[i].checked) return true;
		}
	}

	return false;
}

//------------------------------------------
// Fim
//------------------------------------------



//------------------------------------------
// Funes de validao de radio
//------------------------------------------

function isRadioSelected(objeto){
	var fn_form = objeto.form;
	var fn_name = objeto.name;

	for(var i=0;i<fn_form.elements.length;i++) {
		if (fn_form.elements[i].type == 'radio' && fn_form.elements[i].name == fn_name) {
			if(fn_form.elements[i].checked) return true;
		}
	}

	return false;
}

//------------------------------------------
// Fim
//------------------------------------------








//------------------------------------------
// Incio das funes de validao de email
//------------------------------------------

function isEmail(param){
	var testresults;
	var str=param;
	var filter= /^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.biz)|(\.g12)|(\.inf)|(\.adv)|(\.arq)|(\.mil)|(\.gov)|(\.org)|(\..{2,2}))$/i
	return(filter.test(str))
}

//------------------------------------------
// Fim das funes de validao de email
//------------------------------------------









//------------------------------------------
// Incio das funes de validao de vazio
//------------------------------------------

function isEmpty(param) {
	if (param.replace(/ /g,'').length < 1) return (true);
	return (false);
}

//------------------------------------------
// Fim das funes de validao de vazio
//------------------------------------------







//------------------------------------------
// Incio das funes de validao de data
//------------------------------------------

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}


function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}


function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}


function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}


function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		return false
	}
return true
}

function DateDiff(interval, start, end)
{
	var iOut = 0, rounding=true;
	var bufferA = Date.parse(start);
	var bufferB = Date.parse(end );

	// check that the start parameter is a valid Date.
	if ( isNaN (bufferA) || isNaN (bufferB) )
	{
		return 0;
	}
	// check that an interval parameter was not numeric.
	if ( interval.charAt == 'undefined' )
	{
		// the user specified an incorrect interval, handle the error.
		return 0;
	}
	var number = bufferB-bufferA;

	// what kind of add to do?
	switch (interval.charAt(0))
	{
		case 'y': case 'Y':
		iOut = parseInt(number / (86400000*24))+parseInt((number %
		(86400000*24))/((43200000*24)+1));
		break ;
		case 'd': case 'D':
		iOut = parseInt(number / 86400000)+parseInt((number %
		86400000)/43200001);
		break ;
		case 'h': case 'H':
		iOut = parseInt(number / 3600000 )+parseInt((number %
		3600000)/1800001);
		break ;
		case 'm': case 'M':
		iOut = parseInt(number / 60000 )+parseInt((number % 60000)/30001);
		break ;
		case 's': case 'S':
		iOut = parseInt(number / 1000 )+parseInt((number % 1000)/501);
		break ;
		default:
		// If we get to here then the interval parameter
		// didn't meet the d,h,m,s criteria. Handle
		// the error.
		return 0;
	}
	return iOut ;
}

function FormataMMDDYYYY (param) {
	var dtStr = param;
	var dtCh = '/';
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	return strMonth + '/' + strDay + '/' + strYear;
}


//------------------------------------------
// Trmino das funes de validao de data
//------------------------------------------

//------------------------------------------
// Incio das funes de validao de CPF
//------------------------------------------
function limpaParaMascara(sujeira,filtro,tipo){
	numeros = "0123456789";
	valores = "0123456789,";
	letras  = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz&'\"\|@_<>!#$%&*()={[}]?:+-.,;/\\0123456789 ";
	letra_numero  = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ";
	retorno2 = '';
	if (tipo == 1) {
		if (sujeira.substring(0,1) == "-") ind = 1;
		else ind = 0;
	}
	else ind = 0;
	switch (filtro){
		case 'numeros': {
			for ( i=ind; i < sujeira.length; i++ ) {
				if( numeros.indexOf(sujeira.charAt(i))>-1 ) { 
					retorno2 += sujeira.charAt(i);
				}
			}
		break;	}
		case 'valores': {
			for ( i=ind; i < sujeira.length; i++ ) {
				if( valores.indexOf(sujeira.charAt(i))>-1 ) { 
					retorno2 += sujeira.charAt(i);
				}
			}
			if (sujeira.charAt(0)=='-') {
				retorno2 = "-"+retorno2;
			}
		break;	}
		case 'letras': {
			for ( i=0; i < sujeira.length; i++ ) {
				if( letras.indexOf(sujeira.charAt(i))>-1 ) { 
					retorno2 += sujeira.charAt(i);
				}
			}
		break;	}
		case 'letra_numero': {
			for ( i=ind; i < sujeira.length; i++ ) {
				if( letra_numero.indexOf(sujeira.charAt(i))>-1 ) { 
					retorno2 += sujeira.charAt(i);
				}
			}
		break;	}
	}
	if (tipo == 1) {
		if (sujeira.substring(0,1) == "-") retorno2 = "-" + retorno2;
	}
	return retorno2;
}


function validaCPF (CPF) {
    CPF = limpaParaMascara(CPF,'numeros');    
    if (CPF.length != 11) { for(countZeros=0 ; countZeros < ((11-CPF.length)+2) ; countZeros++){ CPF = "0"+CPF; } };
	if(CPF == '00000000000'){ return false; }
    soma = 0;
    for(i=0 ; i<9 ; i++) {
        soma = soma + eval(CPF.charAt(i) * (10 - i));
    }
    Resto = 11 - ( soma - (parseInt(soma / 11) * 11) );
    if ( (Resto == 10) || (Resto == 11) ) { Resto = 0; }
    if ( Resto != eval( (CPF.charAt(9) ) ) ) { return false; }
	soma = 0;
    for (i = 0;i<10;i++) {
        soma = soma + eval(CPF.charAt(i) * (11 - i));
	} 
    Resto = 11 - ( soma - (parseInt(soma / 11) * 11) );
    if ( (Resto == 10) || (Resto == 11)) {
		Resto = 0;
	}
    if ( Resto != eval( (CPF.charAt(10)) )) {
		return false;
	}
	return true;
}
//------------------------------------------
// Trmino das funes de validao de CPF
//------------------------------------------



function MostraSubCategoria(selecionadoItem, nomeItem, idSubCategoria) {
	
	if (selecionadoItem == nomeItem)
	{
	
		document.getElementById(idSubCategoria).style.display = '';
	
	}else{
		
		
		document.getElementById(idSubCategoria).style.display = 'none';	
	}
}


function Mascara(objEvent) {
		objField = objEvent.srcElement;

		strTipo = objField.type;
		strMascara = objField.mascara;
		
		if (strTipo == 'text') {
			// Tarefas
			//------------------------------------------------------
			// 1. Pegar onde o cursor est posicionado no campo
			// 2. Pegar quais so as teclas de número e outros
			// 3. Comparar posio atual com posio do strMascara

			//objEvent.returnValue = true;

			for (var i=0; i < strMascara.length; i++){ 
				arrMascara[i] = strMascara.slice(i,i+1) 
			}
		}
}


function FormataCampo(Campo,teclapres,mascara){ 
strtext = Campo.value 
tamtext = strtext.length 
tammask = mascara.length 
arrmask = new Array(tammask)     
 for (var i = 0 ; i < tammask; i++){ 
  arrmask[i] = mascara.slice(i,i+1) 
 } 
 if (((((arrmask[tamtext] == "#") || (arrmask[tamtext] == "9"))) || (((arrmask[tamtext+1] != "#") || (arrmask[tamtext+1] != "9"))))){ 
  if ((teclapres.keyCode >= 37 && teclapres.keyCode <= 40)||(teclapres.keyCode >= 48 && teclapres.keyCode <= 57)||(teclapres.keyCode >= 96 && teclapres.keyCode <= 105)||(teclapres.keyCode == 8)||(teclapres.keyCode == 9) ||(teclapres.keyCode == 46) ||(teclapres.keyCode == 13)){ 
   Organiza_Casa(Campo,arrmask[tamtext],teclapres.keyCode,strtext)         
  } 
  else{ 
   Detona_Event(Campo,strtext) 
  } 
 } 
 else{ 
  if ((arrmask[tamtext] == "A"))    { 
   charupper = event.valueOf() 
   Detona_Event(Campo,strtext) 
   masktext = strtext + charupper 
   Campo.value = masktext 
  } 
 } 
} 
 
function Organiza_Casa(Campo,arrpos,teclapres_key,strtext){ 
 if (((arrpos == "/") || (arrpos == ".") || (arrpos == ",") || (arrpos == ":") || (arrpos == " ") || (arrpos == "-")) && !(teclapres_key == 8)){ 
  separador = arrpos 
  masktext = strtext + separador 
  Campo.value = masktext 
 } 
}
 
function Detona_Event(Campo,strtext){ 
 event.returnValue = false 
 if (strtext != "") { 
   Campo.value = strtext 
 } 
}

function MarcarTodos(modo){
  var nb;
  var chk;
  if (document.forms[0].chkMestre.value == 0) { 
    chk=1
  } else { 
    chk=0 
  }
  nb = document.forms[0].idNucleo.length
  for (var i=0;i<nb;i++) {
    var e = document.forms[0].idNucleo[i];
    
	if (modo == 0) {
	 e.checked = chk
	}else if (modo == 1) {
	 e.checked = chk
	 e.disabled = chk
	}
  }
document.forms[0].chkMestre.value = chk;
}

/// FUNO PARA FORMATAO DE VALOR
function formataValor(campo,tammax,teclapres) 
{
      var tecla = teclapres.keyCode;
	  if (tecla == 9) {
	  	event.returnValue = true;
		return true;
	  }
      
// if( tecla <  48 || tecla > 57 ) event.returnValue=false;
      
      vr = campo.value;
      vr = vr.replace( "/", "" );
      vr = vr.replace( "/", "" );
      vr = vr.replace( ",", "" );
      vr = vr.replace( ".", "" );
      vr = vr.replace( ".", "" );
      vr = vr.replace( ".", "" );
      vr = vr.replace( ".", "" );
      vr = vr.replace( ".", "" );
      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 )
           with(campo)
           {
           if ( tam <= 2 ){ 
      value = vr ; }
      if ( (tam > 2) && (tam <= 5) ){
      value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ) ; }
      if ( (tam >= 6) && (tam <= 8) ){
      value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ','
+ vr.substr( tam - 2, tam ) ; }
      if ( (tam >= 9) && (tam <= 11) ){
      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) ){
      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) ){
      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 ) ;}
      if ( (tam >= 18) && (tam <= 20) ){
      value = vr.substr( 0, tam - 17 ) + '.' + vr.substr( tam - 17, 3 ) +
'.' + 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 ) ;}
   } 
      else
           event.returnValue=false;
      
}
//// FIM DA FUNO PARA FORMATAO DE VALOR

/// INCIO DA FUNO DE REDIMENSIONAMENTO DE IFRAME 
function ResizeIframe(nomeframe,altura) {
	objtemp = eval('document.all.' + nomeframe);
	objtemp.height = altura;
}
/// FIM DA FUNO DE REDIMENSIONAMENTO DE IFRAME 

	function Grava(theForm) 
	{
    if (theForm.data.value == "") 
	{
        alert("Campo Data ObrigatÃ³rio!");
        theForm.data.focus();
        return false;
    }
	if (theForm.nome.value == "") 
	{
        alert("Campo Nome ObrigatÃ³rio!");
        theForm.nome.focus();
        return false;
    }
	if (theForm.crp.value == "") 
	{
        alert("Campo CRP ObrigatÃ³rio!");
        theForm.crp.focus();
        return false;
    }
	
	if (theForm.cpf.value == "") 
	{
        alert("Campo CPF ObrigatÃ³rio!");
        theForm.cpf.focus();
        return false;
    }
	if (theForm.cpf.value.length < 14) 
	{
        alert("Campo CPF Preenchido Incorretamente!");
        theForm.cpf.focus();
        return false;
    }
	if(valida_cpf(theForm.cpf.value) == false)
	{
		alert("CPF InvÃ¡lido!");
		theForm.cpf.focus();
		return false;	
	}
	if (theForm.municipio.value == "") 
	{
        alert("Selecione um Municipio!");
        theForm.municipio.focus();
        return false;
    }
	if (theForm.email.value == "") 
	{
        alert("Campo Email ObrigatÃ³rio!");
        theForm.email.focus();
        return false;
    }
	if(valida_email(theForm) == false)
	{
		return false;
	}
    
    return true;
}

	function Grava2(theForm) 
	{
    if (theForm.data.value == "") 
	{
        alert("Campo Data ObrigatÃ³rio!");
        theForm.data.focus();
        return false;
    }
	if (theForm.nome.value == "") 
	{
        alert("Campo Nome ObrigatÃ³rio!");
        theForm.nome.focus();
        return false;
    }
	if (theForm.crp.value == "") 
	{
        alert("Campo CRP ObrigatÃ³rio!");
        theForm.crp.focus();
        return false;
    }
	
	if (theForm.cpf.value == "") 
	{
        alert("Campo CPF ObrigatÃ³rio!");
        theForm.cpf.focus();
        return false;
    }
	if (theForm.cpf.value.length < 14) 
	{
        alert("Campo CPF Preenchido Incorretamente!");
        theForm.cpf.focus();
        return false;
    }
	
	if(valida_cpf(theForm.cpf.value) == false)
	{
		alert("CPF InvÃ¡lido!");
		theForm.cpf.focus();
		return false;	
	}
	if (theForm.municipio.value == "") 
	{
        alert("Selecione um Municipio!");
        theForm.municipio.focus();
        return false;
    }
	if (theForm.email.value == "") 
	{
        alert("Campo Email ObrigatÃ³rio!");
        theForm.email.focus();
        return false;
    }
	if(valida_email(theForm) == false)
	{
		return false;
	}
	if (theForm.telefone.value.length < 14) 
	{
        alert("Campo Telefone Preenchido Incorretamente!");
        theForm.telefone.focus();
        return false;
	}
	if (theForm.chkConfirma.checked == false) 
	{
        alert("Ã‰ necessÃ¡rio afirmar a veracidade!");
        theForm.chkConfirma.focus();
        return false;
    }
	if (theForm.chkAutoriza.checked == false) 
	{
        alert("Ã‰ necessÃ¡rio Autorizar a ExibiÃ§Ã£o de seus dados!");
        theForm.chkAutoriza.focus();
        return false;
    }
    
    return true;
}
function valida_cpf(cpf)
      {
		var cpf = cpf;
		cpf = cpf.replace('.','');
		cpf = cpf.replace('.','');
		cpf = cpf.replace('-','');
      var numeros, digitos, soma, i, resultado, digitos_iguais;
      digitos_iguais = 1;
      if (cpf.length < 11)
            return false;
      for (i = 0; i < cpf.length - 1; i++)
            if (cpf.charAt(i) != cpf.charAt(i + 1))
                  {
                  digitos_iguais = 0;
                  break;
                  }
      if (!digitos_iguais)
            {
            numeros = cpf.substring(0,9);
            digitos = cpf.substring(9);
            soma = 0;
            for (i = 10; i > 1; i--)
                  soma += numeros.charAt(10 - i) * i;
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(0))
                  return false;
            numeros = cpf.substring(0,10);
            soma = 0;
            for (i = 11; i > 1; i--)
                  soma += numeros.charAt(11 - i) * i;
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(1))
                  return false;
            return true;
            }
      else
            return false;
      }
	  
	  
function valida_email(nform) {
		prim = nform.email.value.indexOf("@")
		if(prim < 2) {
			alert("O e-mail informado parece nÃ£o estar correto.");
			nform.email.focus();
			nform.email.select();
			return false;
		}
		if(nform.email.value.indexOf("@",prim + 1) != -1) {
			alert("O e-mail informado parece nÃ£o estar correto.");
			nform.email.focus();
			nform.email.select();
			return false;
		}
		if(nform.email.value.indexOf(".") < 1) {
			alert("O e-mail informado parece nÃ£o estar correto.");
			nform.email.focus();
			nform.email.select();
			return false;
		}
		if(nform.email.value.indexOf(" ") != -1) {
			alert("O e-mail informado parece nÃ£o estar correto.");
			nform.email.focus();
			nform.email.select();
			return false;
		}
		if(nform.email.value.indexOf("zipmeil.com") > 0) {
			alert("O e-mail informado parece nÃ£o estar correto.");
			nform.email.focus();
			nform.email.select();
			return false;
		}
		if(nform.email.value.indexOf("hotmeil.com") > 0) {
			alert("O e-mail informado parece nÃ£o estar correto.");
			nform.email.focus();
			nform.email.select();
			return false;
		}
		if(nform.email.value.indexOf(".@") > 0) {
			alert("O e-mail informado parece nÃ£o estar correto.");
			nform.email.focus();
			nform.email.select();
			return false;
		}
		if(nform.email.value.indexOf("@.") > 0) {
			alert("O e-mail informado parece nÃ£o estar correto.");
			nform.email.focus();
			nform.email.select();
			return false;
		}
		if(nform.email.value.indexOf(".com.br.") > 0) {
			alert("O e-mail informado parece nÃ£o estar correto.");
			nform.email.focus();
			nform.email.select();
			return false;
		}
		if(nform.email.value.indexOf("/") > 0) {
			alert("O e-mail informado parece nÃ£o estar correto.");
			nform.email.focus();
			nform.email.select();
			return false;
		}
		if(nform.email.value.indexOf("[") > 0) {
			alert("O e-mail informado parece nÃ£o estar correto.");
			nform.email.focus();
			nform.email.select();
			return false;
		}
		if(nform.email.value.indexOf("]") > 0) {
			alert("O e-mail informado parece nÃ£o estar correto.");
			nform.email.focus();
			nform.email.select();
			return false;
		}
		if(nform.email.value.indexOf("(") > 0) {
			alert("O e-mail informado parece nÃ£o estar correto.");
			nform.email.focus();
			nform.email.select();
			return false;
		}
		if(nform.email.value.indexOf(")") > 0) {
			alert("O e-mail informado parece nÃ£o estar correto.");
			nform.email.focus();
			nform.email.select();
			return false;
		}
		if(nform.email.value.indexOf("..") > 0) {
			alert("O e-mail informado parece nÃ£o estar correto.");
			nform.email.focus();
			nform.email.select();
			return false;
		}
		return true;
}
function mascara(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}

function execmascara(){
    v_obj.value=v_fun(v_obj.value)
}

function Leech(v){
    v=v.replace(/o/gi,"0")
    v=v.replace(/i/gi,"1")
    v=v.replace(/z/gi,"2")
    v=v.replace(/e/gi,"3")
    v=v.replace(/a/gi,"4")
    v=v.replace(/s/gi,"5")
    v=v.replace(/t/gi,"7")
    return v
}

function soNumeros(v){
    return v.replace(/\D/g,"")
}

function Telefone(v){
    v=v.replace(/\D/g,"")                 //Remove tudo o que nÃ£o Ã© dÃ­gito
    v=v.replace(/^(\d\d)(\d)/g,"($1) $2") //Coloca parÃªnteses em volta dos dois primeiros dÃ­gitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")    //Coloca hÃ­fen entre o quarto e o quinto dÃ­gitos
    return v
}

function CPF(v){
    v=v.replace(/\D/g,"")                    //Remove tudo o que nÃ£o Ã© dÃ­gito
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dÃ­gitos
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dÃ­gitos
                                             //de novo (para o segundo bloco de nÃºmeros)
    v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2") //Coloca um hÃ­fen entre o terceiro e o quarto dÃ­gitos
    return v
}

function Cep(v){
    v=v.replace(/D/g,"")                //Remove tudo o que nÃ£o Ã© dÃ­gito
    v=v.replace(/^(\d{5})(\d)/,"$1-$2") //Esse Ã© tÃ£o fÃ¡cil que nÃ£o merece explicaÃ§Ãµes
    return v
}

function Cnpj(v){
    v=v.replace(/\D/g,"")                           //Remove tudo o que nÃ£o Ã© dÃ­gito
    v=v.replace(/^(\d{2})(\d)/,"$1.$2")             //Coloca ponto entre o segundo e o terceiro dÃ­gitos
    v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3") //Coloca ponto entre o quinto e o sexto dÃ­gitos
    v=v.replace(/\.(\d{3})(\d)/,".$1/$2")           //Coloca uma barra entre o oitavo e o nono dÃ­gitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")              //Coloca um hÃ­fen depois do bloco de quatro dÃ­gitos
    return v
}

function Romanos(v){
    v=v.toUpperCase()             //MaiÃºsculas
    v=v.replace(/[^IVXLCDM]/g,"") //Remove tudo o que nÃ£o for I, V, X, L, C, D ou M
    //Essa Ã© complicada! Copiei daqui: http://www.diveintopython.org/refactoring/refactoring.html
    while(v.replace(/^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/,"")!="")
        v=v.replace(/.$/,"")
    return v
}

function Site(v){
    //Esse sem comentarios para que vocÃª entenda sozinho ;-)
    v=v.replace(/^http:\/\/?/,"")
    dominio=v
    caminho=""
    if(v.indexOf("/")>-1)
        dominio=v.split("/")[0]
        caminho=v.replace(/[^\/]*/,"")
    dominio=dominio.replace(/[^\w\.\+-:@]/g,"")
    caminho=caminho.replace(/[^\w\d\+-@:\?&=%\(\)\.]/g,"")
    caminho=caminho.replace(/([\?&])=/,"$1")
    if(caminho!="")dominio=dominio.replace(/\.+$/,"")
    v="http://"+dominio+caminho
    return v
}

function ExcluirPeritos()
	{
	var alertar = confirm("Deseja Realmente Excluir estes Peritos?");
	if(alertar == true)
		{
		counter=0;
		for (i=0; i < document.getElementsByName('IdPerito[]').length; i++)
			{
			if (document.getElementsByName('IdPerito[]')[i].checked == true)
				{
				counter++;
				}
			}

		if (counter==0)
			{
			alert("Selecione pelo menos uma opÃ§Ã£o")
			return false;
			}
		else
			{
			document.getElementById('acao').value = "Excluir";
			document.getElementById('formlistar').submit();	
			}
		return true;
		}
	
	}
