//
// Atributos de Validação: 
//                     
//  GroupLabel          : Especifica a identificacao do Grupo
//                        Ex: GroupLabel = 'Usuário'
//
//  GroupValidationType : Determina a validação especifica para o grupo
//                        Ex: Validar que todos os campos estejam preenchidos no caso 
//								      de telefone e codigo de área					                       
//
//  GroupDimension      : Especifica Dimensao para Itens com Multipla Validação
//								  Se forem 4 itens p. ex. (3)
//
//  GroupIndex          : Especifica o Item de uma validação múltipla    
//                        Se forem 4 itens p. ex. (0,1,2,3)
//
//  Label               : Especifica a identificacao do elemento do form
//                        Ex: label='Nome'  
//
//  Optional            : Especifica se o campo é opcional/obrigatório 
//                        Opções: Yes, No (Default No)
//
//  ValidationType      : Especifica o tipo de validação aplicada ao campo. 
//                        Opções: Number, Email, Text, Date, Digits, CEP, CPF/CNPJ, Phone, Combo, Radio
//
//  LimitInfInc         : Determina o limite inferior incluindo o valor determinado     
//
//  LimitInfExc         : Determina o limite inferior excluindo o valor determinado     
//
//  LimitSupInc         : Determina o limite Superior incluindo o valor determinado     
//
//  LimitSupExc         : Determina o limite Superior excluindo o valor determinado     
//
//  TextLimit           : Determina o limite de caracteres para campos do tipo Text (deprecated; use MaxChars)
//
//  MinChars            : Determina o limite mínimo de caracteres
//  MaxChars            : Determina o limite máximo de caracteres 
//
//  Pattern             : Determina o padrão: US, BR
//
//  DecimalPlaces       : 1....N 
//  
//  EmptyMessage			: Mensagem para campo não preenchido (substitui a padrão)
//
//  ValidationMessage	: Mensagem para erro de validação (substitui a padrão)

//  ValidateFormData: Valida todos elementos de um form conforme seu tipo
function ValidateFormData(oForm, sLang, sBaseClass) {
  this.oForm = oForm;
  this.sLang = sLang;
  this.sBaseClass = sBaseClass;
  this.oField = null;
  this.sField = '';
  this.sMsg = ''; 

  this.enhanceElement = function (oElement, bErro) {
      if (this.sBaseClass != '') {
         if (oElement.type.toLowerCase() != 'checkbox' && oElement.type.toLowerCase() != 'radio') {  
            oElement.className = this.sBaseClass + 'Field' + (bErro? 'Erro' : '');
            oElement.parentNode.className = this.sBaseClass + (bErro? 'Erro' : '');
         }
      }
      if (bErro) {
         oElement.focus();
         this.oField = oElement;
      }
  }     

  this.enhanceAllElements = function (bErro) {
      for(i = 0; i < oForm.elements.length; i++) {
         if (oForm.elements[i].getAttribute('ValidationType')!= null) {
            this.enhanceElement (oForm.elements[i], bErro);
         }
      }
  }     

  this.validate = function () {
    var sValidation;
   
    // Valida os Itens de um form individualmente
    for(i = 0; i < oForm.elements.length; i++) {
        oElement = oForm.elements[i];
		  sValidation = oElement.getAttribute('ValidationType');
		      
        if (sValidation != null) {
            var sOptional = 'no';
            var bValidate   = true;
            var oValidation;
				var sObjectType = '';
				var iMinChars = 0, iMaxChars = 0;
				
				this.sField = oElement.getAttribute('Label'); 
				
				switch (oElement.tagName.toLowerCase()) {
				
				case 'select':	sObjectType = 'combo';
									break; 

				case 'input':	sObjectType = oElement.type;
									break; 
									
				case 'textarea': sObjectType = 'text';
            }
            
            if (sObjectType == 'text' || sObjectType == 'password') {
					// Os campos com optional="No" devem ser validados sempre                                            
					// Se o campo for opcional, so valida quando preenchido
			      if (oElement.getAttribute('MinChars') != null) {
					   iMinChars = parseInt(oElement.getAttribute('MinChars'));
					   if (isNaN(iMinChars)) { iMinChars = 0; }
					}
			      if (oElement.getAttribute('MaxChars') != null) {
					   iMaxChars = parseInt(oElement.getAttribute('MaxChars'));
					   if (isNaN(iMaxChars)) { iMaxChars = 0; }
					}
					if (oElement.getAttribute('Optional') != null) {
					   sOptional = oElement.getAttribute('Optional').toLowerCase();
					}

					if (sOptional == 'no') {
					   if (oElement.value == '') {
							 if (oElement.getAttribute('EmptyMessage') != null) { 
								  this.sMsg = oElement.getAttribute('EmptyMessage');
					       } else {
							 switch (this.sLang) {
							 case 'P': 
								 this.sMsg = 'Campo obrigatório';
  							    break;

							 case 'E':
								 this.sMsg = 'This field is mandatory';
								  break;
							 }
							 }
							 	  
 							 this.enhanceElement(oElement, true);
							 return false;					       
					   }
					} else {
					   if (oElement.value == '') {	
					       bValidate = false;
					   }
					}
               
               // Valida min/max chars
               if (bValidate) {
                  if ((iMinChars > 0) && (oElement.value.length < iMinChars)) {
                      switch (this.sLang) {
							 case 'P': 
								 this.sMsg = 'O campo deve possuir no mínimo ' + Number(iMinChars).toString() + ' caracteres';
  							    break;

							 case 'E':
								 this.sMsg = 'This field must have at least ' + Number(iMinChars).toString() + ' characters';
								  break;
							 } 
                      this.enhanceElement(oElement, true);
							 return false;	                    
                  }
                  if ((iMaxChars > 0) && (oElement.value.length > iMaxChars)) {
                      switch (this.sLang) {
							 case 'P': 
								 this.sMsg = 'O campo deve possuir no máximo ' + Number(iMaxChars).toString() + ' caracteres';
  							    break;

							 case 'E':
								 this.sMsg = 'This field must have at most ' + Number(iMaxChars).toString() + ' characters';
								  break;
							 } 
                      this.enhanceElement(oElement, true);
							 return false;	                    
                  }
               }	
				}
			   
            if (bValidate) {
               //Ativa a classe dependendo tipo definido		
					switch(sValidation.toLowerCase()){
					case 'caracter':
	    	          oValidation = new ValidateElementTypeCaracter(oElement, this.sLang);   						   
			          break; 
               
			      case 'number':
     					 oValidation = new ValidateElementTypeNumber(oElement, this.sLang);   						   
						 break; 

               case 'text':
			          oValidation = new ValidateElementTypeText(oElement, this.sLang);
		  	          break; 

               case 'date':
				       oValidation = new ValidateElementTypeDate(oElement, this.sLang);
                   break; 

               case 'email':
			          oValidation = new ValidateElementTypeEmail(oElement, this.sLang);						  
                   break; 				    

               case 'cpf/cnpj':
			         oValidation = new ValidateElementTypeCPFCNPJ(oElement, this.sLang);						  
                  break; 				    
                  
               case 'cep':
			         oValidation = new ValidateElementTypeCEP(oElement, this.sLang);						  
                  break;
                  
					case 'digits':
			         oValidation = new ValidateElementTypeDigits(oElement, this.sLang);						  
                  break;          
                  
					case 'phone':
			         oValidation = new ValidateElementTypePhone(oElement, this.sLang);						  
                  break;                                    

					case 'combo':
	    	          oValidation = new ValidateElementTypeCombo(oElement, this.sLang);   						   
			          break; 

					case 'radio':
	    	          oValidation = new ValidateElementTypeRadio(document.getElementsByName(oElement.name), this.sLang);   						   
			          break; 
               } 
               // End do Switch

					if (oValidation == null) {
						 switch (this.sLang) {
						 case 'P': 
							  alert(oElement.getAttribute('Label') + ': validação inválida');
							  break;

						 case 'E':
							  alert(oElement.getAttribute('Label') + ': invalid validation type');
							  break;
						 }
					    
                   oElement.focus();                       
                   return false;
               }
					
               if (!oValidation.validate()) {
						 if (oElement.getAttribute('ValidationMessage') == null) {                 
							 this.sMsg = oValidation.sMsgErr;
						 } else {
						 	 this.sMsg = oElement.getAttribute('ValidationMessage');
						 }
						 this.sField = oElement.getAttribute('Label');
                   this.enhanceElement(oElement, true);                       
                   return false;
               }
            }
            this.enhanceElement(oElement, false);
        } 
    } 
	                             
   // Valida os Campos Agrupados
   var i = 0;
   var j;
   var aGroups = new Array;
   
   while (i < oForm.elements.length) {
      oElement = oForm.elements[i];

      if (oElement.getAttribute('GroupLabel') != null) {
         for (j = 0; j < aGroups.length; j++) {
            if (aGroups[j].sLabel == oElement.getAttribute('GroupLabel').toLowerCase()) {
               aGroups[j].aItems[aGroups[j].aItems.length] = oElement;
               break; 
            }
         }
         
         /* novo grupo */
         if (j == aGroups.length) {
            aGroups[j] = new ValidationGroup(oElement.getAttribute('GroupLabel').toLowerCase(), oElement.getAttribute('GroupValidationType'));
            aGroups[j].aItems[0] = oElement;
         }
      }
      i++;
   }

   for (j = 0; j < aGroups.length; j++) {
      if (aGroups[j].sType != null) {
         //Ativa a classe dependendo tipo definido
   		switch(aGroups[j].sType.toLowerCase()){
   		                                        
         case 'fillall':
   		   oValidation = new ValidateGroupTypeFillAll(aGroups[j].aItems, this.sLang);
   	 	   break; 
   
         case 'dateinterval':    
            oValidation = new ValidateGroupTypeDateInterval(aGroups[j].aItems, this.sLang);    	   
   		   break; 

         case 'numberinterval':    
            oValidation = new ValidateGroupTypeNumberInterval(aGroups[j].aItems, this.sLang);    	   
   		   break; 

   
         case 'confirmation':    
            oValidation = new ValidateGroupTypeConfirmation(aGroups[j].aItems, this.sLang);    	   
   		   break; 
   		   
   		case 'checkbox':    
            oValidation = new ValidateGroupTypeCheckbox(aGroups[j].aItems, this.sLang);    	   
   		   break;
   
         } // End do Switch
   
   		if (oValidation == null) {                 
   			 switch (this.sLang) {
   			 case 'P': 
   				  alert(aGroups[j].aItems[0].getAttribute('Label') + ': validação de grupo inválida');
   				  break;
   
   			 case 'E':
   				  alert(aGroups[j].aItems[0].getAttribute('Label') + ': invalid group validation type');
   				  break;
   			 }
   		
             aGroups[j].aItems[0].focus();                       
             return false;
         }
   
         if (!oValidation.validate()) {                 
            this.sMsg = oValidation.sMsgErr;
            this.sField = aGroups[j].aItems[0].getAttribute('Label');
            if (aGroups[j].sType.toLowerCase() != 'checkbox') {
               this.enhanceElement(aGroups[j].aItems[0], true);
            }
            return false;
         }
         this.enhanceElement(aGroups[j].aItems[0], false);       
      }
   } 
   return true;
   } 
}

// ValidateGroupTypeDateInterval

function ValidateGroupTypeDateInterval(aGroup, sLang) {

  this.sMsgErr =  ' '; 
  this.aGroup = aGroup;
  this.sLang = sLang;

  function StringToDate(index){  
     var DateValue = aGroup[index].value;
     var dDate;
     var aDate ;
     var day;
     var month;
     var year;

    // Year 2000 correction
    if (DateValue.length == 6) {
       DateValue = DateValue.substr(0,4) + '20' + DateValue.substr(4,2);     
    }

    // Define fields day,month,year
    aDate = DateValue.split("/");
   
    if (aGroup[index].getAttribute('Pattern') == "US"){     
       month = aDate[0];
       day   = aDate[1];
    } else {
       month = aDate[1];
       day   = aDate[0];
    }

    year   = aDate[2];

    dDate = new Date(year, month-1, day);
    return dDate;
  }
  
  this.validate = function () {
     var sField;
     var sOptional ;
     var oValidation;
     var date1 = new Date();
     var date2 = new Date();
 
     // Verify that all date field is filled
     oValidation = new ValidateGroupTypeFillAll(aGroup);
     
     if (!oValidation.validate()) {   
     		switch (this.sLang) {
			 case 'P': 
				  this.sMsgErr='Todas as datas devem ser preenchidas';               
				  break;

			 case 'E':
				  this.sMsgErr='Please type all dates';               
				  break;
			 }
        return false;
     }

     date1 =  StringToDate(0);   
     date2 =  StringToDate(1);   

     if (date1 > date2) {
     		switch (this.sLang) {
			 case 'P': 
		        this.sMsgErr='O intervalo de datas está incorreto';            
				  break;

			 case 'E':
				  this.sMsgErr='Wrong date interval';               
				  break;
			 }
     
        return false;
     }
 
     return true;    
   }
}

// ValidateGroupTypeConfirmation
function ValidateGroupTypeConfirmation(aGroup, sLang) {

   switch (sLang) {
	case 'P': 
	    this.sMsgErr =  'Os valores digitados no campo ' + aGroup[0].getAttribute('Label') + ' não conferem';
	    break;

	case 'E':
	    this.sMsgErr = 'The values entered in field ' + aGroup[0].getAttribute('Label') + ' do not match';               
	    break;
	}
  this.aGroup = aGroup;
  
  this.validate = function () {
     var sValue;

     sValue = this.aGroup[0].value;  

     for(i=1;i < this.aGroup.length;i++){
        if (this.aGroup[i].value != sValue){
           if (aGroup[0].getAttribute('GroupMessage') != null) {
					this.sMsgErr = aGroup[0].getAttribute('GroupMessage');  
			   }	 
           return false;
        }    
      }
      return true;    
   }
   
}

// ValidateGroupTypeFillAll
function ValidateGroupTypeFillAll(aGroup, sLang) {

   switch (sLang) {
	case 'P': 
	    this.sMsgErr = 'Todos os valores devem ser preenchidos';
	    break;

	case 'E':
	    this.sMsgErr = 'All fields must be filled';               
	    break;
	}
  this.aGroup = aGroup;
  
  this.validate = function () {
     var bOpt = false;
     var iFields  = 0;

     for(i=0;i<aGroup.length;i++){
        switch (aGroup[i].tagName.toLowerCase()) {

	     case 'select':	if (aGroup[i].selectedIndex >= 0) {
                           if (aGroup[i].options[aGroup[i].selectedIndex].value != '') { iFields++ };
                        }
		  		            break; 

		  case 'input':	if (aGroup[i].value != '') { iFields++ };
		  		            break;
									
		  case 'textarea': if (aGroup[i].text != '') { iFields++ };
		                   break;
        }     
      }

      if (iFields > 0 && iFields < aGroup.length){
			 if (aGroup[0].getAttribute('GroupMessage') != null) {
				 this.sMsgErr = aGroup[0].getAttribute('GroupMessage');  
			 }	 
          return false;                  
      }

      return true;    
   }
   
}

// ValidateGroupTypeNumberInterval
function ValidateGroupTypeNumberInterval(aGroup, sLang) {

  this.sMsgErr =  ' '; 
  this.aGroup = aGroup;
  this.sLang = sLang;

  this.validate = function () {
     var num1, num2;
     var i;

     for (i=0;i<this.aGroup.length-1;i++) {
         num1 = parseFloat(this.aGroup[i].value);
         num2 = parseFloat(this.aGroup[i+1].value);

         if (num1 > num2) {
        		switch (this.sLang) {
   			 case 'P': 
   		        this.sMsgErr='O valor do campo ' + this.aGroup[i+1].getAttribute('Label') + ' deve ser maior ou igual ao valor do campo ' + this.aGroup[i].getAttribute('Label');            
   				  break;
   
   			 case 'E':
   				  this.sMsgErr='The number in field ' + this.aGroup[i+1].getAttribute('Label') + ' must be equal or greater than the number in field ' + this.aGroup[i].getAttribute('Label');               
   				  break;
   			 }
             return false;
         }
     }
         
     return true;    
   }
}

// ValidateElementTypeCombo
function ValidateElementTypeCombo(oElement, sLang) {

   switch (sLang) {
	case 'P': 
	    this.sMsgErr =  'Selecione uma das opções do campo ' + oElement.getAttribute('Label');
	    break;

	case 'E':
	    this.sMsgErr = 'Please choose one of the options from field ' + oElement.getAttribute('Label');               
	    break;
	}
  this.oElement = oElement;

  this.validate = function () {	
    if (oElement.options[oElement.selectedIndex].value=='') {	
       return false; 
    }     
    return true;
  }
}

// ValidateElementTypeRadio
function ValidateElementTypeRadio(oElement, sLang) {
   switch (sLang) {
	case 'P': 
	    this.sMsgErr =  'Selecione uma das opções do campo ' + oElement[0].getAttribute('Label');
	    break;

	case 'E':
	    this.sMsgErr = 'Please choose one of the options from field' + oElement[0].getAttribute('Label');
	    break;
	}
  this.oElement = oElement;

  this.validate = function () {	
	 var i;
	 
	 for (i=0;i<oElement.length;i++) {
		if (oElement[i].checked) {	
         return true; 
      }     
    }  
    return false;
  }
}

// ValidateElementTypePhone
function ValidateElementTypePhone(oElement, sLang) {
   switch (sLang) {
	case 'P': 
	    this.sMsgErr =  'Telefone inválido';
	    break;

	case 'E':
	    this.sMsgErr =  'Invalid telephone number';
	    break;
   }
  this.oElement = oElement;

  this.validate = function () {	
    if (!(/^(\d\d)(\d)?(\d)?(-)?(\d\d\d\d)+$/.test(oElement.value))) {	
       return false; 
    }     
    return true;
  }
}

// ValidateElementTypeDigits
function ValidateElementTypeDigits(oElement, sLang) {
   switch (sLang) {
	case 'P': 
	    this.sMsgErr =  'O valor do campo ' +  oElement.getAttribute('Label') + ' não é válido';
	    break;

	case 'E':
	    this.sMsgErr =  'Please type a valid value in field ' +  oElement.getAttribute('Label');
	    break;
	}
  this.oElement = oElement;

  this.validate = function () {	
    if (!(/^(\d)+$/.test(oElement.value))) {	
       return false; 
    }     
    return true;
  }
}

// ValidateElementTypeCaracter
function ValidateElementTypeCaracter(oElement, sLang) {
   switch (sLang) {
	case 'P': 
	    this.sMsgErr =  'O campo ' +  oElement.getAttribute('Label') + ' não pode conter caracteres especiais';
	    break;

	case 'E':
	    this.sMsgErr =  'Please do not type special characters in field ' +  oElement.getAttribute('Label');
	    break;
	}
  this.oElement = oElement;

  this.validate = function () {	
    if (!(/^(\w|\d)+$/.test(oElement.value))) {	
       return false; 
    }     
    return true;
  }
}

// ValidateElementTypeCEP
function ValidateElementTypeCEP(oElement, sLang) {
   switch (sLang) {
	case 'P': 
	    this.sMsgErr =  'CEP inválido';
	    break;

	case 'E':
	    this.sMsgErr =  'Invalid ZIP Code';
	    break;
	}
  this.oElement = oElement;

  this.validate = function () {	
    if (!(/^(\d\d\d\d\d(-)?\d\d\d)+$/.test(oElement.value))) {	
       return false; 
    }     
    return true;
  }
}

// ValidateElementTypeDate
function ValidateElementTypeDate(oElement, sLang) {
   switch (sLang) {
	case 'P': 
	    this.sMsgErr =  'Data inválida';
	    break;

	case 'E':
	    this.sMsgErr =  'Invalid date';
	    break;
	}
  this.oElement = oElement;

  this.validate = function () {	
    var Datevalue = "";
    var day;
    var month;
    var year;
    var leap = 0;
    var i;
    var aDate = new Array();
    var sPart01;
    var sPart02;
    var sPart03;	

    DateValue = oElement.value;

    // Validate Date's shape 
    if (!(/^\d{1,2}\/\d{1,2}\/\d{2,2}(\d{2,2})?$/.test(DateValue))) {			 		 	   
       return false; 									
    } 

    // Year 2000 correction
   if (DateValue.length == 6) {
       DateValue = DateValue.substr(0,4) + '20' + DateValue.substr(4,2);     
    }

    // Define fields day,month,year
    aDate = DateValue.split("/");
   
    if (oElement.getAttribute('Pattern') == "US"){     
       month = aDate[0];
       day   = aDate[1];
    }
    else {
       month = aDate[1];
       day   = aDate[0];
    }
     
    year = aDate[2];

    // Validate Month and day
    if ((month < 1) || (month > 12)) {
      return false;
    }

    if (day < 1) {
     return false;
    }
   
    if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12"))) {
      return false;
    }
 
    if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) {
      return false;
    }   

    // Validation leap-year / february / day */
    if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) {
      leap = 1;
    }
    if ((month == 2) && (leap == 1) && (day > 29)) {
      return false;
    }
    if ((month == 2) && (leap != 1) && (day > 28)) {
      return false;
    }

    return true;
    }
}

// Classe ValidateElementTypeNumber 

function ValidateElementTypeNumber(oElement, sLang) {
   switch (sLang) {
	case 'P': 
	    this.sMsgErr =  'Número inválido';
	    break;

	case 'E':
	    this.sMsgErr =  'Invalid number';
	    break;
	}
  this.oElement = oElement;
  this.sLang = sLang

  function CreateMask(){
    var sMask ;
    var sSeparator = "";
    var reRegExp

    sMask= "^[-]?";
    sMask = sMask + "(\\d+)"; 

    if (oElement.getAttribute('Pattern') == 'US') {
       sSeparator = "[.]";
    } else {
       sSeparator = "[,]";
    }
   
    if (oElement.getAttribute('DecimalPlaces') != null) {
      sMask = sMask + "(" + sSeparator + "\\d{1," + oElement.getAttribute('DecimalPlaces') + "}" + ")?";   
    } 

    sMask= sMask + "$"; 

    reRegExp = new RegExp(sMask);

    return reRegExp;
  }

  this.validate = function () {	
    var reRegExp = CreateMask();
    var dNumber  = oElement.value;

    var sInterval ="";

    if (!(reRegExp.test(dNumber))){			 		 	
      return false; 									
    }

    // Replace "," to "." 
    dNumber= dNumber.replace(",",".");
    
    // Verify interval
    // sequence LII,LIE,LSI,LSE , possible S - Exists, N - Not Exists
 
    if (oElement.getAttribute('LimitInfInc') != null) { 
       sInterval = "SN";
    } else {
      if (oElement.getAttribute('LimitInfExc') != null) {  
        sInterval = "NS";
      } else {
        sInterval = "NN";
      }
    }

    if (oElement.getAttribute('LimitSupInc') != null){ 
       sInterval = sInterval + "SN";
    }
    else{
      if (oElement.getAttribute('LimitSupExc') != null){ 
         sInterval = sInterval + "NS";
      } else {
         sInterval = sInterval + "NN";
      }
    }

   switch (this.sLang) {
	case 'P': 
	    this.sMsgErr = 'O valor digitado para o campo ' + oElement.getAttribute('Label') + ' não está dentro dos limites permitidos';
	    break;

	case 'E':
	    this.sMsgErr =  'The value you typed in field ' + oElement.getAttribute('Label') + ' is out of bounds';
	    break;
	}
    
    //After verify Interval Validate		
    switch (sInterval) {
    case 'SNNN':
       if (!(dNumber >= parseFloat(oElement.getAttribute('LimitInfInc')))) {
			 return false;
       }
       break;

    case 'SNSN':
       if (!(dNumber >= parseFloat(oElement.getAttribute('LimitInfInc')) && dNumber <= parseFloat(oElement.getAttribute('LimitSupInc')))) {
			 return false;
       }
       break;

    case 'SNNS':
       if (!(dNumber >= parseFloat(oElement.getAttribute('LimitInfInc')) && dNumber < parseFloat(oElement.getAttribute('LimitSupExc')))) {
			 return false;
       }
       break;

    case 'NSNN':	
       if (!(dNumber > parseFloat(oElement.getAttribute('LimitInfExc')))) {
			 return false;
       }
       break;

    case 'NSSN':	
       if (!(dNumber > parseFloat(oElement.getAttribute('LimitInfExc')) && dNumber <= parseFloat(oElement.getAttribute('LimitSupInc')))) {
			 return false;
       }
       break;

    case 'NSNS':	
       if (!(dNumber > parseFloat(oElement.getAttribute('LimitInfExc')) && dNumber < parseFloat(oElement.getAttribute('LimitSupExc')))) {
		    return false;
       }
       break;

    case 'NNSN':
       if (!(dNumber <= parseFloat(oElement.getAttribute('LimitSupInc')))){
	       return false;
       }
       break;

    case 'NNNS':	
       if (!(dNumber < parseFloat(oElement.getAttribute('LimitSupExc')))) {
			 return false;
       }
       break;
    }
   
    return true;	

  }                                                  
}

// ValidateElementTypeEmail

function ValidateElementTypeEmail(oElement, sLang) {
   switch (sLang) {
	case 'P': 
	    this.sMsgErr =  'E-mail inválido';
	    break;

	case 'E':
	    this.sMsgErr =  'Invalid e-mail';
	    break;
	}
  this.oElement = oElement;

  this.validate = function () {	
    if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(oElement.value))) {	
       return false; 
    }     
    return true;	
  }                                                  
}

// Classe ValidateElementTypeText  

function ValidateElementTypeText(oElement, sLang) {

  this.sMsgErr =  ' ';
  this.oElement = oElement;
  this.sLang = sLang;

  this.validate = function Validate() {	
    var sText = oElement.value;
 	 var iLimit;
 	 
 	 if (oElement.getAttribute('TextLimit') != '') {
 		iLimit = parseInt(oElement.getAttribute('TextLimit'));
		if (sText.length > iLimit) {	
			switch (this.sLang) {
			case 'P': 
			    this.sMsgErr =  'O campo ' +  oElement.getAttribute('Label') + ' deve ter no máximo ' + iLimit  + ' caracteres';	       
			    break;

			case 'E':
			    this.sMsgErr =  'Type at most ' + iLimit  + ' characters in field ' + oElement.getAttribute('Label');	       
			    break;
			}
		   return false; 
		}     
	 }   
    return true;	
  }                                                  
}

// Classe ValidateElementTypeCPFCNPJ 

function ValidateElementTypeCPFCNPJ(oElement, sLang) {
  var strCPFPat = /^\d{3}\.\d{3}\.\d{3}-\d{2}$/;
  var strCNPJPat = /^\d{2}\.\d{3}\.\d{3}\/\d{4}-\d{2}$/;

	switch (sLang) {
		case 'P': 
		    this.sMsgErr = 'O valor digitado não é um CPF válido';
		    break;

		case 'E':
		    this.sMsgErr = 'Invalid CPF';
		    break;
	}
  this.oElement = oElement;

  function DigitoCPFCNPJ(numCIC) {
      var numDois = numCIC.substring(numCIC.length-2, numCIC.length);
      var novoCIC = numCIC.substring(0, numCIC.length-2);

     //Alternate between CIC or CNPJ
     switch (numCIC.length){
     case 11 :
       numLim = 11;
       break;
     case 14 :
       numLim = 9;
       break;
     default : return false;
     }

     //Initiate process
     var numSoma = 0;
     var Fator = 1;

     for (var i=novoCIC.length-1; i>=0 ; i--) {
         Fator = Fator + 1;
         if (Fator > numLim) {
            Fator = 2;
         }
         numSoma = numSoma + (Fator * Number(novoCIC.substring(i, i+1)));
     }

     numSoma = numSoma/11;

     var numResto = Math.round( 11 * (numSoma - Math.floor(numSoma)));

     if (numResto > 1) {
        numResto = 11 - numResto;
     }
     else {
        numResto = 0;
     }
 
     //-- Primeiro dígito calculado. Fará parte do novo cálculo.
     var numDigito = String(numResto);
     novoCIC = novoCIC.concat(numResto);

    //--
    numSoma = 0;
    Fator = 1;
    for (var i=novoCIC.length-1; i>=0 ; i--) {
        Fator = Fator + 1;
        if (Fator > numLim) {
           Fator = 2;
        }
        numSoma = numSoma + (Fator * Number(novoCIC.substring(i, i+1)));
    }
    numSoma = numSoma/11;
    numResto = numResto = Math.round( 11 * (numSoma - Math.floor(numSoma)));
    if (numResto > 1) {
        numResto = 11 - numResto;
    }
    else {
        numResto = 0;
    }
  
    //-- Segundo dígito calculado.
    numDigito = numDigito.concat(numResto);
    if (numDigito == numDois) {
        return true;
    }
    else {
        return false;
    }

  }

  this.validate = function Validate() {	
     var sCPFCNPJ = oElement.value;
 	  var i; 
 		
 	  if (!(sCPFCNPJ.match(/^\d{3}\.\d{3}(\.)?\d{3}-\d{2}$/) || sCPFCNPJ.match(/^\d{11}$/) ||		
 	       sCPFCNPJ.match(/^\d{2}\.\d{3}\.\d{3}\/\d{4}-\d{2}$/) || sCPFCNPJ.match(/^\d{14}$/))) {
 	       return false;
 	  }     
 	
 	  sCPFCNPJ = sCPFCNPJ.replace(/[.-]/g, '');
 	  
     if (!DigitoCPFCNPJ(sCPFCNPJ)) {
         return false;
     }

     return true;
  }   
}

//  ValidationGroup: object to hold validation groups
function ValidationGroup (sLabel, sType) {
   this.sLabel = sLabel;
   this.sType = sType;
   this.aItems = new Array();
}

//  selectItem: selects an item in a combo
function selectItem (cbo, value) {
var i;

   for (i=0;i<cbo.options.length;i++) {
      if (cbo.options[i].value == value) {
         cbo.options[i].selected = true;
         break;
      }   
   }
}

// ValidateGroupTypeCheckbox
function ValidateGroupTypeCheckbox(aGroup, sLang) {

   switch (sLang) {
	case 'P': 
	    this.sMsgErr =  'No campo ' + aGroup[0].getAttribute('Label') + ', você deve marcar ao menos um item ';
	    break;

	case 'E':
	    this.sMsgErr = 'Check at least one ' + aGroup[0].getAttribute('Label');               
	    break;
	}
  this.aGroup = aGroup;
  
  this.validate = function () {
     var found = false

     for(i=0;i < this.aGroup.length;i++){
        if (this.aGroup[i].checked){
           found = true;
           break;
        }
     }
     if (!found) { 
        if (aGroup[0].getAttribute('GroupMessage') != null) {
				this.sMsgErr = aGroup[0].getAttribute('GroupMessage');  
		   }	 
        return false;
     }    
     return true;    
   }
}

