// ---------------------------------------------

// Mindnet Informática                 	

// Projeto Biblioteca de Funções de JavaScript 	

// Data de criação: 19/09/2004          	

// Última modificação: 19/09/2004       	

// Programação: João Carlos  			

// Ultima atualização: João Carlos		

// ---------------------------------------------

// -----[ FUNÇÕES 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- goToNextField(objeto,tamanho)		

// 24- getIndex(input)	

// 25- openWindowNScroll(pagina,largura,altura)			

// ---------------------------------------------



// Verifica se um campo está vazio pegando inclusive espaço em branco

// Tipo de retorno: BOOLEAN

// Domínio: [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

// Domínio: 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

// Domínio: 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 ítem dentro de um combo

// Tipo de retorno: Não possui retorno

// Domínio: Não possui domínio

function setSelectedValue(combo,valor){

	for(i=0; i<=(combo.options.length-1); i++){

		if(combo.options[i].value == valor){

			combo.options[i].selected = true;

		}

	}

}



// Dá um refresh na página à partir de um combo

// Tipo de retorno: Não possui retorno

// Domínio: Não possui domínio

function refreshPage(combo, pagina){

	combo.value = getSelectedValue(combo);

	combo.form.action = pagina;

	combo.form.submit();

}



// Impede a digitação 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: Não possui retorno

// Domínio: Não possui domínio

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 máximo permitido é de ' + maxChars + ' caracteres.');

		target.focus();

        }

}



// Obtem o valor de um radio button selecionado

// Tipo de retorno: STRING

// Domínio: 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 está selecionado. Pode ser utilizado para objetos tipo radiobutton ou checkbox

// Tipo de retorno: BOOLEAN

// Domínio: [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;

}



// Coloca um checkbox ou radiobutton selecionados

// Tipo de retorno: Não possui retorno

// Domínio: Não possui domínio

function setSelectedObject(objeto, relacao){

	var i;

	var j;

	for(i=0; i<objeto.length; i++){

		objeto[i].checked = false;

		break;

	}

	if(relacao.indexOf(',') >= 0){

		array_aux = relacao.split(',');

		for(i=0; i<array_aux.length; i++){

			for(j=0; j<objeto.length; j++){

				if((objeto[j].checked == false) && (objeto[j].value == array_aux[i])){

					objeto[j].checked = true;

					break;

				}

			}

		}

	} else {

		for(i=0; i<objeto.length; i++){

			if((objeto[i].checked == false) && (objeto[i].value == relacao)){

				objeto[i].checked = true;

				break;

			}

		}

	}

}



// Verifica se no máximo foi selecionado X ítens. Pode ser utilizado para objetos tipo radiobutton ou checkbox

// Tipo de retorno: BOOLEAN

// Domínio: [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 está TRUE ou FALSE, no caso de estar FALSE,

// coloca todos os objetos radiobutton ou checkbox dependentes (visão de negócio) como FALSE

// Tipo de retorno: Não possui retorno

// Domínio: [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

// Domínio: [true | false]

function isAccentedVowel(campo){ 

	ls = campo.toLowerCase(); 

        if ((ls.indexOf("á")>=0) || (ls.indexOf("à")>=0) || (ls.indexOf("ã")>=0) || (ls.indexOf("â")>=0) || (ls.indexOf("é")>=0) || (ls.indexOf("í")>=0) || (ls.indexOf("ó")>=0) || (ls.indexOf("õ")>=0) || (ls.indexOf("ô")>=0) || (ls.indexOf("ú")>=0) || (ls.indexOf("ü")>=0))

        	return true; 

}



// Verifica se o e-mail informado é válido

// Tipo de retorno: BOOLEAN

// Domínio: [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) após o @

        if (s.lastIndexOf(".") < s.indexOf("@")) 

		retorno = false;

        return retorno; 

}



// Retira espaços em branco (desnecessários) de uma string

// Tipo de retorno: STRING

// Domínio: String sem espaços em branco desnecessários

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 conteúdo de um textbox com outro

// Tipo de retorno: BOOLEAN

// Domínio: [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

// Domínio: [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

// Domínio: [true | false]

function isValidDate(day,month,year){

	// 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

// Domínio: [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

// Domínio: [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 usuário

// Tipo de retorno: Não possui retorno

// Domínio: Não possui domínio

function openWindow(pagina,largura,altura){

	window.open(pagina,"Imagen","width=" + largura + ",height=" + altura + ",toolbar=0,status=0,menubar=0,scrollbars=1,directories=0"); 

}



// Abre uma nova janela sem scroll no estilo popup com url,largura e altura definidos pelo usuário

// Tipo de retorno: Não possui retorno

// Domínio: Não possui domínio

function openWindowNScroll(pagina,largura,altura){

	window.open(pagina,"Imagen","width=" + largura + ",height=" + altura + ",toolbar=0,status=0,menubar=0,scrollbars=0,directories=0"); 

}



// Emite uma pergunta para o usuário 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 exclusão?')">excluir</a>

// Tipo de retorno: BOOLEAN

// Domínio: [true | false]

function checkClick(link,text){

	var isconfirmed = confirm(text);

	if(isconfirmed){

		link.href += '&opt=1'; 

	}

	return isconfirmed; 

}



// Verifica se CPF é válido através de checagem do DV (não utilizar ífem)

// Tipo de retorno: BOOLEAN

// Domínio: [true | false]

function isCPF(CPF){ 

	CPF.replace('\.','');

	CPF.replace('\-','');

	

	alert(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; 

}



//Descrição: Função para barra que seja digitado um conteúdo inválido 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: Não possui retorno

// Domínio: Não possui domínio

function checkCharsEntry(intervalo,caracter){

	var bvalido = false; 

	if(((caracter.toUpperCase) != 'NULL') || (caracter != '')){

		if(caracter == "PONTUACAO"){

			caracter = 'ãáâéêíîõóôúûçÃÁÂÉÊÍÎÕÓÔÚÛÇ ';

			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;

			}

		}

	}

}



// Auto-Tab (Ex.: onKeyUp="goToNextField(this,2)")

// Tipo de retorno: Não possui retorno

// Domínio: Não possui dominio

function goToNextField(objeto,tamanho){

	if(objeto.value.length == tamanho){

		objeto.form[(getIndex(objeto)+1)].focus();

	}

}



// Recupera o indice de um objeto dentro de um form

// Tipo de retorno: INTEGER

// Domínio: Indice do objeto

function getIndex(input) {

	var index = -1, i = 0, found = false;

	while (i < input.form.length && index == -1)

	if (input.form[i] == input)index = i;

	else i++;

	return index;

}



// Modifica a gif de uma imagem ON para uma imagem OFF ou de uma imagem OFF para uma imagem ON

// dependendo da imagem que estiver setada no momento

// Tipo de retorno: Não possui retorno

// Domínio: Não possui domínio

function setImageOnToImageOff(img_target,img_on,img_off){

	var str = img_target.src;

	if(str != ''){

		var lastIndexOfFileSeparator = str.lastIndexOf('/');

		var lastIndexOfUrlSeparator  = str.lastIndexOf('\\');

		var lastUsableIndexOf = 0;

		var webServerPathImage = '';

		var fileNameImage = '';

		

		if((lastIndexOfFileSeparator != -1) && (lastIndexOfFileSeparator > lastIndexOfUrlSeparator)){

		    	lastUsableIndexOf = lastIndexOfFileSeparator;

		} else if((lastIndexOfUrlSeparator != -1) && (lastIndexOfFileSeparator < lastIndexOfUrlSeparator)){

		    	lastUsableIndexOf = lastIndexOfUrlSeparator;

		}

		

		webServerPathImage = str.substr(0,(lastUsableIndexOf + 1));

		fileNameImage = str.substr((lastUsableIndexOf + 1));

		

		if(fileNameImage == imageOn){

			img_target.src = webServerPathImage + img_off;

		} else {

			img_target.src = webServerPathImage + img_on;

		}

	}

}



// Modifica a gif de uma imagem para outra especificada

// Tipo de retorno: Não possui retorno

// Domínio: Não possui domínio

function setNewImage(img_target, new_image){

	var str = img_target.src;

	if(str != ''){

		var lastIndexOfFileSeparator = str.lastIndexOf('/');

		var lastIndexOfUrlSeparator  = str.lastIndexOf('\\');

		var lastUsableIndexOf = 0;

		var webServerPathImage = '';

		var fileNameImage = '';

		

		if((lastIndexOfFileSeparator != -1) && (lastIndexOfFileSeparator > lastIndexOfUrlSeparator)){

		    	lastUsableIndexOf = lastIndexOfFileSeparator;

		} else if((lastIndexOfUrlSeparator != -1) && (lastIndexOfFileSeparator < lastIndexOfUrlSeparator)){

		    	lastUsableIndexOf = lastIndexOfUrlSeparator;

		}

		

		webServerPathImage = str.substr(0,(lastUsableIndexOf + 1));

		fileNameImage = str.substr((lastUsableIndexOf + 1));

		

		img_target.src = webServerPathImage + new_image;

	}

}






function checkDomain(nname)
{
var arr = new Array(
'.com','.net','.org','.biz','.coop','.info','.museum','.name',
'.pro','.edu','.gov','.int','.mil','.ac','.ad','.ae','.af','.ag',
'.ai','.al','.am','.an','.ao','.aq','.ar','.as','.at','.au','.aw',
'.az','.ba','.bb','.bd','.be','.bf','.bg','.bh','.bi','.bj','.bm',
'.bn','.bo','.br','.bs','.bt','.bv','.bw','.by','.bz','.ca','.cc',
'.cd','.cf','.cg','.ch','.ci','.ck','.cl','.cm','.cn','.co','.cr',
'.cu','.cv','.cx','.cy','.cz','.de','.dj','.dk','.dm','.do','.dz',
'.ec','.ee','.eg','.eh','.er','.es','.et','.fi','.fj','.fk','.fm',
'.fo','.fr','.ga','.gd','.ge','.gf','.gg','.gh','.gi','.gl','.gm',
'.gn','.gp','.gq','.gr','.gs','.gt','.gu','.gv','.gy','.hk','.hm',
'.hn','.hr','.ht','.hu','.id','.ie','.il','.im','.in','.io','.iq',
'.ir','.is','.it','.je','.jm','.jo','.jp','.ke','.kg','.kh','.ki',
'.km','.kn','.kp','.kr','.kw','.ky','.kz','.la','.lb','.lc','.li',
'.lk','.lr','.ls','.lt','.lu','.lv','.ly','.ma','.mc','.md','.mg',
'.mh','.mk','.ml','.mm','.mn','.mo','.mp','.mq','.mr','.ms','.mt',
'.mu','.mv','.mw','.mx','.my','.mz','.na','.nc','.ne','.nf','.ng',
'.ni','.nl','.no','.np','.nr','.nu','.nz','.om','.pa','.pe','.pf',
'.pg','.ph','.pk','.pl','.pm','.pn','.pr','.ps','.pt','.pw','.py',
'.qa','.re','.ro','.rw','.ru','.sa','.sb','.sc','.sd','.se','.sg',
'.sh','.si','.sj','.sk','.sl','.sm','.sn','.so','.sr','.st','.sv',
'.sy','.sz','.tc','.td','.tf','.tg','.th','.tj','.tk','.tm','.tn',
'.to','.tp','.tr','.tt','.tv','.tw','.tz','.ua','.ug','.uk','.um',
'.us','.uy','.uz','.va','.vc','.ve','.vg','.vi','.vn','.vu','.ws',
'.wf','.ye','.yt','.yu','.za','.zm','.zw');

var mai = nname;
var val = true;

var dot = mai.lastIndexOf(".");
var dname = mai.substring(0,dot);
var ext = mai.substring(dot,mai.length);
//alert(ext);
	
if(dot>2 && dot<57)
{
	for(var i=0; i<arr.length; i++)
	{
	  if(ext == arr[i])
	  {
	 	val = true;
		break;
	  }	
	  else
	  {
	 	val = false;
	  }
	}
	if(val == false)
	{
	  	 alert("A extensão "+ext+" não é válida. Certifique-se de digitar tudo em minúsculas.");
		 return false;
	}
	else
	{
		for(var j=0; j<dname.length; j++)
		{
		  var dh = dname.charAt(j);
		  var hh = dh.charCodeAt(0);
		  if((hh > 47 && hh<59) || (hh > 64 && hh<91) || (hh > 96 && hh<123) || hh==45 || hh==46)
		  {
			 if((j==0 || j==dname.length-1) && hh == 45)	
		  	 {
		 	  	 alert("Domínios não podem iniciar com '-'");
			      return false;
		 	 }
		  }
		else	{
		  	 alert("O domínio não pode conter caracteres especiais.");
			 return false;
		  }
		}
	}
}
else
{
 alert("O domínio informado é muito longo ou curto.");
 return false;
}	

return true;
}



