var agt    = navigator.userAgent.toLowerCase();

var is_mac = (agt.indexOf("mac")!=-1);
//********************************************************************
function HabilitaCampo (oCampo, bModo)
{
oCampo.disabled = (bModo == false)?true:false;
oCampo.style.backgroundColor = (bModo == false)?CorFdCampoDesab():"";
}
//********************************************************************
function CorFdCampoDesab ()
{
return (window.cCorFdCampoDesab || "#DADADA");     
// Cor anterior #EAF9FF
// Cor anterior #DADADA
}
//********************************************************************
function ElementosForm (oForm)
{
	var oElementos;
	if (is_mac == false) 
	{
		oElementos = oForm.elements;
	} 	
	else 
	{
		oElementos = oForm.all;
	}
	return (oElementos);
}
//********************************************************************
function DesabilitaCampos ( oForm, bPK )
{
	var cNome, cPK, bTestarPK, nCont, oElementos, cCorFdCampoDesab;
	
	if ( bPK == true || bPK == false ) 
	{
		bTestarPK = true;
	}
	else
	{
		bTestarPK = false;
	}
	
	cCorFdCampoDesab = CorFdCampoDesab();
	
	oElementos = ElementosForm (oForm);
	
	for ( nCont=0; nCont < oElementos.length; nCont++ )
	{
		cNome=oElementos[nCont].name;
		cNome=cNome || '';

		if ( cNome != '' ) 
		{
			cNome=cNome.toLowerCase();
			if (cNome.slice(0,3) != "hid" &&
				cNome.slice(0,3) != "dis")
			{
				if ( bTestarPK == true ) 
				{
					if (cNome != "btnsalvar" && cNome != "btnexclui")
					{
						cPK = oElementos[nCont].SMKPK || "N";
						
						if (cPK.toUpperCase() == "S") 
						{
							oElementos[nCont].disabled = (bPK == true)?true:false;
						}
						else 
						{
							oElementos[nCont].disabled = (bPK == true)?false:true;
						}
				
						if (oElementos[nCont].disabled == true)
						{
							//oElementos(nCont).SMKHabOnLoad = "N";
							oElementos[nCont].style.backgroundColor = cCorFdCampoDesab; 
						}
					}
				}
				else 
				{
					//oElementos[nCont].disabled = true;
					//oElementos(nCont).SMKHabOnLoad = "N";
					//oElementos[nCont].style.backgroundColor = cCorFdCampoDesab; 
					HabilitaCampo(oElementos[nCont],false);
				}
			}
		}
	}
}
//********************************************************************
function HabilitaCampos ( oForm, cRotina )
{

	var nCont, cNome, oElementos;

	//window.nHabilitaCampos = true;

	oElementos = ElementosForm (oForm);
	
	for ( nCont=0; nCont < oElementos.length; nCont++ )
	{
		
		//cNome = oElementos(nCont).name;
		cNome = oElementos[nCont].name;
		
		cNome = cNome || '';
		if ( cNome != '' ) 
		{
			cNome = cNome.toLowerCase();
			
			if (cNome.substr(0,3) != "btn") 
			{
				if ( oElementos[nCont].disabled == true )
				{
					oElementos[nCont].disabled = false;
					if (cRotina != "SubmitForm")  
					{                              
						oElementos[nCont].style.backgroundColor = "";
					}
				}
			}
		}
	}
}
//********************************************************************
function RetCampo(cConteudo, cDelim, nPosCampo)
{
var cAux = new String (cConteudo);

var aAux = cAux.split (cDelim);

if (nPosCampo > aAux.length){
    
	return ("");
	
}else{
    
	return (aAux[nPosCampo - 1]);
	
}
}
//********************************************************************
function ValidaArea(oCampo)
{
    try
    {
        // Testa tamanho do campo textarea 
                   
        var nTam = parseInt( 1000, 10 );
                            
        var cText = oCampo.value;
                       
        if ( parseInt(cText.length, 10) > parseInt(nTam, 10) )
        {
            alert ("Número de caracteres do campo texto supera o máximo permitido(" + parseInt(nTam, 10) + "). Favor revisar conteúdo !");
            oCampo.focus();
            oCampo.value = cText.substr(0, nTam);
            return false;
        }
    }
 
    catch(e)
    {
        ExibeMens ("Ocorreu erro durante execução !" + e.description, true);
        return false;
    }
}
//********************************************************************
function ExibeErro(oForm,oCampo,bTrue)
{
	try

	{
	
	if (bTrue == true){
	
		alert("Campo requerido não informado !");
	
	} else {

		oCampo.style.backgroundColor ="#FF0000";
		oCampo.style.borderColor ="#FF0000";
		oCampo.style.color ="#FFFFFF";
	
	}

	    oCampo.value = "";
		
		if(oCampo.disabled == false)
		{
			oCampo.focus();
		}
					
	    setTimeout("LimpaErro("+oForm+")",3000);
	
	}
	
	catch (e)
	{
		alert("Ocorreu algum erro durante execução !" + e.description, true);
		return false;
	}
}
//********************************************************************
function LimpaErro(oForm)
{
	try

	{   
		var nCont;
		var oElementos;
		
		oElementos = ElementosForm (oForm);
		   
		for ( nCont=0; nCont < oElementos.length; nCont++ )
		{
			if ( oElementos[nCont].disabled == false)
			{
				if (oElementos[nCont].name.substr[0,3] != "btn")
				{
					oElementos[nCont].style.backgroundColor = "";
					oElementos[nCont].style.borderColor = "";
					oElementos[nCont].style.color = "#000000";
				}
			}
		}
	
	}
	
	catch (e)
	{
		alert("Ocorreu algum erro durante execução !" + e.description, true);
		return false;
	}

}
//********************************************************************
function CampoInformado(oCampo)
{

var cValor;

//	alert(oCampo.name);

var cNome = oCampo.name;

if (cNome.substr(0, 3) == "cmb") {

	cValor = oCampo.value;

} else {

	cValor = RetiraEspacos (oCampo.value);
}

if ( cValor == ""){

	return false;

} else {

	return true;

}
//********************************************************************
}
function RetiraEspacos ( cString )
{

var cAux;

cAux = cString;

cAux = ( cAux.replace ( /^ +/, '' ) ).replace ( / +$/ ,'');

return ( cAux );

}
//********************************************************************
function JanelaCentro(URL,Janela,Scrollbars,Status,Largura,Altura)
{		
	var window_top  = (screen.height - Altura)/2;
	var window_left = (screen.width  - Largura)/2;
	
	window.open(''+ URL + '',''+ Janela + '','Scrollbars=' + Scrollbars + ',Status=' + Status + ',width=' + Largura + ',height=' + Altura + ',top=' + window_top + ',left=' + window_left);
}
//*****************************************************************************
function CriarObjAjax() {
//Interface genérica para acesso ao conector remoto.
try{ return new ActiveXObject("Msxml2.XMLHTTP");}catch(e){}
try{ return new ActiveXObject("Microsoft.XMLHTTP");}catch(e){}
try{ return new XMLHttpRequest();}catch(e){}
alert("Ajax não suportado por esse navegador!");
return null;
}
//**********************************************************************
// Contem objeto para solicitar recursos remotos.
var HttpReq = CriarObjAjax();
//**********************************************************************
function ExecutaSQLAjax(cSQL, cFlgMens) {
	
	var cRetorno = "";
	//var cIdLoad = document.getElementById(cIdLoad);
	var cURL    = "../includes/ExecutaSQLAjax.asp?cSQL=" + cSQL;
	alert(cSQL);
	if(cFlgMens) {
//		elmt.innerHTML = "Carregando... ";
		//xpgMessagesLoading()
	}

  	HttpReq.open("GET", cURL, true); 
	HttpReq.onreadystatechange = function() 
	{
		if (HttpReq.readyState == 4) 
		{
			if (HttpReq.status == 200) 
			{
				//cIdLoad.innerHTML = http.responseText;
				cRetorno = HttpReq.responseText;
				alert(cRetorno);
							
			} else {
			
				//cIdLoad.innerHTML = "Erro ao chamar requisição:\n" + HttpReq.statusText;
				cRetorno = "";
			
			}
       		//xpgMessagesHideAll()
		}
	}
	HttpReq.send(null);
	
	if (cRetorno != "undefined" && cRetorno != ""){
	
		return (cRetorno);
	
	} else {
	
		return ("");
	
	}          

}
//**********************************************************************    
function ExecutaSQL(Sql)
{
	var cRetorno;

	var cURL = "../Includes/ExecutaSQLJS.asp?Sql="+Sql;
	
	cURL = cURL.replace (/\%/g, "%25");
	cURL = cURL.replace (/\+/g, "%2B");

    
	
	cRetorno = new String(AbreJanModal (cURL, window,"200px",(is_mac==false)?"50px":"201px"));

    //cRetorno = new String(window.showModalDialog(URL,"Executando Comandos SQL","dialogHeight=50px;dialogWidth=200px;status=0;edge=raised;help=0;center=1;scroll=0"));

	if (cRetorno != "undefined" && cRetorno != ""){
	    
		return (cRetorno);
		
	} else {
	    
		return ("");
		
	}
}
//*****************************************************************************
function AbreJanModal (cUrl, cParam, nWidth, nHeight, nLeft, nTop, cOpcoesModal)
{
var cOpcoes, cRetorno;
cOpcoes="dialogWidth:" + nWidth + "; dialogHeight:" + nHeight + "; ";
if ( (nLeft || -1) != -1 && (nTop || -1) != -1 )  
{
	cOpcoes+="dialogLeft:" + nLeft + "; dialogTop:" + nTop + "; ";
}
cOpcoes+="status:0; help:0; center=1; scroll=0"

if ((cOpcoesModal || '') != '') 
{
	cOpcoes+="; " & cOpcoesModal;
}
	cRetorno = window.showModalDialog(cUrl, cParam, cOpcoes);
	
	//cRetorno = window.showModalDialog(cUrl, cParam, "dialogHeight=50px;dialogWidth=200px;status=0;edge=raised;help=0;center=1;scroll=0");
	return (cRetorno);
}
//*****************************************************************************
function ValidaEmail(txtEmail,vEmail)
{
	try

	{
	    
		if ((vEmail.search(/;/i) == -1)  &&
			(vEmail.search(/,/i) == -1)  &&
			(vEmail.indexOf("..") == -1) &&
			(vEmail.indexOf(".@") == -1) &&
			(vEmail.indexOf("@.") == -1) &&
			(vEmail.search(/ /i) == -1)  &&
			(vEmail.search(/"/i) == -1)  &&
			(vEmail.search(/'/i) == -1)  &&
			(vEmail.indexOf("^") == -1)  &&
			(vEmail.search(/`/i) == -1)  &&
			(vEmail.search(/~/i) == -1)  &&
			(vEmail.search(/ç/i) == -1)  &&
			(vEmail.length != 0)         &&
			(vEmail.search(/@/i) >= 2)   &&
			(vEmail.substr(0,1) != ".")  &&             /*Não pode começar com ponto*/
			(vEmail.substr(vEmail.length-1) != ".")  && /*Não pode terminar com ponto*/
			(vEmail.indexOf("hotmail.com.br") == -1) &&
			(vEmail.indexOf("aol.com.br") == -1))
			return (true);
		else if (vEmail.indexOf("hotmail.com.br") >= 0)
			{
			alert("Atenção: O E-mail HOTMAIL não termina com .BR\nEle será automaticamente corrigido");
			txtEmail.value = vEmail.replace("hotmail.com.br", "hotmail.com");
			return (false);
			}
		else if (vEmail.indexOf("aol.com.br") >= 0)
			{
			alert("Atenção: O E-mail AOL não termina com .BR\nEle será automaticamente corrigido");
			txtEmail.value = vEmail.replace("aol.com.br", "aol.com");
			return (false);
			}
		else if (vEmail.indexOf(" ") >= 0)
			{
			alert("Atenção: O E-mail não deve conter espaços em branco\nEle será automaticamente corrigido");
			while(vEmail.indexOf(" ") >= 0)
			vEmail = vEmail.replace(" ", "");
			txtEmail.value = vEmail
			return (false);
			}
		else
			{
			alert("Formato do endereço de E-mail Incorreto!");
			return (false);
			}
	}
	
	catch (e)
	{
        alert("Ocorreu algum erro durante execução !" + e.description, true);
        return false;
	}
	
}
//*****************************************************************************
function EventoCampo ()
{
//var oCampo;
var cEvento;
var cMyEvento;
var cFuncao;
var nRet;
var FrameCalend;

oCampo = event.srcElement;
cEvento = event.type;
//cEvento = oCampo.type;
cMyEvento = "";
cTipo = oCampo.Tipo || 'C';
cTipo = cTipo.toUpperCase ();

switch ( cEvento )
{
case "focus": 

    cMyEvento = "OnFocus";
    
    FrameCalend = document.all("frameCalend");
    
    if (FrameCalend != null){
        FrameCalend.style.display = "none";
    }
    
    nRet = ExibeValorCampo ( oCampo, "OnFocus" );
    
    break;

case "keypress": 

    cMyEvento = "OnKeyPress";
    
    nRet = ValidaTecla ( oCampo )
    
    break;
    
case "blur" : 
    
    cMyEvento = "OnBlur";
    
switch (cTipo)
{
    case "C":
    case "T": 
    
        if (oCampo.SMKMaiusculo == 'S' && oCampo.TecladoCtrlV == 'S') 
        {
            oCampo.value = oCampo.value.toUpperCase ();
            oCampo.ControlV = 'N';
        }
        
        nRet = ExibeValorCampo ( oCampo, "OnBlur" );
        
        break;
        
    case "D": 
        
        nRet = ValidaData ( oCampo );
        break;
        
    case "M":  
        
        nRet = ValidaMesAno ( oCampo );
        break;
    
    case "H":  
        
        nRet = ValidaHora ( oCampo );
        break;
        
    case "V":

        nRet = ValidaValores ( oCampo );
        break;
        
    default: 
    
        nRet = ExibeValorCampo ( oCampo, "OnBlur" );
        break;
}
    break;
}


if ( nRet == true && cMyEvento.length > 0 )
{
    cFuncao = eval ("oCampo." + cMyEvento) || '';
    if ( cFuncao > '' )
    {
        nRet = eval ( cFuncao );
    }
}

if ( window.nProcessaSubmit == true && ( cEvento == "keypress" || cEvento == "blur" ) )
{
    if (cEvento == "keypress")
    {
        nRet = false;
        event.keyCode = 0;
        event.returnCode = false;
    }
    
    if (is_mac == false) 
    {
        parent.window.focus(); 
        
    } else {
        
        var oBotao = document.all("btnAcao"); 
        
        if (oBotao != null)
        {
            if (oBotao.disabled == false)
            {
                
            oBotao.focus();
            oBotao.focus();
            
            }
        }
}

if ( cEvento == "keypress" ) 
{
    if ((oCampo.EventoOnBlur || '') == '' && cTipo != 'D' && cTipo != 'M' && cTipo != 'H' && cTipo != 'V')
    {
    
        ProcessaSubmit ();
    
    }
} else {
    
    ProcessaSubmit ();
}

}
if (is_mac == false) 
{
    
    //oCampo.returnValue = nRet;
    event.returnValue = nRet;
    
}

return ( nRet );

}
//*****************************************************************************
function ValidaValores (oCampo)
{
var nDec, nTam, nMaxInt, cAux, nPos, nTamInt;

nDec = oCampo.Decimais || 2;
nTam = oCampo.maxLength;

nMaxInt = (nTam - nDec - 1);

if (nMaxInt > 3)
{
    if (nMaxInt % 3 == 0) 
    {
        nMaxInt -= parseInt (((nMaxInt / 3)- 1), 10);
    } else {
        nMaxInt -= parseInt ((nMaxInt / 3), 10);
    }
}

cAux = new String (oCampo.value);
nPos = cAux.indexOf(",");

if (nPos == -1)
{
    nTamInt = cAux.length;
} else {
    nTamInt = nPos;
}

if (nTamInt > nMaxInt)
{
    alert("Informe no máximo " + nMaxInt + " dígitos na parte inteira.");
    oCampo.value = "";
    oCampo.focus();
    return (false);
    
}

ExibeValorCampo ( oCampo, "OnBlur" );
return (true);

}
//*****************************************************************************
function ValidaTecla ( oCampo )
{

var nRet;
//var oCampo = event.srcElement;

//Tipo do Campo
cTipo = oCampo.Tipo || 'C';
cTipo = cTipo.toUpperCase ();

//Se é maisculo
cMaiusculo  = oCampo.Maisculo || 'N';
cMaiusculo  = cMaiusculo .toUpperCase ();

// Tecla Pressionada !
nKeyCode = event.keyCode;

if (cMaiusculo  == 'S' && oCampo.TecladoCtrlV == 'S' ){

    oCampo.value = oCampo.value.toUpperCase ();

    return ( true );
  
} else {
//Verificando o Tipo do Campo
switch ( cTipo )
{
// Númerico        
case "N": 
    
    if ( nKeyCode > 47 && nKeyCode < 58 )
    {
        nRet = true;
    
    } else {
    
        nRet = false;
    
    }
    
    break;
    
// Valores
case "V": 

if ( nKeyCode > 47 && nKeyCode < 58 )
{
    nRet = true;
    
} else {
    
    if ( nKeyCode == 44 || nKeyCode == 46 ){
        
        cValue = oCampo.value;
        
        if ( cValue.indexOf( "," ) == -1 ){
            
            event.keyCode = 44;
            
            nRet = true;
            
        } else {
            
            nRet = false;
        }
        
    } else {
        
        if ( nKeyCode == 45 && ((oCampo.Minimo || 0) < 0)){
            
            cValue = oCampo.value;
            
            if ( cValue.indexOf( "-" ) == -1 ){
                
                nRet = true;
                
            } else {
                
                nRet = false;
                
            }
            
        } else {
        
            nRet = false;
        
        }
    }
}

break;

case "C": 
// Texto
case "T": 

    if ( cMaiusculo  == 'S' ){
        
        if ( ( nKeyCode > 96  && nKeyCode < 123 ) || ( nKeyCode > 223 && nKeyCode < 254 )){
            // Subtração para achar a letra correspondente Maiuscula
            event.keyCode = ( nKeyCode - 32 );
        }
    }
    
    nRet = true; 

break;

case "D": 
     
case "M": 

    if (( nKeyCode > 47 && nKeyCode < 58 ) || nKeyCode == 47 )
    {
        nRet = true;
        
    } else {
        
        nRet = false;
    }
    
break;

case "H": 

    if ( nKeyCode > 47 && nKeyCode < 59 ){
        
        nRet = true;
        
    } else {
        
        nRet = false;
        
    }

break;

default : 

nRet = true;

}
if (nRet == false){
    
    event.keyCode = 0;
   
}

}

return ( nRet );

}
//*****************************************************************************
function ExibeValorCampo ( oCampo, cEvento )
{
var bOnBlur;
var bOnFocus;
var bSeparador;
var cAux;

bOnFocus = (cEvento == 'OnFocus')?true:false;
bOnBlur = (cEvento == 'OnBlur')?true:false;

cTipo = oCampo.Tipo || 'C';
cTipo = cTipo.toUpperCase();

nDecimais = oCampo.Decimais || 2;

switch ( cTipo )
{
case "C" :
break;
case "N" :
break;
case "V" :
    
    cNumero = oCampo.value;
    
    if ( cNumero == "," || cNumero == "/0" || cNumero == "" )
    {
        oCampo.value = "";
        
    } else {
        
        bSeparador = ( bOnFocus == true )?false:true;
        
        oCampo.value = FormataNumeros( cNumero, nDecimais, bSeparador );
        
    }
    break;
    
case "D" :
case "M" :
    
    cAux = oCampo.value;
    cAux = cAux.replace (/\//g,'');
    oCampo.value = cAux;
    break;
    
case "H" :

    cAux = oCampo.value;
    cAux = cAux.replace (/:/g,'');
    oCampo.value = cAux;
    break;
    
}

if ( bOnFocus == true )
{
    if ( oCampo.type != "select-one" && oCampo.type != "select-multiple") 
    {
        oCampo.focus();
        oCampo.select();
    }
}

return ( true );
}
//*****************************************************************************
function FormataNumeros( cNumero, nDecimais, bSepMilhar, bConvVlrBr )
{

var bNegativo;
nDecimais = parseInt(nDecimais, 10);

if (isNaN(nDecimais) == true)
{
    nDecimais = 2;
}

bSepMilhar = bSepMilhar || false;

if (bConvVlrBr == true)
{
    cNumero = ConvVlrBr(cNumero);
}

cNumero = new String(cNumero);

if (cNumero.indexOf( "-" ) != -1 )
{

    bNegativo = true;
    cNumero = cNumero.replace(/-/g, ''); 

} else {

    bNegativo = false;

}

cNumero = cNumero.replace(/\./g, '');
cNumero = cNumero.replace(/\,/g, '.');
nPos = cNumero.indexOf(".");

if (nPos >= 0)
{
    cInteiro = cNumero.substr ( 0, nPos );
    cDecimais = cNumero.substr ( nPos + 1 );
    
    if (cDecimais.length > nDecimais )
    {
        nPos = nPos + nDecimais + 1;
        nDig = parseInt ( cNumero.substr ( nPos, 1 ), 10 );
        cNumero = cInteiro + '.' + cDecimais.substr ( 0, nDecimais );
        
        if ( nDig >= 5 )
        {
            nAux = Arredonda(parseFloat(cNumero) + parseFloat('0.' + Preenche ("1", "0", "E", nDecimais)),nDecimais);
            cNumero = new String (nAux);
        }
    }
}

if (parseFloat( cNumero ) == 0)
{
    cNumero = "0";
    
} else {
    
    if (nDecimais == 0)
    {
        cNumero = cNumero.replace(/\./g, '');
    } else {
        nPos = cNumero.indexOf ( "." );
        
        if ( cNumero.value != "" )
        {
            if ( nPos < 0 )
            {
                cNumero = cNumero + "," + Preenche ( "", "0", "D", nDecimais );
            } else {
                cDecimais = cNumero.substring ( nPos + 1 ) ;
                
                if (nPos > 0)
                {
                    cNumero = cNumero.substring ( 0, nPos );
                } else {
                    cNumero = "0";
                }
                
                cNumero+= "," + Preenche ( cDecimais, "0", "D", nDecimais );
            }
        }
    }

if (bSepMilhar == true)
{
    nTamDig = cNumero.length - nDecimais - 2;
    nCont = 0;
    cAuxNumer = "";

    for ( i = nTamDig; ( i >= 0 ) ; i-- )
    {
        if ( (nCont == 3) && (cNumero.substr(i, 1) != ".") )
        {
            if ( bSepMilhar == true )
            {
                cAuxNumer = "." + cAuxNumer;
            } else {
                cAuxNumer = "" + cAuxNumer;
            }
            
            nCont = 0;
        }
    
        nCont++;
        cAuxNumer = cNumero.substr ( i, 1 ) + cAuxNumer;
    }
        cNumero = cAuxNumer + cNumero.substr ( nTamDig + 1, nDecimais + 1 );
    }
}

if (bNegativo == true)
{
    cNumero = "-" + cNumero;
}
return( cNumero );
}
//*****************************************************************************
function Arredonda (nNum, nDec)
{
	nNum = parseFloat(nNum);
	nDec = nDec || 2;
	nRet = Math.round(nNum*Math.pow(10,nDec))/Math.pow(10,nDec);
	return (nRet);			
}
//*****************************************************************************
function Preenche ( cString, cChar, cEsqDir, nTam )
{
var cAux = new String(cString);
var nMax = (parseInt (nTam, 10) - cAux.length);
var nCont;

cChar   = cChar.substr(0,1)
cEsqDir = cEsqDir.substr(0,1);
cEsqDir = cEsqDir.toUpperCase();

for ( nCont = 1; nCont <= nMax; nCont++ )
{
    if (cEsqDir == "E")
    cAux = cChar + cAux;
    else
    cAux+= cChar;
}

return (cAux);
}
//*****************************************************************************
function ValidaData ( oCampo )
{
if ( CampoInformado ( oCampo, false ) == false )
{
    return ( true );
}

var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;
var dateStr = new String(oCampo.value);

if (dateStr.length == 1) 
{
    //dateStr = dateStr;
    dateStr = '0' + dateStr;
}

if (dateStr.length == 2) 
{
    var cDtAtual = new Date();
    dateStr += Preenche ((cDtAtual.getMonth() + 1), '0', 'E', 2);
    dateStr += cDtAtual.getFullYear();
}

if (dateStr.length == 4) 
{
    var cDtAtual = new Date();
    dateStr += cDtAtual.getFullYear();
} else {
    if (dateStr.length == 5 && dateStr.substr(2,1) == '/')
    {
        var cDtAtual = new Date();
        dateStr += '/' + cDtAtual.getFullYear();
    }
}

if ( dateStr.indexOf ( "/" ) == -1 && ( dateStr.length == 6 || dateStr.length == 8 ) )
{
    dateStr = dateStr.substr ( 0, 2 ) + "/" +
    dateStr.substr ( 2, 2 ) + "/" +
    dateStr.substr ( 4, 4 );
}

var matchArray = dateStr.match ( datePat ); 

if ( matchArray == null )
{
    event.returnValue = false;
    alert( "Formato de data inválida! (deve ser dia/mes/ano ou ddmmaaaa)" );
    oCampo.value="";
    oCampo.focus ();
    return ( false );
}

nMes = matchArray [ 3 ]; 
nDia = matchArray [ 1 ];   
nAno = matchArray [ 4 ];

if ( nAno.length == 2 ) 
{
if ( parseInt ( nAno, 10 ) < 40 ) 
    nAno = "20" + nAno;
else                     
    nAno = "19" + nAno;
} else {
    if ( nAno < 1900 || nAno > 2100 ) 
    {
        alert( "Ano inválido! (deve ser de 1900 a 2100)." );
        oCampo.value="";
        oCampo.focus ();
        return ( false );
    }
}

if ( nMes < 1 || nMes > 12 ) 
{
    alert( "Mês inválido! (deve ser de 1 a 12)." );
    oCampo.value='';
    oCampo.focus ();
    return ( false );
}

if ( nDia < 1 || nDia > 31 ) 
{
    alert( "Dia inválido! (deve ser de 1 a 31)." );
    oCampo.value='';
    oCampo.focus ();
    return ( false );
}

if ( (nMes==4 || nMes==6 || nMes==9 || nMes==11) && nDia == 31 ) 
{
    alert ( "O mês " + nMes + " não tem 31 dias!" )
    oCampo.value='';
    oCampo.focus ();
    return ( false );
}

if ( nMes == 2 ) 
{
    var isleap = (nAno % 4 == 0 && (nAno % 100 != 0 || nAno % 400 == 0));
    if ( nDia>29 || (nDia==29 && !isleap))
    {
        alert( "Fevereiro " + nAno + " não tem " + nDia + " dias!" );
        oCampo.value='';
        oCampo.focus ();
        return ( false );
    }
}

dateStr = Preenche(nDia,"0","E",2) + "/" + Preenche(nMes,"0","E",2) + "/" +

nAno; 

if (oCampo.value != dateStr) 
    oCampo.value = dateStr;
    return ( true );
}
//*****************************************************************************
function SubmitForm(form)
{
	try

	{		

		if (ValidaCampos(form) == true){
			
			ExibeImgProcessando();
			
			HabilitaCampos(form);
			
      		document.body.scrollTop  = 0; 
      		document.body.scrollLeft = 0; 
			
			if (form.btnSalvar) 
			{
				HabilitaCampo(form.btnSalvar,false);
			}

			if (form.btnExcluir) 
			{
				HabilitaCampo(form.btnExcluir,false);
			}

			if (form.btnPesquisar) 
			{
				HabilitaCampo(form.btnPesquisar,false);
			}

			if (form.btnLimpar) 
			{
				HabilitaCampo(form.btnLimpar,false);
			}				

			form.submit();
			
		}
		
	}

	catch (e)
	{
		alert("Ocorreu algum erro durante execução !" + e.description, true);
		return false;
	}
}
//*****************************************************************************
function ProcessaOnload()
{
	try

	{
			
		if (window.cExecOnLoad.length > 0)
		{
			eval (window.cExecOnLoad);
			window.cExecOnLoad = "";
	
		}
		
		CarregaImgProcessando();
		
	}
	catch (e)
	{
		alert("Ocorreu algum erro durante execução !" + e.description, true);
		return false;
	}
}	

function ChanceColorTR(nCor)
{
	cObjTR = event.srcElement;
	cObjTR.className = "";
	cObjTR.style.backgroundColor = nCor;
	//OnMouseOver="ChanceColorTR('#FFFFFF');" OnMouseOut="ChanceColorTR('#DADADA');"
}
function CarregaImgProcessando()
{
		
	var cObjCarregando;
	
	window.imgLoading = document.createElement("IMG");
	window.imgLoading.src    = "../v2/imagens/img_carregando.gif";
	window.imgLoading.width  = "196";
	window.imgLoading.height = "47"
	
	/*
	window.imgLoading.style.position   = "absolute";
	window.imgLoading.style.width      = "201px";
	window.imgLoading.style.height     = "30px";
	
	cObjCarregando = "<table width=\"100%\" border=\"0\" cellpadding=\"2\" cellspacing=\"2\" bordercolor=\"#999999\" bgcolor=\"#FFFFFF\" class=\"FontePadrao\">";
	cObjCarregando += "<tr>";
	cObjCarregando += "<td style=\"width: 17%; height: 39px\"><img src=\"../imagens/img_carregando.gif\" width=\"33\" height=\"33\" id=\"imgCarregando\"></td>";
	cObjCarregando += "<td width=\"83%\" style=\"height: 39px\"><strong>Processando, aguarde... </strong></td>";
	cObjCarregando += "</tr>";
	cObjCarregando += "</table>";	
	
	window.imgLoading.innerHTML = cObjCarregando;
	
	cObjCarregando  = '<OBJECT id=\"ObjPlayer\" name=\"ObjPlayer\" CLASSID=\"CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6\" width=\"320\" height=\"240\">\n');
	cObjCarregando += '<param name=\"FileName\" value=\"\">\n';
	cObjCarregando += '<param name=\"AutoStart\" value=\"False\">\n';
	cObjCarregando += '<param name=\"TransparentAtStart\" value=\"0\">\n';
	cObjCarregando += '<param name=\"ShowStatusBar\" value=\"0\">\n';
	cObjCarregando += '<param name=\"ShowDisplay\" value=\"0\">\n';
	cObjCarregando += '<param name=\"AutoSize value=\"0\">\n';
	cObjCarregando += '<param name=\"UImode\" value=\"none\">\n';
	cObjCarregando += '<param name=\"AnimationAtStart\" value=\"True\">\n';
	cObjCarregando += '<param name=\"StretchToFit\" value=\"False\">\n';
	cObjCarregando += '<param name=\"EnableContextMenu\" value=\"False\">\n';
	cObjCarregando += '</OBJECT>\n';	
	*/	

}
function ExibeImgProcessando ()
{
	var oImg, nTop, nLeft;
	var owidth, oheight

	if ((window.imgLoading || '') == '')
	{
		CarregaImgProcessando();
	}	
	
	document.body.appendChild(window.imgLoading);
	
	oImg = window.imgLoading;

	nTop =  ((document.body.offsetHeight - oImg.height)/2);
	nLeft = ((document.body.offsetWidth  -  oImg.width)/2); 
	
	oImg.style.position   = "absolute";
	oImg.style.top        = 10;
	oImg.style.left       = 10;
	oImg.style.visibility = "visible";
}
function OcultaImgProcessando ()
{
	var oImg = window.imgLoading;
	
	oImg.style.visibility = 'hidden';
	
}

//function CarregaImgProcessando ()
//{
//	if (document.all ("imgProcessando") == null)
//	{
//		window.imgProcessando = document.createElement("IMG");
//		window.imgProcessando.src = '/Systemakers/PadraoSMK/images/processando.gif';
//	}
//}
//function ExibeImgProcessando ()
//{
//var oImg, nTop, nLeft;
//
//oImg = document.all ("imgProcessando");
//
//if (oImg == null)
//{
//	if ((window.imgProcessando || '') == '')
//	{
//		CarregaImgProcessando();
//	}
//
//	document.body.appendChild(window.imgProcessando);
//	oImg = window.imgProcessando;
//
//}
//
//if (oImg.width > document.body.offsetWidth)
//{
//	var nWidth = document.body.offsetWidth - 30;
//	oImg.height=(oImg.height * ( nWidth / oImg.width));
//	oImg.width=nWidth;
//}
//
//nTop = ((document.body.offsetHeight - oImg.height)/2);
//nLeft = ((document.body.offsetWidth - oImg.width)/2);
//oImg.style.position = "absolute";
//oImg.style.top = nTop;
//oImg.style.left= nLeft;
//oImg.style.visibility= "visible";
//
//}

function ExibeMens (cMens)
{
	document.getElementById('cMens').innerHTML = cMens;
	setTimeout("LimpaMens()",4000);
}

function LimpaMens()
{
	document.getElementById('cMens').innerHTML = '';
}
/*
pagina.html: Obrigatório. O endereço e o documento HTML que será exibido.
argumentos: Opcional. Argumentos, definidos por você, que serão utilizados por showModalDialog ao criar a caixa de diálogo e exibir a página HTML.
atributos: Opcional. Atributos como altura, largura e posição da janela, para personalizar a exibição da caixa de diálogo.
dialogHeight: altura da janela.
dialogLeft: posição da borda esquerda da janela.
dialogTop: posição da borda superior da janela.
dialogWidth: largura da janela.
center: Define se a janela será exibida centralizada. Pode assumir os valores: yes, no, 1, 0, on, off.
edge: Especifica o estilo da borda. Valores: sunken e raised.
help: Exibe / oculta o ícone ( ? ) de ajuda na barra de título. Aquele botão com a exclamação que você vê em todas as caixas de diálogo do Word, Excel, etc., etc. Valores: yes, no, 1, 0, on, off.
resizable: Define se a janela poderá ser redimensionada com o ponteiro do mouse. Valores: yes, no, 1, 0, on, off.
scroll: Exibe / oculta as barras de rolagem. Valores: yes, no, 1, 0, on, off.
status: Exibe / oculta a barra de status. Valores: yes, no, 1, 0, on, off.
*/
var BaladakiCookies = {
	date: new Date(),
	// Cria o(s) cookie(s)
	// Forma de uso: BaladakiCookies.CriarCookie('nome_do_cookie','valor',dias_para_expirar);
	CriarCookie: function(strName, strValue, intDays) {
		if ( intDays ) {
			this.date.setTime(this.date.getTime()+(intDays*24*60*60*1000));
			var expires = "; expires=" + this.date.toGMTString();
		} else {
			var expires = "";
		}
		document.cookie = strName + "=" + strValue + expires + "; path=/";
	},
	// Ler as informações de um cookie em específico
	// Forma de uso: BaladakiCookies.LerCookie('nome_do_cookie');
	LerCookie: function(strName) {
		var strNameIgual = strName + "=";
		var arrCookies = document.cookie.split(";");
		for ( var i = 0, strCookie; strCookie = arrCookies[i]; i++ ) {
			while ( strCookie.charAt(0) == " ") {
				strCookie = strCookie.substring(1,strCookie.length);
			}
			if ( strCookie.indexOf(strNameIgual) == 0 ) {
				return strCookie.substring(strNameIgual.length,strCookie.length);
			}
		}
		return null;
	},
	// Delete um cookie desejado
	// Forma de uso: BaladakiCookies.Apagar('nome_do_cookie');
	Apagar: function(strName) {
		this.create(strName,"",-1);
	}
}