/* Based on: Travis Beckham ::
http://www.squidfingers.com | http://www.podlob.com
Based on: Manzi Olivier :: http://www.imanzi.com/
Based on: jgw (jgwang@csua.berkeley.edu )/ */
function isCPF(str) {

	cpf = str;
	erro = new String;
	if(cpf.length==0)
	erro+="";
	else if (cpf.length < 14) erro += "Sao necessarios 11 digitos para verificacao do CPF! \n\n";

	else if ((cpf.charAt(3) != ".") || (cpf.charAt(7) != ".") || (cpf.charAt(11) != "-") ){
		if (erro.length == 0) erro += "É necessário preencher corretamente o número do CPF! \n\n";
	}

	//substituir os caracteres que não são números
	if(document.layers && parseInt(navigator.appVersion) == 3){
		x = cpf.substring(0,3);
		x += cpf. substring (4,7);
		x += cpf. substring (8,11);
		x += cpf. substring (12,14);
		/* x += cpf. substring (11,15);
		x += cpf. substring (16,18);*/
		cpf = x;
	} else {
		cpf = cpf. replace (".","");
		cpf = cpf. replace (".","");
		cpf = cpf. replace ("-","");
	}


	var nonNumbers = /\D/;
	if (nonNumbers.test(cpf)) erro += "A verificacao de CPF suporta apenas numeros! \n\n";
	if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){
		erro += "Numero de CPF invalido!"
	}
	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; }
	if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
		erro +="Digito verificador com problema!";
	}

	if(erro.length==0)
	return true;

}


function isCNPJ(str) {
	CNPJ = str;
	erro = new String;
	if(CNPJ.length>0) {

		if (CNPJ.length < 18) { erro += "É necessario preencher corretamente o número do CNPJ! \n\n";
		form1.cnpj.focus();
		}
		if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
			if (erro.length == 0) erro += "É necessário preencher corretamente o número do CNPJ! \n\n";
			form1.cnpj.focus();
		}
		//substituir os caracteres que não são números
		if(document.layers && parseInt(navigator.appVersion) == 4){
			x = CNPJ.substring(0,2);
			x += CNPJ. substring (3,6);
			x += CNPJ. substring (7,10);
			x += CNPJ. substring (11,15);
			x += CNPJ. substring (16,18);
			CNPJ = x;
		} else {
			CNPJ = CNPJ. replace (".","");
			CNPJ = CNPJ. replace (".","");
			CNPJ = CNPJ. replace ("-","");
			CNPJ = CNPJ. replace ("/","");
		}
		var nonNumbers = /\D/;
		if (nonNumbers.test(CNPJ)) erro += "A verificação de CNPJ suporta apenas números! \n\n";
		var a = [];
		var b = new Number;
		var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
		for (i=0; i<12; i++){
			a[i] = CNPJ.charAt(i);
			b += a[i] * c[i+1];
		}
		if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
		b = 0;
		for (y=0; y<13; y++) {
			b += (a[y] * c[y]);
		}
		if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
		if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
			erro +="Dígito verificador com problema!";
		}

	}
	if(erro.length==0)
	return true;

}

function checkCapsLock( e ) {
	var myKeyCode=0;
	var myShiftKey=false;

	// Internet Explorer 4+
	if ( document.all ) {
		myKeyCode=e.keyCode;
		myShiftKey=e.shiftKey;

		// Netscape 4
	} else if ( document.layers ) {
		myKeyCode=e.which;
		myShiftKey=( myKeyCode == 16 ) ? true : false;

		// Netscape 6
	} else if ( document.getElementById ) {
		myKeyCode=e.which;
		myShiftKey=( myKeyCode == 16 ) ? true : false;

	}

	// Upper case letters are seen without depressing the Shift key, therefore Caps Lock is on
	if ( ( myKeyCode >= 65 && myKeyCode <= 90 ) && !myShiftKey ) {
		alert( errormsg[100] );

		// Lower case letters are seen while depressing the Shift key, therefore Caps Lock is on
	} else if ( ( myKeyCode >= 97 && myKeyCode <= 122 ) && myShiftKey ) {
		alert( errormsg[100] );

	}
}

function CalcKeyCode(aChar) {
	var character = aChar.substring(0,1);
	var code = aChar.charCodeAt(0);
	return code;
}

function checkNumber(val) {
	var strPass = val.value;
	var strLength = strPass.length;
	var lchar = val.value.charAt((strLength) - 1);
	var cCode = CalcKeyCode(lchar);


	/* Check if the keyed in character is a number
	do you want alphabetic UPPERCASE only ?
	or lower case only just check their respective
	codes and replace the 48 and 57 */

	if (cCode < 48 || cCode > 57 ) {
		var myNumber = val.value.substring(0, (strLength) - 1);
		val.value = myNumber;
	}
	return false;
}
function isEmpty(str){
	return (str == null) || (str.length == 0) || (str=="0");
}
// returns true if the string is a valid email
function isEmail(str){
	if(isEmpty(str)) return false;
	var re = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i
	return re.test(str);
}

// returns true if the string only contains characters A-Z or a-z
function isAlpha(str){
	var re = /[^a-zA-Z]/g
	if (re.test(str)) return false;
	return true;
}
// returns true if the string only contains characters 0-9
function isNumeric(str){
	var re = /[\D]/g
	if (re.test(str)) return false;
	return true;
}
// returns true if the string only contains characters A-Z, a-z or 0-9
function isAlphaNumeric(str){
	var re = /[^a-zA-Z0-9]/g
	if (re.test(str)) return false;
	return true;
}
// returns true if the string's length equals "len"
function isLength(str, len){
	return str.length == len;
}
// returns true if the string's length is between "min" and "max"
function isLengthBetween(str, min, max){
	return (str.length >= min)&&(str.length <= max);
}
// returns true if the string is a US phone number formatted as...
// (000)000-0000, (000) 000-0000, 000-000-0000, 000.000.0000, 000 000 0000, 0000000000
function isPhoneNumber(str){
	//var re = /^\(?[2-9]\d{2}[\)\.-]?\s?\d{3}[\s\.-]?\d{4}$/
	var re = /^\(?\d{2}[\)\.-]?\s?\d{4}[\s\.-]?\d{4}$/
	return re.test(str);
}
// returns true if the string is a valid date formatted as...
// mm dd yyyy, mm/dd/yyyy, mm.dd.yyyy, mm-dd-yyyy
function isDate(str){
	var re = /^(\d{1,2})[\s\.\/-](\d{1,2})[\s\.\/-](\d{4})$/
	if (!re.test(str)) return false;
	var result = str.match(re);
	var y = (result[3]);
	var m = (result[2]);
	var d = (result[1]);
	//alert("dia "+d+"mes "+m+"ano "+y);
	if(m < 0 || m > 12 || y < 1900 || y > 2100) return false;
	if(m == 2){
		var days = ((y % 4) == 0) ? 29 : 28;
	}else if(m == 04 || m == 06 || m == 09 || m == 11){
		var days = 30;
	}else{
		var days = 31;
	}
	return (d >= 1 && d <= days);
}
// returns true if "str1" is the same as the "str2"
function isMatch(str1, str2){
	return str1 == str2;
}
// returns true if the string contains only whitespace
// cannot check a password type input for whitespace
function isWhitespace(str){ // NOT USED IN FORM VALIDATION
	var re = /[\S]/g
	if (re.test(str)) return false;
	return true;
}
// removes any whitespace from the string and returns the result
// the value of "replacement" will be used to replace the whitespace (optional)
function stripWhitespace(str, replacement){// NOT USED IN FORM VALIDATION
	if (replacement == null) replacement = '';
	var result = str;
	var re = /\s/g
	if(str.search(re) != -1){
		result = str.replace(re, replacement);
	}
	return result;
}
// validate the form
function validateForm(f, preCheck, newClass, alerttype){
	var errors = '';
	var errorsa = '';
	if(preCheck != null) errors += preCheck;
	var i,e,t,n,v;
	for(i=0; i < f.elements.length; i++){
		e = f.elements[i];

		if(e.optional) continue;
		t = e.type;
		n = e.id;
		v = e.value;
		if(t == 'text' || t == 'password' || t == 'textarea'){

			if(isEmpty(v)){
				errors += n+errormsg[1]+ '<br>';
				errorsa += n+errormsg[1]+'\n';
				e.className=newClass;
				continue;
			}
			else {
				e.className='checkit';
			}
			/*if(v == e.defaultValue){
			errors += n+errormsg[2]+ '<br>';
			errorsa += n+errormsg[2]+'\n';
			e.className=newClass;
			continue;
			}
			else {
			e.className='checkit';
			}*/
			if(e.isAlpha){
				if(!isAlpha(v)){
					errors += n+errormsg[3]+ '<br>';
					errorsa += n+errormsg[3]+'\n';
					overlib('eaaaa');
					e.className=newClass;
					continue;
				}
				else {
					e.className='checkit';
				}
			}

			if(e.isCPF){
				if(!isCPF(v)){
					errors += n+errormsg[14]+ '<br>';
					errorsa += n+errormsg[14]+'\n';
					//overlib('eaaaa');
					e.className=newClass;
					continue;
				}
				else {
					e.className='checkit';
				}
			}

			if(e.isCNPJ){
				if(!isCNPJ(v)){
					errors += n+errormsg[14]+ '<br>';
					errorsa += n+errormsg[14]+'\n';
					//overlib('eaaaa');
					e.className=newClass;
					continue;
				}
				else {
					e.className='checkit';
				}
			}

			if(e.isNumeric){
				if(!isNumeric(v)){
					errors += n+errormsg[4]+ '<br>';
					errorsa += n+errormsg[4]+'\n';
					e.className=newClass;
					continue;
				}
				else {
					e.className='checkit';
				}
			}
			if(e.isAlphaNumeric){
				if(!isAlphaNumeric(v)){
					errors += n+errormsg[5]+ '<br>';
					errorsa += n+errormsg[5]+'\n';
					e.className=newClass;
					continue;
				}
				else {
					e.className='checkit';
				}
			}
			if(e.isEmail){
				if(!isEmail(v)){
					errors += v+errormsg[6]+ '<br>';
					errorsa += n+errormsg[6]+'\n';
					e.className=newClass;
					continue;
				}
				else {
					e.className='checkit';
				}
			}
			if(e.isLength != null){
				var len = e.isLength;
				if(!isLength(v,len)){
					errors += n+errormsg[7]+ len + '<br>';
					errorsa += n+errormsg[7]+'\n';
					e.className=newClass;
					continue;
				}
				else {
					e.className='checkit';
				}
			}
			if(e.isLengthBetween != null){
				var min = e.isLengthBetween[0];
				var max = e.isLengthBetween[1];
				if(!isLengthBetween(v,min,max)){
					errors += n+errormsg[8] + min + ' e no máximo ' + max + ' caracteres<br>';
					errorsa += n+errormsg[8] + min + ' e no máximo ' + max + ' caracteres\n';
					e.className=newClass;
					continue;
				}
				else {
					e.className='checkit';
				}
			}
			if(e.isPhoneNumber){
				if(!isPhoneNumber(v)){
					errors += v+errormsg[9]+ '<br>';
					errorsa += n+errormsg[9]+'\n';
					e.className=newClass;
					continue;
				}
				else {
					e.className='checkit';
				}
			}
			if(e.isDate){
				if(!isDate(v)){
					errors += v+errormsg[10]+ '<br>';
					errorsa += n+errormsg[10]+'\n';
					e.className=newClass;
					continue;
				}
				else {
					e.className='checkit';
				}
			}
			if(e.isMatch != null){
				if(!isMatch(v, e.isMatch)){
					errors += n+errormsg[11]+ '<br>';
					errorsa += n+errormsg[11]+'\n';
					e.className=newClass;
					continue;
				}
				else {
					e.className='checkit';
				}
			}
		}
		if(t.indexOf('select-one') != -1){
			if(isEmpty(e.options[e.selectedIndex].value) || e.options[e.selectedIndex].value=="----"){
				errors += n+errormsg[12]+ '<br>';
				errorsa += n+errormsg[12]+'\n';
				e.className=newClass;
				continue;
			}
			else {
				e.className='checkit';
			}
		}
		if(t == 'file'){
			if(isEmpty(v)){
				errors += n+errormsg[13]+'<br>';
				errorsa += n+errormsg[13]+'\n';
				e.className=newClass;
				continue;
			}
			else {
				e.className='checkit';
			}
		}
	}
	div = document.getElementById('errordiv');
	if(errors != '') {
		if(alerttype == '2' || alerttype == '3') {
			alert(errorsa);
		}
		if(alerttype == '1' || alerttype == '3') {
			return dispErr(errors, div);
		}
	}
	div.style.display="none";
	return errors == '';
}

dispErr = function(error, divo) {
	divo.style.display="block";
	divo.innerHTML = error;
	return false;
}


function formatar(src, mask) {
	var i = src.value.length;
	var saida = mask.substring(0,1);

	var texto = mask.substring(i)

	if (texto.substring(0,1) != saida) {
		src.value += texto.substring(0,1);
	}
}


/*
The following elements are not validated...

button   type="button"
checkbox type="checkbox"
hidden   type="hidden"
radio    type="radio"
reset    type="reset"
submit   type="submit"

All elements are assumed required and will only be validated for an
empty value or defaultValue unless specified by the following properties.

isEmail = true;          // valid email address
isAlpha = true;          // A-Z a-z characters only
isNumeric = true;        // 0-9 characters only
isAlphaNumeric = true;   // A-Z a-z 0-9 characters only
isLength = number;       // must be exact length
isLengthBetween = array; // [lowNumber, highNumber] must be between lowNumber and highNumber
isPhoneNumber = true;    // valid phone number. See "isPhoneNumber()" comments for the formatting rules
isDate = true;           // valid date. See "isDate()" comments for the formatting rules
isMatch = string;        // must match string
optional = true;         // element will not be validated

alerttype = 0            // no error msg
alerttype = 1            // error msg in div
alerttype = 2            // error msg in alert
alerttype = 3            // error msg in div and alert
*/

//============================

// error msg depends on the language
var errormsg = new Array();
errormsg[0] = 'Selecione pelo menos um checkbox!<br>';
errormsg[1] = ' não pode ser vazio!';
errormsg[2] = ' não pode usar o valor padrão!';
errormsg[3] = ' pode conter apenas caracteres A-Z a-z!';
errormsg[4] = ' pode conter apenas caracteres numéricos (0-9)!';
errormsg[5] = ' pode conter apenas caracteres alfanuméricos (A-Z a-z 0-9)!';
errormsg[6] = ' não é um e-mail válido!';
errormsg[7] = ' deve conter números menores que ';
errormsg[8] = ' deve conter no mínimo ';
errormsg[9] = ' não é um telefone válido!';
errormsg[10] = ' não é uma data válida!';
errormsg[11] = ' não confere!';
errormsg[12] = ' deve ter uma opção selecionada!';
errormsg[13] = ' precisa de um arquivo para upload!';
errormsg[14] = ' deve conter um número válido!';
errormsg[99] = 'Todas as informações serão apagadas!';
errormsg[100] = 'Caps Lock está ligado.\n\nPara evitar problemas com a senha, \naperte a tecla novamente para desativá-la.';



function limparCampos(f){
	if(confirm("Deseja limpar o formulário?")) {
		for(i=0; i < f.elements.length; i++){
			e = f.elements[i];

			if(e.type!="submit" && e.type!="button" && e.type!="hidden" && e.type!="textarea" && e.name!="usuario_up") {
				if(e.type=="select-one")
				e.value="0";

				else
				e.value="";

				e.className='limpo';
			}
		}
	}
	div = document.getElementById('errordiv');
	div.style.display="none";
}


function confirmBox() {
	  var total=0;
	  for (var i=0;i<document.form1.elements.length;i++) {
	    var x = document.form1.elements[i];
	   // if (x.name == 'UIDL') {		
		    	if(x.checked == true) {
				total+=1;
				}//if x.checked
	}//for
	
	if(total>0) {

	if (confirm("Deseja realmente excluir os registros selecionados?")) {
				form1.submit();
	}//if confirm
	}//if total
	

}//função


ok=false;
function checkAll() {
	if(!ok){
	  for (var i=0;i<document.form1.elements.length;i++) {
	    var x = document.form1.elements[i];
	   // if (x.name == 'UIDL') {		
		    	x.checked = true;
				document.form1.botao.value="Desmarcar";
				ok=true;
		//	}
	    }
	}
	else{
	for (var i=0;i<document.form1.elements.length;i++) {
	    var x = document.form1.elements[i];
	 //   if (x.name == 'UIDL') {		
		    	x.checked = false;
				document.form1.botao.value="Marcar";
				ok=false;
		//	}
	    }	
	}
}




function PrintPage() {
	if (window.print)
	window.print()
	else
	alert("O script não conseguiu enviar o documento diretamente para impressão,nPressione Ctrl+P ou selecione Imprimir no menu Arquivo para imprimir esta página.");
}


function disableForm(theform) {
	if (document.all || document.getElementById) {
		for (i = 0; i < theform.length; i++) {
			var tempobj = theform.elements[i];
			if (tempobj.type.toLowerCase() == "submit" || tempobj.type.toLowerCase() == "reset")
			tempobj.disabled = true;
		}
		setTimeout('alert("Por favor, aguarde um momento.")', 2000);
		return true;
	}
	else {
		alert("The form has been submitted.  But, since you're not using IE 4+ or NS 6, the submit button was not disabled on form submission.");
		return false;
	}
}
