////////////////////////////////////////////////////////////////////////////////
//                              MADE Form Checker
//
//  Version: 2.1.1
//  Authors: Jorge Mimica (jmimica@made.com.br)
//           Fábio Salles (fsalles@made.com.br)
//           Robson Douglas
//			 Alexandra Kondrat da Fonseca
//
////////////////////////////MADE//Internet//Services////////////////////////////

////////////////////////////////////////////////////////////////////////////////
//
//  I n s t r u c t i o n s :
//
//  In order to check if certain inputs of a form are properly filled, the
//  following attributes need to be added to the form elements' tags:
//
//   - fieldType = Defines the custom type of data being checked.
//                 Existing types: data, email, numero, cpf, cnpj, cep
//   - fieldName = Alias of the field which is used in the error message.
//
//  All form elements which have a declared fieldName will be checked.
//
//  Some custom data types are composed of more than one INPUT TEXT. In these
//  cases, the attributes are to be placed only in the sufix of the data type.
//  Ex.
//    <input type=text name="CPF_01" fieldName="CPF" fieldType = "cpf">
//    <input type=text name="CPF_02">.
//    <input type=text name="CPF_03">/
//    <input type=text name="CPF_DV">
//
////////////////////////////MADE//Internet//Services////////////////////////////

////////////////////////////////////////////////////////////////////////////////
//  Custom Variables
////////////////////////////MADE//Internet//Services////////////////////////////

// Error Messages of the Form Checker
// The @@@ will be substituted by the filedName when necessary
var mfcErrorMsg_HEADER      = "Os seguintes erros foram encontrados no preenchimento deste formulário:\n\n" ;
var mfcErrorMsg_TEXT        = "- O campo \"@@@\" não foi preenchido.\n" ;
var mfcErrorMsg_TEXT_INTEGER = "- No campo \"@@@\", use apenas números inteiros.\n" ;
var mfcErrorMsg_TEXT_NUMBER = "- No campo \"@@@\", você deve usar ponto ao invés de vírgula.\n" ;
var mfcErrorMsg_TEXT_NUMBER_MAX = "- O campo \"@@@\" é maior que o permitido.\n";
var mfcErrorMsg_TEXT_NUMBER_MIN = "- O campo \"@@@\" é menor que o permitido.\n";
var mfcErrorMsg_TEXT_NUMBER_STEP= "- O campo \"@@@\" deve ser de 0.5 em 0.5 ponto.\n";
var mfcErrorMsg_SELECT      = "- O campo \"@@@\" não foi escolhido.\n" ;
var mfcErrorMsg_RADIO       = "- O campo \"@@@\" não foi escolhido.\n" ;
var mfcErrorMsg_DATA        = "- Data do campo \"@@@\" está incorreta.\n" ;
var mfcErrorMsg_HORA        = "- Hora do campo \"@@@\" está incorreta.\n" ;
var mfcErrorMsg_MINUTOS     = "- Minutos do campo \"@@@\" estão incorretos.\n" ;
var mfcErrorMsg_CPF         = "- O número de CPF fornecido não é válido. (Formato correto: XXX.XXX.XXX-XX)\n" ;
var mfcErrorMsg_CEP         = "- CEP fornecido está preenchido de forma incorreta. (Formato correto: XXXXX-XXX)\n" ;
var mfcErrorMsg_SENHA       = "- Senha fornecida está diferente da Confirmação da senha\n" ;
var mfcErrorMsg_EMAIL       = "- O E-mail fornecido não é válido\n" ;
var mfcErrorMsg_DOUBLEDATE  = "- A data de início deve ser menor do que a data de expiração!\n" ;


////////////////////////////MADE//Internet//Services////////////////////////////

// Function which Checks the form
// @input: Form which will be validated
// @output: void
function madeCheckForm( frm ) {

	var iCont ;
	var errorMsg = mfcErrorMsg_HEADER ;
	var errorBuff = "" ;
	var strTmp = "" ;
	var campoFocus ;
    
	// Loops through all inputs of the form
	for ( iCont = frm.elements.length - 1 ; iCont > (-1) ; iCont-- ) {

		if (frm.elements[iCont].getAttribute("fieldName") != null) {

			strTmp = "" ;
			strTmp = madeCheckField( frm.elements[ iCont ] ) ;
			errorBuff = strTmp + errorBuff ;

			if ( strTmp != "" ) {
				if( frm.elements[iCont].type!="hidden" ) 
					campoFocus = frm.elements[iCont];
			} // if
		} // if
	} // for

	if ( errorBuff != "" ) {   
		alert( errorMsg + errorBuff ) ;
		if ( campoFocus != null )
			campoFocus.focus() ;
	} else
		frm.submit();
}

function madeCheckFormReturn( frm )
{

	var iCont ;
	var errorMsg = mfcErrorMsg_HEADER ;
	var errorBuff = "" ;
	var strTmp = "" ;
	var campoFocus ;
    
	// Loops through all inputs of the form
	for ( iCont = frm.elements.length - 1 ; iCont > (-1) ; iCont-- ) {

		if (frm.elements[iCont].getAttribute("fieldName") != null) {

			strTmp = "" ;
			strTmp = madeCheckField( frm.elements[ iCont ] ) ;
			errorBuff = strTmp + errorBuff ;

			if ( strTmp != "" ) {
				if( frm.elements[iCont].type!="hidden" ) 
					campoFocus = frm.elements[iCont];
			} // if
		} // if
	} // for

	if ( errorBuff != "" ) {   
		alert( errorMsg + errorBuff ) ;
		if ( campoFocus != null )
		{
			campoFocus.focus() ;
			return false;
		}
	} else
		return true;
}

// Function checks an element of the form
// @input: Element which will be validated
// @output: Empty string or error message
function madeCheckField( cmpo ) {

	var tipo ;
    
	// Checking field type
	if ( cmpo.getAttribute("fieldType") != null )
		tipo = cmpo.getAttribute("fieldType") ;
	else
		tipo = cmpo.type ;

	// Switch between different types of FIELDS
    switch ( tipo ) {

		// Field TEXT ( DEFAULT )
		case "text" :

			var strTemp = cmpo.value ;

			// Removing white spaces
			while( strTemp.indexOf( " " ) != (-1) )
				strTemp = strTemp.replace( " ", "" ) ;

			if ( strTemp.length == 0 )
				return mfcErrorMsg_TEXT.replace( "@@@", cmpo.getAttribute("fieldName") ) ;
			else
				return "" ;

		// Field TEXT-NUMBER
		case "number" :

			var strTemp = cmpo.value ;


			// Removing white spaces
			while( strTemp.indexOf( " " ) != (-1) )
				strTemp = strTemp.replace( " ", "" ) ;

			if ( strTemp.length == 0 )
				return mfcErrorMsg_TEXT.replace( "@@@", cmpo.getAttribute("fieldName") ) ;
			
			else if ( isNaN(strTemp) )
				return mfcErrorMsg_TEXT_NUMBER.replace( "@@@", cmpo.getAttribute("fieldName") ) ;
			
			else if ( ( parseFloat(strTemp) < parseFloat(cmpo.getAttribute("fieldMin")) ) && ( parseFloat(strTemp) != 0 ) )
				return mfcErrorMsg_TEXT_NUMBER_MIN.replace( "@@@", cmpo.getAttribute("fieldName") ) ;
			
			else if ( parseFloat(strTemp) > parseFloat(cmpo.getAttribute("fieldMax")) )
				return mfcErrorMsg_TEXT_NUMBER_MAX.replace( "@@@", cmpo.getAttribute("fieldName") ) ;
			
			else if ( parseInt(parseFloat(strTemp)/parseFloat(cmpo.getAttribute("step"))) != parseFloat(parseFloat(strTemp)/parseFloat(cmpo.getAttribute("step"))) )
			    return mfcErrorMsg_TEXT_NUMBER_STEP.replace( "@@@", cmpo.getAttribute("fieldName") ) ;

			else
				return "" ;

		// Field TEXT-NUMBER
		case "integer" :

			var strTemp = cmpo.value ;
			var intObrigatorio = 1;

			if ( cmpo.getAttribute("fieldRequired") != null )
				 intObrigatorio = cmpo.getAttribute("fieldRequired")

			// Removing white spaces
			while( strTemp.indexOf( " " ) != (-1) )
				strTemp = strTemp.replace( " ", "" ) ;

			if (parseInt(intObrigatorio) == 1)
			{
				if ( strTemp.length == 0 )
					return mfcErrorMsg_TEXT.replace( "@@@", cmpo.getAttribute("fieldName") ) ;
			}

			if (strTemp.length != 0)
			{
				if ( isNaN(strTemp) )
					return mfcErrorMsg_TEXT_INTEGER.replace( "@@@", cmpo.getAttribute("fieldName") ) ;
				
				else if ( parseInt(strTemp) != parseFloat(strTemp) ) //Só aceita inteiros!
					return mfcErrorMsg_TEXT_INTEGER.replace( "@@@", cmpo.getAttribute("fieldName") ) ;

				else if ( parseInt(strTemp) < parseInt(cmpo.getAttribute("fieldMin")) )
					return mfcErrorMsg_TEXT_NUMBER_MIN.replace( "@@@", cmpo.getAttribute("fieldName") ) ;
				
				else if ( parseInt(strTemp) > parseInt(cmpo.getAttribute("fieldMax")) )
					return mfcErrorMsg_TEXT_NUMBER_MAX.replace( "@@@", cmpo.getAttribute("fieldName") ) ;
				else
					return "" ;
			}
			return "" ;

		// Field TEXTAREA ( DEFAULT )
		case "textarea" :

			var strTemp = cmpo.value ;

			// Removing white spaces
			while( strTemp.indexOf( " " ) != (-1) )
				strTemp = strTemp.replace( " ", "" ) ;

			if ( strTemp.length == 0 )
				return mfcErrorMsg_TEXT.replace( "@@@", cmpo.getAttribute("fieldName") ) ;
			else
				return "" ;

		// Field HIDDEN ( DEFAULT )
		case "hidden" :

			var strTemp = cmpo.value ;

			// Removing white spaces
			while( strTemp.indexOf( " " ) != (-1) )
				strTemp = strTemp.replace( " ", "" ) ;

			if ( strTemp.length == 0 )
				return mfcErrorMsg_TEXT.replace( "@@@", cmpo.getAttribute("fieldName") ) ;
			else
				return "" ;
        
		// Field SELECT without multiple ( DEFAULT )
		case "select-one" : 
			if ( cmpo.selectedIndex <= 0 )
				return mfcErrorMsg_SELECT.replace( "@@@", cmpo.getAttribute("fieldName") ) ;
			else
				return "" ;
		  
		// Field SELECT with multiple ( DEFAULT )
		case "select-multiple" : 
			if ( cmpo.selectedIndex < 0 )
				return mfcErrorMsg_SELECT.replace( "@@@", cmpo.getAttribute("fieldName") ) ;
			else
				return "" ;
		  
		// Field RADIO ( DEFAULT )  
		case "radio" :

			var check = false;

			radio = eval( cmpo.form.name + "." + cmpo.name ) ;

			if ( !radio.length )
			{
				check = radio.checked ;
			}

			for ( var j = 0 ; j < radio.length ; j++ ) {
				if ( radio[j].checked ) {
					check = true ;
					break ;
				}
			}
			
			if ( !check )
				return mfcErrorMsg_RADIO.replace( "@@@", cmpo.getAttribute("fieldName") ) ;
			else
				return "" ;

		// Field PASSWORD ( fieldName )
		// Two INPUT TEXT representing a password and a password confirmation
		case "password" :
		
			var strTemp = cmpo.value ;

			// Removing white spaces
			while( strTemp.indexOf( " " ) != (-1) )
				strTemp = strTemp.replace( " ", "" ) ;

			if ( strTemp.length == 0 )
				return mfcErrorMsg_TEXT.replace( "@@@", cmpo.getAttribute("fieldName") ) ;

			try
		    {
			    if ( strTemp != eval( cmpo.form.name + "." + cmpo.name + "Confirm.value" ) )
				    return mfcErrorMsg_SENHA.replace( "@@@", cmpo.getAttribute("fieldName") ) ;
			}
			catch(e)
		    {
				// Não possui campo Confirm!
			}
			return "" ;

		// Field DATE (fieldName )
		// Three INPUT TEXT representing a date

		case "date" :

			var dia = String( parseInt( cmpo.value, 10 ) ) ;
			var mes = String( parseInt( eval( cmpo.form.name + "." + cmpo.name + "_m.value" ), 10 ) ) ;
			var ano = String( parseInt( eval( cmpo.form.name + "." + cmpo.name + "_y.value" ), 10 ) ) ;

			if ( ano.length != 4 || isNaN( ano ) )
				return mfcErrorMsg_DATA.replace( "@@@", cmpo.getAttribute("fieldName") ) ;

			if ( mes > 12 || mes < 1 || isNaN(mes) )
				return mfcErrorMsg_DATA.replace( "@@@", cmpo.getAttribute("fieldName") ) ;

			meses = new Array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ) ;

			if ( ( ( ano - 96 ) % 4 ) == 0 )
				meses[1] = 29 ;

			mes = mes - 1; 

			if ( dia > meses[mes] || dia < 1 || isNaN(dia) )
				return mfcErrorMsg_DATA.replace( "@@@", cmpo.getAttribute("fieldName") ) ;

			return "" ;

		// Field HORA ( fieldName )
		// Two INPUT TEXT representing time in the format HH:MM
		case "hora" :
		
			if ( parseInt( eval( cmpo.form.name + "." + cmpo.getAttribute("fieldName") + "Hour.value" ) ) > 23 || eval( cmpo.form.name + "." + cmpo.getAttribute("fieldName") + "Hour.value.length" ) != 2  )
				return mfcErrorMsg_HORA.replace( "@@@", cmpo.getAttribute("fieldName") ) ;

			if ( parseInt( eval( cmpo.form.name + "." + cmpo.fieldName + "Minute.value" ) ) > 59 ||  eval( cmpo.form.name + "." + cmpo.getAttribute("fieldName") + "Minute.value.length" ) != 2  )
				return mfcErrorMsg_MINUTOS.replace( "@@@", cmpo.getAttribute("fieldName") ) ;
			
			return "" ;

                // Field HORAHH  ( fieldName )
		// Two INPUT TEXT representing time in the format HH
		case "horahh" :

			if ( cmpo.value > 23 || isNaN( cmpo.value ) || cmpo.value == "" )
				return mfcErrorMsg_HORA.replace( "@@@", cmpo.getAttribute("fieldName") ) ;
		
			return "" ;
                
                // Field HORAMM  ( fieldName )
		// Two INPUT TEXT representing time in the format MM
		case "horamm" :

			if ( cmpo.value > 59 || isNaN( cmpo.value ) || cmpo.value == "" )
				return mfcErrorMsg_MINUTOS.replace( "@@@", cmpo.getAttribute("fieldName") ) ;
		
			return "" ;

		// Field CEP ( fieldName )
		// Two INPUT TEXT representing a CEP
		case "cep" :
		
			if ( eval( cmpo.form.name + "." + cmpo.getAttribute("fieldName") + "_01.value.length" ) != 5 || eval( cmpo.form.name + "." + cmpo.getAttribute("fieldName") + "_02.value.length" ) != 3 )
				return mfcErrorMsg_CEP.replace( "@@@", cmpo.getAttribute("fieldName") ) ;
			else
				return "" ;

		// Field CPF ( fieldName )
		// Four INPUT TEXT representing a CPF
		case "cpf" :
			dig_1 = 0 ;
			dig_2 = 0 ;
			controle_1 = 10 ;
			controle_2 = 11 ;
			lsucesso = 1 ;

			CPF_01 = eval( cmpo.form.name + "." + cmpo.getAttribute("fieldName") + "_01.value" ) ;
			CPF_02 = eval( cmpo.form.name + "." + cmpo.getAttribute("fieldName") + "_02.value" ) ;
			CPF_03 = eval( cmpo.form.name + "." + cmpo.getAttribute("fieldName") + "_03.value" ) ;
			CPF_DV = eval( cmpo.form.name + "." + cmpo.getAttribute("fieldName") + "_DV.value" ) ;
			  
			if ( CPF_01.length != 3 || CPF_02.length != 3 || CPF_03.length != 3 || CPF_DV.length != 2 ) {
				return mfcErrorMsg_CPF ;
			} else {

				numero = CPF_01 + CPF_02 + CPF_03 ;

				for ( j=0 ; j < 9 ; j++) {
					dig_1 = dig_1 + parseInt( numero.substring( j, j+1 ) * controle_1 ) ;
					controle_1 = controle_1 - 1;
				}
				
				resto = dig_1 % 11;
				dig_1 = 11 - resto;
				
				if ((resto == 0) || (resto == 1))
					dig_1 = 0;
				
				for ( j=0 ; j < 9 ; j++) {
					dig_2 = dig_2 + parseInt( numero.substring( j, j+1 ) * controle_2 ) ;
					controle_2 = controle_2 - 1 ;
				}
				
				dig_2 = dig_2 + 2 * dig_1;
				resto = dig_2 % 11;
				dig_2 = 11 - resto;
				if ((resto == 0) || (resto == 1))
					dig_2 = 0;
				
				dig_ver = (dig_1 * 10) + dig_2;

				if ( dig_ver != parseInt( CPF_DV, 10 ) )
					return mfcErrorMsg_CPF ;
				else
					return "" ;  
			}
        
		// Field e-mail ( fieldName )
		// INPUT TEXT representing an e-mail
		case "email" :
			var bAprovado = true ;
			var strTemp = cmpo.value ;
			
			while( strTemp.indexOf(" ") != (-1) )
				strTemp = strTemp.replace(" ", "");

			if ( strTemp.length == 0 )
				return mfcErrorMsg_TEXT.replace( "@@@", cmpo.getAttribute("fieldName") ) ;
			
			if ( cmpo.value.indexOf("@") < 0 )
				bAprovado = false;
			
			if ( cmpo.value.indexOf(".") < 0 )
				bAprovado = false;

			if ( cmpo.value.length == 0 )
				bAprovado = false;

			if ( !bAprovado )
				return mfcErrorMsg_EMAIL ;
			else
				return "";
        
		// Field Double-Date ( fieldName )
		// INPUT TEXT representing two dates.
		case "doubledate":

			var dtInicial       = eval(cmpo.form.name + "." + cmpo.getAttribute("fieldName") + "Ini.value") ;
			var dtInicialHora   = eval(cmpo.form.name + "." + cmpo.getAttribute("fieldName") + "Ini_Hora.value");
			var dtInicialMinuto = eval(cmpo.form.name + "." + cmpo.getAttribute("fieldName") + "Ini_Minuto.value") ;
         
			var dtFinal       = eval(cmpo.form.name + "." + cmpo.getAttribute("fieldName") + "Fim.value") ;
			var dtFinalHora   = eval(cmpo.form.name + "." + cmpo.getAttribute("fieldName") + "Fim_Hora.value") ;
			var dtFinalMinuto = eval(cmpo.form.name + "." + cmpo.getAttribute("fieldName") + "Fim_Minuto.value") ;

			var fullDateIni = dtInicial+" "+dtInicialHora+":"+dtInicialMinuto;
			var fullDateFim = dtFinal+" "+dtFinalHora+":"+dtFinalMinuto;
         
			fullDateIni = formataDataUSA(fullDateIni);
			fullDateFim = formataDataUSA(fullDateFim);
         
			if ( validaData( fullDateIni, fullDateFim ) )
				return "";
			else
				return mfcErrorMsg_DOUBLEDATE ;
/*
		// Debug
		default :
			return "- Tipo inválido\n"; //Modo de depuração
*/
	}
}  

////////////////////////////MADE//Internet//Services////////////////////////////
