/* Funções para Troca de Imagens */
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

/* Funções para o Menu */
var cssdropdown={
disappeardelay: 250, //set delay in miliseconds before menu disappears onmouseout
disablemenuclick: true, //when user clicks on a menu item with a drop down menu, disable menu item's link?
enableswipe: 1, //enable swipe effect? 1 for yes, 0 for no

dropmenuobj: null, ie: document.all, firefox: document.getElementById&&!document.all, swipetimer: undefined, bottomclip:0,

getposOffset:function(what, offsettype){
var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
var parentEl=what.offsetParent;
while (parentEl!=null){
totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
parentEl=parentEl.offsetParent;
}
return totaloffset;
},

swipeeffect:function(){
if (this.bottomclip<parseInt(this.dropmenuobj.offsetHeight)){
this.bottomclip+=10+(this.bottomclip/10) //unclip drop down menu visibility gradually
this.dropmenuobj.style.clip="rect(0 auto "+this.bottomclip+"px 0)"
}
else
return
this.swipetimer=setTimeout("cssdropdown.swipeeffect()", 10)
},

showhide:function(obj, e){
if (this.ie || this.firefox)
this.dropmenuobj.style.left=this.dropmenuobj.style.top="-500px"
if (e.type=="click" && obj.visibility==hidden || e.type=="mouseover"){
if (this.enableswipe==1){
if (typeof this.swipetimer!="undefined")
clearTimeout(this.swipetimer)
obj.clip="rect(0 auto 0 0)" //hide menu via clipping
this.bottomclip=0
this.swipeeffect()
}
obj.visibility="visible"
}
else if (e.type=="click")
obj.visibility="hidden"
},

iecompattest:function(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
},

clearbrowseredge:function(obj, whichedge){
var edgeoffset=0
if (whichedge=="rightedge"){
var windowedge=this.ie && !window.opera? this.iecompattest().scrollLeft+this.iecompattest().clientWidth-15 : window.pageXOffset+window.innerWidth-15
this.dropmenuobj.contentmeasure=this.dropmenuobj.offsetWidth
if (windowedge-this.dropmenuobj.x < this.dropmenuobj.contentmeasure)  //move menu to the left?
edgeoffset=this.dropmenuobj.contentmeasure-obj.offsetWidth
}
else{
var topedge=this.ie && !window.opera? this.iecompattest().scrollTop : window.pageYOffset
var windowedge=this.ie && !window.opera? this.iecompattest().scrollTop+this.iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18
this.dropmenuobj.contentmeasure=this.dropmenuobj.offsetHeight
if (windowedge-this.dropmenuobj.y < this.dropmenuobj.contentmeasure){ //move up?
edgeoffset=this.dropmenuobj.contentmeasure+obj.offsetHeight
if ((this.dropmenuobj.y-topedge)<this.dropmenuobj.contentmeasure) //up no good either?
edgeoffset=this.dropmenuobj.y+obj.offsetHeight-topedge
}
}
return edgeoffset
},

dropit:function(obj, e, dropmenuID){
if (this.dropmenuobj!=null) //hide previous menu
this.dropmenuobj.style.visibility="hidden" //hide menu
this.clearhidemenu()
if (this.ie||this.firefox){
obj.onmouseout=function(){cssdropdown.delayhidemenu()}
//obj.onclick=function(){return !cssdropdown.disablemenuclick} //disable main menu item link onclick?
this.dropmenuobj=document.getElementById(dropmenuID)
this.dropmenuobj.onmouseover=function(){
  cssdropdown.clearhidemenu();
  //Mesmo style para o parent
  //obj.style.backgroundColor = "#939598";
  obj.style.backgroundColor = "#CFCFCF";
  obj.style.border          = "1px solid";
  obj.style.borderColor     = "#828282";
//  obj.style.color           = "#696969";

}
this.dropmenuobj.onmouseout=function(){
  cssdropdown.dynamichide(e);
  //Remove style do parent
  obj.style.backgroundColor ="";
  //obj.style.borderColor     = "#E8E8E8";
  obj.style.border          = "0";
  //obj.style.color  = "#696969";
  }
this.dropmenuobj.onclick=function(){cssdropdown.delayhidemenu()}
this.showhide(this.dropmenuobj.style, e)
this.dropmenuobj.x=this.getposOffset(obj, "left")
this.dropmenuobj.y=this.getposOffset(obj, "top")
this.dropmenuobj.style.left=this.dropmenuobj.x-this.clearbrowseredge(obj, "rightedge")+"px"
this.dropmenuobj.style.top=this.dropmenuobj.y-this.clearbrowseredge(obj, "bottomedge")+obj.offsetHeight+1+"px"
}
},

contains_firefox:function(a, b) {
while (b.parentNode)
if ((b = b.parentNode) == a)
return true;
return false;
},

dynamichide:function(e){
var evtobj=window.event? window.event : e
if (this.ie&&!this.dropmenuobj.contains(evtobj.toElement))
this.delayhidemenu()
else if (this.firefox&&e.currentTarget!= evtobj.relatedTarget&& !this.contains_firefox(evtobj.currentTarget, evtobj.relatedTarget))
this.delayhidemenu()
},

delayhidemenu:function(){
this.delayhide=setTimeout("cssdropdown.dropmenuobj.style.visibility='hidden'",this.disappeardelay) //hide menu
},

clearhidemenu:function(){
if (this.delayhide!="undefined")
clearTimeout(this.delayhide)
},

startchrome:function(){
for (var ids=0; ids<arguments.length; ids++){
var menuitems=document.getElementById(arguments[ids]).getElementsByTagName("a")
for (var i=0; i<menuitems.length; i++){
if (menuitems[i].getAttribute("rel")){
var relvalue=menuitems[i].getAttribute("rel")
menuitems[i].onmouseover=function(e){
var event=typeof e!="undefined"? e : window.event
cssdropdown.dropit(this,event,this.getAttribute("rel"))
}
}
}
}
}

}

/* Função para menu de ficha */
function MostraMenu(pThis,pMenu){
  var bot = $x(pThis);
  var nmenu = 'menu_ficha'+pMenu;
  var menu = document.getElementById(nmenu);

  menu.style.zIndex = 100;
  //menu.style.position = 'absolute';
  //menu.style.top = parseInt(findPosY(bot) + parseInt(bot.offsetHeight))+3;
  //menu.style.left = parseInt(findPosX(bot)) - 10;/* parseInt(bot.offsetWidth));*/

  $(menu).css('position','absolute');
  jQuery.each(jQuery.browser, function(i) {
    if($.browser.msie){
      $(menu).css('top',parseInt(findPosY(bot) + parseInt(bot.offsetHeight))+3);
      $(menu).css('left',parseInt(findPosX(bot)) - 10);
    }
    else{
      $(menu).css('top',parseInt(findPosY(bot) + parseInt(bot.offsetHeight))-9);
      $(menu).css('left',parseInt(findPosX(bot)) - 8);
    }
  });

  html_ToggleElement(nmenu);
}

/*Funções usada para formatar a data no evento OnKeyPress*/
function mascara_data(pthis){
        v_tam = pthis.value;
        if (v_tam.length == 2){
          pthis.value += '/';
        }
        if (v_tam.length == 5){
          pthis.value += '/';
        }
}

/* Função usada para formatar mês e ano no evento OnKeyPress */
function mascara_mes_ano(pthis){
  v_tam = pthis.value;
  if (v_tam.length == 2){ pthis.value += '/'; }
}

/*Funções usada para formatar a hora no evento OnKeyPress*/
function mascara_hora(pthis){
        v_tam = pthis.value;

    if (v_tam.length == 2){
      pthis.value += ':';
    }

    if (v_tam.length == 5){
      pthis.value += ':';
    }
}

/*Funções usada para formatar CPF no evento OnKeyPress*/
function mascara_cpf(pthis){
        v_tam = pthis.value;

        if (v_tam.length == 3){
          pthis.value += '.';
        }
        if (v_tam.length == 7){
          pthis.value += '.';
        }
        if (v_tam.length == 11){
          pthis.value += '-';
        }
        if (v_tam.length == 14){
        }
}

/*Funções usada para formatar CNPJ no evento OnKeyPress*/
function mascara_cnpj(pthis){
        v_tam = pthis.value;

        if (v_tam.length == 2){
          pthis.value += '.';
        }
        if (v_tam.length == 6){
          pthis.value += '.';
        }
        if (v_tam.length == 10){
          pthis.value += '/';
        }
        if (v_tam.length == 15){
          pthis.value += '-';
        }
}

/*Funções usada para formatar CEP no evento OnKeyPress*/
function mascara_cep(pthis){
  v_tam = pthis.value;

  if (v_tam.length == 5){
    pthis.value += '-';
  }
}

function mascara_cartao(pthis){
  v_tam = pthis.value;

  if (v_tam.length == 4){
    pthis.value += ' ';
  }
  if (v_tam.length == 9){
    pthis.value += ' ';
  }
  if (v_tam.length == 14){
    pthis.value += ' ';
  }
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
 janela=window.open(theURL,winName,features);
}

/* Função para abrir uma url dentro de um popup de tamanho passado como parâmetro */
function popup (v_url,v_width,v_height, v_scroll) {
  w = open(v_url,"winLov","Scrollbars=1,resizable=1,menubar=1,width="+v_width+",height="+v_height);
  if (w.opener == null)
  w.opener = self;
  w.focus();
}

/* Função genérica para mensagem de confirmação */
function confirmar_msg(msg, req){
  if(req == null){
    req = 'Acao'
  }

  var conf = msg;

  if(conf == null){
    conf = confirm("Confirma a ação?");
  }else{
    conf = confirm(msg);}

  if (conf == true){
    doSubmit(req);
  }else{
    doSubmit('CANCELADO');
  }
}

/* Mensagens para o usuário */
htmldb_delete_message='Gostaria de executar esta ação de deleção?';
apex_nova_proposta='Deseja lançar nova proposta?';
bloqueia_cartao='Deseja realmente efetuar o bloqueio do cartão?';
cancela_cartao='Essa opera&ccedil;&atilde;o dever&aacute; cancelar definitivamente o cart&atilde;o, n&atilde;o<br>ser&aacute; permitido gerar 2ª Via e nem mesmo utilizar esse cart&atilde;o.<br>Deseja realmente efetuar o cancelamento?';
desbloqueia_cartao='Deseja realmente desbloquear o cartão?';
gera_2via_cartao='Confirma a geração de 2ª via?';
msg_usu_demitir='Esta operação será realizada para todos os produtos do Usuário que estão relacionados com a Empresa! Deseja continuar?';
msg_usu_demitir_confirmar='O usuário será demitido, todas as movimentações que possuem lançamentos futuros serão antecipadas, esta operação não poderá ser desfeita! Deseja continuar?';
msg_usu_readmitir_confirmar='O usuário será readmitido pelo sistema. Deseja continuar?';
msg_2via_cartao='Deseja realmente gerar outra via do cart&atilde;o?';
msg_pedido_venda_copiar='Ser&aacute; gerado novo pedido de venda baseado no pedido informado!<br>Deseja realmente realizar a opera&ccedil;&atilde;o?';
msg_processando_dados='Processando dados';
msg_enviar_senha_responsavel='Deseja realmente enviar a senha do respons&aacute;vel?';
msg_excluir='Deseja realmente efetuar a exclus&atilde;o?';
msg_gerando_relatorio='Gerando informa&ccedil;&otilde;es para o relat&oacute;rio...';
msg_aguarde_proc='Aguarde processamento...';
msg_confirma_operacao='Deseja realmente efetuar esta opera&ccedil;&atilde;o?';


icn_pergunta='P';
btn_simnao='SN';

tit_2via_cartao='Gerar Via de Cart&atilde;o';
tit_confirmar='Confirma&ccedil;&atilde;o';
tit_excluir='Exclus&atilde;o';


/* Função para o Help dos Itens */
function ajax_help(pThis,pId){
  this.dTimeout;
  clearTimeout(this.dTimeout);
  this.dGet = dGet;
  this.dShow = dShow;
  this.dCancel = dCancel;
  var get = new htmldb_Get(null,$x('pFlowId').value,'APPLICATION_PROCESS=AJAX_ITEM_HELP',0);
  this.dGet();
  return;

  function dGet(){
    this.dTimeout = setTimeout("this.dCancel()",60000);
    get.add('ITEM_HELP_NAME',pId);
    get.add('ITEM_HELP_PAGE',$x('pFlowStepId').value);
    get.GetAsync(dShow);
  }
  	
  function dShow(){
    $x_Hide('rollover');
    if(p.readyState == 1){
    }else if(p.readyState == 2){
    }else if(p.readyState == 3){
    }else if(p.readyState == 4){
      $x('rollover_content').innerHTML = p.responseText;
      $x_Show('rollover');
      htmldb_IE_Select_Item_Fix($x('rollover'));
      //para IE
      $x_Style('rollover','left',findPosX(pThis)+pThis.offsetWidth+5);
      $x_Style('rollover','top',findPosY(pThis));

      //para outros navegadores
      $('#rollover').css({'left': function(){ return findPosX(pThis)+pThis.offsetWidth+5} , 'top' : function(){return findPosY(pThis)}});


      document.onclick = function(e){
        dCheckClick(e);
      }
    }else{return false;}
  }
  
  function dCheckClick(e){
    var elem = html_GetTarget(e);
    try{
      var lTable = $x_UpTill(elem,"DIV");
      if(lTable.id!='rollover_content'){dCancel();}
      else{}
    }catch(err){dCancel();}
  }
  	
  function dCancel(){
    $x_Hide('rollover');
    document.onclick = null;
    get = null;
  }
}

/* Função de validar mascara generica #61762 */
/* Efetuada correção #69801 */
function validar_mascara(pthis,pitem){
  for (var i = 0; i < 8; i++)
  {
    if (document.getElementById(pitem+'_'+i).checked)
    {
      mascara(pthis,pitem+'_'+i);
    }
  }
}

/* Função usada para formatar CEI no evento OnKeyPress */
function mascara_cei(pthis){
  v_tam = pthis.value;
  if (v_tam.length ==  2){ pthis.value += '.'; }
  if (v_tam.length ==  6){ pthis.value += '.'; }
  if (v_tam.length == 12){ pthis.value += '/'; }
}

/* Função de validar mascara generica #61762 */
function mascara(pthis,pitem){
  if (document.getElementById(pitem).value == 'F')
  {
    pthis.maxLength=14;
    mascara_cpf(pthis);
  }
  else if (document.getElementById(pitem).value == 'J')
  {
    pthis.maxLength=18;
    mascara_cnpj(pthis);
  }
  else if (document.getElementById(pitem).value == 'E')
  {
    pthis.maxLength=15;
    mascara_cei(pthis);
  }
}


bp_aguarde='Aguarde...';

/* Função que retorna o nome abreviado, usada no evento onblur */
function abrevia_nome(pVal,pRet){
/*   var get = new htmldb_Get(null,html_GetElement('pFlowId').value,'APPLICATION_PROCESS=ABREVIAR_NOME',0);
  get.add('APP_NOME_ABREVIADO',pVal.value);
  gReturn = get.get(); 
  var str = gReturn;
 
  html_GetElement(pRet).value = str; 
*/
  doSubmit(pVal);
  html_GetElement(pRet).focus();
  return;
/*  str=null;
  pRet=null;
*/
}

/* Função que exibe a mensagem de aguardar e logo após exibe o nome abreviado */
function msg_aguarde_abreviar(pThis,pMsg,pTexto,pTempo,pIcone,pRet){
  var vIcone;
  var p;
  p = new XMLHttpRequest();
  if  (html_GetElement(pRet).value == '') 
  {
     if (pIcone == 'P') vIcone = Ext.MessageBox.QUESTION;
     if (pIcone == 'E') vIcone = Ext.MessageBox.ERROR;
     if (pIcone == 'I') vIcone = Ext.MessageBox.INFO;
     if (pIcone == 'A') vIcone = Ext.MessageBox.WARNING;
     if (pIcone == 'D') vIcone = 'ext-mb-download';
   
     Ext.MessageBox.show({
       msg: pMsg,
       progressText: pTexto,
       width:300,
       wait:true,
       waitConfig: {interval:200},
       icon: vIcone,
       animEl: pThis
     });
     /*  doSubmit(pThis);*/
     p=p;
     if(p.readyState == 0){
       setTimeout(function(){
         Ext.MessageBox.hide(abrevia_nome(pThis,pRet));
       }, pTempo);
     }
  }
  else
  {
    return;
  }
};

function ini_cons_cep(pend,pbairro,pcidade,puf){
  $x(pend).disabled="true";
  $x(pbairro).disabled="true";
  $x(pcidade).disabled="true";
  $x(puf).disabled="true";
}

function delay(pmillis) 
{
  var complete = new Date();   
  complete.setTime(complete.getTime() + pmillis);   
  while (new Date().getTime() < complete.getTime());   
} 

function consulta_cep(pThis,pcep,pend,pbairro,pcidade,puf,pend1,pbairro1,pcidade1,puf1,pdisable){
 if ($x(pcep).value == '') return;
  var v_codresp  = -1;
  var v_retorno = new Array(6);
  this.dTimeout;
  clearTimeout(this.dTimeout);
  this.dGet = dGet;
  this.dShow = dShow;
  this.dCancel = dCancel;
  var get = new htmldb_Get(null,$x('pFlowId').value,'APPLICATION_PROCESS=AJAX_CONSULTA_CEP_WS',0);
  this.dGet();
  return;

  function dGet(){
    this.dTimeout = setTimeout("this.dCancel()",60000);
    get.add('ITEM_CEP_VALOR',$x(pcep).value);
    $x_Show(pcep+'_PROG');
    get.GetAsync(dShow);
    if ($x(pdisable ).value == '') ini_cons_cep(pcep,pend,pbairro,pcidade,puf);
  }
  	
  function dShow(){
   try{
    if(p.readyState == 1){
    }else if(p.readyState == 2){
    }else if(p.readyState == 3){
    }else if(p.readyState == 4){    
     v_retorno = p.responseText.split('@');
     v_codresp = parseInt(v_retorno[4]);
     if (parseInt(v_codresp) == 0){
       $x_Hide(pcep+'_PROG');
       var v_aux = v_retorno[0];
       if (v_aux == ''){
         $x_disableItem(pend, false);
         html_GetElement(pend).focus();
       }else{
         $x(pend).value = v_aux;
         $x(pend).disabled="true";   
       }
       v_aux =  v_retorno[1];
       if (v_aux == ''){
         $x_disableItem(pbairro, false);
       }else{
         $x(pbairro).value = v_aux;
         $x(pbairro).disabled="true";
       }
       $x(pcidade).value = v_retorno[2];
       if ($x(pcidade).value == ''){
         $x_disableItem(pcidade, false);
       }else $x(pcidade).disabled="true";
       $x(puf).value     = v_retorno[3];       
       if ($x(puf).value == ''){
         $x_disableItem(puf, false);
        }else $x(puf).disabled="true";
       if ($x(pend).value == '') $x(pend).value = $x(pend1).value; else $x(pend1).value = $x(pend).value;
       if ($x(pbairro).value == '') $x(pbairro).value = $x(pbairro1).value; else $x(pbairro1).value = $x(pbairro).value;
       $x(pcidade1).value = $x(pcidade).value;
       $x(puf1).value     = $x(puf).value;
    }else{ 
       $x_Hide(pcep+'_PROG');
       $x_disableItem(pend, false); 
       html_GetElement(pend).focus();
       $x_disableItem(pbairro, false);

       $x_disableItem(pcidade, false);
       $x_disableItem(puf, false);
       $x('rollover_content').innerHTML = v_retorno[5];
       $x_Show('rollover');
       htmldb_IE_Select_Item_Fix($x('rollover'));
       $x_Style('rollover','left',findPosX(pThis)+pThis.offsetWidth+5);
       $x_Style('rollover','top',findPosY(pThis));
       document.onclick = function(e,v_codresp){
         dCheckClick(e);}
     }
    }else{
      $x_Hide(pcep+'_PROG');
      return false;
    }
    }catch(e){
      $x_Hide(pcep+'_PROG');
      return false;
    }
  }
  function dCheckClick(e){
    var elem = html_GetTarget(e);
    try{
      var lTable = $x_UpTill(elem,"DIV");
      if(lTable.id!='rollover_content'){dCancel();}
      else{}
    }catch(err){dCancel();}
  }
  function dCancel(){
    html_GetElement(pend).focus();
    $x_Hide('rollover');
    document.onclick = null;
    get = null;
  }
}

/*------------------------------------------------------------------------------------------
--  Function : popula_combo_xml
--  Descrição: Função para popular combos dinamicamente (XML)
--  Entrada  : pThis    - Combo Selecionado
--             pSelect  - Combo de Destino
--             pProcess - Processo sob demanda com PL/SQL de retorno
--  Histórico:
--  01/02/2010 - Fabio - #78848 - Implementação
------------------------------------------------------------------------------------------
-- Utilização no APEX > Atributo do Elemento do Form -> onchange="popula_combo_xml(this,combo_destino,processo_on_demand,pagina);"
------------------------------------------------------------------------------------------*/
function popula_combo_xml(pThis,pSelect,pProcess,pPagina){
  var l_Select = html_GetElement(pSelect);
  //função do APEX para requisições AJAX
  var get = new htmldb_Get(null,html_GetElement('pFlowId').value,'APPLICATION_PROCESS='+pProcess,pPagina);
  get.add('AJAX_ITEM',pThis.value);

  gReturn = get.GetAsync(Retorno);

  function Retorno(){
    if(p.readyState == 1){
      l_Select.length = 0;
      $(l_Select).after('<img id="carregando" src=/i/themes/fwcard_portal/images/loading4.gif width="16px" height="16px" style="position:absolute;">');
    }
    else if(p.readyState == 2){}
    else if(p.readyState == 3){}
    else if(p.readyState == 4){
      $('#carregando').remove();
      var l_Count = p.responseXML.getElementsByTagName("option").length;
      for(var i=0;i<l_Count;i++){
          var l_Opt_Xml = p.responseXML.getElementsByTagName("option")[i];
          if(i == 0){
            l_Opt_Xml.firstChild.nodeValue = l_Opt_Xml.firstChild.nodeValue.replace('-','');
          }
          appendToSelect(l_Select, l_Opt_Xml.getAttribute('value'), l_Opt_Xml.firstChild.nodeValue);
      }
    }
    else{
      return false;
    }
  }

  //função que monta o combo box
  function appendToSelect(pSelect, pValue, pContent) {
    var l_Opt = document.createElement("option");
    l_Opt.value = pValue;

    if(document.all){
      pSelect.options.add(l_Opt);
      l_Opt.innerText = pContent;
    }
    else{
      l_Opt.appendChild(document.createTextNode(pContent));
      pSelect.appendChild(l_Opt);
    }
  }
  get = null;
}

/* Novas Funções para Caixa de Mensagem */
function msg_confirmar_aguarde(pThis,pTitulo,pMsg,pBotao,pIcone,pNao,pMsgAg,pTexto,pTempo){
  var vBotao,vIcone;
  if (pBotao == 'SNC') vBotao = Ext.MessageBox.YESNOCANCEL;
  if (pBotao == 'SN') vBotao = Ext.MessageBox.YESNO;
  if (pBotao == 'O') vBotao = Ext.MessageBox.OK;
  if (pBotao == 'OC') vBotao = Ext.MessageBox.OKCANCEL;
  if (vBotao == null)  vBotao = Ext.MessageBox.YESNOCANCEL;

  if (pIcone == 'P') vIcone = Ext.MessageBox.QUESTION;
  if (pIcone == 'E') vIcone = Ext.MessageBox.ERROR;
  if (pIcone == 'I') vIcone = Ext.MessageBox.INFO;
  if (pIcone == 'A') vIcone = Ext.MessageBox.WARNING;
  if (pIcone == 'D') vIcone = 'ext-mb-download';

  Ext.onReady(function(){
    Ext.MessageBox.show({
      title:pTitulo,
      msg: pMsg,
      buttons: vBotao,
      fn: Retorno,
      animEl: pThis,
      icon: vIcone
    });

    function Retorno(btn){
      if ((btn == 'ok' || btn == 'yes') && pBotao != 'O' ){
        msg_aguarde(pThis,pMsgAg,pTexto,pTempo,vIcone)
      } else { 
        if (pNao != null) doSubmit(pNao);
      }
    };

  });
};

function msg_aguarde(pThis,pMsg,pTexto,pTempo,pIcone){
  var vIcone;
  if (pIcone == 'P') vIcone = Ext.MessageBox.QUESTION;
  if (pIcone == 'E') vIcone = Ext.MessageBox.ERROR;
  if (pIcone == 'I') vIcone = Ext.MessageBox.INFO;
  if (pIcone == 'A') vIcone = Ext.MessageBox.WARNING;
  if (pIcone == 'D') vIcone = 'ext-mb-download';

  Ext.MessageBox.show({
     msg: pMsg,
     progressText: pTexto,
     width:300,
     wait:true,
     waitConfig: {interval:200},
     icon: vIcone,
     animEl: pThis
  });
  doSubmit(pThis);
  setTimeout(function(){
      Ext.MessageBox.hide();
  }, pTempo);
};

function msg_confirmar(pThis,pTitulo,pMsg,pBotao,pIcone,pNao){
  var vBotao,vIcone;
  if (pBotao == 'SNC') vBotao = Ext.MessageBox.YESNOCANCEL;
  if (pBotao == 'SN') vBotao = Ext.MessageBox.YESNO;
  if (pBotao == 'O') vBotao = Ext.MessageBox.OK;
  if (pBotao == 'OC') vBotao = Ext.MessageBox.OKCANCEL;
  if (vBotao == null)  vBotao = Ext.MessageBox.YESNOCANCEL;

  if (pIcone == 'P') vIcone = Ext.MessageBox.QUESTION;
  if (pIcone == 'E') vIcone = Ext.MessageBox.ERROR;
  if (pIcone == 'I') vIcone = Ext.MessageBox.INFO;
  if (pIcone == 'A') vIcone = Ext.MessageBox.WARNING;
  if (pIcone == 'D') vIcone = 'ext-mb-download';

  Ext.onReady(function(){
    Ext.MessageBox.show({
      title:pTitulo,
      msg: pMsg,
      buttons: vBotao,
      fn: Retorno,
      animEl: pThis,
      icon: vIcone
    });

    function Retorno(btn){
      if ((btn == 'ok' || btn == 'yes') && pBotao != 'O' ){
        doSubmit(pThis);
      } else { 
        if (pNao != null) doSubmit(pNao);
      }
    };

  });
};

/* Função que mascara os números: */
/*  fld: Objeto field do formulário */
/*  milSep: separador de milhar */
/*  decSep: separador de decimal */
/*  e: evento (usado normalmente -> event) */
/* onkeypress="return FormataValor(this,'', ',', event);"*/
function FormataValor(fld, milSep, decSep, e) {
  var sep = 0;
  var key = '';
  var i = j = 0;
  var len = len2 = 0;
  var strCheck = '0123456789';
  var aux = aux2 = '';
  
  var whichCode;
  if (window.event) whichCode = window.event.keyCode;
  else if (e) whichCode = e.which;
  //var whichCode = (window.Event) ? e.which : e.keyCode;

  if (whichCode == 13 || whichCode == 8 || whichCode == 0 )
    return true;  /* Enter */
  key = String.fromCharCode(whichCode);  /* Get key value from key code */
  if (strCheck.indexOf(key) == -1) 
    return false;  /* Not a valid key */
  len = fld.value.length;
  for(i = 0; i < len; i++)
    if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) 
      break;
  aux = '';
  for(; i < len; i++)
    if (strCheck.indexOf(fld.value.charAt(i))!=-1)
      aux += fld.value.charAt(i);
  aux += key;
  len = aux.length;
  if (len == 0) fld.value = '';
  if (len == 1) fld.value = '0'+ decSep + '0' + aux;
  if (len == 2) fld.value = '0'+ decSep + aux;
  if (len > 2) {
    aux2 = '';
    for (j = 0, i = len - 3; i >= 0; i--) {
      if (j == 3) {
        aux2 += milSep;
        j = 0;
      }
      aux2 += aux.charAt(i);
      j++;
    }
    fld.value = '';
    len2 = aux2.length;
    for (i = len2 - 1; i >= 0; i--)
      fld.value += aux2.charAt(i);
    fld.value += decSep + aux.substr(len - 2, len);
  }
  return false;
}


/*
** get_values_ajax - função que carrega valores via Ajax
**
** Parâmetros
**    key_value - chave de pesquisa.
**    nome_processo - nome do processo responsável pela pesquisa.
**
** Análista
**    Bruno.Silva - Implementação 09/06/2010
*/
function get_select_lists_ajax(key_value,nome_processo)
{
	var get = new htmldb_Get(null,html_GetElement('pFlowId').value,'APPLICATION_PROCESS=' + nome_processo,0);
	get.add('P0_ID_AJAX',key_value);
	gReturn = get.get("XML");
	
	if(gReturn)
	{
		 var cont = gReturn.getElementsByTagName('item').length;
         
		 limpa_select(gReturn,cont);
		 
		 for(var i = 0; i < cont; i ++)
		 {
			 var elemento_xml = gReturn.getElementsByTagName('item')[i];
			 var e_1 = elemento_xml.getAttribute('id');
			 var elemento_pagina = html_GetElement(e_1);
			 
			 if(elemento_pagina.tagName == 'SELECT')
			 { 
				 var elemento_option = document.createElement('option');
				 elemento_option.value = elemento_xml.getAttribute('value');
				 elemento_option.innerHTML = replace_ajax(elemento_xml.firstChild.nodeValue);
				 elemento_pagina.appendChild(elemento_option);
			 }
			 else if(elemento_pagina.tagName == 'INPUT')
			 {
				 elemento_pagina.value = elemento_xml.firstChild.nodeValue;
			 }
		 }
	}
}

function limpa_select(xmlDocument, numElements)
{
	var count;
	
	for(var i = 0; i < numElements; i++)
	{
		var elemento_xml = xmlDocument.getElementsByTagName('item')[i];
		var e_1 = elemento_xml.getAttribute('id');
		var elemento_pagina = html_GetElement(e_1);
		
		if(elemento_pagina.tagName == 'SELECT')
		{
		    elemento_pagina.length = 0;	
		}
	}
}




/******************************************************************************************
* Funçao:  show_hide_item
*
* Descrição:
*   Função que monta o combobox, ou textbox que sera exibido, dinamicamente a partir de outro,
*   e exibe/esconde se necessario.
*
* Entrada:
*  campo_id_combo: ID que será buscado, ou seja value que será do combobox.
*  campo_descricao_combo: Descriçao que será buscada, ou seja o que será exibido no combo para o usuario
*  tabela: Tabela a qual se deseja fazer a busca.
*  campo_busca: Campo que será feito o filtro.
*  valor_busca: Valor que será passado para o filtro.
*  campo_exibir: Nome do Campo que será mostrado/escondido conforme achar os dados(PX_0000)
*  esconde: Opçao que se S, esta ativo o esconder/exibir campo, se N, esta desativado e sempre sera exibido
*  nome_processo: Nome do processo que sera utilizado.
*
* Histórico:
*   17/08/2010 - Thamires - Implementação
*
********************************************************************************************/


function show_hide_item(campo_id_combo, campo_descricao_combo, tabela, campo_busca, valor_busca, campo_exibir, esconde , nome_processo)
{
	var get = new htmldb_Get(null,html_GetElement('pFlowId').value,'APPLICATION_PROCESS=' + nome_processo,0);

        //Concatena a string que sera quebrada pela função para montar o sql dinamico
        var v_string = campo_id_combo +";"+ campo_descricao_combo +";"+ tabela +";"+ campo_busca +";"+ valor_busca +";"+ campo_exibir;

        //Seta o item na Pagina Zero
        get.add('P0_ID_AJAX', v_string);

 	gReturn = get.get("XML");

	var campo = document.getElementById(campo_exibir);

	if(gReturn)
	{

              var cont = gReturn.getElementsByTagName('item').length;
      
      	      campo.length = 0;

      	      if(cont > 1)
      	      {
                //Mostra ou esconde apenas se setado como S a opcao esconde
                if (esconde == 'S' )
                {
      		   campo.parentNode.parentNode.style.display = 'block';
      		   campo.parentNode.parentNode.removeAttribute('style');
                }

                for(var i = 0; i < cont; i++)
      		{
      			var elemento_xml = gReturn.getElementsByTagName('item')[i];
      			var e_1 = elemento_xml.getAttribute('id');
      			var elemento_pagina = html_GetElement(e_1);

      			if(elemento_pagina.tagName == 'SELECT')
			 { 
				 var elemento_option = document.createElement('option');
				 elemento_option.value = elemento_xml.getAttribute('value');
				 elemento_option.innerHTML = replace_ajax(elemento_xml.firstChild.nodeValue);
				 elemento_pagina.appendChild(elemento_option);
			 }
			 else if(elemento_pagina.tagName == 'INPUT')
			 {
                               if(i == 1)
                                  elemento_pagina.value = replace_ajax(elemento_xml.firstChild.nodeValue);
			 }
      		}

      	     }
      	     else
             {
                  //Mostra ou esconde apenas se setado como S a opcao esconde
                if (esconde == 'S' )
                {
		     campo.parentNode.parentNode.style.display = 'none';
                 }
             }
       }
       else
       {
         //Mostra ou esconde apenas se setado como S a opcao esconde
         if (esconde == 'S' )
         {
             campo.parentNode.parentNode.style.display = 'none';
         }    
       }

}

/*
** Função genérica que faz a validação de strings retornados pelo XmlHttpRequest
**
** Análista
**    Thamires Luz - Copiado do card dia 17/08/2010
*/
function replace_ajax(p_str)
{
	var array1 = new Array(43);
	var array2 = new Array(43);
	
	// carrega dados de origem em array1
	array1[0] = '#A-agudo#';
	array1[1] = '#C-cedilha#';
	array1[2] = '#E-agudo#';
	array1[3] = '#I-agudo#';
	array1[4] = '#O-agudo#';
	array1[5] = '#U-agudo#';
	array1[6] = '#i-agudo#';
	array1[7] = '#c-cedilha#';
	array1[8] = '#A-crase#';
	array1[9] = '#E-crase#';
	array1[10] = '#I-crase#';
	array1[11] = '#O-crase#';
	array1[12] = '#U-crase#';
	array1[13] = '#A-chapeu#';
	array1[14] = '#E-chapeu#';
	array1[15] = '#I-chapeu#';
	array1[16] = '#O-chapeu#';
	array1[17] = '#U-chapeu#';
	array1[18] = '#A-tio#';
	array1[19] = '#O-tio#';
	array1[20] = '#E-pontos#';
	array1[21] = '#U-pontos#';
	array1[22] = '#a-agudo#';
	array1[23] = '#e-agudo#';
	array1[24] = '#i-agudo#';
	array1[25] = '#o-agudo#';
	array1[26] = '#u-agudo#';
	array1[27] = '#a-crase#';
	array1[28] = '#e-crase#';
	array1[29] = '#i-crase#';
	array1[30] = '#o-crase#';
	array1[31] = '#u-crase#';
	array1[32] = '#a-chapeu#';
	array1[33] = '#e-chapeu#';
	array1[34] = '#i-chapeu#';
	array1[35] = '#o-chapeu#';
	array1[36] = '#u-chapeu#';
	array1[37] = '#a-tio#';
	array1[38] = '#o-tio#';
	array1[39] = '#u-pontos#';
	array1[40] = '#e-comercial#';
	array1[41] = '#acento-agudo#';
	array1[42] = '->';
	
	// carrega dados de substituição em array2;
	array2[0] = 'Á';
	array2[1] = 'Ç';
	array2[2] = 'É';
	array2[3] = 'Í';
	array2[4] = 'Ó';
	array2[5] = 'Ú';
	array2[6] = 'í';
	array2[7] = 'ç';
	array2[8] = 'À';
	array2[9] = 'È';
	array2[10] = 'Ì';
	array2[11] = 'Ò';
	array2[12] = 'Ù';
	array2[13] = 'Â';
	array2[14] = 'Ê';
	array2[15] = 'Î';
	array2[16] = 'Ô';
	array2[17] = 'Û';
	array2[18] = 'Ã';
	array2[19] = 'Õ';
	array2[20] = 'Ë';
	array2[21] = 'Ü';
	array2[22] = 'á';
	array2[23] = 'é';
	array2[24] = 'í';
	array2[25] = 'ó';
	array2[26] = 'ú';
	array2[27] = 'à';
	array2[28] = 'è';
	array2[29] = 'ì';
	array2[30] = 'ò';
	array2[31] = 'ù';
	array2[32] = 'â';
	array2[33] = 'ê';
	array2[34] = 'î';
	array2[35] = 'ô';
	array2[36] = 'û';
	array2[37] = 'ã';
	array2[38] = 'õ';
	array2[39] = 'ü';
	array2[40] = '&';
	array2[41] = '´';
	array2[42] = '';
	
	for(var i = 0; i < 43; i++)
	{
		p_str = p_str.replace(array1[i],array2[i]);
	}
	
	return p_str;
}
function resize() {
  var w_newWidth = 0;
  var w_newHeight = 0;
  var w_maxWidth=930;
  var w_maxHeight=screen.height;

  if( typeof( window.innerWidth ) == 'number' ) {
    /* Non-IE */
    w_newWidth = window.innerWidth-10;
    w_newHeight = window.innerHeight-10;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    /* IE 6+ in standards compliant mode */
    w_newWidth = document.documentElement.clientWidth-10;
    w_newHeight = document.documentElement.clientHeight-10;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    /* IE 4 compatible */
    w_newWidth = document.body.clientWidth-10;
    w_newHeight = document.body.clientHeight-10;
  }

  if (w_newWidth>w_maxWidth)
    w_newWidth=w_maxWidth;
  if (w_newHeight>w_maxHeight)
    w_newHeight=w_maxHeight;

  if( document.getElementById("Corpo") ) {
    document.getElementById("Corpo").style.width = w_newWidth-10;
  }
  window.scroll(0,0);
}

function atalhoTecla(e, pSubmeterProx, pSubmeterAnt){
    var e=(e)?e:window.event;
    var vTecla = (e.keyCode)?e.keyCode:e.which;
    if (e.altKey){
        if (vTecla == 79){//Tecla O
            doSubmit(pSubmeterProx);
        }else if (vTecla == 78){//Tecla N
            doSubmit(pSubmeterAnt);
        }
    }
}

/*------------------------------------------------------------------------------------------
--  Function : abreviaN
--  Descrição: Função que abrevia o nome e mostra  a imagem de carregando
--  Entrada  : pNome: nome do item da aplicação que sera abreviado ex: PX_NOME
--             pNomeAbreviado: nome do item da aplicação que sera retornado ex: PX_NOME_ABREVIADO
-- Importante: colocar apos o elemento pNome atalho "PROGRESSO_1" onde ficara a imagem de carregando
-- Ex de pagina> 1551
--  Histórico:
--  27/12/2010 - Thamires - 89567 - Implementação
------------------------------------------------------------------------------------------*/
function abreviaN(pNome, pNomeAbreviado)
{
  var obj_nome_abre = html_GetElement(pNomeAbreviado);
  var obj_nome      = html_GetElement(pNome);

  if(obj_nome.value != "" && obj_nome_abre.value == "")
  {
    $('#'+pNome+'_PROG').show();
    var get = new htmldb_Get(null,html_GetElement('pFlowId').value,'APPLICATION_PROCESS=ABREVIAR_NOME',0);
    get.add('APP_NOME_ABREVIADO', obj_nome.value);
    gReturn = get.get();
    obj_nome_abre.value = gReturn;

    gReturn = get.GetAsync(Retorno);
  }
  function Retorno()
  {
        if(p.readyState == 1){}
        else if(p.readyState == 2){}
        else if(p.readyState == 3){}
        else if(p.readyState == 4){
             $('#'+pNome+'_PROG').hide();

        }
        else{
            $('#'+pNome+'_PROG').hide();
            return false;
        }
  }

}


