/*
+ --------------------------------------------------------------------- +
| OBJETIVO: Função que abre uma janela parametrizada no centro da tela. |
+ ------------ + ------------------------------------------------------ +
| PARAMETROS   | DESCRIÇÃO 						    			   		|
+ ------------ + ------------------------------------------------------ +
| mypage	   | Arquivo a ser aberto na janela.						|
+ ------------ + ------------------------------------------------------ +
| myname	   | Nome da janela.										|
+ ------------ + ------------------------------------------------------ +
| largura      | Seta o atributo width da janela (valor em pixel)		|
+ ------------ + ------------------------------------------------------ +
| altura       | Seta o atributo height da janela (valor em pixel)		|
+ ------------ + ------------------------------------------------------ +
| local		   | Seta o atributo location da janela						|
+ ------------ + ------------------------------------------------------ +
| menu		   | Seta o atributo menubar da janela						|
+ ------------ + ------------------------------------------------------ +
| resize	   | Seta o atributo resizable da janela					|
+ ------------ + ------------------------------------------------------ +
| scroll	   | Seta o atributo scrollbars da janela					|
+ ------------ + ------------------------------------------------------ +
| stat		   | Seta o atributo statusbar da janela					|
+ ------------ + ------------------------------------------------------ +
| tool		   | Seta o atributo toolbar da janela						|
+ ------------ + ------------------------------------------------------ +
*/
function PoupUp(mypage, myname, largura, altura, local, menu, resize, scroll, stat, tool)
{
	var winl = (screen.width - largura) / 2;
	var wint = (screen.height - altura) / 2;

	winprops = 'height='+altura+', width='+largura+', top='+wint+', left='+winl+', scrollbars='+scroll+', resizable='+resize+', location='+local+', menubar='+menu+', statusbar='+stat+', toolbar='+tool+''
	
	if(!window.werror)
		win = window.open(mypage, myname, winprops);

	if (parseInt(navigator.appVersion) >= 4) {win.window.focus();}
}


// Função que seta o campo action de um formulário com um valor e depois submete o formulário.
function setActionSubmit(formName, urlDest)
{
	document.forms[formName].action=urlDest;
	document.forms[formName].submit();
}


// Função que move o foco do cursor para o primeiro elemento do primeiro formulário.
function putFocus(formInst, elementInst)
{
	if(formInst && elementInst)
	{
		if (document.forms.length > 0)	{ document.forms[formInst].elements[elementInst].focus(); }	
	}
}


// Função utilizada para fechar uma janela do browser no tempo especificado.
function close_automatic(sec)
{
	var time = sec; // time in secs
	var real = time * 1000;
	
	setTimeout("window.close();",real);
}


// Função que marca e desmarca todos os itens de uma lista de checkbox.
var checkflag = "false";

function CheckAll(formName)
{
	for (var i = 0; i < document.forms[formName].elements.length; i++)
	{
		if(document.forms[formName].elements[i].type == 'checkbox')
		{
		  document.forms[formName].elements[i].checked = !(document.forms[formName].elements[i].checked);
		}
	}

	if (checkflag == "false")
	{
		checkflag = "true";

		return "DESMARCAR TODAS";
	}
	else
	{
		checkflag = "false";
	
		return "MARCAR TODAS";
	}
}


// Função para a passagem de foco quando o n. de caracteres é igual ao maxlength do campo.
var isNN = (navigator.appName.indexOf("Netscape") != -1);

function autoTab(input,len, e)
{
	var keyCode = (isNN) ? e.which : e.keyCode; 
	var filter  = (isNN) ? [0, 8, 9] : [0, 8, 9, 16, 17, 18, 37, 38, 39, 40, 46];

	if(input.value.length >= len && !containsElement(filter, keyCode))
	{
		input.value = input.value.slice(0, len);
		input.form[(getIndex(input) + 1) % input.form.length].focus();
	}

	function containsElement(arr, ele)
	{
		var found = false, index = 0;

		while(!found && index < arr.length)
			if(arr[index] == ele)	{ found = true; }
			else					{ index++; }

		return found;
	}

	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;
	}

	return true;
}





/*
+-------------------------------------------+
| Funções de Auto Completition e Formatação |
+-------------------------------------------+
*/

// Função que auto completa CPF.
function CompleteCPF(campo)
{
	var cgc = campo.value;

	if(cgc.length == 3 || cgc.length == 7)	{campo.value += '.';}
	if(cgc.length == 11)					{campo.value += '-';}
}


// Função que auto completa CNPJ.
function CompleteCNPJ(campo)
{
	var cnpj = campo.value;

	if(cnpj.length == 2 || cnpj.length == 6)	{campo.value += '.';}
	if(cnpj.length == 10)					    {campo.value += '/';}
	if(cnpj.length == 15)					    {campo.value += '-';}
}


// Função que auto completa CEP.
function CompleteCEP(campo)
{
	var cep = campo.value;
	
	if(cep.length == 5)	{campo.value += '-';}
}


// Função que auto completa datas inserindo barras.
function CompleteDate(tipo, campo)
{
	var data = campo.value;

	if(tipo == "TIME1") {
		if(data.length == 2)    {campo.value += ':';}		
	}
	else {
		if(tipo == "TIME2") {
			if(data.length == 3 || data.length == 6)    {campo.value += ':';}			
		}
		else {
			if(data.length == 2 || data.length == 5)    {campo.value += '/';}
			
			if(tipo == "DATETIME") {
		
				if(data.length == 10)    {campo.value += ' ';}
				if(data.length == 13)    {campo.value += ':';}	
			}
		}
	}
}


// Função que valida campo numérico e formata o valor
function ChkNumber(campo, status, nDec)
{
	var numero, digitos = "0123456789,.", flag = true, virgula = false;

	if(campo.value != "")
	{
		numero = campo.value;
		numero = numero.toString();
		numero = numero.replace(/[.]/g,"");

		// VALIDANDO O VALOR
		if(numero.length <= 12)
		{
			if((digitos.indexOf(numero.charAt(0)) > 1) || (digitos.indexOf(numero.charAt(0)) < 9))
			{
				for(var i = 1; ((i < numero.length) && (flag)); i++)
				{
					if(digitos.indexOf(numero.charAt(i)) < 0)    { flag = false; }
					if(digitos.indexOf(numero.charAt(i)) == 10)
					{
						if (((numero.length-i) <= (nDec + 1)) && (!virgula)) { virgula = true; }
						else    { flag = false; }
					}
				}
			}
			else { flag = false; }
		}
		else    { flag = false; }

		
		// FORMATANDO O VALOR
		if(flag)
		{ 
		  valor = PutCents(numero, nDec);
		  campo.value = PutMilion(valor, nDec); 
		}
		else
		{
			alert( "Valor digitado não é válido: " + numero);

			campo.value = "";
			campo.select();
		}
	}
	else    { flag = false; }

	if (status)    { return flag; }
}


// Função que insere as casas decimais em um campo numérico
function PutCents(numero, nDec)
{
	var i = 0;

	numero = numero.toString();
	numero = numero.replace(/[.]/g,",");

	while ((numero.charAt(i) != ",") && (i < numero.length)) { i++; }

	if ((numero.length - i) > nDec)    { numero = numero.substr(0, i + (nDec + 1)); }
	else if(nDec == 2)
	{
		switch (numero.length - i)
		{
			case 0: numero += ",00"; break;
			case 1: numero += "00"; break;
			case 2: numero += "0"; break;
		}
	}
	else
	{
		switch (numero.length - i)
		{
			case 0: numero += ",000"; break;
			case 1: numero += "000"; break;
			case 2: numero += "00"; break;
			case 3: numero += "0"; break;
		}
	}

	return(numero);
}


// Função que insere os pontos de milhares num campo numérico
function PutMilion(numero, nDec)
{
	var i = 0;

	numero = numero.toString();
	numero = numero.replace(/[.]/g,"");
	numero = numero.replace(/[,]/g,"");

	tamanho = numero.length;

	numerosemdecimais = numero.substring(0, tamanho - nDec);
	tamanhosemdecimais = tamanho - nDec;
	decimais = numero.substring(tamanho - nDec, tamanho);
	numeropontosdecimais = parseInt((tamanho - nDec) / 3);
	numero2 = "";

	for(i = 0; i < numeropontosdecimais * 3; i += 3)
		numero2 = "." + numerosemdecimais.substring(tamanhosemdecimais - i - 3, tamanhosemdecimais - i) + numero2;

	numero2 = numerosemdecimais.substring(0, tamanhosemdecimais - i) + numero2;
	numero2 = numero2 + "," + decimais;

	if(numero2.substr(0,1) == '.')
	{
		tamanho = numero2.length;
		numero2 = numero2.substr(1, tamanho - 1);
	}

	return (numero2);
}


// Formata valores utilizando duas casas decimais.
function Format2Dec(field, milSep, decSep, e)
{
	var strCheck = '0123456789';
	var key = aux = aux2 = '';
	var i = j = sep = len = len2 = 0;

	var whichCode = (window.Event) ? e.which : e.keyCode;

	if (whichCode == 13)    { return true; }  // Enter

	key = String.fromCharCode(whichCode);  // Get key value from key code

	if (strCheck.indexOf(key) == -1)    { return false; }  // Not a valid key

	len = field.value.length;

	for(i = 0; i < len; i++)
	{
		if ((field.value.charAt(i) != '0') && (field.value.charAt(i) != decSep))    { break; }
	}

	aux = '';

	for(; i < len; i++)
	{
		if (strCheck.indexOf(field.value.charAt(i)) != -1)    { aux += field.value.charAt(i); }
	}

	aux += key;
	len = aux.length;

	if (len == 0) field.value = '';
	if (len == 1) field.value = '0' + decSep + '0' + aux;
	if (len == 2) field.value = '0' + decSep + aux;

	if (len > 2)
	{
		aux2 = '';

		for (j = 0, i = len - 3; i >= 0; i--)
		{
			if (j == 3)
			{
				aux2 += milSep;
				j = 0;
			}
	
			aux2 += aux.charAt(i);
			j++;
		}

		field.value = '';
		len2 = aux2.length;

		for (i = len2 - 1; i >= 0; i--)    { field.value += aux2.charAt(i); }

		field.value += decSep + aux.substr(len - 2, len);
	}

	return false;
}


// Formata valores utilizando três casas decimais.
function Format3Dec(fld, milSep, decSep, e)
{
	var strCheck = '0123456789';
	var key = aux = aux2 = '';
	var sep = i = j = len = len2 = 0;

	var whichCode = (window.Event) ? e.which : e.keyCode;

	if (whichCode == 13)    { return true; }  // Enter

	key = String.fromCharCode(whichCode);  // Get key value from key code

	if (strCheck.indexOf(key) == -1)    { return false; }  // Not a valid key

	len = fld.value.length;

	for(i = 0; i < len; i++)
	{
		if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep))    { break; }
	}

	aux = '';

	for(; i < len; i++)
	{
		if (strCheck.indexOf(fld.value.charAt(i))!=-1)    { aux += fld.value.charAt(i); }
	}

	aux += key;
	len = aux.length;

	if (len == 0) fld.value = '';
	if (len == 1) fld.value = '0'+ decSep + '00' + aux;
	if (len == 2) fld.value = '0'+ decSep + '0' + aux;
	if (len == 3) fld.value = '0'+ decSep + aux;

	if (len > 3)
	{
		aux2 = '';
	
		for (j = 0, i = len - 4; i >= 0; i--)
		{
			if (j == 3)
			{
				aux2 += milSep;
				j = 0;
			}
	
			aux2 += aux.charAt(i);
			j++;
		}
	
		fld.value = '';
		len2 = aux2.length;
	
		for (i = len2 - 1; i >= 0; i--)    { fld.value += aux2.charAt(i); }

		fld.value += decSep + aux.substr(len - 3, len);
	}

	return false;
}





/*
+----------------------+
| Funções de Validação |
+----------------------+
*/

// Função para limitar o número de caracteres de um campo text de um formulário.
function textCounter(field, countfield, maxlimit)
{
	if (field.value.length > maxlimit) // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
	else // otherwise, update 'characters left' counter
		countfield.value = maxlimit - field.value.length;
}


// Função que abre uma janela de alert com um warning caso o usuário esteja com o CAPS Lock ligado.
function checkCapsLock( e )
{
	var myKeyCode = 0;
	var myShiftKey = false;
	var myMsg = 'CAPS LOCK LIGADO.\n\nTo prevent entering your password incorrectly,\nyou should press Caps Lock to turn it off.';

	if ( document.all ) // Internet Explorer 4+
	{
		myKeyCode  = e.keyCode;
		myShiftKey = e.shiftKey;
	}
	else if ( document.layers ) // Netscape 4
	{
		myKeyCode  = e.which;
		myShiftKey = ( myKeyCode == 16 ) ? true : false;
	}
	else if ( document.getElementById ) // Netscape 6
	{
		myKeyCode  = e.which;
		myShiftKey = ( myKeyCode == 16 ) ? true : false;
	}

	if ( ( myKeyCode >= 65 && myKeyCode <= 90 ) && !myShiftKey ) // Upper case letters are seen without depressing the Shift key, therefore Caps Lock is on
	{
		alert( myMsg );
	}
	else if ( ( myKeyCode >= 97 && myKeyCode <= 122 ) && myShiftKey ) // Lower case letters are seen while depressing the Shift key, therefore Caps Lock is on
	{
		alert( myMsg );
	}
}

// Função para filtragem de arquivos para upload.
extArray = new Array(".gif", ".jpg", ".png");

function LimitAttach(form, file)
{
	allowSubmit = false;
	
	if (!file) return;

	while (file.indexOf("\\") != -1)
		file = file.slice(file.indexOf("\\") + 1);
		ext = file.slice(file.indexOf(".")).toLowerCase();

	for (var i = 0; i < extArray.length; i++)
	{
		if (extArray[i] == ext) { allowSubmit = true; break; }
	}

	if (allowSubmit)	{ form.submit(); }
	else				{ alert("Please only upload files that end in types:  " + (extArray.join("  ")) + "\nPlease select a new " + "file to upload and submit again."); }
}