﻿
//id do navegador.
var gstrNavegador = "";
//id do sistema operacional.
var gstrOS = "";
var childWindow = null;
var children = Array();

function closeAllchildren()
{
    for(var n = 0; n < children.length; n++)
    {
        try
        {
            if ((!isUndefined(children[n])) && (isObject(children[n])))
            {
                children[n].close();
                children[n] = null;
            }
        }
        catch(e)
        {
            children[n] = null;
        }
    }
    //mata todas as janelas q existiam
    //children = Array();
} 

if (navigator.userAgent.indexOf("Opera") != -1)
	{gstrNavegador = "OP";}
else if (navigator.userAgent.indexOf("MSIE") != -1)
	{gstrNavegador = "IE";}
else if (navigator.userAgent.indexOf("Safari") != -1)
	{gstrNavegador = "GC";}
else if (navigator.userAgent.indexOf("Firefox") != -1)
	{gstrNavegador = "FF";}
else
	{gstrNavegador = "NI";}

if (navigator.userAgent.indexOf("Windows NT 5.1") != -1)
	{gstrOS = "XP"}

function TipoNavegador() { return gstrNavegador; }

function elementsById(id){
  var nodes = [];
  var tmpNode = document.getElementById(id);
  while(tmpNode){
    nodes.push(tmpNode);
    tmpNode.id = "";
    tmpNode = document.getElementById(id);
  }
  for(var x=0; x<nodes.length; x++){
    nodes[x].id = id;
  }
  return nodes;
}

function myGetElementById(id){
  
  return document.getElementById(id);
}

function fecha() {
	document.getElementById('linha_abrir').style.display = 'block';
	document.getElementById('tabela_detalhes').style.display = 'none'; 
}

function ChangeClassName(objId, strClassName)
{
    //document.getElementById(objId).className = strClassName;
    objId.className = strClassName;
}

function abre() {
	document.getElementById('linha_abrir').style.display = 'none';
	document.getElementById('tabela_detalhes').style.display = 'block'; 
}

function AlteraValor(idCampo, valor) { document.getElementById(idCampo).innerHTML = valor; }

function SetaFoco(idCampo) { document.getElementById(idCampo).focus(); }

function isUndefined(n) 
{ 
    if (isNull(n))
    {
        return true;
    }
    else
    {
        return n + '' == 'undefined'; 
    }
}

function isObject(n) 
{ 
    if (isNull(n))
    {
        return false;
    }
    else
    {
        return typeof(n) == 'object';
    }
}

function isNull(n) { return n == null; }

function isEmpty(param) 
{
    //se for um objeto, não valida se está empty.
    if (isObject(param)) { return false; }
    
    valor = param;
    exp = / /g;
    valor = valor.toString().replace(exp, ""); 

	if (valor.length <= 0) 
	    { return true; }
	else 
	    { return false; }
}

function TrimString(value) 
{
    return value.replace(/^\s+|\s+$/g, '');
}

function isNullOrEmpty(n)
{
    if (isNull(n))
    {
        return true;
    }
    
    if (isEmpty(n))
    {
        return true;
    }
    
    return false;
}

function isNullOrEmptyOrUndefined(n)
{
    if (isUndefined(n))
    {
        return true;
    }
    
    if (isEmpty(n))
    {
        return true;
    }
    
    return false;
}

function returnaYMDHMS()
{
    var today=new Date();
    
    var y=today.getFullYear().toString();
    var mon=(today.getMonth() + 1).toString();
    var d=today.getDate().toString();
    var h=today.getHours().toString();
    var min=today.getMinutes().toString();
    var s=today.getSeconds().toString();

    return (y+mon+d+"_"+h+min+s);
}

/*Abre popUp pequena para imagens*/
function abrePopUp(nomePagina, _width, _height, _geraNome) {
    
    if (isUndefined(_width) || isNaN(_width)) { _width = 400;  }
    if (isUndefined(_height) || isNaN(_height)) { _height = 319;  }
    if (isUndefined(_geraNome)) { _geraNome = false; }
    
    var TelaLargura = window.screen.availWidth;
    var TelaAltura =  window.screen.availHeight - 35;
    
    var bScrollBars = 'no';
    if (_height > TelaAltura) 
    { 
        bScrollBars = 'yes'; 
        _height = TelaAltura - 75;
        _width += 16;
    } 
    
    var CentroX = ((TelaLargura - _width) / 2);
    var CentroY = ((TelaAltura - _height) / 2);
        
    //window.open(nomePagina, '_blank','dependent=no, hotkeys=no, toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=' + bScrollBars + ', resizable=no, copyhistory=no, top=' + CentroY + ', left='+ CentroX + ', width=' + _width + ', height=' + _height);
    
    var _strNome = "";  
    //WorkAround para corrigir abrir popUp no google chrome
    if ((_geraNome) || (gstrNavegador == "GC"))
    {
        _strNome = "_" + returnaYMDHMS();
    }
        
    childWindow = window.open(nomePagina, 'abrePopUp' + _strNome,'z-lock=no, dependent=no, hotkeys=no, toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=' + bScrollBars + ', resizable=no, copyhistory=no, top=' + CentroY + ', left='+ CentroX + ', width=' + _width + ', height=' + _height);
    children[children.length]= childWindow;
    //
    if (!_geraNome)
    {
        if (gstrNavegador != "GC") //'WorkAround para corrigir abrir popUp no google chrome
        { 
            var iHeight = (gstrNavegador == "IE") ? 85 : 52;
            var iWidth = (gstrNavegador == "IE") ? 11 : 10;
            
            try
            {
                childWindow.resizeTo(_width + iWidth, _height + iHeight); 
                childWindow.moveTo(CentroX, CentroY);   
            }
            catch(e)
            { }
        }
    }
    
    try
    { childWindow.focus(); }
    catch(e)
    { }
    
    void(0); 
}

function abrePopUpFull(nomePagina)
{
    var _left = 0
    var _top = 0
    var _width = window.screen.availWidth - (window.screen.availWidth * 0.02);
    var _height = window.screen.availHeight - (window.screen.availHeight  * 0.22);
        
    var janela = window.open(nomePagina, 'abrePopUpFull', 'z-lock=no, hotkeys=yes, dependent=no, directories=yes, location=yes, menubar=yes, resizable=yes, scrollbars=yes, titlebar=yes, toolbar=yes, status=yes, copyhistory=yes, top=' + _top + ', left='+ _left + ', width=' + _width + ', height=' + _height);
    try
    {
        DimensionaTela(janela);
    }
    catch(e)
    { }
    
    try
    { janela.focus(); }
    catch(e) 
    {
    //alert('erro'); 
    }
    void(0); 
}

/*Abre popUp de qq tamanho, mas se não for informado nenhum, abre com os tamanhos da tela*/
function abrePopUp2(nomePagina, _width, _height, _geraNome) {
    var _left = 0;
    var _top = 0;
    //if (isUndefined(_left)) {_left = window.screen.availWidth * 0.01; }
    //if (isUndefined(_top)) { _top = window.screen.availHeight * 0.01; }
    if (isUndefined(_width)) { _width = window.screen.availWidth - (window.screen.availWidth * 0.03);  }
    if (isUndefined(_height)) { _height = window.screen.availHeight - (window.screen.availHeight  * 0.06);  }
    if (isUndefined(_geraNome)) { _geraNome = false; }
    
    var _left = ((window.screen.availWidth - _width) / 2);
    var _top = (((window.screen.availHeight - 35) - _height) / 2);
    
    var _strNome = "";  
    if (_geraNome)
    {
        _strNome = "_" + returnaYMDHMS();
    }
    
    childWindow = window.open(nomePagina, 'abrePopUp2' + _strNome,'z-lock=no, dependent=no, hotkeys=no, toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=no, top=' + _top + ', left='+ _left + ', width=' + _width + ', height=' + _height + '');
    //z-lock=no, dependent=no, hotkeys=no, toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=no, top=' + _top + ', left='+ _left + ', width=' + _width + ', height=' + _height + '');
    //location=no, menubar=no, resizable=yes, scrollbars=yes, status=yes, toolbar=no'
    children[children.length]= childWindow;
    
    try
    { childWindow.focus(); }
    catch(e)
    { }
    void(0); 
}

function setNewUrlLocation(nomePagina)
{
    if (!isNullOrEmptyOrUndefined(nomePagina))
    {
        window.location.href = nomePagina;
    }
}

function AlteraImgBtnToProgress(imgAnimate, bolImgAlterGrande, objLbl, strMsg)
{
    if (isUndefined(bolImgAlterGrande)) { bolImgAlterGrande = true; }
    if (isUndefined(strMsg)) { strMsg = null; }

    var _imgAlternativa = "";

    if (bolImgAlterGrande) //sera utilizado o gif animado grande
        _imgAlternativa = "processando.gif";
    else //será utilizado o gif animado pequeno 
        _imgAlternativa = "progress.gif";

    if (isObject($get(imgAnimate)))
    {
        $get(imgAnimate).src = "../img/" + _imgAlternativa;
        $get(imgAnimate).style.display = '';
    }

    if (!isNullOrEmptyOrUndefined(objLbl))
    {
        if (!isObject(objLbl))
            objLbl = $get(objLbl);

        if (!isNullOrEmpty(strMsg)) //se possui mensagem diferente
        {
            if (!isUndefined(objLbl.firstChild)) //se objeto não é nulo
            {
                if (!isUndefined(objLbl.firstChild.data)) //se objeto não é nulo
                {
                    objLbl.firstChild.data = strMsg;
                }
            }
        }
        //faz o show de um label que tenha algo do tipo, "processando..., ou aguarde..."
        objLbl.style.display = '';
    }
    return true;
}

function AlteraImgBtnSubmit(objBtn, strImgDefault, strImgAlter, content, bolFocus, objLbl)
{   
    /*
    -> PARAMETROS:
    objBtn   : BOTÃO QUE SERÁ ALTERADO A IMAGEM
    objParent: OBJETO QUE CONTÉM OS REQUIRED FIELD VALIDATORS (PODE SER UMA TABLE RUNAT=SERVER, PODE SER UM PANEL, UM UPDATEPANEL
    */
    //if (!isObject(objBtn)) { objBtn = myGetElementById(objBtn); }
    
    if (!isNullOrEmptyOrUndefined(objBtn))
    {
        if (!isObject(objBtn)) 
            objBtn = $get(objBtn);
    }
    else 
        objBtn = '';
    
    if (!isNullOrEmptyOrUndefined(objLbl))
    {
        if (!isObject(objLbl)) 
            objLbl = $get(objLbl);
    }
    else 
        objLbl = '';
    
    if (isOKRFVObj(content, bolFocus))
    {
        if (!isNullOrEmptyOrUndefined(strImgAlter))
        {
            //muda a imagem do botão
            if (isObject(objBtn)) 
            { 
                var caminho = window.location.href.toLowerCase();
                if (caminho.indexOf('/errorpage.aspx') == -1)
                { caminho = "../img/"; }
                else
                { caminho = "img/"; }
                objBtn.src = caminho + strImgAlter; 
            }
                    
            //faz o show de um label que tenha algo do tipo, "processando..., ou aguarde..."
            if (isObject(objLbl)) { objLbl.style.display = ''; }
        }
        
        return true;
    }
    else
    {        
        //esconde um label que tenha algo do tipo, "processando..., ou aguarde..."
        if (isObject(objLbl)) 
            objLbl.style.display = 'none';

        return false;
    }
}

function AlteraImageShowToSubmit(imgAnimate, bolImgAlterGrande, content, bolFocus, objLbl)
{
    if (isOKRFVObj(content, bolFocus))
    {
        if (!isNullOrEmptyOrUndefined(imgAnimate))
        {
            var caminho = window.location.href.toLowerCase();
            if (caminho.indexOf('/errorpage.aspx') == -1)
                caminho = "../img/";
            else
                caminho = "img/";
            
            var strImgAlter = "";    
            if (bolImgAlterGrande) //sera utilizado o gif animado grande
                strImgAlter = "processando.gif";
            else //será utilizado o gif animado pequeno 
                strImgAlter = "progress.gif";
        
            if (isObject($get(imgAnimate)))
            {
                $get(imgAnimate).src = caminho + strImgAlter;
                $get(imgAnimate).style.display = '';
            }
        }
        
        //faz o show de um label que tenha algo do tipo, "processando..., ou aguarde..."
        if (isObject($get(objLbl)))
            $get(objLbl).style.display = '';

        return true;
    }
    else
    {
        //esconde um label que tenha algo do tipo, "processando..., ou aguarde..."
        if (isObject($get(objLbl)))
            $get(objLbl).style.display = 'none';

        if (isObject($get(imgAnimate)))
            $get(imgAnimate).style.display = 'none';

        return false;
    }
}

function DimensionaTela(janela)
{
    if (isNullOrEmptyOrUndefined(janela)) 
        janela = top;
    
    janela.top.window.moveTo(0, 0);
    if (document.all || gstrNavegador == "GC" || gstrNavegador == "FF")
        janela.top.window.resizeTo(screen.availWidth, screen.availHeight);
    else if (document.layers || document.getElementById)
    {
        if (janela.top.window.outerHeight < screen.availHeight || janela.top.window.outerWidth < screen.availWidth)
        {
            janela.top.window.outerHeight = screen.availHeight;
            janela.top.window.outerWidth = screen.availWidth;
        }
    }
}

function hasInitialValue(valor)
{
    //valida se o campo possui um valor inicial.
    //caso estiver com o valor inicial retorna true.
    switch (valor)
    {
        case '(__) ____-____': //Telefone com espaço e com traço
            return true;
            break;
        case '': //Branco
            return true;
            break;
        case '__/__/____': //Data
            return true;
            break;
        case '__:__': //Hora
            return true;
            break;
        case '(__)____-____': //Telefone sem espaço e com traço
            return true;
            break;
        case '(__) ____.____': //Telefone com espaço e com ponto
            return true;
            break;
        case '(__)____.____': //Telefone sem espaço e com ponto
            return true;
            break;
        case '___.___.___-__': //CPF 
            return true;
            break;
        case '__.___.___\____-__': //CNPF 
            return true;
            break;
        case '__.___.___-__': //RG
            return true;
            break;
        default:
            return false;
    }
}

//busca por objetos do tipo required field validators
function isOKRFVObj(content, bolFocus)
{   
    /*
    -> PARAMETROS DA isOKRFVObj:
    ROTINA QUE ACIONA OS RFV E PARA A EXECUÇÃO NO PRIMEIRO QUE RETORNAR FALSE AO VALIDAR O COMPONENTE DA PROPRIEDADE controltovalidate

    * content: OBJETO QUE CONTÉM OS REQUIRED FIELD VALIDATORS (PODE SER UMA TABLE RUNAT=SERVER, PODE SER UM PANEL, UM UPDATEPANEL
    * bolExecVal: Boolean Execute Validate, se for informado true, ele executa a validação do objeto RFV
    * bolFocus: Boolean Focus, se for informado true, faz o foco no objeto
    */
    //var isValidateEmptyText = true;
    
    //obj passado por parametro é string, e deve possuir um valor
    try
    {
        if (isUndefined(Page_Validators)) { return true; }
        if (Page_Validators.length == 0) { return true; }
    }
    catch(e)
    {
        return true;
    }
    
    if ((isUndefined(content))  || (isNullOrEmpty(content)))  { return true; }
    if ((isUndefined(bolFocus)) || (isNullOrEmpty(bolFocus))) { bolFocus = true; }
    
    //varre todos os validators que existem na tela.
    for (var i = 0; i < Page_Validators.length; i++)
    {
        //verifica se o validator é do content que deve ser validado, do mesmo validationGroup
        if (Page_Validators[i].validationGroup == content)
        {
            var objToValidate = document.getElementById(Page_Validators[i].controltovalidate);
            if (isObject(objToValidate) && ((isUndefined(Page_Validators[i].enabled)) || (Page_Validators[i].enabled == true))) // se o Page_Validators[i].enabled é undefined, é pq está com o valor padrão TRUE
            {
                //testa apenas o validator do componente, se ele estiver false, dai testa todos da pagina
                if (!Page_Validators[i].evaluationfunction(Page_Validators[i]))
                {
                    //alert(content);
                    Page_ClientValidate(content);
                    if (bolFocus)
                    {
                        try
                        { 
                            objToValidate.focus(); //executa o foco do campo.                            
                        }
                        catch(e) 
                        { 
                            //return true; //workaround pra controlar quando está sendo validado um obj mas ele está escondido, mas o seu validator está true
                            break;
                        }
                    }
                    return false;
                } //end if
            } //end if
        } //end if
    } //for
    
    //Chama novamente esta rotina de validação, pois se chegou aqui, ela não foi chamada anteriormente
    Page_ClientValidate(content);
    //se chegou até aqui é pq todos os objetos RFV estão ok, e pode seguir adiante no submit
    return Page_IsValid;
}

//captura o evento keypress do documento, verificando se a tecla 'ENTER' pressionada
//document.onkeypress = ChamaVerificaENTER;			

/*
 * Liga o evento keypress do documento a uma funcao parametrizada para manipulacao do mesmo.
 *
 * e	Evento	Click capturado a partir do documento.
 */

//function ChamaVerificaENTER(e) {
//	var objBotao = 
//	VerificaENTER(e, document.getElementById('cmdLogin'));
//}

/*
 * Associa o pressionamento da tecla 'ENTER' ao disparo de um botao especificado.
 *
 * pEvento		Evento	Clique capturado a partir de um documento qualquer.
 * pobjBotao	Objeto	Botao que sera relacionado ao pressionamento da tecla 'enter'.
 */
//function VerificaENTER(pEvento, pobjBotao)
//{
//	//variaveis locais
//	var codigoTecla;	//codigo da tecla pressionada

//	//captura o codigo da tecla pressionada
//	if (gstrNavegador == "IE")
//	{
//	    codigoTecla = event.keyCode;
//	}
//	else
//	{
//	    codigoTecla = pEvento.charCode;
//	}
//	
//	if (gstrNavegador == "IE")
//	{	
//	    if (codigoTecla == 13 && pobjBotao && !pobjBotao.disabled)
//	    {
//	        pobjBotao.click();
//	    }
//	}
//	else
//	{
//	    if (codigoTecla == 13 && pobjBotao && !isNull(pobjBotao))
//	    {
//	        pobjBotao.click();
//	    }
//	}
//}

function submitForm(frm) {    
    //usar para cada campo uma propriedade obrigatorio=true
    for( i=0; i < frm.elements.length; i++) {
        if( frm.elements[i].type == "text" && frm.elements[i].value == "" ) {
            alert("Todos os campos são obrigatórios");
            frm.elements[i].focus();
            return false;
        }
    }
    
    return true;
    //onsubmit="return submitForm(this);"
}

function posLoading(e)
{
    //alert('teste1');
    
    if (!isUndefined(e))
    {
        var posx = 0, posy = 0;
        if ( e.pageX == undefined ) // IE
        {
            //posx = e.x;
            posx = event.clientX+document.body.scrollLeft;
            posy = event.clientY+document.body.scrollTop;
            //posy = e.y;
        }
        else
        {
            posx = e.pageX;
            posy = e.pageY;
        }
        posx = posx + 10;
        posy = posy - 5;
        document.getElementById("loading").style.top     = posy;
        document.getElementById("loading").style.left    = posx;
    }
    document.getElementById("loading").style.display = '';
}

function ValidaTamanhoNome(source, args)
{
    args.IsValid = !(args.Value.length < 3);
    try
    {
        if (!args.IsValid) { $get(source.controltovalidate).focus(); }
    }
    catch (e)
    {}
}

function ValidaTamanhoNome2(source, args)
{
    if ((args.Value.length < 6) || (args.Value.length > 10))
        {args.IsValid = false;}
    else
        {args.IsValid = true;}
}

function ValidarCEP(source, args)
{
    var cep = args.Value;
    exp = /\.|\-|\_|\,/g;
    cep = cep.toString().replace(exp, ""); 
    
    if (cep.length != 8 || 
        cep == "00000000" || 
        cep == "11111111" || 
        cep == "22222222" || 
        cep == "33333333" || 
        cep == "44444444" || 
        cep == "55555555" || 
        cep == "66666666" || 
        cep == "77777777" || 
        cep == "88888888" || 
        cep == "99999999" ||
        isNaN(cep))
    { 
        args.IsValid = false; 
        //args.Value = '';
    }
    else { args.IsValid = true; }
}

function isValidTelefone(valor, ValidateEmptyText)
{
    if (isUndefined(ValidateEmptyText)) { ValidateEmptyText = true; }
    
    var fone = valor;
    exp = /\.|\-|\_|\,|\(|\)/g;
    fone = fone.toString().replace(exp, ""); 
    
    exp = / /g;
    fone = fone.toString().replace(exp, ""); 
    
    //se false, não valida o conteudo em branco e retorna OK
    //essa opção serve para campos de tela q não são obrigatórios, 
    //e são validados somente quando possuem valor
    if ((!ValidateEmptyText) && (isNullOrEmpty(fone)))
    {
        return true;
    }
    
    if (fone.length != 10 || 
        fone == "0000000000" || 
        fone == "1111111111" || 
        fone == "2222222222" || 
        fone == "3333333333" || 
        fone == "4444444444" || 
        fone == "5555555555" || 
        fone == "6666666666" || 
        fone == "7777777777" || 
        fone == "8888888888" || 
        fone == "9999999999" ||
        isNaN(fone))
    { return false; }
    else { return true; }
}

function ValidaTelefone(source, args)
{
    var isValidateEmptyText = true;
        
    if (!isUndefined(source.validateemptytext))
    {
        isValidateEmptyText = source.validateemptytext;
    }
    else if (source.evaluationfunction.toString().indexOf("CustomValidator") != -1)
    {
        //por default, se um objeto do tipo customvalidator estiver com a propriedade validateemptytext = false
        //ela retorna undefined, portanto, se a rotina de validação do validator for uma custom, força o valor false
        //caso contrário retorna o true.
        isValidateEmptyText = false;
    }
    args.IsValid = isValidTelefone(args.Value, isValidateEmptyText);
    
    if (!args.IsValid)
    {
        //args.Value = '';
    }
}

//controla show e hide de um elemento
var show = 'S';
var hide = 'H';
function showHide(theID, action) {
	var obj = elementsById(theID);
	var strDsp;
	if (action)
		strDsp = (action == show ? '' : 'none');
	else
		strDsp = (document.getElementById(theID).style.display == '' ? 'none' : '');
	if (obj.length) {
		for (var i=0; i<obj.length; i++)
			obj[i].style.display = strDsp;
	} else if (!isUndefined(obj.style))
		obj.style.display = strDsp;

	return ( (strDsp == '') ? true : false);
}

//valida o CPF digitado
function ValidarCPF(source, args)
{
    var cpf = args.Value;
    exp = /\.|\-|\_|\,/g;
    cpf = TrimString(cpf.toString().replace(exp, ""));

    if (cpf.length != 11 ||
        cpf == "00000000000" ||
        cpf == "11111111111" ||
        cpf == "22222222222" ||
        cpf == "33333333333" ||
        cpf == "44444444444" ||
        cpf == "55555555555" ||
        cpf == "66666666666" ||
        cpf == "77777777777" ||
        cpf == "88888888888" ||
        cpf == "99999999999" ||
        isNaN(cpf))
    {
        args.IsValid = false;
        return;
    }
    
    var multiplicador1 = new Array ( 10, 9, 8, 7, 6, 5, 4, 3, 2 );
    var multiplicador2 = new Array ( 11, 10, 9, 8, 7, 6, 5, 4, 3, 2 );
    var tempCpf, digito, soma, resto;

    if (cpf.length != 11)
    {
        args.IsValid = false;
        return;
    }

    tempCpf = cpf.substr(0, 9);
    soma = 0;
    for (var i = 0; i < 9; i++)
        soma += parseInt(tempCpf.charAt(i).toString(), 10) * multiplicador1[i];

    resto = soma % 11;
    if (resto < 2)
        resto = 0;
    else
        resto = 11 - resto;

    digito = resto.toString();
    tempCpf = tempCpf + digito;

    soma = 0;
    for (var i = 0; i < 10; i++)
        soma += parseInt(tempCpf.charAt(i).toString(), 10) * multiplicador2[i];

    resto = soma % 11;
    if (resto < 2)
        resto = 0;
    else
        resto = 11 - resto;

    digito = digito + resto.toString();

    args.IsValid = (cpf.substr(cpf.length - digito.length) == digito);
}


function ValidaCNPJ(source, args)
{
    var cnpj = args.Value;
    exp = /\.|\-|\_|\,/g;
    cnpj = cnpj.toString().replace(exp, "");
    cnpj = cnpj.toString().replace("/", "");
    cnpj = TrimString(cnpj);

    var i = 0;
    var l = 0;
    var strNum = "";
    var strMul = "6543298765432";
    var character = "";
    var iValido = 1;
    var iSoma = 0;
    var strNum_base = "";
    var iLenMul = 0;
    var iLenNum_base = 0;

    if (isNullOrEmpty(cnpj))
    {
        args.IsValid = false;
        return;
    }

    l = cnpj.length;
    for (i = 0; i < l; i++)
    {
        caracter = cnpj.substring(i, i + 1)
        if ((caracter >= '0') && (caracter <= '9'))
            strNum = strNum + caracter;
    };

    if (strNum.length != 14 ||
        strNum == "00000000000000" ||
        strNum == "11111111111111" ||
        strNum == "22222222222222" ||
        strNum == "33333333333333" ||
        strNum == "44444444444444" ||
        strNum == "55555555555555" ||
        strNum == "66666666666666" ||
        strNum == "77777777777777" ||
        strNum == "88888888888888" ||
        strNum == "99999999999999" ||
        isNaN(strNum))
    {
        args.IsValid = false;
        return;
    }

    strNum_base = strNum.substring(0, 12);
    iLenNum_base = strNum_base.length - 1;
    iLenMul = strMul.length - 1;
    for (i = 0; i < 12; i++)
        iSoma = iSoma +
                        parseInt(strNum_base.substring((iLenNum_base - i), (iLenNum_base - i) + 1), 10) *
                        parseInt(strMul.substring((iLenMul - i), (iLenMul - i) + 1), 10);

    iSoma = 11 - (iSoma - Math.floor(iSoma / 11) * 11);
    if (iSoma == 11 || iSoma == 10)
        iSoma = 0;

    strNum_base = strNum_base + iSoma;
    iSoma = 0;
    iLenNum_base = strNum_base.length - 1
    for (i = 0; i < 13; i++)
        iSoma = iSoma +
                        parseInt(strNum_base.substring((iLenNum_base - i), (iLenNum_base - i) + 1), 10) *
                        parseInt(strMul.substring((iLenMul - i), (iLenMul - i) + 1), 10)

    iSoma = 11 - (iSoma - Math.floor(iSoma / 11) * 11);
    if (iSoma == 11 || iSoma == 10)
        iSoma = 0;
    strNum_base = strNum_base + iSoma;
    if (strNum != strNum_base)
    {
        args.IsValid = false;
        return;
    }

    args.IsValid = true;
}

function ValidarRGNumerico(source, args)
{
    var rg = args.Value;
    exp = /\.|\-|\_|\,/g;
    rg = rg.toString().replace( exp, "" ); 
        
    if (rg.length != 10 || 
        rg == "0000000000" || 
        rg == "1111111111" || 
        rg == "2222222222" || 
        rg == "3333333333" || 
        rg == "4444444444" || 
        rg == "5555555555" || 
        rg == "6666666666" || 
        rg == "7777777777" || 
        rg == "8888888888" || 
        rg == "9999999999" ||
        isNaN(rg))
        { 
            args.IsValid = false; 
            return;
        }
        else { args.IsValid = true; }
}

function ValidarRG(source, args)
{
    var rg = args.Value;
    exp = /\.|\-|\_|\,|\'|\"|\!|\@|\#|\$|\%|\&|\*|\(|\)|\+|\=|\<|\>|\:|\?|\/|\{|\}|\[|\]|\\/g;
    rg = rg.toString().replace(exp, ""); 
    
    exp = / /g;
    rg = rg.toString().replace(exp, ""); 
    
//    var obj = myGetElementById(source.controltovalidate);
//    obj.value = rg;
    
    if (rg.length != args.Value.length)
    {
        args.IsValid = false; 
    }
    else
    {
        args.IsValid = true; 
    }
}

//======================================================================================================================================================================
//função do calendário - Início
//======================================================================================================================================================================
function popdate(obj,div,tam,ddd,confDiv)
{
   date_Form = myGetElementById(obj);
   if (isNull(date_Form))
   {
      //Caso seja null, pega o elemento de forma normal. Possivelmente esta chamando pelo FireFox
      date_Form = eval(obj);
   }
   
   if (isUndefined(ddd))
   {
      ddd = date_Form.value;
   }
   
   exp = /\/|\_/g; //tira os "_" e os "/" do campo data, pois pode estar usando o maskExtender do ajax, __/__/____
   var dateTemp = ddd.toString().replace(exp, ""); 
   
   if ((!isNullOrEmptyOrUndefined(ddd)) && (!isNullOrEmpty(dateTemp))) 
   {
       day = "";
       mmonth = "";
       ano = "";
       c = 1;
       ichar = "";
       for (s=0;s<parseInt(ddd.length, 10);s++)
       {
           ichar = ddd.substr(s,1);
           if (ichar == "/") 
           {
               c++; 
               s++; 
               ichar = ddd.substr(s,1);
           }
           if (c==1) day    += ichar;
           if (c==2) mmonth += ichar;
           if (c==3) ano    += ichar;
       }
       //ddd = mmonth + "/" + day + "/" + ano
	   ddd = ano + "/" + mmonth + "/"  + day;
   }
   else { ddd = ""; }
   
   if (isNaN(new Date(ddd))) { ddd = ""; }
   
   if(!ddd) {today = new Date();} else {today = new Date(ddd);}
   
   //if (date_Form.value == "") 
   if (ddd == "")
   { 
        //pega a data do sistema
        date_Form = new Date();
   } 
   else 
   {
       //pega a data inicial que o objeto possui
       //date_Form = new Date(date_Form.value);
       date_Form = new Date(ddd);
   }
 
   ano = today.getFullYear();
   mmonth = today.getMonth ();
   day = today.toString ().substr (8,2)
 
   umonth = new Array ("Janeiro", "Fevereiro", "Mar&ccedil;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='#efefef' style='border:solid #ffffff; border-width:2' cellspacing='0' cellpadding='3' border='0' width='"+tam+"' height='"+tam*1.1 +"'>"
	txt  = "<table bgcolor='#efefef' style='border:solid silver; border-width:2' cellspacing='0' cellpadding='2' border='0' width='"+tam+"' height='"+tam*1.1 +"'>";

	// CONTROLES DE AVANÇO
	txt  += "	<tr class='conteudoTabelaCorForte'>";
	txt  += "		<td colspan='7' align='center'>";
	txt  += "			<table border='0' cellpadding='0' width='100%' class='conteudoTabelaCorForte'>";
	txt  += "				<tr>";
	txt  += "					<td width=20% align=center class='conteudoTabelaCorForte'>";
	txt  += "						<a style='font-weight: normal;text-decoration:none' href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+((mmonth+1).toString() +"/01/"+(ano-1).toString())+"') class='conteudoTabelaCorForte' title='Ano Anterior'><<</a>";
	txt  += "					</td>";
	txt  += "					<td width=20% align=center class='conteudoTabelaCorForte'>";
	txt  += "						<a style='font-weight: normal;text-decoration:none' href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+( "01/" + (month_prior+1).toString() + "/" + year_prior.toString())+"') class='conteudoTabelaCorForte' title='M&ecirc;s Anterior'><</a>";
	txt  += "					</td>";
	txt  += "					<td width=20% align=center class='conteudoTabelaCorForte'>";
	txt  += "						<a style='font-weight: normal;text-decoration:none' href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+( "01/" + (month_next+1).toString()  + "/" + year_next.toString())+"') class='conteudoTabelaCorForte' title='Pr&oacute;ximo M&ecirc;s'>></a>";
	txt  += "					</td>";
	txt  += "					<td width=20% align=center class='conteudoTabelaCorForte'>";
	txt  += "						<a style='font-weight: normal;text-decoration:none;' href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+((mmonth+1).toString() +"/01/"+(ano+1).toString())+"') class='conteudoTabelaCorForte' title='Pr&oacute;ximo Ano'>>></a>";
	txt  += "					</td>";
	txt  += "					<td width=20% align=right class='conteudoTabelaCorForte'>";
	txt  += "						<a style='font-weight: normal;text-decoration:none;' href=javascript:force_close('"+div+"') class='conteudoTabelaCorForte' title='Fechar Calend&aacute;rio'><b>X</b></a>";
	txt  += "					</td>";
	txt  += "				</tr>";
	txt  += "			</table>";
	txt  += "		</td>";
	txt  += "	</tr>";

	// MES E ANO
	txt  += "	<tr>";
	txt  += "		<td colspan='7' align='left' bgcolor='#333333' class='botao'>&nbsp;";
	txt  += "			<b>";
	txt  += "				<a style='text-decoration:none; color:#FFFFFF' href=javascript:pop_month('"+obj+"','"+div+"','"+tam+"','" + ano + "') >" + umonth[mmonth] + "</a> de ";
	txt  += "				<a style='text-decoration:none; color:#FFFFFF' href=javascript:pop_year('"+obj+"','"+div+"','"+tam+"','" + (mmonth+1) + "')>" + ano.toString() + "</a>";
	txt  += "				<div id='popd' style='position:absolute'></div>";
	txt  += "			</b>";
	txt  += "		</td>";
	txt  += "	</tr>";

	// TITULO DO DIA DA SEMANA
	txt  += "	<tr bgcolor='#646464'>";
	txt  += "		<td width='14%' style='font-weight: bold;' class='conteudoTabelaCorForte' align=center>Dom</td>";
	txt  += "		<td width='14%' style='font-weight: bold;' class='conteudoTabelaCorForte' align=center>Seg</td>";
	txt  += "		<td width='14%' style='font-weight: bold;' class='conteudoTabelaCorForte' align=center>Ter</td>";
	txt  += "		<td width='14%' style='font-weight: bold;' class='conteudoTabelaCorForte' align=center>Qua</td>";
	txt  += "		<td width='14%' style='font-weight: bold;' class='conteudoTabelaCorForte' align=center>Qui</td>";
	txt  += "		<td width='14%' style='font-weight: bold;' class='conteudoTabelaCorForte' align=center>Sex</td>";
	txt  += "		<td width='14%' style='font-weight: bold;' class='conteudoTabelaCorForte' align=center>S&aacute;b</td>";
	txt  += "	</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='#efefef' 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='#D4D7DA' " : "" );
					 mesp = mmonth+1;
					 if (mesp<10){
					 mes_sh = '0' + mesp;
					 }else{
					 mes_sh = mesp;
					 }
					 
					 if(d<10){
					 	d = '0' + d;
					 }
					 
           txt += "<td"+colorcell+" style='font-weight: normal;text-decoration:none' class='ConteudoTabelaCorFraca' align=center><a href=javascript:block('"+ d + "/" + (mes_sh).toString() + "/" + ano.toString() +"','"+ obj +"','" + div +"') style='font-weight: normal;text-decoration:none;color: Black;font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10px; color: #000000; text-decoration: none; height:20px;' class='ConteudoTabelaCorFraca'>"+ d.toString() + "</a></td>";
           d ++;
       } 
       else 
       { 
           txt += "<td style='font-weight: normal;text-decoration:none' class='ConteudoTabelaCorFraca' align=center> </td>";
       }
       week ++;
       if (week == 8) 
       { 
           week = 1; 
           txt += "</tr>";
       }
    }
    txt += "</table>";
   
    div2 = myGetElementById(div);
    if (isNull(div2))
    {
       //Caso seja null, pega o elemento de forma normal. Possivelmente esta chamando pelo FireFox
       div2 = eval (div);
    }	   
    div2.innerHTML = txt;
    
    if (confDiv)
    {
       div2.style.display='block';
       window.scrollTo(1000,1000);
    }
}
 
// função para exibir a janela com os meses
function pop_month(obj, div, tam, ano)
{
 txt  = "<table bgcolor='#cccccc' border='0' width=80 class='ConteudoTabelaCorForte'>"
 for (n = 0; n < 12; n++) { txt += "<tr><td align=center class='ConteudoTabelaCorFraca'><a href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+("01/" + (n+1).toString() + "/" + ano.toString())+"') style='text-decoration:none; color:#000000;'>" + 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='#cccccc' border='0' width=160 class='ConteudoTabelaCorForte'>"
 l = 1
 
 var d=new Date();
 
 for (n=d.getFullYear()-35; n<d.getFullYear() - 17; n++)
 {  if (l == 1) txt += "<tr>"
    txt += "<td class='ConteudoTabelaCorForte' align=center><a href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+(umonth.toString () +"/01/" + n) +"') style='text-decoration:none; color:#000000;'>" + 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 = myGetElementById(div);
    if (isNull(div2))
    {
        div2 = eval (div); 
    }   
   	div2.innerHTML = '';
	//new Effect.SlideUp('pop1')
}
   
// 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 = myGetElementById(obj);
   if (isNull(obj2))
   {
       obj2 = eval(obj); 
   }   
   obj2.value = data; 
}
//=====================================
//função do calendário - fim
//=====================================

// ValidaData ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
function ValidaData (data, validaRange, isValidateEmptyText) 
{
    if (isUndefined(validaRange)) { validaRange = false; }
    if (isUndefined(isValidateEmptyText)) { isValidateEmptyText = false; }
    
    if ((!isValidateEmptyText) && (hasInitialValue(data)))
    {
        return true;
    }
    
    //Verifica se a data é válida (data em português)
    var curYear = (new Date()).getFullYear();
       
    exp = /\/|\_/g; //tira os "_" e os "/" do campo data, pois pode estar usando o maskExtender do ajax, __/__/____
    var dateTemp = data.toString().replace(exp, ""); 
    
    if ((isNaN(new Date(data))) || (isNullOrEmpty(dateTemp))) {
        return (false) ;
    }  
    else 
    {
  
        var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4}|\d{2})$/;
        //var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/; //4 dígitos no ano

        var matchArray = data.match(datePat); // is the format ok?
        if (matchArray == null) {
            return (false);
        }
  
        var day = parseInt(matchArray[1], 10); // parse date into variables
        var month = parseInt(matchArray[3], 10);
        var year = parseInt(matchArray[4], 10);

        if (month < 1 || month > 12) { // check month range
            return (false);
        }
        if (day < 1 || day > 31) {
            return (false);
        }
        if ((month==4 || month==6 || month==9 || month==11) && day==31) {
            return (false);
        }
        if (month == 2) { // check for february 29th
            var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
	        if (day>29 || (day==29 && !isleap)) {
	            return (false);
	        }
        }
        if (validaRange)
        {//verifica se pessoa possui no maximo 100 anos e no mínimo 18 anos
            if ((curYear - year > 100) || (curYear - year < 18)) {
                return false;
            }
        }
    }
    return (true);  // date is valid
}
// isValidaData ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
function isValidaData(source, args) 
{
    var isValidateEmptyText = false;
    if (!isUndefined(source.validateemptytext))
    {
        isValidateEmptyText = source.validateemptytext;
    }
        
    if (!ValidaData(args.Value, false, isValidateEmptyText)) 
        { args.IsValid = false; }
    else
        { args.IsValid = true; }
}

function isValidaDataRange(source, args) 
{        
    var isValidateEmptyText = false;
    if (!isUndefined(source.validateemptytext))
    {
        isValidateEmptyText = source.validateemptytext;
    }
    
    if (!ValidaData(args.Value, true, isValidateEmptyText)) 
        { args.IsValid = false; }
    else
        { args.IsValid = true; }
}

function ValidaExtensao(tipo, arquivo)
{
    var extensao = arquivo.substring(arquivo.length-4).toLowerCase();
    //alert(extensao);
    switch (tipo)
    {
        case 0:
            if (extensao != '.pdf')
            {
                return false;
            }
            break;
        case 1:
            if (extensao != '.jpg')
            {
                return false;
            }
            break;
    }
    return true;
}

function GetXmlHttpObject(filePath)
{
    var xmlHttp;
    try
    {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }
    catch (e)
    {
        // Internet Explorer
        try
        {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            try
            {
                xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e)
            {
                //alert("Your browser does not support AJAX!");
                return null;
            }
        }
    }
    return xmlHttp;
}

function CountLength(field, maxLen, campoContador)
{    
    if (isNullOrEmptyOrUndefined(field)) { return; }
	
    if (!isObject(field))
	{
	    field = myGetElementById(field);
	}
    
	fieldLen = field.value.length;
	
	if (isUndefined(maxLen) || isNaN(maxLen)) 
    { 
        maxLen = parseInt(field.attributes["maxLength"].value, 10);
    }
    
    //alert("maxLen: " + maxLen);
    
	if (fieldLen >= maxLen)
	{
		field.value = field.value.substring(0, maxLen);
		charsLeft = maxLen;
	}
	else
	{
		charsLeft = fieldLen;
	}
	//se campo for passado como string, retorna o objeto da tela
	if (!isNullOrEmptyOrUndefined(campoContador))
	{
	    if (!isObject(campoContador))
	    {
	        campoContador = myGetElementById(campoContador);
	    }
	    campoContador.value = charsLeft;
	}
}

 function maxLength(field, maxChars)
 {
    if (isNullOrEmptyOrUndefined(maxChars) || isNaN(maxChars)) 
    { 
        maxChars = parseInt(field.attributes["maxLength"].value, 10);
    }
    
    if(field.value.length >= maxChars) 
    {
        event.returnValue = false;
        return false;
    }
 }  

 function maxLengthPaste(field, maxChars)
 {
    if (isNullOrEmptyOrUndefined(maxChars) || isNaN(maxChars)) 
    { 
        maxChars = parseInt(field.attributes["maxLength"].value, 10);
    }
    
    event.returnValue = false;
    if((field.value.length + window.clipboardData.getData("Text").length) > maxChars) 
    {
        return false;
    }
    event.returnValue = true;
 }
 
function setFormInterval(reload, velocidade, tempo, closeForm) 
{
	if (isUndefined(velocidade)) { velocidade = 30000; } //30000; //30 segundos
	if (isUndefined(tempo)) { tempo = 60000; }  //180000; //3 minutos
	if (isUndefined(reload)) { reload = true; }
	if (isUndefined(closeForm)) { closeForm = true; }
	//if (isUndefined(reloadOpener)) { reloadOpener = false; }
	
	var intervalo;
	if (reload)
	    intervalo = window.setInterval(function() { reloadPage(false); }, velocidade);
	else
	    intervalo = window.setInterval(function() { self.close(); void(0); }, velocidade);
	    
	window.setTimeout(function() { clearInterval(intervalo); if (closeForm) { self.close(); void(0); } }, tempo);
}

function mudaStringLabelIntervalo(lblMsg, msg, velocidade, fontWeight, fontColor, cssClass)
{
    if (!isObject(lblMsg)) { lblMsg = $get(lblMsg); }
    
    window.setTimeout(function() { mudaStringLabel(lblMsg, msg, fontWeight, fontColor, cssClass); }, velocidade);
    
//    var intervalo = window.setInterval(function() { mudaStringLabel(lblMsg, msg, fontWeight, fontColor, cssClass); }, velocidade);
//    
//    var tempo = 10000; //10 segundos
//    window.setTimeout(function() { clearInterval(intervalo); }, tempo);
}

function mudaStringLabel(lblMsg, msg, fontWeight, fontColor, cssClass)
{
    if (isUndefined(fontWeight)) { fontWeight = 'bold'; } 
    if (isUndefined(fontColor)) { fontColor = 'red'; } 
    if (isUndefined(lblMsg.firstChild)) { return; }
    if (isUndefined(lblMsg.firstChild.data)) { return; }
        
    lblMsg.firstChild.data = msg;
    lblMsg.style.fontWeight = fontWeight;
    lblMsg.style.color = fontColor; 
        
    if (!isUndefined(cssClass)) 
        { ChangeClassName(lblMsg, cssClass); } 
//    else 
//    {
//        lblMsg.style.fontWeight = fontWeight;
//        lblMsg.style.color = fontColor; 
//    }
}

function reloadPage(isOpener)
{
    //alert("reloadPage.isOpener: " + isOpener);
    if (isUndefined(isOpener)) { isOpener = false; }
    try
    {
        if (isOpener)
        {
            window.opener.location.reload();
        }
        else
        {
            setNewUrlLocation(window.location.href);
            //window.location.reload();
        }
    }
    catch (ex)
    {
        //alert(ex.Description);//
    }
}

function validaOpener(isOpener)
{
    //alert("validaOpener.isOpener: " + isOpener);
    if (isUndefined(isOpener)) { isOpener = true; }
    try
    {
        if ((!(window.opener)) || (!(window.opener.location)) || (!(window.opener.location.href))) 
        {
            self.close(); 
            void(0);
        } 
        else 
        {
            var caminho = window.opener.location.href.toLowerCase();
            if ((caminho.indexOf('/home.aspx') == -1) && (caminho.indexOf('/login.aspx') == -1) && (caminho.indexOf('/default.aspx') == -1))
            {
                reloadPage(isOpener);
            }
        }
    }
    catch (ex)
    {
        self.close(); 
        void(0);
    }
}

function validaOpenerPopUp(newUrlLocation)
{
    var varTeste = null;
    try
    {
        try
        {
            varTeste = window.opener || window.opener.location || window.opener.location.href;
        }
        catch (ex)
        {
            if (gstrNavegador != "IE") { varTeste = "0"; }
        }
        
        if (varTeste)
        {
            //
        }
        else if (window.opener.length > 0)
        {
            varTeste = null;
        }
        else if (window.opener.location.href.toLowerCase().indexOf("/area_de_trabalho/area_de_trabalho.aspx") == -1)
        {
            varTeste = null;
        }
        else
        {
            varTeste = "0";
        }	
        //alert(varTeste);
    }
    catch (ex)
    { //ERRO 
        varTeste = null;
    }

    try
    {
        if (isUndefined(varTeste)) 
        { 
            //se não possui opener, foi digitado a URL direto então tenta fazer um new location
            setNewUrlLocation(newUrlLocation);
        } 
        else 
        { 
            //se possui opener, fecha a janela
            self.close(); 
            void(0); 
        }
    }
    catch (ex)
    {
        //se der algum erro, tenta fechar a janela. 
        self.close(); 
        void(0);
    }
}

function ChamaBotaoDefault2(e, objBotao)
{     
    if(isKey(13, e)) { window.setTimeout(function() { __doPostBack(objBotao,'');}, 0); }
}

function ChamaBotao(e, objBotao)
{     
    window.setTimeout(function() { __doPostBack(objBotao,'');}, 0);
}

function ChamaBotaoDefault(e, objBotao, objCaller, validationGroup)
{   
    ///Só chama o botão enter, se estiver vinculado a validators.
    if (!isNullOrEmptyOrUndefined(validationGroup)) 
    { 
        objCaller.onkeyup = function() { if(isKey(13, e)) { if (Page_ClientValidate(validationGroup)) { window.setTimeout(function(){ __doPostBack(objBotao,''); }, 0) } } };
    }
}

function ChamaBotaoESC(e, objBotao)
{    
    if(isKey(27, e))
    {
        objBotao.click();
        return;
    }
}

function StopEventJS(pE)
{
    if (!pE)
        if (window.event)
            pE = window.event;
        else
            return;
    if (pE.cancelBubble != null)
        pE.cancelBubble = true;
        
    if (pE.stopPropagation)
        pE.stopPropagation();
        
    if (pE.preventDefault)
        pE.preventDefault();
        
    if (window.event)
        pE.returnValue = false;
        
    if (pE.cancel != null)
        pE.cancel = true;
        
    return false;
}  // StopEvent

function upperCaseOnBlur(input)
{
    input.value = input.value.toUpperCase();
}

function lowerCaseOnBlur(input)
{
    input.value = input.value.toLowerCase();
}

function moveToEnd(obj)
{
    //alert(obj.createTextRange);
    if (!isUndefined(obj.createTextRange)) 
    {
        //alert("entrou");
		var r = document.selection.createRange().duplicate();
		//alert("r: " + r);
		//alert(obj.value.length);
		r.moveEnd('character', obj.value.length);
	}
}

function upperCaseOnType(e,obj) 
{
    var tecla = (document.all) ? e.keyCode : e.which;
    //alert("e.which: " + e.which);
    //alert("e.keyChar: " + e.keyChar);
    //alert("e.keyCode: " + e.keyCode);
    //alert(tecla);
    if (tecla!="8" && tecla!="0")
    {
        if (obj.setSelectionRange)
        {
            var selectionStart = obj.selectionStart;
            var selectionEnd = obj.selectionEnd;
            if (selectionStart != selectionEnd)
            {
                obj.value = obj.value.substring(0, selectionStart) + 
                String.fromCharCode(tecla).toUpperCase() +
                obj.value.substring(selectionEnd);
                //significa que o objeto está selecionado, portanto limpa antes o conteudo
                //obj.value = '';
            }
            else
            {
                obj.value += String.fromCharCode(tecla).toUpperCase();
            }
        }
        else
        {
            if (gstrNavegador == "IE")
    	    { StopEventJS(e); }
            obj.value += String.fromCharCode(tecla).toUpperCase();
        }
        return false;
    }
    else
    {
        return true;
    }
}
///////////////////////////////////////////////////////////////////////////////////
function isChar(e) 
{
    var key = (window.event) ? event.keyCode : e.which;

    var retval =
        (key >= 48 && key <= 90) ||
        (key >= 96 && key <= 111) ||
        (key >= 188 && key <= 222);

    return retval;
}

function isKey(k, e) 
{
    var key = (window.event) ? event.keyCode : e.which;
    return (key == k);
}

function ValidaJanela(strIDJanela, intAcao)
{
    //    alert(window.name);
    //    alert(strIDJanela);
    //    alert(window.name != strIDJanela);
    if (window.name != strIDJanela)
    {
        switch (intAcao)
        {
            //                   
            case 1:
                alert('Solicitação proveniente de servidor sem permissão!\n\nSe este erro persistir, você pode entrar em contato, em horário comercial, com a Entidade da sua cidade.');
                self.close();
                void (0);
                break;
            //                   
            case 2:
                alert('Operação excedeu o limite de tempo permitido!\n\nSe este erro persistir, você pode entrar em contato, em horário comercial, com a Entidade da sua cidade.');
                self.close();
                void (0);
                break;
        }
    }
}

function select(campo) 
{
    campo.focus();
    campo.select();
}

function MascaraMoeda(objTextBox, e)
{
    var key = "";
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = "0123456789";
    var SeparadorMilesimo = ".";
    var SeparadorDecimal = ",";
    var aux = aux2 = "";
    var whichCode = (window.event) ? event.keyCode : e.which;

    if (whichCode == 0 || whichCode == Sys.UI.Key.backspace) return true; //8=BACKSPACE, 0=TAB ENTRE OUTRAS TECLAS DE CONTROLE
    if (whichCode == Sys.UI.Key.enter) return true;

    key = String.fromCharCode(whichCode); // Valor para o código da Chave
    if (strCheck.indexOf(key) == -1) return false; // Chave inválida
    len = objTextBox.value.length;
    if (len >= objTextBox.maxLength)
    {
        objTextBox.value = objTextBox.value.substr(0, objTextBox.maxLength);
        return false;
    }
    for (i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
    aux = '';
    for (; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i)) != -1) aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) objTextBox.value = '';
    if (len == 1) objTextBox.value = '0' + SeparadorDecimal + '0' + aux;
    if (len == 2) objTextBox.value = '0' + SeparadorDecimal + aux;

    if (len > 2)
    {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--)
        {
            if (j == 3)
            {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
            objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
    }
    //
    StopEventJS(e);
    return true;
}

function TrocaValidator(origem, destino, content)
{    
    for (var i = 0; i < Page_Validators.length; i++)
    {
        //verifica se o validator é do content que deve ser validado, do mesmo validationGroup
        if (Page_Validators[i].validationGroup == content)
        {
            var objToValidate = Page_Validators[i].controltovalidate;
            if (isUndefined(Page_Validators[i].enabled) || Page_Validators[i].enabled == true) // se o Page_Validators[i].enabled é undefined, é pq está com o valor padrão TRUE
            {
                //testa apenas o validator do componente, se ele estiver false, dai testa todos da pagina
                if (origem == objToValidate)
                {
                    Page_Validators[i].controltovalidate = destino;
                    break;                    
                } //end if
            } //end if
        } //end if
    } //for
}

function getDocumentSelection()
{
    //devolve o texto selecionado no form
    if (gstrNavegador != "IE")
    { return document.getSelection(); }
    else
    { return document.selection.createRange(); }
}

function callDoPostBackWithOptions(eventTarget, validationGroup, disable, executeTwoTimes, simpleDoPostBack)
{
    if (isNullOrEmptyOrUndefined(validationGroup))
        return;

    if (Page_ClientValidate(validationGroup))
    {
        callDoPostBack(eventTarget, '', disable, executeTwoTimes, simpleDoPostBack);
    }
}

function callDoPostBack(eventTarget, eventArgument, disable, executeTwoTimes, simpleDoPostBack)
{
    var tempObj = null;

    if (isNullOrEmptyOrUndefined(executeTwoTimes))
        executeTwoTimes = true;

    if (isNullOrEmptyOrUndefined(simpleDoPostBack))
        simpleDoPostBack = true;

    if (isNullOrEmptyOrUndefined(eventTarget))
        return;

    if (isNullOrEmptyOrUndefined(eventArgument))
        eventArgument = '';

    if (isNullOrEmptyOrUndefined(disable))
        disable = false;

    if ((!isObject(eventTarget)) && (eventTarget.toString().indexOf("_") != -1))
    { //foi passado o ID _
        eventTarget = $get(eventTarget).name;
        tempObj = $get(eventTarget);
    }
    else if ((!isObject(eventTarget)) && (eventTarget.toString().indexOf("$") != -1))
    { //foi passado o name $
        var exp = /\$/g;
        tempObj = $get(eventTarget.toString().replace(exp, "_"));
    }
    else if (isObject(eventTarget))
    {// foi passado o objeto
        tempObj = eventTarget;
        eventTarget = tempObj.name;
    }

    if (isObject(tempObj))
        if (disable)
        tempObj.setAttribute("disabled", "disabled");

    if (simpleDoPostBack)
        __doPostBack(eventTarget, eventArgument);
    else
        window.setTimeout(function() { __doPostBack(eventTarget, eventArgument); }, 550);
        
    if (executeTwoTimes)
    {
        if (typeof (Page_ClientValidate) == 'function')
        {
            if (!Page_IsValid)
            {
                //executa 2x o post, pois na segunda vez, mesmo com os validators, ele consegue executar
                __doPostBack(eventTarget, eventArgument);
                //Page_ClientValidate('cadastro');
            }
        }
    }
}

//////////////////////////////////////////////////////////////////////////////////////////////        
//      DMF 20090623    
//      Retorna codigo da tecla pressionada
//      var key = retornaKey(evento);

function retornaKey(evento)
{
    return ((window.event) ? event.keyCode : evento.which);
}
//////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////
//      DMF 20090625
//      VERIFICA SE A TECLA DIGITADA É DE CONTROLE (BACKSPACE, ESPAÇO, TAB, CTRL, ETC)
//      Retorno: Boolean

function isControlKey(key)
{
    var keys = new Array(0, 8, 13); //Teclas de controle/Backspace/Enter/Delete
    for (var i = 0; i < keys.length; i++)
        if (key == keys[i]) return true;

    if (key < 47)
        return true;
    else
        return false;
}
//////////////////////////////////////////////////////////////////////////////////////////////

function SelectNext(nextObj, evento)
{
    try
    {
        if (isKey(Sys.UI.Key.enter, evento))
            return true;

        var currObj = null;

        if (gstrNavegador == "IE")
            currObj = evento.srcElement;
        else
            currObj = evento.target;

        if ((currObj.value.length >= currObj.maxLength) && (!isControlKey(retornaKey(evento))))
        {
            currObj.value = currObj.value.substr(0, currObj.maxLength);
            select(nextObj);
        }
        StopEventJS(evento);
        return true;
    }
    catch (e) { }
}

function strZero(valor, tamanho)
{
    var retorno = retornaNumber(valor);
    var nTamanho = retorno.length;
    var sZeros = "";
    if (nTamanho >= tamanho)
        return retorno.substr(0, tamanho);

    if (isNumeric(retorno))
    {
        for (var i = nTamanho; i < tamanho; i++)
            sZeros += "0";
            
        return sZeros + retorno;
    }
    else
        return "";
}

//////////////////////////////////////////////////////////////////////////////////////////////        
//      RSP 20090921    
//      SOMENTE NUMEROS

function isNumeric(valor)
{
    var strCheck = "0123456789";
    var nTamanho = valor.length;
    if (nTamanho == 0) return false;

    for (var i = 0; i < nTamanho; i++)
    {
        if ((strCheck.indexOf(valor.charAt(i)) == -1) && (isNaN(valor.charAt(i))))
            return false;
    }

    return true;
}
//////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////        
//      RSP 20090921
//      SOMENTE NUMEROS
//      onblur="retornaNumber(this.value)"

function retornaNumber(valor)
{
    var strCheck = "0123456789";
    var nTamanho = valor.length;
    var retorno = "";

    if (nTamanho == 0) return retorno;

    for (var i = 0; i < nTamanho; i++)
    {
        if (strCheck.indexOf(valor.charAt(i)) != -1)
            retorno += valor.charAt(i);
    }

    return retorno;
}
//////////////////////////////////////////////////////////////////////////////////////////////

function ValidaNum(source, args)
{
    var valor = args.Value;
    exp = /\.|\-|\_|\,/g;
    valor = valor.toString().replace(exp, "");
    try
    {
        valor = parseFloat(valor);
    }
    catch (e)
    {
        valor = 0;
    }

    args.IsValid = ((!isNaN(valor)) && (valor > 0));
    return args.IsValid;
}

//function enhanceLinks() {
// 	var links = document.getElementsByTagName("a");
//	 var thisDomain = document.domain.split('www.');
// 	var thisDomain = (thisDomain[1]) ? thisDomain[1] : document.domain ;
// 	alert(links.length);
//	 for (var i = 0; i < links.length; i++) {
//		alert(links[i].href);
//  		if(links[i].href.indexOf(thisDomain) == -1 && links[i].href != '') {
//			alert('1');
//			   links[i].target = '_blank';
//   			links[i].className = 'link_ext';
// 		 }
//	}
//}

//// Multiple onload function created by: Simon Willison
//// http://simon.incutio.com/archive/2004/05/26/addLoadEvent
//function addLoadEvent(func) {
//alert('3');
//  var oldonload = window.onload;
//  if (typeof window.onload != 'function') {
//    window.onload = func;
//  } else {
//    window.onload = function() {
//      if (oldonload) {
//        oldonload();
//      }
//      func();
//    }
//  }
//}

//addLoadEvent(function() {
//	alert('2');
//  enhanceLinks();
//});

