

function ValidaEmail(objField) 
{
	var f = objField.value
	
	if(f.length > 0 )
	{
		if (f.search("@") == -1 || f.search("[.*]") == -1) 
		{ 
			alert("O preenchimento do campo E-mail está incorreto!"); 
			return(false); 
		}
	}	
}


function isValidCPF(objField) {
	var i; 
	f = objField.value; 
	f = Replace(f,".","");
	f = Replace(f,"-","");
	f = Replace(f,"_","");
	
	for (i=0;i<10;i++)
	{
		if (Replace(f,i,"") == "")
			return false;
	}

	if (f.length !=11)
		return false;
	
	s = limpa_string(f); 
	var c = s.substr(0,9); 
	var dv = s.substr(9,2); 
	var d1 = 0; 
	for (i = 0; i < 9; i++) { 
		d1 += c.charAt(i)*(10-i); 
	} 
	if (d1 == 0) 
	{ 
		return false; 
	} 
	d1 = 11 - (d1 % 11); 
	if (d1 > 9) d1 = 0; 
	if (dv.charAt(0) != d1)
		return false; 
	
	d1 *= 2; 
	for (i = 0; i < 9; i++) 
	{ 
		d1 += c.charAt(i)*(11-i); 
	} 
	d1 = 11 - (d1 % 11); 
	if (d1 > 9) d1 = 0; 
	if (dv.charAt(1) != d1) 
		return false; 

	return true;
}

/*
* Função:	
*	ClientValidation 
*	 Apenas centraliza as chamadas dos scripts de validação.
* Parâmetros: 
*   objForm é o objeto form que está chamando a função
* Retorno:
*	true ou false.
* Observações:
*	No caso de retorno false será mostrada uma mensagem de alerta para o usuário 
*/
/*
    Padrão de nomes...
    Nome do textbox:                        nome1
    Nome do hidden de atributos:            nome1_attrib
    Nome do hidden com o titulo do erro:    nome1_title
*/
function ClientValidation(objForm)
{
	var i;
    
    // Percorro todos os elementos do FORM
    for (i=0; i<objForm.elements.length ; i++)
    {
        var elemActual = objForm.elements[i];
        
        // Verifico se é um hidden e o nome contém '_attrib' (inserido pelo NAS)
        if (elemActual.type == 'hidden' && elemActual.name.indexOf('_attrib') >= 0)
        {
            var attributes = elemActual;
            // Monto o ID do campo textbox através do nome do hidden de atributos
            var idObjTextbox = attributes.name.replace('_attrib','');
            var objInput = GetElem(idObjTextbox);
            var lstattributes = attributes.value;
           
			/*esta validação foi adicionada pois este script não estava
			validando os campos na ordem que está na tela.
			alert("ZIP CODE"); */
			if (idObjTextbox == "usr_homezip") {
				var cepTmp;
				cepTmp = GetElem("usr_homezip").value;
				cepTmp = Replace(cepTmp,"_","");
				cepTmp = Replace(cepTmp,"-","");
				if (cepTmp.length!=8)
				{
					alert("Por favor, preencha seu CEP válido.");
					GetElem("usr_homezip").focus();
					return false;
				}
				cepTmp = null;
			}

			/*esta validação foi adicionada pois este script não estava
			validando os campos na ordem que está na tela.
			alert("email"); */
			if (idObjTextbox == "usr_homeemail") {
				var bRet = ValidaEmail(GetElem("usr_homeemail"));
				if (bRet==false)
				{
					GetElem("usr_homeemail").focus();
					return false;
				}
			}
			/* alert("DadosPessoais_PostValidation"); */
			if (idObjTextbox == "TBLE_DEFICIENTE") {
				if (GetElem("TBLE_DEFICIENTE").value != "N" && GetElem("TBLE_DEFICIENTE").value != "") {
					if (GetElem("TBLE_DEFICIENCIA").value.length < 1) {
						alert("O campo 'Deficiencia' é requerido.");
						GetElem("TBLE_DEFICIENCIA").focus();
						return false;
					}
				}
			}

			/* 
			esta validação foi adicionada pois este script não estava
			validando os campos na ordem que está na tela.
			*/
			if (idObjTextbox == "usr_homezip") {
				if (GetElem("usr_homezip").value == "_____-___") {
					alert("O campo 'CEP' é requerido.");
					GetElem("usr_homezip").focus();
					return false;
				}
			}
			
			if(!objInput.disabled)
			{
	            if(!IsValidContent(objInput,lstattributes))
	            {
	                return  false;
	            }    
			}
        }
		
		if((elemActual.type == 'select-one' || elemActual.type == 'select-multiple') && (elemActual.value == "" || elemActual.value == null)){
			if (!elemActual.disabled){
				alert("Selecione um valor no combo.");
				elemActual.focus();
				return false;
			}
		}
    }
}

// formato dos atributos: "notnull,minlen=1,maxlen=100"
function IsValidContent(objInput, lstattributes)
{
    var i;
    var inputValue = Replace(objInput.value, " ","");
    
    // Retiro todos os espaços
    lstattributes = Replace(lstattributes, " ", "");
    
    // quebro os atributos, para ficar attributes[0]=notnull , attributes[1]=minlen=1, attributes[2]=maxlen=100
    var attributes = lstattributes.split(",");
    
    // percorro cada atributo
    for(i=0;i<attributes.length;i++)
    {
        var attribute,attributeName, attributeValue;
        
        // alguns atributos não tem valor somente o nome (como notnull...) que não precisa valor
        if(attributes[i].indexOf("=") >= 0)
        {
            attribute = attributes[i].split("=");
            attributeName = attribute[0];
            attributeValue = attribute[1];
        }else{
            attributeName = attributes[i];
            attributeValue = "";
        }
        attributeName = attributeName.toLowerCase();
        switch(attributeName)
        {
            // Testa campo vazio.
            case "notnull":
                if (inputValue == "")
                {
                   ShowAlert(objInput, "é requerido.");
                   return false;
                }
                
            break;
            
            // Testa valor inteiro.
            case "int":
            case "integer":
                if (inputValue == "")
                {
                   ShowAlert(objInput, "é requerido.");
                   return false;
                }
                
                if(parseInt(inputValue).toString() == "NaN")
                {
                   ShowAlert(objInput, "não é um número.");
                   return false;
                }
            break;
			
			// Testa valor decimal.
            case "dec":
            case "decimal":
                if (inputValue == "")
                {
                   ShowAlert(objInput, "é requerido.");
                   return false;
                }
                
                if(parseFloat(inputValue).toString() == "NaN")
                {
                   ShowAlert(objInput, "não é um número válido.");
                   return false;
                }
            break;

			
            // Testa valor minimo.
            case "minval":
                if (inputValue == "")
                {
                   ShowAlert(objInput, "é requerido.");
                   return false;
                }
                
                if(parseInt(inputValue).toString() == "NaN")
                {
                   ShowAlert(objInput, "não é um número.");
                   return false;
                }
                
                if(parseFloat(inputValue) < parseFloat(attributeValue))
                {
                   ShowAlert(objInput, "deve conter uma valor maior que '" + attributeValue +"'");
                   return false;
                }
            break;
            
            // Testa valor máximo.
            case "maxval":
                if (inputValue == "")
                {
                   ShowAlert(objInput, "é requerido.");
                   return false;
                }
                
                if(parseInt(inputValue).toString() == "NaN")
                {
                   ShowAlert(objInput, "não é um número.");
                   return false;
                }
                
                if(parseFloat(inputValue) > parseFloat(attributeValue))
                {
					ShowAlert(objInput, "deve conter uma valor menor que '" + attributeValue +"'");
					return false;
                }
            break;
            
            // Testa minimo de caracteres.
            case "minlen":
                if(inputValue.length < attributeValue)
                {
                   ShowAlert(objInput, "deve conter no mínimo '" + attributeValue +"' caracteres.");
                   return false;
                }
            break;
            
            // Testa máximo de caracteres.
            case "maxlen":
                if(inputValue.length > attributeValue)
                {
                   ShowAlert(objInput, "deve conter no máximo '" + attributeValue +"' caracteres.");
                   return false;
                }
            break;
            
            // Testa data.
            case "date":
                if (inputValue == "")
                {
                   ShowAlert(objInput, "é requerido.");
                   return false;
                }
                

                if (!IsValidDate(objInput.value))
	            {
					ShowAlert(objInput, "é inválido.");
	                return  false;
	            }    
            break;
        }
    
    }

    return true;

}

function IsValidDate(dateValue)
{
	if (ExecuteRegex(dateValue,/^(0?[1-9]|[12][0-9]|3[01])[\-\/](1[0-2]|0?[1-9])[\-\/]((19|20)\d{2})$/))
	{
		var temp_date = Replace(dateValue,'/','-');
		temp_date = temp_date.split('-');

		var isBissextile = ((parseInt(temp_date[2]) - 1884) / 4);
		if(isBissextile == Math.floor(isBissextile)) 
		{
			var arrayMonthDays= [31,29,31,30,31,30,31,31,30,31,30,31];
		}else{ 
			var arrayMonthDays= [31,28,31,30,31,30,31,31,30,31,30,31];
		}
		
		if(temp_date[0] > arrayMonthDays[parseInt(temp_date[1])-1] ) //verifica o dia
		{
			return false;
		}	
		arrayMonthDays=null;
	}else{
		
		return false;
	}
	return true;
}



function ExecuteRegex(strToMatch,regularExpression)
{
	return regularExpression.test(strToMatch);
}

function AppendNote(sText)
{
	alert(sText);
}

function ShowAlert(objInput, sulfixText)
{
    // Monto o campo que contém o errorTitle através do nome do textbox
    var errorTitle = GetElem(objInput.id+'_title');

    // o campo errorTitle pode não ser definido, por isso precisa da verificação
    if (errorTitle) 
    {
        AppendNote("O Campo '"+ errorTitle.value +"' "+sulfixText);
    }else{
        AppendNote("Campo '"+ objInput.id+'_title' +"'requerido.");
    }
    
	try
	{
		objInput.focus();
	}catch(e)
	{
	}
}


