// ---------------------------------------------
// Advice NetBusiness                   	
// Projeto Biblioteca de Funcoes de JavaScript 	
// Data de criacao: 21/03/2003          	
// Ultima modificacao: 27/03/2003       	
// Programacao: Joao Carlos  			
// Ultima atualizacao: Joao Carlos		
// ---------------------------------------------
// -----[ FUNCOES CONTIDAS NESTE ARQUIVO ]------
// 01- isNull(campo)				
// 02- getSelectedValue(combo)			
// 03- getSelectedText(combo)			
// 04- setSelectedValue(combo,valor)		
// 05- refreshPage(combo, pagina)		
// 06- checkLen(target,maxChars)		
// 07- getRadioValue(campo)			
// 08- isSelectedObject(objeto)			
// 09- isMaxSelectedObject(objeto,max)		
// 10- changeDependenceFields(objeto,dependente)
// 11- isAccentedVowel(campo)			
// 12- isMail(email)				
// 13- trim(campo)				
// 14- isEquals(campo1,campo2)			
// 15- isValidDate(day,month,year)		
// 16- isDate(data)				
// 17- isNumber(number)				
// 18- isUnaccentedText(text,caseType,separator)
// 19- openWindow(pagina,largura,altura)	
// 20- checkClick(link,text)			
// 21- isCPF(CPF)				
// 22- checkCharsEntry(intervalo,caracter)	
// 23- checkHora(campoH,campoM)
// ---------------------------------------------

// Verifica se um campo esta vazio pegando inclusive espaco em branco
// Tipo de retorno: BOOLEAN
// Dominio: [true | false]
function isNull(campo){
	strAux = ""; 
	strAux = campo.split(" "); 
	strAux = strAux.join(""); 
	if (strAux == ''){
		return true;
	}
	else{
		return false;
	}
}

// Recupera o value de um combo
// Tipo de retorno: STRING
// Dominio: Valor contido no value do option do objeto select
function getSelectedValue(combo){
	if(combo.options.length > 0){
		return combo.options[combo.selectedIndex].value;
	}
}

// Recupera o text de um combo
// Tipo de retorno: STRING
// Dominio: Valor contido no text do option do objeto select
function getSelectedText(combo){
	if(combo.options.length > 0){
		return combo.options[combo.selectedIndex].text;
	}
}

// Seleciona um item dentro de um combo
// Tipo de retorno: Nao possui retorno
// Dominio: Nao possui dominio
function setSelectedValue(combo,valor){
	for(i=0; i<=(combo.options.length-1); i++){
		if(combo.options[i].value == valor){
			combo.options[i].selected = true;
		}
	}
}

// Da um refresh na pagina a partir de um combo
// Tipo de retorno: Nao possui retorno
// Dominio: Nao possui dominio
function refreshPage(combo, pagina){
	combo.value = getSelectedValue(combo);
	combo.form.action = pagina;
	combo.form.submit();
}

// Impede a digitacao de mais de X caracteres em um campo 
// Utilizado pelos eventos onchange="CheckLen(this)" onfocus="CheckLen(this)" onkeydown="CheckLen(this)" onkeyup="CheckLen(this)"
// Tipo de retorno: Nao possui retorno
// Dominio: Nao possui dominio
function checkLen(target,maxChars){
	StrLen = target.value.length;
        if (StrLen > maxChars) {
		target.value = target.value.substring(0,maxChars);
                CharsLeft = 0;
		alert('Quantidade de caracteres excedida.\nO maximo permitido é de ' + maxChars + ' caracteres.');
		target.focus();
        }
}

// Obtem o valor de um radio button selecionado
// Tipo de retorno: STRING
// Dominio: Valor contido no value do radio button selecionado
function getRadioValue(campo){
	chk = "";
        for(i=0; i<campo.length;i++) {
		if(campo[i].checked == true) {
			chk = campo[i].value;
                        break;
                }
        }
        return chk;
}

// Verifica se ao menos um objeto esta selecionado. Pode ser utilizado para objetos tipo radiobutton ou checkbox
// Tipo de retorno: BOOLEAN
// Dominio: [true | false]
function isSelectedObject(objeto){
	var i;
	result = false;
	if(objeto.length > 0){
		for(i=0; i<objeto.length; i++){
			if(objeto[i].checked == true){
				result = true;
				break;
			}
		}
	}
	else{
		result = objeto.checked;
	}
	return result;
}

// Verifica se no maximo foi selecionado X itens. Pode ser utilizado para objetos tipo radiobutton ou checkbox
// Tipo de retorno: BOOLEAN
// Dominio: [true | false]
function isMaxSelectedObject(objeto,max){
	var i;
	var selectedCount = 0;
	result = false;
	if(objeto.length > 0){
		for(i=0; i<objeto.length; i++){
			if(objeto[i].checked == true){
				selectedCount += 1;
			}
		}
	}
	if(selectedCount <= max) return true;
	else return false;
}

// Verifica se o status do objeto checkbox esta TRUE ou FALSE, no caso de estar FALSE,
// coloca todos os objetos radiobutton ou checkbox dependentes (visao de negocio) como FALSE
// Tipo de retorno: Nao possui retorno
// Dominio: [true | false]
function changeDependenceFields(objeto,dependente){
	var i;
	if((objeto.checked == false) && (isSelectedObject(dependente))){
		for(i=0; i<dependente.length; i++){
			if(dependente[i].checked == true){
				dependente[i].checked = false;
			}
		}
	}
}

// Verifica se tem alguma vogal acentuada na string
// Tipo de retorno: BOOLEAN
// Dominio: [true | false]
function isAccentedVowel(campo){ 
	ls = campo.toLowerCase(); 
        if ((ls.indexOf("a")>=0) || (ls.indexOf("à")>=0) || (ls.indexOf("a")>=0) || (ls.indexOf("â")>=0) || (ls.indexOf("é")>=0) || (ls.indexOf("i")>=0) || (ls.indexOf("ó")>=0) || (ls.indexOf("õ")>=0) || (ls.indexOf("ô")>=0) || (ls.indexOf("ú")>=0) || (ls.indexOf("ü")>=0))
        	return true; 
}

// Verifica se o e-mail informado e valido
// Tipo de retorno: BOOLEAN
// Dominio: [true | false]
function isMail(email){ 
	var s = new String(email);
	var retorno = true;
        // Verifica se existe caracteres como: { } ( ) < > [ ] | \ / 
        if ((s.indexOf("{")>=0) || (s.indexOf("}")>=0) || (s.indexOf("(")>=0) || (s.indexOf(")")>=0) || (s.indexOf("<")>=0) || (s.indexOf(">")>=0) || (s.indexOf("[")>=0) || (s.indexOf("]")>=0) || (s.indexOf("|")>=0) || (s.indexOf("\"")>=0) || (s.indexOf("/")>=0) ) 
        	retorno = false; 
        if (isAccentedVowel(email)) 
		retorno = false; 
        // Verifica se existe caracteres como: & * $ % ? ! ^ ~ ` ' " 
	if ((s.indexOf("&")>=0) || (s.indexOf("*")>=0) || (s.indexOf("$")>=0) || (s.indexOf("%")>=0) || (s.indexOf("?")>=0) || (s.indexOf("!")>=0) || (s.indexOf("^")>=0) || (s.indexOf("~")>=0) || (s.indexOf("`")>=0) || (s.indexOf("'")>=0) ) 
		retorno = false; 
	// Verifica se existe caracteres como: , ; : = # 
        if ((s.indexOf(",")>=0) || (s.indexOf(";")>=0) || (s.indexOf(":")>=0) || (s.indexOf("=")>=0) || (s.indexOf("#")>=0) ) 
        	retorno = false; 
        // Verifica se existe caracteres como: @ 
	if ( (s.indexOf("@") < 0) || (s.indexOf("@") != s.lastIndexOf("@")) ) {
		retorno = false; 
        }
        else{
		indice_tmp = s.indexOf("@");
           	proximo_char = email.charAt(indice_tmp + 1);
           	if (proximo_char == "." ){
			retorno = false;
           	}
        }
        // Verifica se existe caracteres como: . (ponto) apos o @
        if (s.lastIndexOf(".") < s.indexOf("@")) 
		retorno = false;
        return retorno; 
}

// Retira espacos em branco (desnecessarios) de uma string
// Tipo de retorno: STRING
// Dominio: String sem espacos em branco desnecessarios
function trim(campo){
	for (var i=0; i<campo.length; i++) {
		if (campo.charAt(i)!=" ") {
			campo = campo.substring(i,(campo.length));
                        break;
		}
                else if(i == campo.length-1){
			return "";
		}
	}
        for (var i=(campo.length)-1; i>=0; i--) {
		if (campo.charAt(i)!=" ") {
			campo = campo.substring(0,i+1);
                        break;
		}
	}
        return campo;
}

// Compara o conteudo de um textbox com outro
// Tipo de retorno: BOOLEAN
// Dominio: [true | false]
function isEquals(campo1,campo2){
	if((isNull(campo1)) && (isNull(campo2))){
		return false;
	}
	else{
		if((trim(campo1)) == (trim(campo2))){
			return true;
		}
		else{
			return false;
		}
	}
}

// Verifica se o valor passado como parâmetro é um número
// Tipo de retorno: BOOLEAN
// Dominio: [true | false]
function isNumber(number){
	answer = true;
        for (var i=0; i<number.length; i++) {
		if (!parseFloat(number.charAt(i))) {
			if(number.charAt(i) != "0") {
				answer = false;
                                break;
                        }
		}
	}
        return answer;
}

// Verifica se a data informada é correta
// Tipo de retorno: BOOLEAN
// Dominio: [true | false]
function isValidDate(day,month,year){

	 day   = "0" + day;
	 month = "0" + month;
	 
	 
	 day = day.substring(day.length-2,day.length);
	 month = month.substring(month.length-2,month.length);
	 
	 
	
	
	if (year < 1850) {
		return false;
	}

	// se o parametro vier no primeiro campo como dd/mm/aaaa
	if((day.length != 2) || (month.length != 2) || (year.length != 4)){
		return false;
	}
	
	if((!isNumber(day)) || (!isNumber(month)) || (!isNumber(year))){
		return false;
	}
	
        if (month=="undefined"){
                if (day.length!=10){
			return false;
		}
                year  = day.charAt(6) + day.charAt(7) + day.charAt(8) + day.charAt(9);
                month = day.charAt(3) + day.charAt(4);
                day   = day.charAt(0) + day.charAt(1);
        }
		
	if (month == "02"){
                var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
                if (day>29 || (day==29 && !isleap)){
			return false;
		}
        }

        if ((day > "31") || (month > "12")){
		return false;
	}
        if ((month == "04") || (month == "06") || (month == "09") || (month == "11")){
                if(day == "31"){
			return false;
		}
                else{
			return true;
		}
        }
        else{
		return true;
	}
}

// Verifica se a data informada é correta
// Tipo de retorno: BOOLEAN
// Dominio: [true | false]
function isDate(data){
	if((!isNull(data)) && (data.indexOf("/") >= 0)){
		var arData = data.split("/");
		if(arData.length != 3){
			return false;
		}
		else{
			return isValidDate(arData[0],arData[1],arData[2]);
		}
	}
	else{
		return false;
	}
}

// Verifica se o valor passado como parâmetro contém somente texto e baseado
// no parâmetro critica o case sensitive
// Tipo de retorno: BOOLEAN
// Dominio: [true | false]
function isUnaccentedText(text,caseType,separator){
	var result 			= true;
	var firstUpperChar 		= new String("A");
	var lastUpperChar 		= new String("Z");
	var firstLowerChar 		= new String("a");
	var lastLowerChar		= new String("z");
	var separatorChar		= new String(" ");
	for(var i=0; i<text.length; i++){
		if(isNumber(text.charAt(i))){
			result = false;
			break;
		}
		else{
			if(!isNull(caseType)){
				if(caseType.toLowerCase() == "upper"){
					if((text.charCodeAt(i) < firstUpperChar.charCodeAt()) || (text.charCodeAt(i) > lastUpperChar.charCodeAt())) {
						if(separator){
							if((text.charCodeAt(i)) != (separatorChar.charCodeAt())){
								result = false;
								break;
							}
						}
						else{
							result = false;
							break;
						}
					}
				}
				else if(caseType.toLowerCase() == "lower"){
					if((text.charCodeAt(i) < firstLowerChar.charCodeAt()) || (text.charCodeAt(i) > lastLowerChar.charCodeAt())){
						if(separator){
							if((text.charCodeAt(i)) != (separatorChar.charCodeAt())){
								result = false;
								break;
							}
						}
						else{
							result = false;
							break;
						}
					}
				}
			}
		}
	}
	return result;
}

// Abre uma nova janela no estilo popup com url,largura e altura definidos pelo usuario
// Tipo de retorno: Nao possui retorno
// Dominio: Nao possui dominio
function openWindow(pagina,largura,altura){
	window.open(pagina,"Imagen","width=" + largura + ",height=" + altura + ",toolbar=0,status=0,menubar=0,scrollbars=1,directories=0"); 
}

// Emite uma pergunta para o usuario onde ele opta por OK ou Cancelar e retorna o resultado
// Exemplo de chamada: <a href="excluir.jsp?id=2" onclick="return checkClick(this,'Confirma exclusao?')">excluir</a>
// Tipo de retorno: BOOLEAN
// Dominio: [true | false]
function checkClick(link,text){
	var isconfirmed = confirm(text);
	if(isconfirmed){
		link.href += '&opt=1'; 
	}
	return isconfirmed; 
}

// Verifica se CPF e valido através de checagem do DV (nao utilizar ifem)
// Tipo de retorno: BOOLEAN
// Dominio: [true | false]
function isCPF(CPF){ 
	if (CPF.length != 11 		|| CPF == "00000000000" 	|| CPF == "11111111111" || 
		CPF == "22222222222" 	|| CPF == "33333333333" 	|| CPF == "44444444444" || 
		CPF == "55555555555" 	|| CPF == "66666666666" 	|| CPF == "77777777777" || 
		CPF == "88888888888" 	|| CPF == "99999999999"){
		return false;
	}
	soma = 0; 
	for (i=0; i < 9; i ++){
		soma += parseInt(CPF.charAt(i)) * (10 - i);
	}
	resto = 11 - (soma % 11); 
	if (resto == 10 || resto == 11){
		resto = 0;
	}
	if (resto != parseInt(CPF.charAt(9))){
		return false;
	}
	soma = 0; 
	for (i = 0; i < 10; i ++){
		soma += parseInt(CPF.charAt(i)) * (11 - i);
	}
	resto = 11 - (soma % 11); 
	if (resto == 10 || resto == 11){
		resto = 0;
	}
	if (resto != parseInt(CPF.charAt(10))){
		return false;
	}
	return true; 
}

//DescriCao: Funcao para barra que seja digitado um conteudo invalido no campo 
//intervalo = 'A..Z' ou se tiver mais de um, faz-se: 'A..Z;a..z' 
//caracter = '-/@!$' 
//ex.: <input type="text" name="questao1[]" size="1" onkeypress="JavaScript:checkCharsEntry('1..5','NULL');">
// Tipo de retorno: Nao possui retorno
// Dominio: Nao possui dominio
function checkCharsEntry(intervalo,caracter){
	var bvalido = false; 
	if(((caracter.toUpperCase) != 'NULL') || (caracter != '')){
		if(caracter == "PONTUACAO"){
			caracter = 'aaâéêiîõóôúûCÃÁÂÉÊÍÎÕÓÔÚÛC ';
			for(i=0;i<=(caracter.length);i++){
				if((event.keyCode) == (caracter.charCodeAt(i))){ 
					bvalido = true; 
				}
			}
		}
		if(!bvalido){ 
			var Inicio 		= "";
			var Fim    		= "";
			var bRetornaFalso  	= false;
			var bEncontrou  	= false;
			var location   		= -1;
			location = intervalo.indexOf(";");
			if((location) > -1){
				var restricoes = intervalo.split(";");
				for(i=0;i<=(restricoes.length-1);i++){
					Inicio  = restricoes[i].substring(0,1);
					Fim  	= restricoes[i].substring(3,4);
					if((event.keyCode >= Inicio.charCodeAt()) && (event.keyCode <= Fim.charCodeAt())){ //48 57
						bEncontrou = true; 
						i = restricoes.length; 
					} 
				} 
				if(!bEncontrou){
					bRetornaFalso = true; 
				}
			}
			else if(intervalo.length == 4){
				Inicio  = intervalo.substring(0,1);
				Fim  = intervalo.substring(3,4);
				if((event.keyCode >= Inicio.charCodeAt()) && (event.keyCode <= Fim.charCodeAt())){ //48 57
					bEncontrou = true;
				}
				if(!bEncontrou){
					bRetornaFalso = true;
				}
			}
			if(bRetornaFalso){
				event.returnValue = false;
			}
		}
	}
}


//Descricao: Funcao para validar hora/minuto 
// Tipo de retorno: BOOLEAN
// Dominio: [true | false]
function checkHora(campoH,campoM){
	if ((parseInt(campoH) >= 0 && parseInt(campoH) < 24) && (parseInt(campoM) >=0 && parseInt(campoM) < 60)){ 
    return true;
  } else {
    return false;
  }
}

