/**
 * Project: STpl
 * File: form.js
 *
 * Funções para formulários.
 *
 * @author Frederico Galvão <fredgalvao@gmail.com>
 * @Last-Modified: 07/09/2007 16:40
 * @Version: 1.0
 */



/**
 * Restringe a entrada de um campo a apenas dígitos.
 *
 * @param   obj e:  evento
 * @return  bool
 * -----------------------------------------------------
 * Exemplo:
 * <input type="text" id="numero" size="25" maxlength="10" onkeypress="return inputOnlyNumber( event );" />
 */
function inputOnlyNumber( e )
{
	var kCode;

	kCode = ( window.Event ) ? e.which : e.keyCode;

	if( kCode == 8 || kCode == 0 ) { // pressionando o Backspace, Home, End, Delete <-, -> ...
		return true;
	}
	
	if ( ( kCode < 48 || kCode > 57 ) ) {
		return false;
	}

	return true;
}


/**
 * Restringe a entrada de um campo ao alfabeto.
 *
 * @param   obj e:  evento
 * @return  bool
 * -----------------------------------------------------
 * Exemplo:
 * <input type="text" id="alfabeto" size="25" maxlength="10" onkeypress="return inputOnlyLetter( event );" />
 */
function inputOnlyLetter( e )
{
	var kCode;

	kCode = ( window.Event ) ? e.which : e.keyCode;

	if( kCode == 8 || kCode == 0 ) { // pressionando o Backspace, Home, End, Delete <-, -> ...
		return true;
	}

	if ( ( kCode < 65 || kCode > 122 ) ) {
		return false;
	}

	return true;
}


/**
 * Passa o foco para o próximo elemento 
 * quando o campo atingir a sua qtde. 
 * máxima de caracteres (maxlength).
 *
 * @param   obj elemt:  elemento do formulário
 * @param   obj e:      evento
 * @return  bool
 * -----------------------------------------------------
 * Exemplo:
 * <input type="text" id="codigo" size="25" maxlength="5" onkeyup="return autoTab( this, event );" />
 */
 function autoTab( elemt, e )
{
	var keyCode, elemtIk;
	var keyFilter = [ 0, 8, 9, 16, 17, 18, 20, 35, 36, 37, 38, 39, 40 ];
	var arrElemtType = [ 'checkbox', 'password', 'radio', 'text', 'select-one', 'select-multiple', 'textarea', 'file', 'submit', 'button' ];

	var formObj = elemt.form;
	var arrElemtNxt = [];

	if( ( elemt.maxLength == 2147483647 ) || ( elemt.maxLength == -1 ) ) { // atributo não foi definido.
		return true;
	}

	keyCode = (window.Event) ? e.which : e.keyCode;

	if( ( elemt.value.length >= elemt.maxLength ) && ( keyFilter.search( keyCode ) == -1 ) )
	{
		elemt.value = elemt.value.slice( 0, elemt.maxLength );

		for ( var i = 0; i < formObj.length; i++ )
		{
			var elemtForm = formObj.elements[i];

			if ( ( arrElemtType.search( elemtForm.type ) != -1 ) && !elemtForm.readOnly && !elemtForm.disabled )
			{
				if  ( i > elemtIk ) {
					formObj.elements[i].focus();
					
					return true;
				}

				arrElemtNxt.push( i );

				if ( elemtForm.id == elemt.id ) {
					elemtIk = i;
				}
			}
		}

		formObj.elements[ arrElemtNxt[0] ].focus();
	}

	return true;
}


/**
 * Completa automaticamente os marcadores de 
 * um número de telefone usando as máscaras: 
 * (NNN) NNNN-NNNN ou NNNN-NNNN.
 *
 * No momento em que o usuário preenche os números, 
 * os marcadores são adicionados ao seu valor.
 *
 * @param  obj elemt:  elemento do formulário
 * --------------------------------------------------
 * Instruções: 
 * --------------------------------------------------
 * Esta função deve ser utilizada na tag html 'onkeyup'.
 * É obrigatório o uso da função 'inputOnlyNumber' na 
 * tag 'onkeypress' para que os valores inputados pelo 
 * usuário sejam apenas numéricos.
 * --------------------------------------------------
 * Exemplo:
 * <input type="text" id="fone" size="25" maxlength="15" onkeyup="compPhone( this );" onkeypress="return inputOnlyNumber(event);" />
 */
function compPhone ( elemt )
{
	var numChars = elemt.value.length;

	if ( arguments.length != 2 ) // With AreaCode
	{
		if( numChars == 1 ) {
			elemt.value = '(' + elemt.value;
		}
		else if( numChars == 4 ) {
			elemt.value += ') ';
		}
		else if( numChars == 10 ) {
			elemt.value += '-';
		}
	}
	else {
		if( numChars == 4 ) {
			elemt.value += '-';
		}
	}
}


/**
 * Completa automaticamente os marcadores de 
 * um CEP usando a máscara NNNNN-NNN.
 *
 * No momento em que o usuário preenche os números, 
 * os marcadores são adicionados ao seu valor.
 *
 * @param  obj elemt:  elemento do formulário
 * --------------------------------------------------
 * Instruções: 
 * --------------------------------------------------
 * Esta função deve ser utilizada na tag html 'onkeyup'.
 * É obrigatório o uso da função 'inputOnlyNumber' na 
 * tag 'onkeypress' para que os valores inputados pelo 
 * usuário sejam apenas numéricos. O atributo 'maxlength' 
 * do campo deve ter o valor igual a 9.
 * --------------------------------------------------
 * Exemplo:
 * <input type="text" id="cep" size="25" maxlength="9" onkeyup="compCEP( this );" onkeypress="return inputOnlyNumber(event);" />
 */
function compCEP ( elemt )
{
	var numChars = elemt.value.length;

	if ( numChars == 5 ) {
		elemt.value += '-';
	}
}


/**
 * Completa automaticamente os marcadores de 
 * um CPF usando a máscara NNN.NNN.NNN-NN.
 *
 * No momento em que o usuário preenche os números, 
 * os marcadores são adicionados ao seu valor.
 *
 * @param  obj elemt:  elemento do formulário
 * --------------------------------------------------
 * Instruções: 
 * --------------------------------------------------
 * Esta função deve ser utilizada na tag html 'onkeyup'.
 * É obrigatório o uso da função 'inputOnlyNumber' na 
 * tag 'onkeypress' para que os valores inputados pelo 
 * usuário sejam apenas numéricos. O atributo 'maxlength' 
 * do campo deve ter o valor igual a 14.
 * --------------------------------------------------
 * Exemplo:
 * <input type="text" id="cpf" size="25" maxlength="14" onkeyup="compCPF( this );" onkeypress="return inputOnlyNumber(event);" />
 */
function compCPF ( elemt )
{
	var numChars = elemt.value.length;

	if( numChars == 3 || numChars == 7 ) {
		elemt.value += '.';
	}
	if( numChars == 11 ) {
		elemt.value += '-';
	}
}


/**
 * Completa automaticamente os marcadores de 
 * um CNPJ usando a máscara NN.NNN.NNN/NNNN-NN.
 * 
 * No momento em que o usuário preenche os números, 
 * os marcadores são adicionados ao seu valor.
 *
 * @param  obj elemt:  elemento do formulário
 * --------------------------------------------------
 * Instruções: 
 * --------------------------------------------------
 * Esta função deve ser utilizada na tag html 'onkeyup'.
 * É obrigatório o uso da função 'inputOnlyNumber' na 
 * tag 'onkeypress' para que os valores inputados pelo 
 * usuário sejam apenas numéricos. O atributo 'maxlength' 
 * do campo deve ter o valor igual a 18.
 * --------------------------------------------------
 * Exemplo:
 * <input type="text" id="cnpj" size="25" maxlength="18" onkeyup="compCNPJ( this );" onkeypress="return inputOnlyNumber(event);" />
 */
function compCNPJ ( elemt )
{
	var numChars = elemt.value.length;

	if ( numChars == 2 || numChars == 6 ) {
		elemt.value += '.';
	}
	if ( numChars == 10 ) {
		elemt.value += '/';
	}
	if ( numChars == 15 ) {
		elemt.value += '-';
	}
}


/**
 * Completa automaticamente os marcadores de 
 * um data, hora e data / hora usando 
 * uma máscara específica.
 *
 * No momento em que o usuário preenche os números, 
 * os marcadores são adicionados ao seu valor.
 *
 * @param  obj elemt:    elemento do formulário
 * @param  string mask:  mascara utilizada
 * ----------------------------------------------+
 * mask        | format              | maxlength |
 * ----------------------------------------------+
 * DATE        | DD/MM/YYYY          | 10        |
 * ----------------------------------------------+
 * TIME        | HH:MI               | 5         |
 * ----------------------------------------------+
 * TIMESEC     | HH:MI:SS            | 8         |
 * ----------------------------------------------+ 
 * DATETIME    | DD/MM/YYYY HH:MI    | 16        |
 * ----------------------------------------------+
 * DATETIMESEC | DD/MM/YYYY HH:MI:SS | 19        |
 * ----------------------------------------------+
 *
 * Instruções: 
 * --------------------------------------------------
 * Esta função deve ser utilizada na tag html 'onkeyup'.
 * É obrigatório o uso da função 'inputOnlyNumber' na 
 * tag 'onkeypress' para que os valores inputados pelo 
 * usuário sejam apenas numéricos. Consulte a tabela 
 * acima para definir o valor do atributo 'maxlength'.
 * --------------------------------------------------
 * Exemplo:
 * <input type="text" id="dtNascimento" size="25" maxlength="10" onkeyup="compDate( this, 'DATE' );" onkeypress="return inputOnlyNumber(event);" />
 */
function compDate ( elemt, mask )
{
	var numChars = elemt.value.length;

	if ( ( mask == 'DATE' ) || ( mask == 'DATETIME' ) || ( mask == 'DATETIMESEC' ) )
	{
		if( numChars == 2 || numChars == 5 ) {
			elemt.value += '/';
		}

		if( ( mask == 'DATETIME' ) || ( mask == 'DATETIMESEC' ) )
		{
			if ( numChars == 10 ) {
				elemt.value += ' ';
			}
			if ( numChars == 13 ) {
				elemt.value += ':';
			}

			if ( mask == 'DATETIMESEC' ) {
				if ( numChars == 16 ) {
					elemt.value += ':';
				}
			}
		}
	}
	else
	{
		if ( numChars == 2 ) {
			elemt.value += ':';
		}

		if ( mask == 'TIMESEC' ) {
			if( numChars == 5 ) {
				elemt.value += ':';
			}
		}
	}
}


/**
 * Formata valores numéricos com o número 
 * de casas decimais especificada.
 *
 * @param   obj input:  elemento do formulário
 * @param   int nDec:   número de casas decimais
 * @param   obj e:      evento
 * @return  bool
 * ------------------------------------------------
 * Exemplo:
 * <input type="text" name="vlVenda" size="25" maxlength="12" onkeypress="return compDecimal( this, 2, event );" />
 */
function compDecimal( input, nDec, e )
{
	var kCode;

	var milSep = '.';
	var decSep = ',';

	var strCheck = '0123456789';

	var key = aux = aux2 = '';
	var len2 = 0;

	var elemtVal = input.value;
	var elemtMax = input.maxLength;
	var elemtLen = elemtVal.length;

	
	kCode = (window.Event) ? e.which : e.keyCode;

	if(kCode == 8 || kCode == 0) { // pressionando o Backspace, Home, End, Delete <-, -> ...
		return true;
	}

	if(elemtLen >= elemtMax) { // input maxlength is exceed
		return false;
	}

	key = String.fromCharCode( kCode );  // Get key value from key code

	if ( strCheck.indexOf( key ) == -1 ) { // Not a valid key
		return false;
	}

	aux  = String(elemtVal).replace(/\D/g, '').replace(/^0+/, ''); // Elimina caracteres de formatação e zeros à esquerda da string
	aux += key;

	elemtLen = aux.length;

	if( elemtLen <= nDec )
	{
		for( ; elemtLen < nDec; elemtLen++ ) {
			aux = '0' + aux;
		}

		input.value = '0,' + aux;
	}
	else
	{
		for( var j = 0, i = elemtLen - (nDec + 1); i >= 0; i-- )
		{
			if ( j == 3 )
			{
				aux2 += milSep;
				j = 0;
			}

			aux2 += aux.charAt( i );
			j++;
		}

		input.value = '';
		len2 = aux2.length;

		for ( i = len2 - 1; i >= 0; i-- ) {
			input.value += aux2.charAt( i );
		}

		input.value += decSep + aux.substr( elemtLen - nDec, elemtLen );
	}

	return false;
}


/**
 * Seta o atributo 'action' de uma tag 
 * 'form' e depois o submete o formulário.
 *
 * @param  string formId:  identificador do formulário
 * @param  string url:     url do script
 * ---------------------------------------------
 * Exemplo: 
 *
 * <form id="formParent" action="?dest=alterar" method="post">
 *
 *    <fieldset>
 *		  <label for="vlVenda">Vl. Venda:</label>
 *		  <input type="text" name="vlVenda" id="vlVenda" size="25" maxlength="12" onkeypress="return compDecimal( this, 2, event );" /> <br />
 *
 *		  <input type="submit" value="ALTERAR" />
 *		  <input type="button" value="GERAR RELATÓRIO" onclick="setActionSubmit( 'formParent', '?dest=relatorio' );" />
 *	  </fieldset>
 *
 * </form>
 */
function setActionSubmit( formId, url )
{
	document.forms[formId].action = url;
	document.forms[formId].submit();
}


/**
 * Seta o valor dos elementos editáveis do formulário para vazio.
 *
 * @param  string formId:  identificador do formulário
 */
function resetFormElemts ( formId )
{
	var formObj = document.getElementById ( formId );

	var filter1 = new Array( 'text', 'password', 'textarea', 'file' );
	var filter2 = new Array( 'checkbox', 'radio' );
	var filter3 = new Array( 'select-one', 'select-multiple' );

	for ( var i = 0; i < formObj.length; i++ )
	{
		var elemt = formObj.elements[i];

		if( filter1.search( elemt.type ) != -1 )	{
			if( !elemt.disabled && !elemt.readOnly ) {
				elemt.value = '';
			}
		}
		else if( filter2.search( elemt.type ) != -1 ) {
			if( !elemt.disabled && !elemt.readOnly ) {
				elemt.checked = false;
			}
		}
		else if( filter3.search( elemt.type ) != -1 ) {
			if( !elemt.disabled ) { 
				elemt.options.selectedIndex = 0;
			}
		}
	}
}


/**
 * Move o foco do cursor para o elemento especificado.
 *
 * @param  string elemtId: identificador do elemento.
 * ---------------------------------------------
 * Exemplo: 
 *
 * <script type="text/javascript">
 *
 *     window.onload = function () {
 *         setFocus ( 'vlVenda' );
 *     }
 *
 * </script>
 *
 *
 * <form id="formParent" action="?dest=cadastrar" method="post">
 *
 *    <fieldset>
 *		  <label for="vlVenda">Vl. Venda:</label>
 *		  <input type="text" name="vlVenda" id="vlVenda" size="25" maxlength="12" onkeypress="return compDecimal( this, 2, event );" />
 *	  </fieldset>
 *
 * </form>
 */
function setFocus ( elemtId ) {
	document.getElementById( elemtId ).focus();
}


/**
 * Marca e desmarca todos os elementos 
 * do tipo checkbox de um formulário.
 *
 * @param   string formId:  identificador do formulário.
 * @return  string
 * ---------------------------------------------
 * Exemplo: 
 *
 * <form id="formParent" action="?dest=cadastrar" method="post">
 *
 *    <fieldset>
 *	      <label for="hobby1">Livros:</label><input type="checkbox" name="hobby[]" id="hobby1" value="L" />
 *		  <label for="hobby2">Filmes:</label><input type="checkbox" name="hobby[]" id="hobby2" value="F" />
 *	      <label for="hobby3">Namorar:</label><input type="checkbox" name="hobby[]" id="hobby3" value="N" /><br />
 *
 *	  	  <input type="button" value="MARCAR TODAS" onclick="this.value=checkboxCkAll( 'formParent' );" />
 *	  </fieldset>
 *
 * </form>
 */
var flagCheckboxCk = false;

function checkboxCkAll( formId )
{
	var formObj = document.forms[formId];
	
	for ( var i = 0; i < formObj.length; i++ ) {
		if( formObj.elements[i].type == 'checkbox' ) {
			formObj.elements[i].checked = !formObj.elements[i].checked;
		}
	}

	flagCheckboxCk = !flagCheckboxCk;
	
	if ( flagCheckboxCk ) {
		return 'DESMARCAR TODAS';
	}

	return 'MARCAR TODAS';
}


/**
 * Limita o input de caracteres 
 * em um elemento do tipo 'textarea'.
 *
 * @param  obj elemt:       textarea a ser imposto um limite.
 * @param  int numMaxChar:  número máximo de caracteres permitidos
 * ---------------------------------------------
 * Exemplo: 
 * <textarea cols="70" rows="5" name="obs" id="obs" onkeydown="limitInputText( this, 500 );" onkeyup="limitInputText( this, 500 );"></textarea>
 */
function limitInputText( elemt, numMaxChar )
{
	if ( elemt.value.length > numMaxChar ) { // if too long...trim it!
		elemt.value = elemt.value.substring( 0, numMaxChar );
	}
}

