//PL_SCRIPT
//BIBLIOTECA DE VALIDAÇÃO DE ENTRADA DE DADOS
//AUTOR: Rodrigo Magno Santos Souza
//VERSÃO: 1.5
//ÚLTIMA ALTERAÇÃO: 04/10/2001

var i = 1;
var vFieldList = new Array();
var vValidateSpaces = new Array();
var focus = "";
var select = "";
var imgFocus = "";
var imgSelect = "";
var errMessage = "";
var dobPattern = /\d{2}\/\d{2}\/\d{4}/;
var timePattern = /\d{2}:\d{2}/;
var yesnoPattern = /[SN]/;
var upperPattern = "ABCDEFGHIJKLMNOPQRSTUVWYXZ ";
var upperNumberPattern = "0123456789"+upperPattern;
var valOK = true;
var q;
var HIDDEN;


function criaValidateSpace(validateSpace, objMsg, outrasValidacoes)
{
	var testArray = new Array();
	testArray = getValidateSpaceArray(validateSpace);

	if(testArray == null)
		vValidateSpaces[vValidateSpaces.length] = new ValidateSpace(validateSpace,new Array(), objMsg,outrasValidacoes);
}

function ValidateSpace (name, array, objMsg,outrasValidacoes)
{
	this.name = name;
	this.array = array;
	this.objMsg = objMsg;
	this.outrasValidacoes = outrasValidacoes;

}

function getValidateSpaceArray( validateSpace)
{
	for(j = 0; j < vValidateSpaces.length; j++)
	{
		if(vValidateSpaces[j].name == validateSpace)
			return vValidateSpaces[j].array;
	}
	return null
}

function getOutrasValidacoes(validateSpace)
{
	for(j = 0; j < vValidateSpaces.length; j++)
	{
		if(vValidateSpaces[j].name == validateSpace)
			return vValidateSpaces[j].outrasValidacoes;
	}
	return null
}


function regCampoVal(validateSpace, fieldObj, fieldLabel, isRequired, dataType, fieldType, hidden)
{
	vArray = getValidateSpaceArray(validateSpace);
	vArray[vArray.length] = new vField(fieldObj, fieldLabel, isRequired, dataType, fieldType, hidden);
}

function vField(fieldObj, fieldLabel, isRequired, dataType, fieldType, hidden)
{
	this.fieldName 	= fieldObj;
	this.fieldObj 	= eval("Page."+fieldObj);
	this.fieldLabel = fieldLabel;
	this.isRequired = isRequired;
	this.dataType 	= dataType;
	this.fieldType 	= fieldType;
	this.hidden 	= hidden;
}

function jsImageSubmit(name, validateSpace)
{
	if (document.all[name].Validar)
	{   
		if (!pageValidate(validateSpace))
		{
			Page.FOCUS.value=imgFocus;
			Page.SELECT.value=imgSelect;
			imgFocus = "";
			imgSelect = "";
			return false;
		}
		var outVal = getOutrasValidacoes(validateSpace); 
		if(outVal != "")
		{
			if(!(eval(outVal)))
			{
				return false;
			}
		}
	}
	if (document.all[name].Confirmar)
	{
		if (!confirm(document.all[name].Msg))
		{
			return false;
		}
	}
	return true;
//	com_sssw_submit(name);
}

function jsImageSubmitAll(name)
{
	for(y = 0; y<vValidateSpaces.length; y++)
	{

		validateSpace = vValidateSpaces[y].name;

		if (!pageValidate(validateSpace))
		{
			eval(focus);
			eval(select);
			focus = "";
			select = "";
			return;
		}
	}
	if (vValidateSpaces.length > 1)
	{
		var msg = "";
		for(y = 1; y<vValidateSpaces.length; y++)
		{
			if(msg != "")
				msg +=	", "+vValidateSpaces[y].objMsg;
			else
				msg +=	vValidateSpaces[y].objMsg;
		}
		alert("Salve os dados de "+msg)	
		return;
	}
	var outVal = getOutrasValidacoes(validateSpace); 
	if(outVal != "")
	{
		if(!(eval(outVal)))
		{
			return false;
		}
	}
	document.forms[0].elements['AgEvtSrc'].value= eval("Page."+name+".name");
	document.forms[0].submit();

}

function jsButtonSubmitAll(name)
{
	for(y = 0; y<vValidateSpaces.length; y++)
	{

		validateSpace = vValidateSpaces[y].name;

		if (!pageValidate(validateSpace))
		{
			if(HIDDEN != "TRUE" || HIDDEN != "true")
			{
				eval(focus);
				eval(select);
			}
			focus = "";
			select = "";
			return;
		}
	}
	if (vValidateSpaces.length > 1)
	{
		var msg = "";
		for(y = 1; y<vValidateSpaces.length; y++)
		{
			if(msg != "")
				msg +=	", "+vValidateSpaces[y].objMsg;
			else
				msg +=	vValidateSpaces[y].objMsg;
		}
		alert("Salve os dados de "+msg)	
		return;
	}
	var outVal = getOutrasValidacoes(validateSpace); 
	if(outVal != "")
	{
		if(!(eval(outVal)))
		{
			return;
		}
	}
	document.forms[0].elements['AgEvtSrc'].value= eval("Page."+name+".name");
	document.forms[0].submit();

}

function jsButtonSubmit(name, validateSpace)
{
	buttonObj = eval("Page."+name);
	if (buttonObj.Validar)
	{
		if (!pageValidate(validateSpace))
		{
			if(HIDDEN != "TRUE" && HIDDEN != "true")
			{
				eval(focus);
				eval(select);
			}
			focus = "";
			select = "";
			return;
		}
		var outVal = getOutrasValidacoes(validateSpace); 
		if(outVal != "")
		{
			if(!(eval(outVal)))
			{
				return;
			}
		}
	}
	if (buttonObj.Confirmar)
	{
		if (!confirm(buttonObj.Msg))
		{
			return;
		}
	}
	document.forms[0].elements['AgEvtSrc'].value= eval("Page."+name+".name");
	document.forms[0].submit();
	
}

function leapYear(Year) 
{
        if (((Year % 4)==0) && ((Year % 100)!=0) || ((Year % 400)==0))
	{
        	return (1);
	}
        else
		return (0);
}

function pageValidate(validateSpace) 
{
	var ddd, yyyy, hh, mm;
	var amIempty;
	q = 0;
	valOK =true;
	errMessage = "";
       
	vFieldList = getValidateSpaceArray(validateSpace);


	while(q<vFieldList.length)
	{
		
		HIDDEN = vFieldList[q].hidden;
		if(vFieldList[q].fieldType == "COMBO")
		{
			index = vFieldList[q].fieldObj.selectedIndex;
			if(index == 0)
			{
				valOK = false;	
				errMessage += "Selecione "+vFieldList[q].fieldLabel+"." ;
				if(focus == "")
				{
					focus = "vFieldList["+q+"].fieldObj.focus()";
					imgFocus = vFieldList[q].fieldName;
				}
			}
		}
		else if(vFieldList[q].fieldType == "FIELD")
		{
			value = vFieldList[q].fieldObj.value;
		
			if ( value == "" ) 
			{
				if (vFieldList[q].isRequired == "TRUE" || vFieldList[q].isRequired == "true") 
				{
					valOK =false;	
					errMessage += "O campo "+vFieldList[q].fieldLabel + " é obrigatório!\n";
					if(focus == "")
					{
						focus = "vFieldList["+q+"].fieldObj.focus()";
						imgFocus = vFieldList[q].fieldName;
					}
				} 
			} 
			else 
			{	
				switch (vFieldList[q].dataType) 
				{
	
					case "INTEGER": 
					{
						testaInteger();
						break;
					}
					case "NUMBER": 
					{
						testaNumber();
						break;
					}
					case "TIME": //time 
					{
						testaTime(value, timePattern,q);
						break;
					}
					case "DATE": 
					{
						testaDate(value,q);
						break;
					}
					case "DATETIME": //Datetime 
					{
						date = value.substring(0,10);
						testaDate(date,q);
						testaDateTime();					
						break;
					}
					case "CPF": 
					{
						testaNumber();
						if(valOK)
							testaCPF(vFieldList[q].fieldObj.value);
						break;
					}
					case "CNPJ": 
					{
						testaNumber();
						if(valOK)
							testaCNPJ(vFieldList[q].fieldObj.value);
						break;
					}
					case "EMAIL": 
					{
						testaEmail(vFieldList[q].fieldObj.value);
						break;
					}
					case "YESNO": 
					{
						testaYesNo();
						break;
					}
					case "STRING_UPPER": 
					{
						testaMaiusculas();
						break;
					}
					case "STRING_UPPER_NUMBER": 
					{
						testaMaiusculasNumeros();
						break;
					}
					case "STRING": 
					{	
						break;
					}
				}
			}
		}
		else
		{
			errMessage = "O tipo do campo não está definido corretamente.";
			q = vFieldList.length;
		}
		q++;
		if(!valOK)
			q = vFieldList.length;		
	}
	if (errMessage != "") 
	{
		alert(errMessage);
		return false;
	} else 
	{
		return true;
	}
}


function getName(id)
{

	if(eval("document.all['"+id+"']"))
	{
		elemento  = eval("document.all['"+id+"']");
		return elemento;
	}
	else
		return "";

/*	var i = 0;
	while (i < document.forms[0].length)
	{
		var idElemento = document.forms[0].elements[i].id
		var nomElemento = document.forms[0].elements[i].name
		if(idElemento == id)
		{
			elemento  = document.forms[0].elements[nomElemento];
			return elemento;
		}	
		i++;	
	}
*/
}

function testaTime(value, q)
{
	if (timePattern.test(value))  
	{
		hh = parseInt(value.substr(0, 2), 10);
		mm = parseInt(value.substr(3, 2), 10);
		if (hh<0 || hh>24 || mm<0 || mm>60)
		{
			valOK = false;	
			errMessage += "Por favor entre com valores válidos " 
				+ vFieldList[q].fieldLabel +".\n";
			if(focus == "")
			{
				select = ("vFieldList["+q+"].fieldObj.select()");
				imgSelect = vFieldList[q].fieldName;
			}
		}
	} 
	else 
	{
		valOK =false;	
		errMessage += "Por favor entre com o formato 'hh:mm' para " 
		+ vFieldList[q].fieldLabel +".\n";
		if(focus == "")
		{
			select = ("vFieldList["+q+"].fieldObj.select()");
			imgSelect = vFieldList[q].fieldName;
		}
	}
}

function testaDate(value, q)
{
	if (dobPattern.test(value)) 
	{
		dd = parseInt(value.substr(0, 2), 10);
		mm = parseInt(value.substr(3, 2), 10);
		yyyy = parseInt(value.substr(6, 4), 10);
		if ((mm == 2 && dd > 28 && leapYear(yyyy)== 0) ||
		   (dd<1 || dd> 31 || yyyy<1 || mm<0 || mm>12) ||
		   ((mm == 4 && dd > 30) || (mm == 6 && dd > 30) || 
		   (mm ==9 && dd > 30) || (mm == 11 && dd > 30)))
		{	
			if(focus == "")
			{
				select = ("vFieldList["+q+"].fieldObj.select()");
				imgSelect = vFieldList[q].fieldName;
			}
			valOK =false;	
			errMessage += vFieldList[q].fieldLabel +" informada é inválida!" ;
		}
		
	} 
	else 
	{
		if(focus == "")
		{
			select = ("vFieldList["+q+"].fieldObj.select()");
			imgSelect = vFieldList[q].fieldName;
		}
		valOK = false;	
		errMessage += "Por favor entre com o formato 'dd/mm/aaaa' para " 
			+vFieldList[q].fieldLabel +".\n";
	}
}

function testaDateTime()
{
	if(value.substring(10,11) != " " && value.substring(10,11) != "" && valOK)
	{
		valOK =false;
		errMessage += "Não há separação entre data e horário."; 
		if(focus == "")
		{
			focus = ("vFieldList["+q+"].fieldObj.focus()");
			imgFocus = vFieldList[q].fieldName;
		}
	}
	else 
	{
		time = value.substring(11,16);
		if(time != "")
		{
			if(valOK)	
			testaTime(time,q);
		}
		else
		{
			valOK =false;
			errMessage += "Informe um horário para "+vFieldList[q].fieldLabel; 
			if(focus == "")
			{
				focus = ("vFieldList["+q+"].fieldObj.focus()");
				imgFocus = vFieldList[q].fieldName;
			}
		}
	}
}

function testaInteger()
{
	if (value.indexOf(',')>=0 || value.indexOf('.')>=0 || isNaN(parseInt(value)))
	{
		valOK =false;	
		errMessage += "O valor de "+vFieldList[q].fieldLabel + " deve ser um inteiro!\n";
		if(focus == "")
		{
			select = ("vFieldList["+q+"].fieldObj.select()");
			imgSelect = vFieldList[q].fieldName;
		}
	}

}

function testaNumber()
{
	if (isNaN(parseFloat(value)))
	{
		valOK =false;
		errMessage += "Valor de "+vFieldList[q].fieldLabel 
		+ " deve ser um número!\n";
		if(focus == "")
		{
			select = ("vFieldList["+q+"].fieldObj.select()");
			imgSelect = vFieldList[q].fieldName;
		}
	}

}

function testaMaiusculas()
{
	text = value
	while(text.length > 0 && valOK)
	{
		if (upperPattern.indexOf(text.substring(0,1)) == -1)
		{
			if(focus == "")
			{
				select = ("vFieldList["+q+"].fieldObj.select()");
				imgSelect = vFieldList[q].fieldName;
			}
			valOK = false;			
			errMessage += "No campo "+vFieldList[q].fieldLabel +" digite apenas letras de A-Z maiúsculas ou espaços.";
		}
		text = text.substring(1,text.length);
	}
	
}

function testaMaiusculasNumeros()
{
	text = value
	while(text.length > 0 && valOK)
	{
		if (upperNumberPattern.indexOf(text.substring(0,1)) == -1)
		{
			if(focus == "")
			{
				select = ("vFieldList["+q+"].fieldObj.select()");
				imgSelect = vFieldList[q].fieldName;
			}
			valOK = false;			
			errMessage += "No campo "+vFieldList[q].fieldLabel +" digite apenas letras de A-Z maiúsculas ou números de 0-9 ou espaços.";
		}
		text = text.substring(1,text.length);
	}	
}


function testaYesNo()
{
	if (!yesnoPattern.test(value))
	{
		if(focus == "")
		{
			select = ("vFieldList["+q+"].fieldObj.select()");
			imgSelect = vFieldList[q].fieldName;
		}
		valOK = false;			
		errMessage += "Por favor entre com 'S' ou 'N' para " 
		+ vFieldList[q].fieldLabel +".\n";
	}
	
}

function testaEmail()
{
	if (!validaEmail(vFieldList[q].fieldObj.value))
	{
		valOK =false;	
		errMessage += "Informe um endereço de email válido\n";
		if(focus == "")
		{
			select = ("vFieldList["+q+"].fieldObj.select()");
			imgSelect = vFieldList[q].fieldName;
		}
	}

}

function testaCPF()
{
	if (!validaCPF(vFieldList[q].fieldObj.value))
	{
		valOK =false;	
		errMessage += "Informe número de CPF válido!\n";
		if(focus == "")
		{
			select = ("vFieldList["+q+"].fieldObj.select()");
			imgSelect = vFieldList[q].fieldName;
		}
	}

}

function mostraUsuarios(controle)
{
	var choice = eval("Page."+controle);
	var grupo = choice.options[choice.selectedIndex].text
	window.open("pgMostraUsuariosGrupo.html?grupo="+grupo,"grupo","toolbars=no,width=350,height=250");	
}

