////////////////////////////////////////////////////////////////////////////////
//                              MADE Form Checker
//
//  Version: 2.0
//  Authors: Fábio Salles (fsalles@made.com.br)
//           Robson Douglas (rdouglas@made.com.br)
//
////////////////////////////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_FILE       = "- O campo \"@@@\" não foi preenchido.\n" ;
var mfcErrorMsg_PASSWORD   = "- O campo \"@@@\" e sua confirmação devem ser iguais.\n" ;
var mfcErrorMsg_SELECT     = "- O campo \"@@@\" não foi escolhido.\n" ;
var mfcErrorMsg_RADIO      = "- O campo \"@@@\" não foi escolhido.\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_CNPJ       = "- O número de CNPJ fornecido não é válido. (Formato correto: XX.XXX.XXX/XXXX-XX)\n" ;
var mfcErrorMsg_CEP        = "- CEP fornecido está preenchido de forma incorreta. (Formato correto: XXXXX-XXX)\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" ;
var mfcErrorMsg_NASC			= "- Data de nascimento inválida!\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).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 ){
		   if ( campoFocus.disabled == false  )
			   campoFocus.focus() ;
		}	
	} else
		frm.submit();
}


// 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.fieldType != null )
		tipo = cmpo.fieldType ;
	else
		tipo = cmpo.type ;

	// Switch between different types of FIELDS
    switch ( tipo ) {
      case "password" :
         var obj1 = cmpo;
         var obj2 = eval( cmpo.form.name + "." + cmpo.name + "_confirm" )
         
         if ( obj1.value == "" && obj2.value == "" ){
            return mfcErrorMsg_TEXT.replace( "@@@", cmpo.fieldName ) ;
         }
         else if ( obj1.value != obj2.value ){
            return mfcErrorMsg_PASSWORD.replace( "@@@", cmpo.fieldName ) ; 
         }
			else
			   return ""
      
      break;
      
		// 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.fieldName ) ;
			else
				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.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.fieldName ) ;
			else
				return "" ;
        
		// Field SELECT without multiple ( DEFAULT )
		case "select-one" : 
			if ( cmpo.selectedIndex == 0 )
				return mfcErrorMsg_SELECT.replace( "@@@", cmpo.fieldName ) ;
			else
				return "" ;
		  
		// Field SELECT with multiple ( DEFAULT )
		case "select-multiple" : 
			if ( cmpo.selectedIndex == 0 )
				return mfcErrorMsg_SELECT.replace( "@@@", cmpo.fieldName ) ;
			else
				return "" ;
		  
		// Field RADIO ( DEFAULT )  
		case "radio" :

			var check = false;

			radio = eval( cmpo.form.name + "." + cmpo.name ) ;

			for ( var j = 0 ; j < radio.length ; j++ ) {
				if ( radio[j].checked ) {
					check = true ;
					break ;
				}
			}
			
			if ( !check )
				return mfcErrorMsg_RADIO.replace( "@@@", cmpo.fieldName ) ;
			else
				return "" ;

		// Field FILE ( DEFAULT )  
		case "file" :

			var strTemp = cmpo.value ;

			// Removing white spaces
			while( strTemp.indexOf( " " ) != (-1) )
				strTemp = strTemp.replace( " ", "" ) ;

			if ( strTemp.length == 0 )
				return mfcErrorMsg_FILE.replace( "@@@", cmpo.fieldName ) ;
			else
				return "" ;
				

		// Field HORA ( fieldName )
		// Two INPUT TEXT representing time in the format HH:MM
		case "hora" :
		
			if ( parseInt( eval( cmpo.form.name + "." + cmpo.fieldName + "Hour.value" ) ) > 23 || eval( cmpo.form.name + "." + cmpo.fieldName + "Hour.value.length" ) != 2  )
				return mfcErrorMsg_HORA.replace( "@@@", cmpo.fieldName ) ;

			if ( parseInt( eval( cmpo.form.name + "." + cmpo.fieldName + "Minute.value" ) ) > 59 ||  eval( cmpo.form.name + "." + cmpo.fieldName + "Minute.value.length" ) != 2  )
				return mfcErrorMsg_MINUTOS.replace( "@@@", cmpo.fieldName ) ;
			
			return "" ;

		// Field CEP ( fieldName )
		// Two INPUT TEXT representing a CEP
		case "CEP" : // Usando um só campo
				if ( eval( cmpo.form.name + "." + cmpo.fieldName + ".value.length" ) < 9)
					return mfcErrorMsg_CEP.replace( "@@@", cmpo.fieldName ) ;
				else
					return "" ;
		
		case "cep" : // Usando dois campos
				if ( eval( cmpo.form.name + "." + cmpo.fieldName + "_01.value.length" ) != 5 || eval( cmpo.form.name + "." + cmpo.fieldName + "_02.value.length" ) != 3 )
					return mfcErrorMsg_CEP.replace( "@@@", cmpo.fieldName ) ;
				else
					return "" ;

		// Field Nasc ( fieldName )
		// Three INPUT TEXT representing a birthday
		case "Nasc" : // Nascimento com três campos Dia, Mês, Ano
				if ( isNaN(Number(eval( cmpo.form.name + "." + cmpo.fieldName + "Dia.value.length" ))))
					return mfcErrorMsg_NASC.replace( "@@@", cmpo.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.fieldName + "_01.value" ) ;
			CPF_02 = eval( cmpo.form.name + "." + cmpo.fieldName + "_02.value" ) ;
			CPF_03 = eval( cmpo.form.name + "." + cmpo.fieldName + "_03.value" ) ;
			CPF_DV = eval( cmpo.form.name + "." + cmpo.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 "" ;  
			}
			
		case "cnpj" :
		
			var dig_1 = 0;
			var dig_2 = 0;
			var controle_1 = 5;
			var controle_2 = 6;

			CNPJ_01 = eval( cmpo.form.name + "." + cmpo.fieldName + "_01.value" ) ;
			CNPJ_02 = eval( cmpo.form.name + "." + cmpo.fieldName + "_02.value" ) ;
			CNPJ_03 = eval( cmpo.form.name + "." + cmpo.fieldName + "_03.value" ) ;
			CNPJ_04 = eval( cmpo.form.name + "." + cmpo.fieldName + "_04.value" ) ;
			CNPJ_DV = eval( cmpo.form.name + "." + cmpo.fieldName + "_DV.value" ) ;
				
			if ( CNPJ_01.length != 2 || CNPJ_02.length != 3 || CNPJ_03.length != 3 || CNPJ_04.length != 4 || CNPJ_DV != 2 ) {
				return mfcErrorMsg_CNPJ ;
			} else {

				numero = CNPJ_01 + CNPJ_02 + CNPJ_03 + CNPJ_04 + CNPJ_DV ;

				for ( var j = 0 ; j < 12 ; j++ ) {
					dig_1 = dig_1 + parseFloat( numero.substring( j, j+1 ) * controle_1 ) ;
					controle_1 = controle_1 - 1 ;
					if (j == 3)
						controle_1 = 9 ;
				}

				resto = dig_1 % 11 ;
				dig_1 = 11 - resto ;

				if ((resto == 0) || (resto == 1))
					dig_1 = 0 ;

				for ( j = 0 ; j < 12 ; j++) {
					dig_2 = dig_2 + parseInt(numero.substring(j, j+1) * controle_2) ;
					controle_2 = controle_2 - 1 ;
					if (j == 4)
						controle_2 = 9 ;
				}

				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_CNPJ ;
				else
					return "" ;  
			}
		
        
		// Field e-mail ( fieldName )
		// INPUT TEXT representing an e-mail
		case "email" :
			var oRegExp = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/ ;

			if ( oRegExp.test( cmpo.value ) )
				return "" ;
			else
				return mfcErrorMsg_EMAIL ;
        
		// Field Double-Date ( fieldName )
		// INPUT TEXT representing two dates.
		case "doubledate":

			var dtInicial       = eval(cmpo.form.name + "." + cmpo.fieldName + "Ini.value") ;
			var dtInicialHora   = eval(cmpo.form.name + "." + cmpo.fieldName + "Ini_Hora.value");
			var dtInicialMinuto = eval(cmpo.form.name + "." + cmpo.fieldName + "Ini_Minuto.value") ;
         
			var dtFinal       = eval(cmpo.form.name + "." + cmpo.fieldName + "Fim.value") ;
			var dtFinalHora   = eval(cmpo.form.name + "." + cmpo.fieldName + "Fim_Hora.value") ;
			var dtFinalMinuto = eval(cmpo.form.name + "." + cmpo.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////////////////////////////
