//=========================================
//
//        Virtualize Framework
//
//        Arivan Bastos. 27/06/2008
//
//        Funções para validação de preenchimento de formulário
//
//
//==========================================

var STATUS_OK 		= -1;
var STATUS_EMPTY 		= 0;
var MIN_LOGIN_SIZE	= 5;
var MIN_PASSWORD_SIZE	= 5;

var VFW_FIELD_ERRORS = new Array(	"Campo %FIELD_NAME% obrigatório.",		// 0
									"E-mail inválido.",		
									"Confirme o seu e-mail.",  
									"Confirmação não coincide com e-mail informado.",
									"Telefone inválido.",
									"CPF inválido", // 5
									"CEP inválido.",
									"CNPJ inválido",
									"O nome de usuário deve ter ao menos " + MIN_LOGIN_SIZE + " caracteres.",
									"A senha deve ter ao menos " + MIN_PASSWORD_SIZE + " caracteres.",
									"Confirme sua senha.", // 10
									"As senhas digitadas não são iguais.",
									"Número inválido.",
									"Data inválida.",
									"Idade inválida."
									);

// ----------------------------------------------------------------------
var nbsp 		= 160;                // non-breaking space char
var emptyString = /^\s*$/
var glb_vfld;
// ---------------------------------------------------------------------

var VFW_FORM_NOTIFICIATION_ALERT = 1;
var VFW_FORM_NOTIFICIATION_SPAN  = 2;



function validateForm(oFormName)
{
    return VFW_ValidateForm(oFormName, VFW_FORM_NOTIFICIATION_SPAN);
}

function VFW_ValidateForm(oFormName, notification_method)
{	
    //alert("validateForm");
    if (typeof oFormName == "string")
    {
        oFormName = document.forms[oFormName] || document.getElementById(oFormName);
    }
	
    var errs 		= 0;
	var errs_str	= "Foram encontrados os seguintes erros no preenchimento do formul�rio:\n";
	var VFW_ValidationFunction = null;
    for (var i = 0; i < oFormName.elements.length; i++) 
    {
        var el = oFormName.elements[i];

        // Campo n�o � obrigat�rio e est� vazio.
        if (VFW_IsNotRequiredAndNotFilled(el))
        {
			if (notification_method == VFW_FORM_NOTIFICIATION_SPAN) VFW_SetSpanContent("inf_" + el.name, "");
        }
        else
        {			
            if (el.getAttribute("vfwtype") != undefined)
            {				
				// Identifica a fun��o de valida��o de acordo com o tipo do campo.
                switch (el.getAttribute("vfwtype")) 
                {
                    case "username"		: VFW_ValidationFunction = VFW_ValidateLogin; break;                    
                    case "password"		: VFW_ValidationFunction = VFW_ValidatePassword; break;
                    case "password_confirm": break;
                    case "number"		: VFW_ValidationFunction = VFW_ValidateNumber; break;
                    case "email"		: VFW_ValidationFunction = VFW_ValidateEmail; break;
                    case "date"			: VFW_ValidationFunction = VFW_ValidateDate; break;
                    case "datetime"		: VFW_ValidationFunction = VFW_ValidateDateTime; break;
                    case "telephone"	: VFW_ValidationFunction = VFW_ValidateTelephone; break;
                    case "cpf"			: VFW_ValidationFunction = VFW_ValidateCPF; break;
                    case "cep"			: VFW_ValidationFunction = VFW_ValidateCEP; break;
                    case "cnpj"			: VFW_ValidationFunction = VFW_ValidateCNPJ;break;
					case "select"		: VFW_ValidationFunction = VFW_ValidateEmpty;break;
                    case ""				: VFW_ValidationFunction = VFW_ValidateEmpty; break;
					default				: VFW_ValidationFunction = VFW_ValidateEmpty; break;
                }
				
				//alert(el.id + " " + VFW_ValidationFunction);
				
				if (VFW_ValidationFunction != null)
				{
					var error_code = VFW_ValidationFunction(el.id, true);
					//errs.push({code: error_code, element_id: el.id, message: VFW_FIELD_ERRORS[error_code]});
				
					if (error_code != STATUS_OK)
					{							
						var label     = (el.getAttribute("label") != undefined ? el.getAttribute("label") : el.name);
						var error_msg = VFW_FIELD_ERRORS[error_code];
						
						if (error_code == STATUS_EMPTY)
						{
							error_msg = error_msg.replace("%FIELD_NAME%", label);
						}					
						errs++;
						switch (notification_method)
						{
							case VFW_FORM_NOTIFICIATION_ALERT: 								
								errs_str += "- " + error_msg + "\n"; 
								break;
							
							default: 
								VFW_SetSpanContent(el.id, error_msg); 
								break;
						}
					} 
					else
					{
						VFW_SetSpanContent(el.id, "");
					}
				}
            }
        }
    }
	
	switch (notification_method)
	{
		case VFW_FORM_NOTIFICIATION_ALERT: if (errs > 0)  alert(errs_str); break;		
		default					: break;
	}
    return (errs == 0);
}

function VFW_IsNotRequiredAndNotFilled(element)
{
    return ((element.getAttribute("vfwrequired") == 0) || (element.getAttribute("vfwrequired") == "")) && (element.value == "");
}

// -----------------------------------------
//                  trim
// Trim leading/trailing whitespace off string
// -----------------------------------------

function trim(str)
{
  return str.replace(/^\s+|\s+$/g, '')
};


// -----------------------------------------
//                  setfocus
// Delayed focus setting to get around IE bug
// -----------------------------------------

function setFocusDelayed(vfld)
{
  glb_vfld.focus()
}

function setfocus(vfld)
{
  glb_vfld = vfld;
  setTimeout( 'setFocusDelayed()', 100 );
}


function VFW_SetSpanContent(id, message)
{
	// setting an empty string can give problems if later set to a 
	// non-empty string, so ensure a space present. (For Mozilla and Opera one could 
	// simply use a space, but IE demands something more, like a non-breaking space.)
	var dispmessage;
	if (emptyString.test(message))    	dispmessage = String.fromCharCode(nbsp);    
	else  								dispmessage = message;
	
	var elem = document.getElementById("inf_" + id);
	if (elem)
	{
		elem.firstChild.nodeValue = dispmessage;  
	}
}


function VFW_IsEmpty(id)
{
    var elem  = document.getElementById(id);
	return emptyString.test(elem.value);
}

function VFW_ValidateEmpty(id, required)
{
	if (VFW_IsEmpty(id)) return STATUS_EMPTY;
	return STATUS_OK;
}

function VFW_ValidateLogin(id, required)
{
	if (required && VFW_IsEmpty (id)) return STATUS_EMPTY;
    
	var elem  = document.getElementById(id);		
	if (elem.value.length < MIN_LOGIN_SIZE) return 8;
    
	return STATUS_OK;
}

function VFW_ValidatePassword(id, required)
{
	if (required && VFW_IsEmpty (id)) return STATUS_EMPTY;
		
	var elem  = document.getElementById(id);
    if (elem.value.length < MIN_PASSWORD_SIZE)
    {
        return 9;
    }

    // Campo de confirma��o de senha.
    var confirm = document.getElementById(id + "_confirm");
    if (confirm)
    {
        // Verifica se a confirma��o e a senha s�o iguais.
        if (confirm.value != elem.value) return 1;
    }  
    return STATUS_OK;
}

function VFW_ValidateEmail  (id, required)   // true if required
{ 
	if (required && VFW_IsEmpty (id)) return STATUS_EMPTY;

	var elem  = document.getElementById(id);
    var tfld = trim(elem.value);  // value of field with whitespace trimmed off
    var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/
    if (!email.test(tfld)) return 1;

    var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/
    if (!email2.test(tfld)) return 1;
    
    // Campo de confirma��o do e-mail.
    var confirm = document.getElementById(id + "_confirm");
    if (confirm)
    {
		if (confirm.value == "") return 1;
		
        // Verifica se a confirma��o e o e-mail s�o iguais.
        if (confirm.value != elem.value) return 2;
    }  	
	
	return STATUS_OK;
}

function VFW_ValidatePassword(id, required)
{
	if (required && VFW_IsEmpty (id)) return STATUS_EMPTY;

	var elem  = document.getElementById(id);
	if (elem.value.length < MIN_PASSWORD_SIZE) return 9;
	
    var confirm = document.getElementById(id + "_confirm");
    if (confirm)
	{
		if (confirm.value == "") return 1;
		
		// Verifica se a confirma��o e o e-mail s�o iguais.
		if (confirm.value != elem.value) return 2;
	}
	
	return STATUS_OK;	
}

function VFW_ValidateInteger(id, required)
{
	if (required && VFW_IsEmpty (id)) return STATUS_EMPTY;

	var elem  	= document.getElementById(id);
    var tfld 	= trim(elem.value);  // value of field with whitespace trimmed off
    var nbr 	= /^[+-]?\d+$/;
    if (!nbr.test(tfld)) 
    {
        return 0;
    }
		
	return STATUS_OK;
}

function VFW_ValidateTelephone(id, required)
{
	if (required && VFW_IsEmpty (id)) return STATUS_EMPTY;
	
	var elem  	= document.getElementById(id);
	var tfld = trim(elem.value);  // value of field with whitespace trimmed off
	var telnr = /^\+?[0-9 ()-]+[0-9]$/
	if (!telnr.test(tfld)) return 4;

	var numdigits = 0;
	for (var j=0; j<tfld.length; j++)
	{
    	if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') numdigits++;
	}

	if (numdigits<6) 		return 4;	
	if (numdigits > 14) 	return 4;
	else if (numdigits < 7) return 4;
	
	return STATUS_OK;
}

function VFW_ValidateCEP(id, required)
{
	if (required && VFW_IsEmpty (id)) return STATUS_EMPTY;

	var elem  	= document.getElementById(id);
	var tfld = trim(elem.value);
	
	var cep_only_num = "";
	var count_num = 0;
	
	for (var j = 0; j < tfld.length; j++) 
	{
		if (tfld.charAt(j) >= '0' && tfld.charAt(j) <= '9') 
		{
			cep_only_num = cep_only_num + tfld.charAt(j);
		}
	}
	
	count_num = cep_only_num.length;
	
	if ( count_num  != 8) return 6;
	return STATUS_OK;
}

// -----------------------------------------
//    validateDate
//    Valida datas
// -----------------------------------------

function VFW_ValidateDate(id, required) 
{
	if (required && VFW_IsEmpty (id)) return STATUS_EMPTY;
	
    var expReg = /^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[1-2][0-9]\d{2})$/;
    
	var elem  	= document.getElementById(id);
    if ((elem.value.match(expReg)) && (elem.value!='')) return STATUS_OK; 

    return 13;
}


// -----------------------------------------
//    validateDateTime
//    Valida date time
// -----------------------------------------

function VFW_ValidateDateTime(id, required) 
{
    /*var expReg = /^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[1-2][0-9]\d{2})\s(d{1,2})\:(\d{1,2})\:(\d{1,2})$/;

    if (!validatePresent(vfld, ifld)) return false;

    if ((vfld.value.match(expReg)) && (vfld.value!='')) return true; 

    msg (ifld, "error", "Data/hora inv�lida.");
    setfocus(vfld);
    return false;*/

    return STATUS_OK;
}

function VFW_ValidateAge(id, required)
{
	if (required && VFW_IsEmpty (id)) return STATUS_EMPTY;

	var elem  	= document.getElementById(id);
	var tfld = trim(elem.value);
	var ageRE = /^[0-9]{1,3}$/
	
	if (!ageRE.test(tfld)) 		return 14;
	if (tfld>130 || tfld < 5) 	return 14;

	return STATUS_OK;
}

function VFW_ValidateNumber(id, required)
{
    return STATUS_OK;
}

function VFW_ValidateCPF(id, required)   // true if required
{
    if (required && VFW_IsEmpty (id)) return STATUS_EMPTY;

	var elem  	= document.getElementById(id);        
    var result 	= ValidateCPF(elem.value);
    if (!result) return 5;    

    return STATUS_OK;
}

function VFW_ValidateCNPJ(id, required)
{
	if (required && VFW_IsEmpty (id)) return STATUS_EMPTY;

    var elem = document.getElementById(id);
    var r 	 = validateCNPJ(elem.value);
    if (!r) return 7;
	
    return STATUS_OK;  
}

//-------------------------------------------------------------------
//	Auxiliares.
//-------------------------------------------------------------------
function ValidateCPF(cpf)
{
    var tfld = trim(cpf);

    var cpf_only_num    = "";
    var count_num       = 0;

    for (var j=0; j<tfld.length; j++)
    {
        if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') 
        {
            cpf_only_num = cpf_only_num  + tfld.charAt(j);
        }
    }

    count_num = cpf_only_num.length;
    if ( count_num  != 11) 
    {
        return false;
    }

    if( (cpf_only_num == '11111111111') || (cpf_only_num == '22222222222') ||
        (cpf_only_num == '33333333333') || (cpf_only_num == '44444444444') ||
        (cpf_only_num == '55555555555') || (cpf_only_num == '66666666666') ||
        (cpf_only_num == '77777777777') || (cpf_only_num== '88888888888') ||
        (cpf_only_num == '99999999999') || (cpf_only_num == '00000000000') ) 
    {
        return false;
    }
                
    //Fun��o de valida��o de CPF
    st2 = cpf_only_num;

    digito1 = st2.substring(9,10);
    digito2 = st2.substring(10,11);
    digito1 = parseInt(digito1,10);
    digito2 = parseInt(digito2,10);

    sum = 0; mul = 10;

    for (i = 0; i < 9 ; i++) 
    {
        digit = st2.substring(i,i+1);
        tproduct = parseInt(digit ,10) * mul;
        sum += tproduct;
        mul--;
    }

    dig1 = ( sum % 11 );

    if ( dig1==0 || dig1==1 )
    dig1=0;
    else
    dig1 = 11 - dig1;

    if (dig1!=digito1) 
    {
        msg (ifld, "error", CPF_ERRORS[1]);
        setfocus(vfld);
        return false;
    }

    sum = 0;
    mul = 11;

    for (i = 0; i < 10 ; i++) 
    {
        digit = st2.substring(i,i+1);
        tproduct = parseInt(digit ,10)*mul;
        sum += tproduct;
        mul--;
    }

    dig2 = (sum % 11);

    if ( dig2==0 || dig2==1 )   dig2=0;
    else                        dig2 = 11 - dig2;
    if (dig2 != digito2)
    {
        return false;
    }
    return true;   
};

function validateCNPJ(cnpj)
{
    var tfld = trim(cnpj);
    var cnpj_only_num = "";
    var count_num = 0;
 
    for (var j=0; j<tfld.length; j++)
    {
        if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') 
        {
            cnpj_only_num = cnpj_only_num  + tfld.charAt(j);
        }
    }

    count_num = cnpj_only_num.length;

    if ( count_num  != 14) 
    {
        return false;
    }

    var i;
    var s = cnpj_only_num;
    var c = s.substr(0,12);
    var dv = s.substr(12,2);
    var d1 = 0;

    for (i = 0; i < 12; i++)
    {
        d1 += c.charAt(11-i)*(2+(i % 8));
    }

    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 < 12; i++)
    {
        d1 += c.charAt(11-i)*(2+((i+1) % 8));
    }

    d1 = 11 - (d1 % 11);
    if (d1 > 9) d1 = 0;

    if (dv.charAt(1) != d1)
    {
        return false;
    }
    
    return true;
}
