////////////////////////////////////////////////////////////////////////////////
//                             MADE Form Checker
//
//  Version: 3.0
//  Authors:Fábio Salles (fsalles@made.com.br)
//          Robson Douglas (rdouglas@made.com.br)
//			Rodrigo Silva (rsilva@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       = "- Campo \"@@@\" não foi preenchido.\n" ;
var mfcErrorMsg_FILE       = "- Campo \"@@@\" não foi preenchido.\n" ;
var mfcErrorMsg_SELECT     = "- Campo \"@@@\" não foi escolhido.\n" ;
var mfcErrorMsg_RADIO      = "- 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        = "- CPF fornecido não é válido. (Formato correto: XXX.XXX.XXX-XX)\n" ;
var mfcErrorMsg_CNPJ       = "- 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      = "- 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" ;
var mfcErrorMsg_PASSWORD   = "- Campo \"@@@\" e sua confirmação devem ser iguais.\n" ;
var mfcErrorMsg_SENHA      = "- Senha fornecida está diferente da Confirmação da senha\n" ;
var mfcErrorMsg_CONFERE    = "- O campo \"@@@\" e sua confirmação não conferem.\n" ;

////////////////////////////MADE//Internet//Services////////////////////////////

// Function which Checks the form
// @input: Form which will be validated
// @output: void
function CheckForm( frm ) {

	var iCont ;
	var errorBuff = "" ;
	var errorField = "" ;
	var campoFocus ;
    
	// Loops through all inputs of the form
	for ( iCont = frm.elements.length - 1 ; iCont > (-1) ; iCont-- ) {

		if (frm.elements(iCont).fieldName != null) {

			errorField = CheckField( frm.elements( iCont ) ) 
			errorBuff =  errorField + errorBuff ;

			if ( errorField != "" ) {
				if( frm.elements(iCont).type!="hidden" ) 
					campoFocus = frm.elements(iCont);
			} // if
		} // if
	} // for

	if ( errorBuff == "" ) {
		return true;
	}
	else {
		alert( mfcErrorMsg_HEADER + errorBuff ) ;
		if ( campoFocus != null ){			
			if ( !campoFocus.length ) {				
				if ( campoFocus.disabled == false  ) 
					//alert("length = 0\n" + campoFocus.name);
					campoFocus.focus() ;
			}
			else {
				if ( campoFocus.disabled == false  ) 
					//alert("length = " + campoFocus.length + "\n" + campoFocus.name);
					campoFocus.focus() ;
			}
		}
		return false;
	}	
}


// Function checks an element of the form
// @input: Element which will be validated
// @output: Empty string or error message
function CheckField( campo ) {

	var tipo ;
    
	// Checking field type
	if ( campo.fieldType != null )
		tipo = campo.fieldType ;
	else
		tipo = campo.type ;

	// Switch between different types of FIELDS
    switch ( tipo ) {
      
		// Field TEXT ( DEFAULT )
		case "text" :
		
			var strTemp = campo.value ;

			// Removing white spaces
			while( strTemp.indexOf( " " ) != (-1) )
				strTemp = strTemp.replace( " ", "" ) ;

			if ( strTemp.length == 0 )
				return mfcErrorMsg_TEXT.replace( "@@@", campo.fieldName ) ;
			else
				return "" ;

		

		// Field TEXTAREA ( DEFAULT )
		case "textarea" :

			var strTemp = campo.value ;

			// Removing white spaces
			while( strTemp.indexOf( " " ) != (-1) )
				strTemp = strTemp.replace( " ", "" ) ;

			if ( strTemp.length == 0 )
				return mfcErrorMsg_TEXT.replace( "@@@", campo.fieldName ) ;
			else
				return "" ;
				


		// Field HIDDEN ( DEFAULT )
		case "hidden" :

			var strTemp = campo.value ;

			// Removing white spaces
			while( strTemp.indexOf( " " ) != (-1) )
				strTemp = strTemp.replace( " ", "" ) ;

			if ( strTemp.length == 0 )
				return mfcErrorMsg_TEXT.replace( "@@@", campo.fieldName ) ;
			else
				return "" ;
        


		// Field SELECT without multiple ( DEFAULT )
		case "select-one" : 
			if ( campo.selectedIndex == 0 )
				return mfcErrorMsg_SELECT.replace( "@@@", campo.fieldName ) ;
			else
				return "" ;
		  


		// Field SELECT with multiple ( DEFAULT )
		case "select-multiple" : 
			if ( campo.selectedIndex == 0 )
				return mfcErrorMsg_SELECT.replace( "@@@", campo.fieldName ) ;
			else
				return "" ;
		  


		// Field RADIO ( DEFAULT )  
		case "radio" :

/*			var check = false;
			var radio = eval( campo.form.name + "." + campo.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( "@@@", campo.fieldName ) ;
			else
*/				return "" ;



		// Field FILE ( DEFAULT )  
		case "file" :

			var strTemp = campo.value ;

			// Removing white spaces
			while( strTemp.indexOf( " " ) != (-1) )
				strTemp = strTemp.replace( " ", "" ) ;

			if ( strTemp.length == 0 )
				return mfcErrorMsg_FILE.replace( "@@@", campo.fieldName ) ;
			else
				return "" ;
				


		// Field DATE (fieldName )
		// Three INPUT TEXT representing a date
		case "date" :

			var dia = String( parseInt( campo.value, 10 ) ) ;
			var mes = String( parseInt( eval( campo.form.name + "." + campo.name + "_m.value" ), 10 ) ) ;
			var ano = String( parseInt( eval( campo.form.name + "." + campo.name + "_y.value" ), 10 ) ) ;

			if ( ano.length != 4 || isNaN( ano ) )
				return mfcErrorMsg_DATA.replace( "@@@", campo.fieldName ) ;

			if ( mes > 12 || mes < 1 || isNaN(mes) )
				return mfcErrorMsg_DATA.replace( "@@@", campo.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( "@@@", campo.fieldName ) ;
			else
				return "" ;



		// Field HORA ( fieldName )
		// Two INPUT TEXT representing time in the format HH:MM
		case "hora" :
		
			if ( parseInt( eval( campo.form.name + "." + campo.fieldName + "Hour.value" ) ) > 23 || eval( campo.form.name + "." + campo.fieldName + "Hour.value.length" ) != 2  )
				return mfcErrorMsg_HORA.replace( "@@@", campo.fieldName ) ;

			if ( parseInt( eval( campo.form.name + "." + campo.fieldName + "Minute.value" ) ) > 59 ||  eval( campo.form.name + "." + campo.fieldName + "Minute.value.length" ) != 2  )
				return mfcErrorMsg_MINUTOS.replace( "@@@", campo.fieldName ) ;
			
			return "" ;



		// Field CEP ( fieldName )
		// Two INPUT TEXT representing a CEP
		case "cep" : // Usando um só campo
				if ( campo.value.length < 9) {
					if ( isNaN(parseInt(campo.value)) )
						return mfcErrorMsg_CEP.replace( "@@@", campo.fieldName ) ;
					else
						return "" ;
				}
				else
					return "" ;
		
		case "cep2" : // Usando dois campos
				if ( eval( campo.form.name + "." + campo.fieldName + "_01.value.length" ) != 5 || eval( campo.form.name + "." + campo.fieldName + "_02.value.length" ) != 3 ){
					if ( !isNaN(parseInt(campo.value)) )
						return mfcErrorMsg_CEP.replace( "@@@", campo.fieldName ) ;
					else
						return "" ;
				}
				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( campo.form.name + "." + campo.fieldName + "_01.value" ) ;
			CPF_02 = eval( campo.form.name + "." + campo.fieldName + "_02.value" ) ;
			CPF_03 = eval( campo.form.name + "." + campo.fieldName + "_03.value" ) ;
			CPF_DV = eval( campo.form.name + "." + campo.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( campo.form.name + "." + campo.fieldName + "_01.value" ) ;
			CNPJ_02 = eval( campo.form.name + "." + campo.fieldName + "_02.value" ) ;
			CNPJ_03 = eval( campo.form.name + "." + campo.fieldName + "_03.value" ) ;
			CNPJ_04 = eval( campo.form.name + "." + campo.fieldName + "_04.value" ) ;
			CNPJ_DV = eval( campo.form.name + "." + campo.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( campo.value ) )
				return "" ;
			else
				return mfcErrorMsg_EMAIL ;
        


		// Field PASSWORD ( fieldName )
		// Two INPUT TEXT representing a password and a password confirmation
		case "password" :
		
			var strTemp = campo.value ;

			// Removing white spaces
			while( strTemp.indexOf( " " ) != (-1) )
				strTemp = strTemp.replace( " ", "" ) ;

			if ( strTemp.length == 0 )
				return mfcErrorMsg_TEXT.replace( "@@@", campo.fieldName ) ;

			if ( strTemp != eval( campo.form.name + "." + campo.name + "Confirm.value" ) && strTemp != eval( campo.form.name + "." + campo.name + "_confirm.value" ) )
				return mfcErrorMsg_SENHA.replace( "@@@", campo.fieldName ) ;

			return "" ;




		// Field CONFIRM ( fieldName )
		// Two INPUT TEXT representing an expression and a confirmation that must match
		case "confirm" :

			if ( campo.value.length == 0 )
				return mfcErrorMsg_TEXT.replace( "@@@", campo.fieldName ) ;

			if ( campo.value != eval( campo.form.name + "." + campo.name + "Confirm.value" ) )
				return mfcErrorMsg_CONFERE.replace( "@@@", campo.fieldName ) ;

			return "" ;


		// Debug
		default :
			return "- Tipo inválido - " + tipo + "\n"; //Modo de depuração

	}
}  


////////////////////////////MADE//Internet//Services////////////////////////////
