/*
Biblioteca para validação de formulários
Autor: Pedro Moraes <pedro@engenhariadeweb.com.br>
Última atualização: Quinta-feira, 15 de Fevereiro de 2001
*/

function set(strRule) {
	arrRules[arrRules.length]=strRule;
}

function getFieldValue(objField) {
	if (objField.type=="select-one")
		return(objField.options[objField.selectedIndex].value);
	else
		return(objField.value);
}

function validateForm(objForm) {
	loadSettings(objForm);
	var strErrorMsg="";
	var objFieldToFocus=null;
	for (intRule=0;intRule<arrRules.length;intRule++) {
		strRuleValue=arrRules[intRule];
		strRuleName=null;
		strFieldName=strRuleValue;
		if (strRuleValue.indexOf("|")>0) {
			strFieldName=strRuleValue.split("|")[1];
			strRuleValue=strRuleValue.split("|")[0];
		}
		if (strRuleValue.indexOf("=")>0) {
			strRuleName=strRuleValue.split("=")[1];
			strRuleValue=strRuleValue.split("=")[0];
		}
		//alert(objForm[strRuleValue] + "|" + strRuleName);
		if (objForm[strRuleValue] || strRuleName=="externalFunction") {
			if (strRuleName) {
				switch (strRuleName) {
					case "externalFunction":
						extFunction=eval(strRuleValue);
						if (typeof(extFunction)=="function" || typeof(extFunction)=="object") {
							if (!extFunction(objForm)) return(false);
						}
						break;
					case "cpf":
						if (!verifyCPF(objForm[strRuleValue])) {
							if (!objFieldToFocus) objFieldToFocus=objForm[strRuleValue];
							strErrorMsg+=" - CPF inválido\n";
						}
						break;
					case "cgc":
						if (!verifyCGC(objForm[strRuleValue])) {
							if (!objFieldToFocus) objFieldToFocus=objForm[strRuleValue];
							strErrorMsg+=" - CGC inválido\n";
						}
						break;
					case "cep":
						if (!verifyCEP(getFieldValue(objForm[strRuleValue]))) {
							if (!objFieldToFocus) objFieldToFocus=objForm[strRuleValue];
							strErrorMsg+=" - CEP inválido\n";
						}
						break;
					case "email":
						if (!verifyMail(getFieldValue(objForm[strRuleValue]))) {
							if (!objFieldToFocus) objFieldToFocus=objForm[strRuleValue];
							strErrorMsg+=" - Email inválido\n";
						}
						break;
					case "date":
						if (trim(getFieldValue(objForm[strRuleValue]))!="") {
							if (!isDate(getFieldValue(objForm[strRuleValue]))) {
								if (!objFieldToFocus) objFieldToFocus=objForm[strRuleValue];
								strErrorMsg+=" - Data inválida - formato aceito: dd/mm/aaaa\n";
							}
						}
						break;
					case "visa":
						if (!isVisa(getFieldValue(objForm[strRuleValue]))) {
							if (!objFieldToFocus) objFieldToFocus=objForm[strRuleValue];
							strErrorMsg+=" - Número de cartão de crédito inválido\n";
						}
						break;
					case "master":
						if (!isMasterCard(getFieldValue(objForm[strRuleValue]))) {
							if (!objFieldToFocus) objFieldToFocus=objForm[strRuleValue];
							strErrorMsg+=" - Número de cartão de crédito inválido\n";
						}
						break;
					case "diners":
						if (!isDinersClub(getFieldValue(objForm[strRuleValue]))) {
							if (!objFieldToFocus) objFieldToFocus=objForm[strRuleValue];
							strErrorMsg+=" - Número de cartão de crédito inválido\n";
						}
						break;
					case "amex":
						if (!isAmericanExpress(getFieldValue(objForm[strRuleValue]))) {
							if (!objFieldToFocus) objFieldToFocus=objForm[strRuleValue];
							strErrorMsg+=" - Número de cartão de crédito inválido\n";
						}
						break;
				}
			}
			else {
				if (isEmpty(getFieldValue(objForm[strRuleValue]))) {
					if (!objFieldToFocus) objFieldToFocus=objForm[strRuleValue];
					strErrorMsg+=" - O campo " + strFieldName + " não foi preenchido\n";
				}
			}
		}
		//else(alert(strRuleValue + " nao eh um nome de campo"));
	}
	//Unir mensagens duplicadas
	arrErrorMsgs=strErrorMsg.split("\n");
	arrCleanErrors=new Array();
	for (i=0;i<arrErrorMsgs.length;i++) {
		if (!inArray(arrErrorMsgs[i],arrCleanErrors)) arrCleanErrors[arrCleanErrors.length]=arrErrorMsgs[i];
	}
	strErrorMsg=explode(arrCleanErrors,"\n");
	if (objFieldToFocus) {
		alert("Os seguintes erros foram encontrados no preenchimento do formulário:\n\n" + strErrorMsg);
		objFieldToFocus.focus();
		return(false);
	}
	return(true);
}

function explode(arrAnyArray,strSeparator) {
	var strReturnValue="";
	for (intPos=0;intPos<arrAnyArray.length;intPos++)
		strReturnValue+=arrAnyArray[intPos] + strSeparator;
	strReturnValue=strReturnValue.substring(0,strReturnValue.length-strSeparator.length);
	return(strReturnValue);
}

function inArray(strItem, arrAnyArray) {
	for (intPos=0;intPos<arrAnyArray.length;intPos++)
		if (arrAnyArray[intPos]==strItem) return true;
	return(false);
}

function isEmpty(strValue) {
	return(strValue==null || trim(strValue)=="");
}

function verifyMail(strEmail,strErrorMsg) {
	if (!strErrorMsg) strErrorMsg="E-mail inválido"; //Use the default error message if nothing is given
	strValidChars="@abcdefghijklmnopqrstuvxywzABCDEFGHIJKLMNOPQRSTUVXYWZ0123456789-_."; //Characters that an email can contain
	arrBoundaryChars=new Array();
	for (intPos=0;intPos<strEmail.length;intPos++) { //Check if all characters are valid
		strThisChar=strEmail.substr(intPos,1);
		if (strValidChars.indexOf(strThisChar)==-1) {
			return(false);
		}
		if (strThisChar=="@" || strThisChar==".") { //Feed the BoundaryChars array
			arrBoundaryChars[arrBoundaryChars.length]=parseInt(intPos);
		}		
	}
	for (intPos=0;intPos<arrBoundaryChars.length;intPos++) { //Check if dots and ats are not in conflict
		intThisItem=arrBoundaryChars[intPos]
		intNextItem=(intPos==arrBoundaryChars.length) ? 0 : arrBoundaryChars[intPos+1]
		if (intThisItem==0 || intThisItem==strEmail.length-1) {
			return(false);
		}
		if (intThisItem+1==intNextItem) {
			return(false);
		}
	}
		
	intFirstAtIndex=strEmail.indexOf("@");
	intLastAtIndex=strEmail.lastIndexOf("@");
	intFirstDotIndex=strEmail.indexOf(".");
	intLastDotIndex=strEmail.lastIndexOf(".");
	
	if (intFirstAtIndex!=intLastAtIndex || intFirstAtIndex==-1 || intFirstDotIndex==-1 || intLastDotIndex<intFirstDotIndex) {
		return(false);
	}
	return(true); //If it got here, it's all ok (I hope)
}

function isDate(date) {
	if (date.indexOf("/")==date.lastIndexOf("/")){ // se houver menos que duas barras caia fora
		return(false)
	}
	day=date.substr(0,date.indexOf("/"))
	month=date.substr(date.indexOf("/")+1,date.lastIndexOf("/")-date.indexOf("/")-1)
	year=date.substr(date.lastIndexOf("/")+1,date.length-date.lastIndexOf("/")-1)
	if (isNaN(day) || isNaN(month) || isNaN(year)) {
		return(false)
	}
	if (day<1 || day>31 || month<1 || month>12 || year<1800 || year>2200) {
		return(false)
	}
	return(true)
}

function trim(str) {
	var startIndex,endIndex,returnValue
	for (i=0;i<str.length;i++) {
		atChar=str.substring(i,1)
		if (atChar!=" " && atChar!="\n" && atChar!="\r" && atChar!="\t") {
			startIndex=i
			break
		}
	}
	for (i=str.length-1;i>=0;i--) {
		atChar=str.substring(i,1)
		if (atChar!=" " && atChar!="\n" && atChar!="\r" && atChar!="\t") {
			endIndex=i
			break
		}
	}
	return(str.substring(startIndex,endIndex+1))
}

function verifyCPF(objField) {
	var	strCPF="";
	for (i=0;i<objField.value.length;i++)
		if (!isNaN(objField.value.charAt(i))) strCPF+=objField.value.charAt(i);
	strCPF=fillLeft(strCPF,"0",11);
	if (strCPF == "00000000000" || strCPF == "11111111111" || strCPF == "22222222222" ||	strCPF == "33333333333" || strCPF == "44444444444" || strCPF == "55555555555" || strCPF == "66666666666" || strCPF == "77777777777" || strCPF == "88888888888" || strCPF == "99999999999")
		return false;
	soma = 0;
	for (i=0; i < 9; i ++)
		soma += parseInt(strCPF.charAt(i)) * (10 - i);
	resto = 11 - (soma % 11);
	if (resto == 10 || resto == 11)
		resto = 0;
	if (resto != parseInt(strCPF.charAt(9)))
		return false;
	soma = 0;
	for (i = 0; i < 10; i ++)
		soma += parseInt(strCPF.charAt(i)) * (11 - i);
	resto = 11 - (soma % 11);
	if (resto == 10 || resto == 11)
		resto = 0;
	if (resto==parseInt(strCPF.charAt(10))) {
		objField.value=strCPF;
		return true;
	}
	else
		return false;
}


function verifyCGC(objField) {
	var	strCGC="";
	for (i=0;i<objField.value.length;i++)
		if (!isNaN(objField.value.charAt(i))) strCGC+=objField.value.charAt(i);
	strCGC=fillLeft(strCGC,"0",14);
	var1 = 0;
	i = 0;
	var4 = 0;
	var5 = 0;
	var2 = 5;
	for (i=0; i < 12; i ++) {
		var1 += parseInt(strCGC.charAt(i)) * var2;
		if (var2>2)
			var2=var2-1;
		else
			var2=9;
	}
	var1=(var1 % 11);
	if (var1 > 1)
		var4 =11 - var1;
	else
		var4=0;
	var1 = 0;
	i = 0;
	var2 = 6;

	for (i=0; i < 13; i ++) {
		var1 += parseInt(strCGC.charAt(i)) * var2;
		if (var2>2)
			var2=var2-1;
		else
			var2=9;
	}
	
	var1 = (var1 % 11);
	if (var1>1)
		var5=11-var1;
	else
		var5=0;
	if (var4==parseInt(strCGC.charAt(12)) && var5==parseInt(strCGC.charAt(13))) {
		objField.value=strCGC;
		return true;
	}
	else
		return false;  
}

function verifyCEP(strCEP) {
	var strJustNumbers="";
	for (intPos=0;intPos<strCEP.length;intPos++) {
		if (!isNaN(strCEP.charAt(intPos))) strJustNumbers+=strCEP.charAt(intPos);
		else if (intPos!=5) return(false);
	}
	return(strJustNumbers.length==8);
}

function fillLeft(strText, strChar, intLength) {
	var strReturnValue=strText;
	for (i=0;i<(intLength-strText.length);i++) {
		strReturnValue=strChar + strReturnValue;
	}
	return(strReturnValue);
}

// Início das funções de validação de cartão de crédito

function isCreditCard(st) {
  if (st.length > 19)
    return (false);

  sum = 0; mul = 1; l = st.length;
  for (i = 0; i < l; i++) {
    digit = st.substring(l-i-1,l-i);
    tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
  }

  if ((sum % 10) == 0)
    return (true);
  else
    return (false);
}

function isVisa(cc) {
  if (((cc.length == 16) || (cc.length == 13)) &&
      (cc.substring(0,1) == 4))
    return isCreditCard(cc);
  return false;
}

function isMasterCard(cc) {
  firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 16) && (firstdig == 5) &&
      ((seconddig >= 1) && (seconddig <= 5)))
    return isCreditCard(cc);
  return false;
}

function isAmericanExpress(cc) {
  firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 15) && (firstdig == 3) &&
      ((seconddig == 4) || (seconddig == 7)))
    return isCreditCard(cc);
  return false;
}

function isDinersClub(cc) {
  firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 14) && (firstdig == 3) &&
      ((seconddig == 0) || (seconddig == 6) || (seconddig == 8)))
    return isCreditCard(cc);
  return false;
}
