/********************************************************************************
 Descrição : Modulo de Validações Genéricas para Formulários.
 Autor     : Ivon Neves Corrêa
 Data      : 06/07/2006
 ****************************** Modificações *************************************
 Descrição : Permitir o uso de "(aspas) no atributo mascara.
 Autor     : Ivon Neves Corrêa
 Data      : 19/07/2006
 ****************************** Modificações *************************************
 Descrição : Colocar validação com funções padrões.
 Autor     : Ivon Neves Corrêa
 Data      : 20/07/2006
 ****************************** Modificações *************************************
 Descrição : Colocar validação de Radion e Select.
 Autor     : Ivon Neves Corrêa
 Data      : 27/07/2006
********************************************************************************/
var strMsgErroPrincipal = null;
var modoselecao = 0;
function ValidaForm(frm) {
    var border      = new Object();		// criando o objeto border
	var intQtdInput = frm.elements.length;
	var alertMsg = "";
	var firstError = "";
	var contaObj = 0;
    border.require  = '1px solid rgb(255,0,0)'; // Define a borda utilizada nos elementos que estiverem
    border.normal   = '1px solid rgb(255,0,0)'; // como requeridos e não passarem nas verificações.
    border.alerta   = '1px solid rgb(0,255,0)'; 
	
	for (i=0; i < intQtdInput; i++) {
		var objCampo = frm.elements[i];
		if (objCampo.id == null) {
			alert('Atenção Desenvolvedor \n INPUT sem id.' + objCampo.name);
			return false;
		}
		if (objCampo.type == "text" || objCampo.type == "textarea" || objCampo.type == "password") {
		    if (objCampo.value == "") {
			  //objCampo.style.border = border.normal;
			}
			/************* Aqui começa a validação *************/
			if (objCampo.value == "") {
				if (objCampo.attributes["required"] != null) {
					if (objCampo.attributes["required"].value == "true") {
						// Se o campo required estiver = true então o campo não pode estar vazio.						
						var strRequiredMSG = objCampo.attributes["requiredmsg"].value;
						alertMsg += ("\t - " + strRequiredMSG + "\n");
						if (contaObj==0) {
   					      firstErro = objCampo;
						  contaObj = 1;
						}
					}
				}
			} else {
				if (objCampo.attributes["mascara"] != null && objCampo.attributes["errormsg"] != null) {
					// Se houver uma mascara e uma mensagem de erro, o campo é validado.
					if (objCampo.attributes["mascara"].value.search('^FNC#') != -1) {
						var strMascara = objCampo.attributes["mascara"].value.replace('FNC#', '');
						strMascara = eval(strMascara);
					}
					else { var strMascara = objCampo.attributes["mascara"].value; }
					var strErrorMSG = objCampo.attributes["errormsg"].value;
					var erroBoolean = false;
					//alert("mascara:" + strMascara + "\n MsgErro:" + strErrorMSG);
					switch (strMascara) 
					{
						case true :
							break;
							
						case false :
							alertMsg += ("\t - " + strErrorMSG + "\n");
						    //if (objCampo.value == "") objCampo.style.border = border.alerta;
							if (contaObj==0) {
   					          firstErro = objCampo;
							  contaObj = 1;
							}
							break;
							
						default :
							if (objCampo.value.search(strMascara) == -1) {
								alertMsg += ("\t - " + strErrorMSG + "\n");
  					            //if (objCampo.value == "") objCampo.style.border = border.alerta;
								if (contaObj==0) {
   					              firstErro = objCampo;
								  contaObj = 1;
								}
							}
					}//switch
				}//if
			}//else
		}//If(text|textarea|password)
		else {
			if (objCampo.type == "radio"){
				/*var checked = false;
				alert(objCampo.checked);
				for (var j=0; j < objCampo.length; j++){
					alert(objCampo[j].checked);
					if (objCampo[j].checked) { checked = true; }
				}
				if (checked && objCampo[0].attributes["required"].value != Null) { 
					alertMsg += ("\t - " + objCampo.attributes["requiredmsg"].value + "\n");
				}*/
			} else {
				if (objCampo.type == "select-one"){
					if (objCampo.options[objCampo.selectedIndex].value == ""){
 		                //objCampo.style.border = border.normal;
						if (objCampo.attributes["required"] != null) {
							if (objCampo.attributes["required"].value == "true") 
								alertMsg += ("\t - " + objCampo.attributes["requiredmsg"].value + "\n");	
						}
					}
				}
			}
		}
  	   if (objCampo.attributes["required"] != null) 
	     if (objCampo.attributes["required"].value == "true")
		    if (objCampo.value == "") objCampo.style.border = border.require;
	}//for
	if(alertMsg.length>0) {
		if (strMsgErroPrincipal != null) {
			alert(strMsgErroPrincipal + "\n\n" + alertMsg);
			if (firstErro.attributes["aba"] != null) {
  			  AlternarAbas('td_'+firstErro.attributes["aba"].value, 'div_'+firstErro.attributes["aba"].value);
			}
            firstErro.focus();		// retorna o foco para o campo			
			return false;
		}
		else {
			alert("Foram detectados os seguintes erros:\n\n" + alertMsg);
			if (firstErro.attributes["aba"] != null) {
  			  AlternarAbas('td_'+firstErro.attributes["aba"].value, 'div_'+firstErro.attributes["aba"].value);
			}
			firstErro.focus();		// retorna o foco para o campo			
			return false;
		}
	}
	else
		return true;
}
function SomenteNumeros() { return "^\\d+$"; }
function SomenteLetras() { return "^[\\D]+$"; }
function Data() { return "^((0?[1-9]|[12]\\d)\\/(0?[1-9]|1[0-2])|30\\/(0?[13-9]|1[0-2])|31\\/(0?[13578]|1[02]))\\/(18|19|20)?\\d{2}$"; }
function Hora() { return "^[\\d]{2}:[\\d]{2}$"}
function Email() { return "^[A-Za-z0-9]+([._+]{1}[a-zA-Z0-9]+)*[@]{1}[A-Za-z0-9]+([._]{1}[a-zA-Z0-9]+)*"; }
function Telefone(pais) {
	switch (pais){
		case "USA" || "CANADA":
			return "^[\\d]{10}$";
			break;
		default:
			return "^[(][\\d]{2}[)][ ][\\d]{4}[-]?[\\d]{4}$";
			break;
	}
}
function Cep(country) {
	switch (country) {
		case "Australia" || "Austria" || "Belgium" || "Netherlands" || "Denmark" || "Switzerland":
			return "^\\d{4}$";
			break;
		case "France" || "Espana" || "spain" || "Germany" || "United States" || "USA" || "Thailand" || "Sweden" || "Puerto Rico" || "Mexico" || "Italy":
			return "^\\d{5}$";
			break;
		case "Malaysia" || "India" || "China" || "Russia" || "Chile" || "Singapore":
			return "^\\d{6}$";
			break;
		case "Japan":
			return "^\\d{7}$";
			break;
		case "Great Britain":
			return "^[a-zA-Z][\\da-zA-Z][\\da-zA-Z][\\da-zA-Z][\\da-zA-Z][a-zA-Z]?[a-zA-Z]?$";
			break;
		case "Canada":
			return "^[0-9a-zA-Z]\\d[0-9a-zA-Z] \\d[0-9a-zA-Z]\\d$";
			break;
		default:
			return "^\\d{5}[-]?\\d{3}$";
			break;
	}
}

function selecao(){
  if (modoselecao==1) {
    modoselecao=0;
  } else {
    modoselecao=1;
  }
  for (i=0;i<document.frmvisualiza.elements.length;i++)
      if(document.frmvisualiza.elements[i].type == "checkbox")
         document.frmvisualiza.elements[i].checked=modoselecao;
}

function isCPF(st) {
	if (st == "")
		return (false);

	l = st.length;

	//aleterado para se usuário não digitar os zeros na frente do CPF, completar sozinho
	if ((l == 9) || (l == 8))
	{
		for (i = l ; i < 10; i++)
		{
			st = '0' + st
		}
	}

	l = st.length;
	st2 = "";
	for (i = 0; i < l; i++) {
		caracter = st.substring(i,i+1);
		if ((caracter >= '0') && (caracter <= '9'));
		st2 = st2 + caracter;
	}

	algUnico = true;
	for (i=1; i<11; i++)
	{
		algUnico = algUnico && (st.charAt(i-1) == st.charAt(i));
	}
	if (algUnico==true)
		return (false);

	if ((st2.length > 11) || (st2.length < 10))
		return (false);

	if (st2.length==10)
		st2 = '0' + st2;

	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)
		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 echeck(str)
{
	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);
	if (str.indexOf(at)==-1)
	{
		return false;
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr)
	{
		return false;
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr)
	{
		return false;
	}

	if (str.indexOf(at,(lat+1))!=-1)
	{
		return false;
	}

	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)
	{
		return false;
	}

	if (str.indexOf(dot,(lat+2))==-1)
	{
		return false;
	}

	if (str.indexOf(" ")!=-1)
	{
		return false;
	}

	return true;
}

