/*************************************************************************}
{*                                                                       *}
{* Author   : Alcindo Schleder                                           *}
{* Copyright: © 2003 by Alcindo Schleder. All rights reserved.           *}
{* Created  : 19/05/2007 - DD/MM/YYYY                                    *}
{* Modified :                                                            *}
{* Version  : 1.0.0.0                                                    *}
{* License  : you can freely use and distribute the included code        *}
{*            for any purpouse, but you cannot remove this copyright     *}
{*            notice. Send me any comments and updates, they are really  *}
{*            appreciated. This software is licensed under MPL License,  *}
{*            see http://www.mozilla.org/MPL/ for details                *}
{* Contact  : alcindo@sistemaprocessa.com.br                             *}
{*            alcindo@processa.org                                       *}
{*            alcindo@processavoip.net                                   *}
{*            http://www.sistemaprocessa.com.br                          *}
{*            http://www.processa.org                                    *}
{*            http://www.processavoip.net                                *}
{*                                                                       *}
{*************************************************************************/

//Hide status bar msg - by Alcindo Schleder
function mostrarLoja(loja) {
	if (document.getElementById(loja).style.display == "block")
		document.getElementById(loja).style.display = "none";
	else
		document.getElementById(loja).style.display = "block";
}


function hidestatus() {
  window.status='';
  return true;
}

if (document.layers)
  document.captureEvents(Event.MOUSEOVER | Event.MOUSEOUT)
document.onmouseover=hidestatus
document.onmouseout=hidestatus

gSpool      = [];
gSpoolIdx   = 0;
gPriorClass = "";
xmlhttp     = false;

function GetHttpObject () {    
  var aXmlObj;
  try {
    if (window.XMLHttpRequest) {
      aXmlObj = new XMLHttpRequest();
      if (aXmlObj.readyState == null) {
      aXmlObj.readyState = 1;
      aXmlObj.addEventListener("load", function () {
          aXmlObj.readyState = 4;
          if (typeof aXmlObj.onReadyStateChange == "function")
            aXmlObj.onReadyStateChange();
        }, false);
      }
     return aXmlObj;
    }
    if (window.ActiveXObject) {
      var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
      for (var i = 0; i < prefixes.length; i++) {
        try {
    				  aXmlObj = new ActiveXObject(prefixes[i] + ".XmlHttp");
          return aXmlObj;
        } catch (ex) {};
      }
    }
  } catch (ex) {}
    alert("XmlHttp Objects not supported by client browser!!!");
}

function Send(pMethod) {
  if (!xmlhttp) 
		  xmlhttp = GetHttpObject();
		aUrl = gSpool[gSpoolIdx][0];
		if (pMethod == "POST")
    aParams = gSpool[gSpoolIdx][1];
  aTarget = gSpool[gSpoolIdx][2];
  if (pMethod == "GET") 
    xmlhttp.open("GET", aUrl, true);
  else {
    xmlhttp.open("POST", aUrl, true);
//    xmlhttp.setRequestHeader("Content-Type", "text/html; charset=iso-8859-1");
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=iso-8859-1");
    xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");  
    xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
    xmlhttp.setRequestHeader("Pragma", "no-cache"); 
		}
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState == 4) {
      aHtmlText=unescape(xmlhttp.responseText.replace(/\+/g," "));
      document.getElementById(aTarget).innerHTML = aHtmlText;
      init();
      gSpoolIdx++;
      if (gSpoolIdx < gSpool.length) 
        if (pMethod == "GET") 
          setTimeout("Send('GET')", 1000);
								else
          setTimeout("Send('POST')", 1000);
						else {
        gSpool    = [];
						  gSpoolIdx = 0;
						}
    }
  }
  if (pMethod == "GET") 
    xmlhttp.send(null);
		else
    xmlhttp.send(aParams);
}

function SendGallery(pMethod) {
  if (!xmlhttp) 
		  xmlhttp = GetHttpObject();
		aUrl = gSpool[gSpoolIdx][0];
		if (pMethod == "POST")
    aParams = gSpool[gSpoolIdx][1];
  aTarget = gSpool[gSpoolIdx][2];
  if (pMethod == "GET") 
    xmlhttp.open("GET", aUrl, true);
  else {
    xmlhttp.open("POST", aUrl, true);
//    xmlhttp.setRequestHeader("Content-Type", "text/html; charset=iso-8859-1");
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=iso-8859-1");
    xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");  
    xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
    xmlhttp.setRequestHeader("Pragma", "no-cache"); 
		}
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState == 4) {
      aHtmlText=unescape(xmlhttp.responseText.replace(/\+/g," "));
      document.getElementById(aTarget).innerHTML = aHtmlText;
      init();
      startGallery();
      gSpoolIdx++;
      if (gSpoolIdx < gSpool.length) 
        if (pMethod == "GET") 
          setTimeout("Send('GET')", 1000);
								else
          setTimeout("Send('POST')", 1000);
						else {
        gSpool    = [];
						  gSpoolIdx = 0;
						}
    }
  }
  if (pMethod == "GET") 
    xmlhttp.send(null);
		else
    xmlhttp.send(aParams);
}

function ValidFields(aType, pGetParams) {
  if ((!aType) || (aType==""))
    return false;
  else {
    if ((aType=="submit") || (aType=="reset") || (aType=="button") || (aType=="label") || (aType=="legend") || (aType=="hidden"))
      if ((pGetParams) && (aType=="hidden"))
        return true;
      else
        return false;
    else 
      return true;
  }
} 

function CheckParms(pForm) {
  for(i=0;i<pForm.elements.length;i++) {
   	nome=pForm.elements[i].name;
   	tipo=pForm.elements[i].type;
 	  pForm.elements[i].value=Trim(pForm.elements[i].value);
    if (pForm.elements[i].value=="") 
		    return false
  }
		return true;
}

function CheckCustomerData(pForm, pTarget) {
	 var aPassword = pForm.Senha.value;
	 var aPwdConf  = pForm.Confirmacao.value;
  if ((aPassword.value=="") || (aPwdConf.value=="") || (aPwdConf.value!=aPassword.value))
    return false;
		if ((!pTarget) || (pTarget==""))
		  return false;
		return SendAjaxForm(pForm, "POST", pTarget)
}

function CheckEMail(pObj) {
  pObj.value=Trim(pObj.value);
  if (pObj.value!="") {
    atPos = pObj.value.indexOf('@');
    atPos1 = pObj.value.indexOf('.');
    if ((atPos < 1) || (atPos1 < 1) || (atPos1 == (pObj.value.length - 1)) || (atPos == (pObj.value.length - 1)))
	     return false;
  }
  return true;
}

function CheckDate(pObj) {
  var expReg = /^((0[1-9]|[12]\d)\/(0[1-9]|1[0-2])|30\/(0[13-9]|1[0-2])|31\/(0[13578]|1[02]))\/(19|20)?\d{2}$/;
  var aRet = true;
  if ((pObj) && (pObj.value.match(expReg)) && (pObj.value != '')) {
    var dia = pObj.value.substring(0,2);
    var mes = pObj.value.substring(3,5);
    var ano = pObj.value.substring(6,10);
    if (mes == 4 || mes == 6 || mes == 9 || mes == 11 && dia > 30) 
      aRet = false;
    else 
      if ((ano % 4) != 0 && mes == 2 && dia > 28) 
        aRet = false;
      else
        if ((ano%4) == 0 && mes == 2 && dia > 29)
          aRet = false;
  }  else 
    aRet = false;  
  return aRet;
}

function PositiveNumber(pObj) {
  if ((pObj) && (pObj.value.match(/[0-9]+/g)) && (Number(pObj.value) != 'NaN') && (Number(pObj.value) > 0)) 
    return true;
  else
    return false;
}

function cascadedStyle(pObj, pCssProperty, pCssPropertyNS){
  if (pObj.currentStyle)
    return pObj.currentStyle[pCssProperty]
  else 
		  if (window.getComputedStyle) {
      var aObjStyle=window.getComputedStyle(pObj, "")
      return aObjStyle.getPropertyValue(pCssPropertyNS)
  }
}

function SetFieldMouseOver() {
	 if (navigator.appName=="Microsoft Internet Explorer") {
    var aTop=event.clientY;
    var aLeft=event.clientX;
  	 var aObj=event.srcElement;
		}
		else {
  	 var aObj=event.target;
    var aTop=aObj.style.pixelTop;
    var aLeft=aObj.style.pixelLeft;
		}
		if (aObj) {
				var aMessage="";
				var aShowHint=cascadedStyle(aObj, "u_showhint", "u_showhint");
				var aShowError=cascadedStyle(aObj, "u_showerror", "u_showerror");
    if (aShowError=="true") 
				  aMessage=aObj.getAttribute("u_invalid");
				else
      if (aShowHint=="true") 
		  		  aMessage=aObj.getAttribute("u_hint");
				showBox(aTop, aLeft, document.getElementById("dvHint"), aMessage, aShowHint, aShowError);
		}
}

function SetFieldMouseOut() {
	 if (navigator.appName=="Microsoft Internet Explorer")
  	 var aObj=event.srcElement;
		else
  	 var aObj=event.target;
		hideBox(document.getElementById("dvHint"));
}

function ValidateFormField(pObj, pAlertMsg) {
  var aRet=true;
  if (ValidFields(pObj, false)) {
    if (pObj.getAttribute("u_required")=="true") {
      var aMsg=pObj.getAttribute("u_invalid");
      if (pObj.value=="") aRet=false;
      if ((pObj.getAttribute("u_validate")) && (aRet)) {
        if ((pObj.getAttribute("u_validate")=="eMail") && (!CheckEMail(pObj)))
          aRet=false;
        if ((pObj.getAttribute("u_validate")=="PosNum") && (!PositiveNumber(pObj)))
          aRet=false;
        if ((pObj.getAttribute("u_validate")=="FloatNum") && (!GenericFloat(pObj)))
          aRet=false;
        if ((pObj.getAttribute("u_validate")=="Date") && (!CheckDate(pObj)))
          aRet=false;
        if ((pObj.getAttribute("u_validate")=="CPF") && (!verificaCPF(pObj.value.replace(/[\.|\-]+/g, ''))))
          aRet=false;
        if ((pObj.getAttribute("u_validate")=="CNPJ") && (!validaCNPJ(pObj.value.replace(/[\.|\/|\-]+/g, ''))))
          aRet=false;
      }
      if (!aRet) {
        pObj.className="form-field-invalid";
        if (pAlertMsg) {
          pObj.focus();
          alert(aMsg);
        }
        return false;
      }
    }
  }
  return true;
}

function SetSelectedLink(pContent, n) {
	 if (pContent) {
    var aLinks=pContent.getElementsByTagName("td");
    for(var i=0;i<aLinks.length;i++)
        aLinks[i].className="menu";
    aLinks[n-1].className="selected";
		}
}

function SetFieldFocus() {
	 if (navigator.appName=="Microsoft Internet Explorer")
    event.srcElement.className="form-field-focus";
		else
  	 event.target.className="form-field-focus";
}

function SetFieldBlur() {
  if (navigator.appName=="Microsoft Internet Explorer")
    var aObj=event.srcElement;
  else
    var aObj=event.target;
  var aValid=ValidateFormField(aObj, false);
  if (aValid)
    aObj.className="form-field-select";
  else
    aObj.className="form-field-invalid";
}

function GetFormParams(pForm) {
  aStr='?';
  for (i=0;i<pForm.elements.length;i++) {
   	Name=pForm.elements[i].name;
   	Type=pForm.elements[i].type;
   	Value=pForm.elements[i].value;
   	if (ValidFields(Type, true))
				  if (Type == "radio") {
						  if (pForm.elements[i].checked)
          aStr=aStr+Name+'='+Value+'&';
						} else
        aStr=aStr+Name+'='+Value+'&';
  }
  return aStr+"ExecMethod=emAjax";
}

function ValidateForm(pForm) {
  if (pForm) {
    for (i = 0; i < pForm.elements.length; i++) {
      var aRet=ValidateFormField(pForm.elements[i], true);
      if (!aRet) return aRet;
    }
  } else 
    return false;
}

function ClearAndConfirmation(pFormName, pOperation) {
	 if ((!pFormName) || (pFormName == '') || (!pOperation) || (pOperation == '')) return false;
		var aForm = document.getElementById(pFormName);
		if (pOperation == 'opNew')
  	 var aResult = true;
		else
  	 var aResult = false;
		if (aForm) {
			 if (pOperation == 'opDelete')
      aResult = confirm('Deseja realmente excluir este registro?');
				else
  				SetSampleValue(aForm);
				if ((aResult) || (pOperation == 'opNew')) 
  				aForm.op.value = pOperation;
  }
		return aResult;
}

function SetDefaultValue(pForm) {
  if (pForm) 
    for (i = 0; i < pForm.elements.length; i++) {
						var aType = pForm.elements[i].type;
						var aValue = '';
						var aValid = pForm.elements[i].getAttribute("u_validate");
						if ((aValid) && (aValid == "eMail"))
						  aValue = '';
						if ((aValid) && (aValid == "PosNum"))
						  aValue = '1';
						if ((aValid) && (aValid == "FloatNum"))
						  aValue = '0.00';
						if (aType == 'text') 
						  pForm.elements[i].value = aValue;
						if (aType == 'password') 
						  pForm.elements[i].value = aValue;
						if (aType == 'checkbox') 
						  pForm.elements[i].checked = 'false';
						if (aType == 'radio') 
						  pForm.elements[i].checked = 'false';
						if (aType == 'file') 
						  pForm.elements[i].value = aValue;
						if (aType == 'hidden') 
						  pForm.elements[i].value = '0';
						if (aType == 'select-one') 
						  pForm.elements[i].selectedIndex = 0;
    }
}

function SetSampleValue(pForm) {
  if (pForm) 
    for (i = 0; i < pForm.elements.length; i++) {
						var aType = pForm.elements[i].type;
						var aValue = '.';
						var aValid = pForm.elements[i].getAttribute("u_validate");
						if ((aValid) && (aValid == "eMail"))
						  aValue = 'teste@teste.com.br';
						if ((aValid) && (aValid == "PosNum"))
						  aValue = '1';
						if ((aValid) && (aValid == "FloatNum"))
						  aValue = '0.00';
						if (aType == 'text') 
						  pForm.elements[i].value = aValue;
						if (aType == 'password') 
						  pForm.elements[i].value = aValue;
						if (aType == 'checkbox') 
						  pForm.elements[i].checked = 'false';
						if (aType == 'radio') 
						  pForm.elements[i].checked = 'false';
						if (aType == 'file') 
						  pForm.elements[i].value = aValue;
						if (aType == 'hidden') 
						  pForm.elements[i].value = '0';
						if (aType == 'select-one') 
						  pForm.elements[i].selectedIndex = 0;
    }
}

function ClearForm(pForm) {
  if (pForm) 
    for (i = 0; i < pForm.elements.length; i++)
      if (ValidateFormField(pForm.elements[i], true))
						  pForm.elements[i].value= '0';
}

function SendAjaxForm(pForm, pMethod, pTarget) {
  if (pForm) {
    for (i=0;i<pForm.elements.length;i++) {
//  				alert('SendAjaxForm: validating field ' + pForm.elements[i].name);
      var aRet=ValidateFormField(pForm.elements[i], true);
      if (!aRet) return aRet;
    }
    var aParams = GetFormParams(pForm);
    if (((!pMethod) && (pMethod=="")) || ((pMethod!="GET") || (pMethod!="POST"))) pMethod="POST";
    if ((pTarget) && (pTarget=="")) pTarget="body";
    document.getElementById(pTarget).innerHTML = "<div class='Loading'>Carregando...</div>";
    gSpool[gSpool.length] = [pForm.action, aParams, pTarget];
    if ((gSpoolIdx + 1) == gSpool.length) {
      Send(pMethod);
   	}
  } else 
    return false;
}

function GetAjaxLink(pLink, pTarget) {
  if ((pLink) && (pLink!="")) {
    if ((pTarget) && (pTarget=="")) pTarget="body";
    document.getElementById(pTarget).innerHTML = "<div class='Loading'>Carregando...</div>";
    gSpool[gSpool.length] = [pLink, '', pTarget];
    if ((gSpoolIdx + 1) == gSpool.length) {
      Send("GET");
    }
  }
}

function init() {
  // Atribui o evento onFocus e OnChange em todos os campos em todos os formulários do documento
  for (i=0;i<document.forms.length;i++) {
    var aForm=document.forms[i];
    for (j=0;j<aForm.elements.length;j++) {
      var aObj=aForm.elements[j];
      var aRet=ValidFields(aObj.type, false);
      if (aRet) {
        aObj.className="form-field-select";
        aObj.onfocus=SetFieldFocus;
        aObj.onblur=SetFieldBlur;
        aObj.onmouseover=SetFieldMouseOver;
        aObj.onmouseout=SetFieldMouseOut;
      }
    }
  }
}

function showBox(pTop, pLeft, pHintObj, pMessage, pShowHint, pShowError) {
  if ((pHintObj) && (pMessage) && (pMessage!="")) {
    if (pTop)
      pHintObj.style.top=pTop;
    if (pLeft)
      pHintObj.style.left=pLeft;
    var aWidth=pMessage.length;
    pHintObj.style.width=(aWidth*0.6)+"em"
    pHintObj.innerHTML=pMessage;
    if (pShowError=="true") 
      pHintObj.className="hintError";
    else
      if (pShowHint=="true") 
        pHintObj.className="hintVisible";
  }
}

function hideBox(pHintObj) {
  if (pHintObj) 
    pHintObj.className="hintInvisible";
}

function GetAjaxGallery(pLink, pTarget) {
  if ((pLink) && (pLink!="")) {
    if ((pTarget) && (pTarget=="")) pTarget="body";
    document.getElementById(pTarget).innerHTML = "<div class='Loading'>Carregando...</div>";
    gSpool[gSpool.length] = [pLink, '', pTarget];
    if ((gSpoolIdx + 1) == gSpool.length) {
      SendGallery("GET");
    }
  }
}
window.onload=init;

///////------------
//MÁSCARA DE VALORES
function txtBoxFormat(objeto, sMask, evtKeyPress) {
    var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;


if(document.all) { // Internet Explorer
    nTecla = evtKeyPress.keyCode;
} else if(document.layers) { // Nestcape
    nTecla = evtKeyPress.which;
} else {
    nTecla = evtKeyPress.which;
    if (nTecla == 8) {
        return true;
    }
}

    sValue = objeto.value;

    // Limpa todos os caracteres de formatação que
    // já estiverem no campo.
    sValue = sValue.toString().replace( "-", "" );
    sValue = sValue.toString().replace( "-", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( ":", "" );
    sValue = sValue.toString().replace( ":", "" );
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( " ", "" );
    sValue = sValue.toString().replace( " ", "" );
    fldLen = sValue.length;
    mskLen = sMask.length;

    i = 0;
    nCount = 0;
    sCod = "";
    mskLen = fldLen;

    while (i <= mskLen) {
      bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/") || (sMask.charAt(i) == ":"))
      bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

      if (bolMask) {
        sCod += sMask.charAt(i);
        mskLen++; }
      else {
        sCod += sValue.charAt(nCount);
        nCount++;
      }

      i++;
    }

    objeto.value = sCod;

    if (nTecla != 8) { // backspace
      if (sMask.charAt(i-1) == "9") { // apenas números...
        return ((nTecla > 47) && (nTecla < 58)); } 
      else { // qualquer caracter...
        return true;
      } 
    }
    else {
      return true;
    }
  }

function LTrim(str)
        /***
                PURPOSE: Remove leading blanks from our string.
                IN: str - the string we want to LTrim

                RETVAL: An LTrimmed string!
        ***/
        {
                var whitespace = new String(" \t\n\r");

                var s = new String(str);

                if (whitespace.indexOf(s.charAt(0)) != -1) {
                    // We have a string with leading blank(s)...

                    var j=0, i = s.length;

                    // Iterate from the far left of string until we
                    // don't have any more whitespace...
                    while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
                        j++;


                    // Get the substring from the first non-whitespace
                    // character to the end of the string...
                    s = s.substring(j, i);
                }

                return s;
        }

function RTrim(str)
        /***
                PURPOSE: Remove trailing blanks from our string.
                IN: str - the string we want to RTrim

                RETVAL: An RTrimmed string!
        ***/
        {
                // We don't want to trip JUST spaces, but also tabs,
                // line feeds, etc.  Add anything else you want to
                // "trim" here in Whitespace
                var whitespace = new String(" \t\n\r");

                var s = new String(str);

                if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
                    // We have a string with trailing blank(s)...

                    var i = s.length - 1;       // Get length of string

                    // Iterate from the far right of string until we
                    // don't have any more whitespace...
                    while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
                        i--;


                    // Get the substring from the front of the string to
                    // where the last non-whitespace character is...
                    s = s.substring(0, i+1);
                }

                return s;
        }

function Trim(str)
        /***
                PURPOSE: Remove trailing and leading blanks from our string.
                IN: str - the string we want to Trim

                RETVAL: A Trimmed string!
        ***/
        {
                return RTrim(LTrim(str));
        }
function validarData(dtData) {
		isValid = false

		if (dtData.substring(2,3) == "/" && dtData.substring(5,6) == "/") {
			dia = dtData.substring(0, 2)
			mes = dtData.substring(3, 5)
			ano = dtData.substring(6, 10)

			if (validarAno(ano)) {
				if (validarMes(mes)) {
					if (validarDia(ano, mes, dia)) {
						isValid = true
					}
				}
			}
		}

		return isValid
	}

function validarAno(ano) {
		isValid = false

		if (ano >= 1900) {
			isValid = true
		}

		return isValid
	}

function validarMes(mes) {
		isValid = false

		if (mes >= 1 && mes <= 12) {
			isValid = true
		}

		return isValid
	}

function validarDia(ano, mes, dia) {
		isValid = true

	    if (mes == 1 || mes == 3 || mes == 5 || mes == 7 || mes == 8 || mes == 10 || mes == 12) {
    		if (dia < 1 || dia > 31) {
        		isValid = false
	      	}
	    }
		else if (mes == 2) {
			if (dia > 0) {				
        		if (ano % 4 == 0) {
          			if (dia > 29) {
            			isValid = false
          			}
        		}				
				else {
          			if (dia > 28) {
            			isValid = false
          			}
				}
			}
			else {
				isValid = false
			}
		}
		else {
      		if (dia < 1 || dia > 30) {
        		isValid = false
      		}
		}

		return isValid
	}

	function verificaCPF(cpf)
	{
		if(cpf == "") {
			return true;
		}
		var dac = "", inicio = 2, fim = 10, soma, digito, i, j
		for (j=1;j<=2;j++) {
			soma = 0
			for (i=inicio;i<=fim;i++) {
				soma += parseInt(cpf.substring(i-j-1,i-j))*(fim+1+j-i)
			}
			if (j == 2) { soma += 2*digito }
			digito = (10*soma) % 11
			if (digito == 10) { digito = 0 }
			dac += digito
			inicio = 3
			fim = 11
		}
		return (dac == cpf.substring(cpf.length-2,cpf.length))
	}


	function isNumeric(valor) {
		isValid = true

		re = /[^0-9]/

		if (valor.length == 0 || valor.match(re) != null) {
			isValid = false
		}

		return isValid
	}

       function validaCGC(s)
	{
		var i;
		s = Trim(s);
		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;
	}

       function modulo11(s)
	{
		s1 = Trim(s); 
		L = s1.length;
		dv = 0;
		p = 9;
		for (i = L-1; i>-1 ; i--)
		{
			dv = dv + (s1.charAt(i))*p;
			p--;
			if (p<2) { p=9};
		}
	        if (dv == 0) { d ='0' }
	        else {
	              dv = (dv % 11);
		      if (dv > 9) d = 'X'
		      else d = dv;
		     }
		return d;
	}

       function dvBanrisul(s)
	{
		s1 = Trim(s); 
		dv=s1.charAt(0)*3 + s1.charAt(1)*2 + s1.charAt(2)*4;
		L = s1.length;
		p = 7;
		for (i=3; i<=L ; i++)
		{
			dv = dv + (s1.charAt(i))*p;
			p--;
			if (p<2) { p=7};
		}
		resto = dv % 11;
	        if (resto == 0) { d ='0' }
	        else {
	              if (resto == 1) { d ='6' }
	              else { d = 11 - resto }
		     }
		return d;
	}


////------------------
/*************************************************************************}
{*                                                                       *}
{* Author   : Alcindo Schleder                                           *}
{* Copyright: © 2003 by Alcindo Schleder. All rights reserved.           *}
{* Created  : 19/05/2007 - DD/MM/YYYY                                    *}
{* Modified :                                                            *}
{* Version  : 1.0.0.0                                                    *}
{* License  : you can freely use and distribute the included code        *}
{*            for any purpouse, but you cannot remove this copyright     *}
{*            notice. Send me any comments and updates, they are really  *}
{*            appreciated. This software is licensed under MPL License,  *}
{*            see http://www.mozilla.org/MPL/ for details                *}
{* Contact  : alcindo@sistemaprocessa.com.br                             *}
{*            alcindo@processa.org                                       *}
{*            alcindo@processavoip.net                                   *}
{*            http://www.sistemaprocessa.com.br                          *}
{*            http://www.processa.org                                    *}
{*            http://www.processavoip.net                                *}
{*                                                                       *}
{*************************************************************************/
//MÁSCARA DE VALORES
function txtBoxFormat(objeto, sMask, evtKeyPress) {
    var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;


if(document.all) { // Internet Explorer
    nTecla = evtKeyPress.keyCode;
} else if(document.layers) { // Nestcape
    nTecla = evtKeyPress.which;
} else {
    nTecla = evtKeyPress.which;
    if (nTecla == 8) {
        return true;
    }
}

    sValue = objeto.value;

    // Limpa todos os caracteres de formatação que
    // já estiverem no campo.
    sValue = sValue.toString().replace( "-", "" );
    sValue = sValue.toString().replace( "-", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( ":", "" );
    sValue = sValue.toString().replace( ":", "" );
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( " ", "" );
    sValue = sValue.toString().replace( " ", "" );
    fldLen = sValue.length;
    mskLen = sMask.length;

    i = 0;
    nCount = 0;
    sCod = "";
    mskLen = fldLen;

    while (i <= mskLen) {
      bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/") || (sMask.charAt(i) == ":"))
      bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

      if (bolMask) {
        sCod += sMask.charAt(i);
        mskLen++; }
      else {
        sCod += sValue.charAt(nCount);
        nCount++;
      }

      i++;
    }

    objeto.value = sCod;

    if (nTecla != 8) { // backspace
      if (sMask.charAt(i-1) == "9") { // apenas números...
        return ((nTecla > 47) && (nTecla < 58)); } 
      else { // qualquer caracter...
        return true;
      } 
    }
    else {
      return true;
    }
  }
// Form Functions

function SendEditorForm(pForm, pTarget) {
  if ((pForm) && (pTarget)) {
    for (i = 0; i < parent.frames.length; ++i)
       if (parent.frames[i].FCK)
         parent.frames[i].FCK.UpdateLinkedField();
    return SendAjaxForm(pForm, pForm.method, pTarget)
  } else return false;
}

function addslashes(pStr) {
  var slash = "\\&";
  var value = "&";
  pStr = pStr.replace(value, slash);
  return pStr;
}

function ComparePassword(pPwd, pConf) {
	 if ((pPwd) && (pConf)) {
			 var aPwd = document.getElementById(pPwd);
			 var aConf = document.getElementById(pConf);
    if (aPwd.value != aConf.value) {
      alert('As senhas informadas são diferentes!! (' + aPwd.value + ' - ' + aConf.value + '). Por favor digite-as novamente!');
	     aPwd.value = '';	
	     aConf.value = '';	
      aPwd.focus;
	     return false; 
    } else {
      return true;
				}
		} else {
	   return false;
		}
}

function MaskField(o,f) {
    v_obj = o;
    v_fun = f;
    setTimeout("ExecMask()",1);
}

function ExecMask() {
    v_obj.value = v_fun(v_obj.value);
}

function Phone(v){
    v=v.replace(/\D/g,"");                 
    v=v.replace(/^(\d\d)(\d)/g,"($1) $2"); 
    v=v.replace(/(\d{4})(\d)/,"$1-$2");    
    return v;
}

function ZipCode(v) {
    v=v.replace(/D/g,"");                
    v=v.replace(/^(\d{5})(\d{3})/,"$1-$2"); 
    return v;
}

function IntegerNumber(v) {
    v=v.replace(/D/g,"");                
    v=v.replace(/[^0-9-]/g, ""); 
    return v;
}

function GenericFloat(pValue, pDecPlaces) {
	 if ((!pDecPlaces) || (pDecPlaces == '') || (pDecPlaces == 'undefined') || (!pDecPlaces.match(/[0-9]+/)))
		  pDecPlaces = '2';
		if (pDecPlaces.length > 1)
		  pDecPlaces = pDecPlaces[0];
  var aRegExp = '([0-9]+)([0-9]{' + pDecPlaces + '})';
		aRegExp = new RegExp(aRegExp);
		var s = pValue;
  pValue = pValue.replace(/([^0-9]+)/g, ""); // delete all characters from string except digits 0-9
//  pValue = pValue.replace(/([^0-9,\.]+)/g, ""); // delete all characters from string except digits 0-9, '-' and decimal point
//		var dec = aS.replace(/\w+[.,]|[^0-9]+/, ""); // get the fractional portion
//		pValue = pValue.substring(0, pValue.length - dec) + decSep + pValue.substring(pValue.length - dec, pValue.length);
  while (pValue.length < (pDecPlaces - 1))
		  pValue = '0' + pValue;
  pValue = pValue.replace(aRegExp, "$1.$2");
		pValue = pValue.replace(/([0]+(?=[\.,]))?(^[0]+(?=[1-9]))?(^[0]+(?=[0-9]))/, ""); // delete all zeros before digits 1-9 and before decimal point
//		pValue = pValue.replace(/[,]/, "."); // set character '.' to decimal point (generic float point)
	 if (s.match(/[-]/))
		  pValue = '-' + pValue;
		return pValue;
}

function Currency(v, pDP) {
	 if ((!pDP) || (pDP == '') || (pDP == 'undefined') || (!pDP.match(/[0-9]+/)))
		  pDP = '2';
		if (pDP.length > 1)
		  pDP = pDP[0];
		v = GenericFloat(v, pDP);
		v = v.replace(/[.]/, ","); // set character ',' to decimal point for brazilian currency
		s = v.replace(/(^[-])|([.,][0-9]+)/g, ""); // get the integer portion
  if (s.length < 4) 
    v=v.replace(/([-0-9]+)([\.,0-9]{2})/, "$1$2");
		else 
    if (s.length < 7) 
      v=v.replace(/([-0-9]{1,3})([0-9]{3})([\.,0-9]{2})/, "$1.$2$3");
 			else
      if (s.length < 10) 
        v=v.replace(/([-0-9]{1,3})([0-9]{3})([0-9]{3})([\.,0-9]{2})/, "$1.$2.$3$4");
    		else 
        if (s.length < 13) 
          v=v.replace(/([-0-9]{1,3})([0-9]{3})([0-9]{3})([0-9]{3})([\.,0-9]{2})/, "$1.$2.$3.$4$5");
				  		else
          if (s.length < 15) 
            v=v.replace(/([-0-9]{1,3})([0-9]{3})([0-9]{3})([0-9]{3})([0-9]{3})([\.,0-9]{2})/, "$1.$2.$3.$4.$5$6");
										else
            v=v.replace(/([-0-9]+)([\.,0-9]{2})/, "$1$2");
		return v;
} 

function cpf(v){
    v=v.replace(/\D/g,"");                    
    v=v.replace(/(\d{3})(\d)/,"$1.$2");       
    v=v.replace(/(\d{3})(\d)/,"$1.$2");       
                                             
    v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2"); 
    return v;
}
 
function Data(v){
    v=v.replace(/\D/g,"");                    
    v=v.replace(/(\d{2})(\d)/,"$1/$2");       
    v=v.replace(/(\d{2})(\d)/,"$1/$2");       
                                             
    v=v.replace(/(\d{2})(\d{2})$/,"$1$2") ;
    return v;
}

function cnpj(v){
    v=v.replace(/\D/g,"");
    v=v.replace(/^(\d{2})(\d)/,"$1.$2");
    v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3");
    v=v.replace(/\.(\d{3})(\d)/,".$1/$2");          
    v=v.replace(/(\d{4})(\d)/,"$1-$2");            
    return v;
}

function UpdateData(pForm, pOp, pTarget, pFile) {
  if ((!pForm) || (pForm == '') || (!pOp) || (pOp == '') || (!pTarget) || (pTarget == '')) 
    return false;
  aForm = document.getElementById(pForm);
  if (!aForm) return false;
  if ((pOp == 'opNew') && (pFile) && (pFile != ''))
    GetAjaxLink(pFile, pTarget);
  else
    if (pOp == 'opCancel')
      aForm.reset(); 
    else
      if (pOp == 'opDelete') {
        aForm.op.value='opDelete';
        SendAjaxForm(aForm, 'POST', pTarget);
      }
      else
        if ((pOp == 'opInsert') || (pOp == 'opUpdate')) 
          pForm.submit();
}

function CryptoGraphp(pDir, pCfg, pSID) {
  document.images.cryptogram.src=pDir+'/cryptographp.php?cfg="' + pCfg + '"&"' + pSID + '"&' + Math.round(Math.random(0)*1000) + 1;
}

//Formata número tipo moeda usando o evento onKeyDown
function FormatCurrency(pObj, e) {
 	if (pObj) {
  	 if ((e.keyCode >= 48 && e.keyCode <= 58) || (e.keyCode == 8)) {
		    if (e.keyCode != 8)
  		  	 pObj.value = pObj.value + e.keyCode;
						else
  		  	 pObj.value = pObj.value.substring(0, pObj.value.length - 1);
						alert(pObj.value);
  				MaskField(pObj, Currency);
				} else 
				  return false;
		}	else
  	 return false;
} 
// **************************************************
// * Autor : Peter M Jordan - uranking@uranking.com *
// * página: www.uranking.com                       *
// **************************************************

// construindo o calendário
function popdate(obj,div,tam,ddd)
{
    if (ddd) 
    {
        day = ""
        mmonth = ""
        ano = ""
        c = 1
        char = ""
        for (s=0;s<parseInt(ddd.length);s++)
        {
            char = ddd.substr(s,1)
            if (char == "/") 
            {
                c++; 
                s++; 
                char = ddd.substr(s,1);
            }
            if (c==1) day    += char
            if (c==2) mmonth += char
            if (c==3) ano    += char
        }
        ddd = mmonth + "/" + day + "/" + ano
    }
  
    if(!ddd) {today = new Date()} else {today = new Date(ddd)}
    date_Form = eval (obj)
    if (date_Form.value == "") { date_Form = new Date()} else {date_Form = new Date(date_Form.value)}
  
    ano = today.getFullYear();
    mmonth = today.getMonth ();
    day = today.toString ().substr (8,2)
  
    umonth = new Array ("Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro")
    days_Feb = (!(ano % 4) ? 29 : 28)
    days = new Array (31, days_Feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)

    if ((mmonth < 0) || (mmonth > 11))  alert(mmonth)
    if ((mmonth - 1) == -1) {month_prior = 11; year_prior = ano - 1} else {month_prior = mmonth - 1; year_prior = ano}
    if ((mmonth + 1) == 12) {month_next  = 0;  year_next  = ano + 1} else {month_next  = mmonth + 1; year_next  = ano}
    txt  = "<table bgcolor='#efefff' style='border:solid #330099; border-width:2' cellspacing='0' cellpadding='3' border='0' width='"+tam+"' height='"+tam*1.1 +"'>"
    txt += "<tr bgcolor='#FFFFFF'><td colspan='7' align='center'><table border='0' cellpadding='0' width='100%' bgcolor='#FFFFFF'><tr>"
    txt += "<td width=20% align=center><a href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+((mmonth+1).toString() +"/01/"+(ano-1).toString())+"') class='Cabecalho_Calendario' title='Ano Anterior'><<</a></td>"
    txt += "<td width=20% align=center><a href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+( "01/" + (month_prior+1).toString() + "/" + year_prior.toString())+"') class='Cabecalho_Calendario' title='Mês Anterior'><</a></td>"
    txt += "<td width=20% align=center><a href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+( "01/" + (month_next+1).toString()  + "/" + year_next.toString())+"') class='Cabecalho_Calendario' title='Próximo Mês'>></a></td>"
    txt += "<td width=20% align=center><a href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+((mmonth+1).toString() +"/01/"+(ano+1).toString())+"') class='Cabecalho_Calendario' title='Próximo Ano'>>></a></td>"
    txt += "<td width=20% align=right><a href=javascript:force_close('"+div+"') class='Cabecalho_Calendario' title='Fechar Calendário'><b>X</b></a></td></tr></table></td></tr>"
    txt += "<tr><td colspan='7' align='right' bgcolor='#ccccff' class='mes'><a href=javascript:pop_year('"+obj+"','"+div+"','"+tam+"','" + (mmonth+1) + "') class='mes'>" + ano.toString() + "</a>"
    txt += " <a href=javascript:pop_month('"+obj+"','"+div+"','"+tam+"','" + ano + "') class='mes'>" + umonth[mmonth] + "</a> <div id='popd' style='position:absolute'></div></td></tr>"
    txt += "<tr bgcolor='#330099'><td width='14%' class='dia' align=center><b>Dom</b></td><td width='14%' class='dia' align=center><b>Seg</b></td><td width='14%' class='dia' align=center><b>Ter</b></td><td width='14%' class='dia' align=center><b>Qua</b></td><td width='14%' class='dia' align=center><b>Qui</b></td><td width='14%' class='dia' align=center><b>Sex<b></td><td width='14%' class='dia' align=center><b>Sab</b></td></tr>"
    today1 = new Date((mmonth+1).toString() +"/01/"+ano.toString());
    diainicio = today1.getDay () + 1;
    week = d = 1
    start = false;

    for (n=1;n<= 42;n++) 
    {
        if (week == 1)  txt += "<tr bgcolor='#efefff' align=center>"
        if (week==diainicio) {start = true}
        if (d > days[mmonth]) {start=false}
        if (start) 
        {
            dat = new Date((mmonth+1).toString() + "/" + d + "/" + ano.toString())
            day_dat   = dat.toString().substr(0,10)
            day_today  = date_Form.toString().substr(0,10)
            year_dat  = dat.getFullYear ()
            year_today = date_Form.getFullYear ()
            colorcell = ((day_dat == day_today) && (year_dat == year_today) ? " bgcolor='#FFCC00' " : "" )
            txt += "<td"+colorcell+" align=center><a href=javascript:block('"+  d + "/" + (mmonth+1).toString() + "/" + ano.toString() +"','"+ obj +"','" + div +"') class='data'>"+ d.toString() + "</a></td>"
            d ++ 
        } 
        else 
        { 
            txt += "<td class='data' align=center> </td>"
        }
        week ++
        if (week == 8) 
        { 
            week = 1; txt += "</tr>"} 
        }
        txt += "</table>"
        div2 = eval (div)
        div2.innerHTML = txt 
}
  
// função para exibir a janela com os meses
function pop_month(obj, div, tam, ano)
{
  txt  = "<table bgcolor='#CCCCFF' border='0' width=80>"
  for (n = 0; n < 12; n++) { txt += "<tr><td align=center><a href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+("01/" + (n+1).toString() + "/" + ano.toString())+"')>" + umonth[n] +"</a></td></tr>" }
  txt += "</table>"
  popd.innerHTML = txt
}

// função para exibir a janela com os anos
function pop_year(obj, div, tam, umonth)
{
  txt  = "<table bgcolor='#CCCCFF' border='0' width=160>"
  l = 1
  for (n=1991; n<2012; n++)
  {  if (l == 1) txt += "<tr>"
     txt += "<td align=center><a href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+(umonth.toString () +"/01/" + n) +"')>" + n + "</a></td>"
     l++
     if (l == 4) 
        {txt += "</tr>"; l = 1 } 
  }
  txt += "</tr></table>"
  popd.innerHTML = txt 
}

// função para fechar o calendário
function force_close(div) 
    { div2 = eval (div); div2.innerHTML = ''}
    
// função para fechar o calendário e setar a data no campo de data associado
function block(data, obj, div)
{ 
    force_close (div)
    obj2 = eval(obj)
    obj2.value = data 
}

function ValidateForm(pForm) {
  if (pForm) {
    for (i=0;i<pForm.elements.length;i++) {
      var aRet=ValidateFormField(pForm.elements[i], true);
      if (!aRet) return aRet;
    }
  }
}
