   //-- Nome.....: Funcoes.js
   //-- Autor....: ?
   //-- Data.....: ?
   //-- Descrição: Possui javascripts usado por grande parte da intranet.
   //--
   //--[ Modificações ]-----------------------------------------------
   //-- 09/11/2007[Eduardo].: Chamado :: 40207
   //-- 22/11/2007[Eduardo].: Chamado :: 21406
   //-- ==============================================================
/*============ VARIAVEIS GLOBAIS NÃO MEXER ======*/
   var netscape = (navigator.vendor == 'Netscape');
   var mozilla = (navigator.product == 'Gecko');//FireFox
   var ie7 = (parseFloat(navigator.appVersion.split("MSIE")[1]) >= 7);
/*================================================================*/
function maxlength(obj, pMax, e)
{
   var max = (pMax != undefined) ? pMax : 500;
   if(obj.value.length > max-1)
   {
      e     = (netscape || mozilla) ? e       : event;
      tecla = (netscape)            ? e.which : e.keyCode;
      
      if(netscape || mozilla)
      {
         var teclas_ex = ((tecla == 8) || (tecla == 13) || (tecla == 0));  // 0 =>'ESC-DEL'
         return (!teclas_ex) ? e.cancelBubble=true : e.cancelBubble=false;
      }
      else
      {
         var teclas_ex = ((tecla == 8) || (tecla == 46) || ((tecla > 36) && (tecla < 41)));
         return (!teclas_ex) ? e.returnValue=false : e.returnValue=true;
      }
   }
}

function limita_texto(obj, tam)
{
   var texto = obj.value;
   if (obj.value.length > tam){
      obj.value = texto.substr( 0, tam );
      alert('Texto só pode conter '+tam+' posições!');
   }
}

//Eduardo
function put_option_on_select(p_obj_sel, p_opt_text, p_opt_value, p_idx)
{
   p_idx = p_idx ? p_idx : 0;
   var v_qtd_opt = p_obj_sel.options.length;
   while(v_qtd_opt-1 >= p_idx)
   {
      v_qtd_opt--;
      v_opt_text = p_obj_sel.options[v_qtd_opt].text;
      v_opt_value = p_obj_sel.options[v_qtd_opt].value;
      p_obj_sel.options[v_qtd_opt+1] = new Option(v_opt_text, v_opt_value);   
   }
   p_obj_sel.options[v_qtd_opt] = new Option(p_opt_text, p_opt_value);
}

function remove_option_on_select(p_obj, p_all)
{
   p_all = p_all ? true : false;
   for(i = p_obj.length-1; i >= 0; i--)
   {
      if(p_obj.options[i].selected || p_all)
      {
        p_obj.options[i] = null;
      }
   }
}

function format_telefone(p_obj)
{
   if(p_obj.value)
      p_obj.value = p_obj.value.substr(0, p_obj.value.length-4)+'-'+p_obj.value.substr(p_obj.value.length-4);
}

function OpenImagemColeta(pIdCol, pIdUsuario)
{
   if(!document.getElementById("ifrReimpCon"))
   {
      var Iframe = document.createElement("iframe");
      Iframe.id = "ifrReimpCon";      
      Iframe.name = "ifrReimpCon";
      Iframe.width = 0;
      Iframe.height = 0;
      document.body.appendChild(Iframe); 
   }
   document.getElementById("ifrReimpCon").src = '../../libext/reimprime_documento.php?id_con='+pIdCol+'&id_usuario='+pIdUsuario+'&acao=Coleta';
   if(document.getElementById('div_conhecimento'))
      imp_html_div('Reimprimindo coleta...', 'div_conhecimento');
}

function OpenImagemCtrc(pIdCon, pIdUsuario)
{
   if(!document.getElementById("ifrReimpCon"))
   {
      var Iframe = document.createElement("iframe");
      Iframe.id = "ifrReimpCon";      
      Iframe.name = "ifrReimpCon";
      Iframe.width = 0;
      Iframe.height = 0;
      document.body.appendChild(Iframe); 
   }
   document.getElementById("ifrReimpCon").src = '../../libext/reimprime_conhec.php?id_con='+pIdCon+'&id_usuario='+pIdUsuario+'&acao=Conhecimento';
   if(document.getElementById('div_conhecimento'))
      imp_html_div('Reimprimindo conhecimento...', 'div_conhecimento');
}

function OpenImagemDuplicata(pNumeroFat,pIdEmpresa, pIdUsuario)
{
   if(!document.getElementById("ifrReimpDup"))
   {
      var Iframe = document.createElement("iframe");
      Iframe.id = "ifrReimpDup";      
      Iframe.name = "ifrReimpDup";
      Iframe.width = 0;
      Iframe.height = 0;
      document.body.appendChild(Iframe); 
   }
   document.getElementById("ifrReimpDup").src = '../../libext/reimprime_duplicata.php?numero_fatura='+pNumeroFat+'&id_empresa='+pIdEmpresa+'&id_usuario='+pIdUsuario;
   if(document.getElementById('div_duplicata'))
      imp_html_div('Reimprimindo duplicata...', 'div_duplicata');	  
}

function DownloadXmlCTe(p_id_conhecimento){
   if(!document.getElementById("ifrDownloadXmlCTe"))
   {
      var Iframe = document.createElement("iframe");
      Iframe.id = "ifrDownloadXmlCTe";      
      Iframe.name = "ifrDownloadXmlCTe";
      Iframe.width = 0;
      Iframe.height = 0;
      document.body.appendChild(Iframe); 
   }
   document.getElementById("ifrDownloadXmlCTe").src = '../../libext/downloadCTe.php?id_conhecimento='+p_id_conhecimento;
}
//
//
//
function addEvent(obj, evType, fn)
{
   if(obj.addEventListener)
   {
      obj.addEventListener(evType, fn, false);
      return true;
   }
   else if(obj.attachEvent)
   {
      var r = obj.attachEvent("on"+evType, fn);
      return r; 
   }
   return false;
}

function getFormByElement(pElement, pE)//pE Evento do Netscape.
{
   if(!mozilla && event && (event.srcElement != null))
      return (event.srcElement.form != null) ? event.srcElement.form : document.forms[0];
   for(var i=0; i< document.forms.length; i++)
   {
      if(document.forms[i].elements[pElement]) {
         return document.forms[i];
      }
   }
   return document.forms[0];
}

// Browser Window Size and Position
// copyright Stephen Chapman, 3rd Jan 2005, 8th Dec 2005
// you may copy these functions but please keep the copyright notice as well
function pageWidth()
{
   return window.innerWidth != null? window.innerWidth : document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;
}

function pageHeight()
{
   return  window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;
}

function posLeft()
{
   return typeof window.pageXOffset != 'undefined' ? window.pageXOffset :document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0;
}

function posTop()
{
   return typeof window.pageYOffset != 'undefined' ?  window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0;
}

function posRight()
{
   return posLeft()+pageWidth();
}

function posBottom()
{
   return posTop()+pageHeight();
}

//=====================================================================
var ugly_selectorText_workaround_flag = false;
var allStyleRules;

function ugly_selectorText_workaround()
{
   if((navigator.userAgent.indexOf("Gecko") == -1) || (ugly_selectorText_workaround_flag))
      return;

   var styleElements = document.getElementsByTagName("style");
   for(var i = 0; i < styleElements.length; i++)
   {
      var styleText = styleElements[i].firstChild.data;
      allStyleRules = styleText.match(/\b[\w-.]+(\s*\{)/g);
   }

   for(var i = 0; i < allStyleRules.length; i++)
      allStyleRules[i] = allStyleRules[i].substr(0, (allStyleRules[i].length - 2));

   ugly_selectorText_workaround_flag = true;
}

//  g - boolean 0: modify global only; 1: modify all elements in document
function setStyleByTag(pElement, pProperty, pValue, g)
{
	if(g)
   {
		var elements = document.getElementsByTagName(pElement);
		for(var i = 0; i < elements.length; i++)
			elements.item(i).style[pProperty] = pValue;
	}
   else
   {
		var sheets = document.styleSheets;
		if(sheets.length > 0)
      {
			for(var i = 0; i < sheets.length; i++)
         {
				var rules = sheets[i].cssRules;
				if(rules.length > 0)
            {
					for(var j = 0; j < rules.length; j++)
               {
						var s = rules[j].style;
						ugly_selectorText_workaround();
						if(allStyleRules)
                  {
							if(allStyleRules[j] == pElement)
								s[pProperty] = pValue;
						}
                  else
                  {
							if(((s[pProperty] != "") && (s[pProperty] != null)) && (rules[j].selectorText == pElement))
								s[pProperty] = pValue;
						}
					}
				}
			}
		}
	}
}

function getStyleByTag(pElement, pProperty)
{
	var sheets = document.styleSheets;
	if(sheets.length > 0)
   {
		for(var i = 0; i < sheets.length; i++)
      {
			var rules = sheets[i].cssRules;
			if(rules.length > 0)
         {
				for(var j = 0; j < rules.length; j++)
            {
					var s = rules[j].style;
					ugly_selectorText_workaround();
					if(allStyleRules)
               {
						if(allStyleRules[j] == pElement)
							return s[pProperty];
					}
               else
               {
						if(((s[pProperty] != "") && (s[pProperty] != null)) && (rules[j].selectorText == pElement))
							return s[pProperty];
					}
				}
			}
		}
	}

	var elements = document.getElementsByTagName(pElement);
	var sawClassOrStyleAttribute = false;
	for(var i = 0; i < elements.length; i++)
   {
		var node = elements.item(i);
		for(var j = 0; j < node.attributes.length; j++)
      {
			if((node.attributes.item(j).nodeName == 'class') || (node.attributes.item(j).nodeName == 'style'))
			   sawClassOrStyleAttribute = true;
		}
		if(! sawClassOrStyleAttribute)
			return elements.item(i).style[pProperty];
	}
}

function setStyleById(pID, pPropertie, pValue)
{
   document.getElementById(pID).style[pPropertie] = pValue;
}

function getStyleById(pID, pPropertie)
{
   var n = document.getElementById(pID);
   var s = eval("n.style."+pPropertie);

   // try inline
   if((s != "") && (s != null))
      return s;

   // try currentStyle
   if(n.currentStyle)
   {
      var s = eval("n.currentStyle." + pPropertie);
      if((s != "") && (s != null))
         return s;
   }

   // try styleSheets
   var sheets = document.styleSheets;
   if(sheets.length > 0)
   {
      // loop over each sheet
      for(var x = 0; x < sheets.length; x++)
      {
         // grab stylesheet rules
         var rules = sheets[x].cssRules;
         if(rules)
         {
            if(rules.length > 0)
            {
               // check each rule
               for(var y = 0; y < rules.length; y++)
               {
                  var z = rules[y].style;
                  ugly_selectorText_workaround();
                  if(allStyleRules)
                  {
                     if(allStyleRules[y] == i)
                        return z[pPropertie];
                  }
                  else
                  {
                     // use the native selectorText and style stuff
                     if(((z[pPropertie] != "") && (z[pPropertie] != null)) || (rules[y].selectorText == i))
                        return z[pPropertie];
                  }
               }
            }
         }
      }
   }
   return null;
}

//Eduardo 08-05-07 Retirado do prototype.
Object.extend = function(destination, source)
{
  for(var property in source)
  {
    destination[property] = source[property];
  }
  return destination;
}

//<Chamada para popups internos>
function AbreJanelaInterna(pObj, e) //Sempre deixar o "e" no final dos parametros.
{
   //Cancela redirecionamento do href(evitar usar href no link usar href="#").
   if(mozilla)
   {
      if(e)
      {
         e.preventDefault();
         e.stopPropagation()
      }
   }
   else if(netscape)
      e.cancelBubble = true;
   else if(event)
      event.returnValue = false;
   
   vObj = Object.extend({title:      null
                        ,url:        null
                        ,width:      200
                        ,height:     200
                        ,position:   'default'
                        ,modal:      true
                        ,className:  'intranet_ta'
                        ,escToClose: false
                        ,posScreenX: null
                        ,posScreenY: null
                        }, pObj || {});

   var maxWidthScreen = pageWidth();
   var maxHeightScreen = pageHeight();

   var vWidth = (vObj.width > maxWidthScreen) ? maxWidthScreen : vObj.width;
   var vHeight = (vObj.height > maxHeightScreen) ? maxHeightScreen : vObj.height;
   var vClassName = vObj.className;
   var vX = vObj.posScreenX ? vObj.posScreenX : null;
   var vY = vObj.posScreenY ? vObj.posScreenY : null;

   var win = new Window({className: vClassName, width:vWidth, height:vHeight});
/*   win.overlayShowEffectOptions = 3;
   win.overlayHideEffectOptions = 3;
showEffect Effect.Appear or
Element.show Show effect function. The default value depends if effect.js of script.aculo.us is included  
hideEffect Effect.Fade or
Element.hide Hide effect function. The default value depends if effect.js of script.aculo.us is included  
showEffectOptions none Show effect options (see script.aculo.us documentation). 
hideEffectOptions none Hid effect options (see script.aculo.us documentation). 
effectOptions none Show and hide effect options (see script.aculo.us documentation). 
*/
   win.setURL(vObj.url);
   if(vX != null || vY != null)
      win.showCenter(vObj.modal, vY, vX); //TRUE = Show Modal.
   else
      win.showCenter(vObj.modal);
   return win;
//      WindowCloseKey.init(); //Fecha janela teclando esc. Problemas com a função esc enter....
}

/*
//<Chamada para alertas internos>
function AlertInterna(pText, pWidth, pHeight)
{
   var vOkLabel = (pOkLabel != undefined) ? pOkLabel : "Ok";

                        
   var vWidth = vObj.width;
   var vHeight = vObj.height;
   var vClassName = vObj.className;
   var vX = vObj.posScreenX ? vObj.posScreenX : 150;
   var vY = vObj.posScreenY ? vObj.posScreenY : 150;

   Dialog.alert(pText, {windowParameters: {className:vClassName, width:vWidth, height:vHeight}
                                   ,okLabel: "Ok"
                                   ,ok:function(win)
                                    {
                                       debug("validate alert panel");
                                       return true;
                                    }
                                   ,cancel:function(win)
                                    {
                                       debug("validate cancel panel");
                                       return true;
                                    }
                }
                );
}
*/

//-- ----------------------------------------------------------------------------------------------------
// Novo (29/07/05) Rafael: Funções que Validada CGC CPF.
// Chamada: valid_cgc_cpf(this)
//-- ----------------------------------------------------------------------------------------------------
if (!PHPSESSID)
{
   var PHPSESSID = '';
}

//Eduardo 31-03-08
function is_cpf_cnpj(p_val)
{
   var re_cpf = /(\d{3}).?(\d{3}).?(\d{3})-?(\d{2})$/;
   var re_cnpj = /(\d{2}).?(\d{3}).?(\d{3})\/?(\d{4})-?(\d{2})$/;
   if(re_cnpj.test(p_val))
      return 'CNPJ';
   else if(re_cpf.test(p_val))
      return 'CPF';
   else
      return '';
}

function TestDigit(p_value,p_type,g)
{
   var dig=0;
   var ind=2;
   for(f=g;f>0;f--)
   {
      dig+=parseInt(p_value.charAt(f-1))*ind;
      if (p_type=='CNPJ')
      {
         if(ind>8)
            ind=2
         else
            ind++
      }
      else
         ind++
   }
   dig%=11;
   if(dig<2)
      dig=0;
   else
       dig=11-dig;

   if(dig!=parseInt(p_value.charAt(g)))
      return(false);
   else
      return(true);
}

function ParseNumb(p_value)
{
   if((parseFloat(p_value) / p_value != 1))
   {
      if(parseFloat(p_value) * p_value == 0)
         return(p_value);
      else
         return(0);
   }
   else
      return(p_value);
}

function Verify(p_value,p_type)
{
   p_value=ParseNumb(p_value)
   if(p_value == 0)
      return(false);
   else
   {
      g=p_value.length-2;
      if(TestDigit(p_value,p_type,g))
      {
         g=p_value.length-1;
         if(TestDigit(p_value,p_type,g))
            return(true);
         else
            return(false);
      }
      else
         return(false);
   }
}

function format_cgc_cpf(p_value)
{
   v_value = p_value;
   v_value=replace(v_value,'-','');
   v_value=replace(v_value,'/','');
   v_value=replace(v_value,',','');
   v_value=replace(v_value,'.','');
   v_value=replace(v_value,'(','');
   v_value=replace(v_value,')','');
   v_value=replace(v_value,' ','');

   if (v_value.length == 14)
      return v_value.substr(0,2) + '.' + v_value.substr(2,3) + '.' + v_value.substr(5,3) + '/' + v_value.substr(8,4) + '-' + v_value.substr(12,2);
   else if (v_value.length == 11)
      return v_value.substr(0,3) + '.' + v_value.substr(3,3) + '.' + v_value.substr(6,3) + '-' + v_value.substr(9,2);
   else
      return v_value;
}

function valid_cgc_cpf(p_obj)
{
   v_value = p_obj.value;
   v_value=replace(v_value,'-','');
   v_value=replace(v_value,'/','');
   v_value=replace(v_value,',','');
   v_value=replace(v_value,'.','');
   v_value=replace(v_value,'(','');
   v_value=replace(v_value,')','');
   v_value=replace(v_value,' ','');


   if (p_obj.value == '') return;

   if (v_value.length == 11)
      var v_type = 'CPF';
   else if (v_value.length == 14)
      var v_type = 'CNPJ';
   else
   {
       alert("CNPJ / CPF  inválido!");
      p_obj.value = '';
      p_obj.focus();
      return;
   }

   if(!Verify(v_value, v_type))
   {
      alert(v_type+" inválido!");
      p_obj.value = '';
      p_obj.focus();
   }


   p_obj.value = format_cgc_cpf(p_obj.value);

   return;
}
//-- ----------------------------------------------------------------------------------------------------
function set_focus_start()
{
   if (document.forms[0])
   {
      var index;
      for (index=0; index != document.forms[0].elements.length; index++)
      {
         if (document.forms[0].elements[index].type == 'hidden' ||
            document.forms[0].elements[index].readOnly ||
            document.forms[0].elements[index].disabled ||
            document.forms[0].elements[index].id == '5')
         {

         }else{
         	try{
            	document.forms[0].elements[index].focus();
            	return true;
            }catch(err){
            	return false;
            }            
         }
      }
      return false;
   }
   else
   {
      return false;
   }
}

//<VALIDAÇÕES DE CAMPO> Usado para validar campos(onFocusOut..)  <!-- NOVO --> Desenvolvido por Eduardo.
   function valida_email(email)
   {
      var ER = /^([\w+\.\-])+\@(([a-zA-Z\d+\-])+\.)+([a-zA-Z\d+]{2,6})+$/;
      if(!ER.test(email.value) && (email.value != ''))
      {
         alert('email invalido!');
         email.focus();
      }
   }

   function ValidaHora(obj)
   {
      ER = /^(([01][0-9])|([2][0123]))[:]?(([012345][0-9]))$/;
      if(!ER.test(obj.value) && (obj.value != ''))
      {
         alert('Hora invalida!');
         obj.focus();
      }
      else if(obj.value != '')
         obj.value = obj.value.substr(0,2)+':'+obj.value.replace(':','').substr(2,4);
   }
   
   function valida_dia_mes(campo)
   {
      data = replace(campo.value,'"/"','');
      data = replace(campo.value,'/','');
      if(data != '')
      {
         dia = data.substring(0,2);
         mes = data.substring(2,4);
         if (dia < 1 || dia > 31 || mes < 1 || mes > 12 || (dia > 30 && (mes == 4 || mes == 6 || mes == 9 || mes == 11)))
         {
            return false;
         }
         else
            return campo.value = dia+'/'+('0'+mes).slice(-2);
      }
      return true;
   }

   function Valida(vale, MaxMemo) // vale->"(campo a ser validado)[(msg)](campo que volta o foco)"
   {
      var msg = '';
      var foco = '';
      with(document.forms[0])
      {
         for(var i=0; elements.length > i; i++)
         {
            if((MaxMemo!='') && (elements[i].type == "textarea") && (MaxMemo < elements[i].value.length))
            {
               alert('Campo deve possuir menos de '+MaxMemo+' caracteres');
               elements[i].focus();
               return false;
            }

            if((elements[i].value == '') && (-1 != vale.indexOf(elements[i].name+'[')))
            {
               for(i=vale.indexOf(elements[i].name+'['); vale.length > i; i++)
               {
                  if (vale.charAt(i) == '[')
                  {
                     i++;
                     while(vale.charAt(i) != ']')
                     {
                        msg+=vale.charAt(i++);
                     }
                     i++;
                     while((vale.charAt(i) != ',') && (vale.length != i))
                     {
                        foco+=vale.charAt(i++);
                     }
                     break;
                  }
               }
               alert(msg);
               elements[foco].focus();
               return false;
            }
         }
      }
      return true;
   }
//</VALIDAÇÕES DE CAMPO>

//<VALIDAÇÕES DE TECLAS> Usado para validar Teclas(onKeyPress..)  <!-- NOVO --> Desenvolvido por Eduardo.
   function validaChar(chars, e) //usar "e" no caso de netscape passando o obj. "event"
   {
      var RE = new RegExp("["+chars+"]");

      e     = (netscape || mozilla) ? e       : event;
      tecla = (netscape)            ? e.which : e.keyCode;
      if(netscape || mozilla)
      {
         var teclas_ex = ((tecla == 8) || (tecla == 13) || (tecla == 0));  // 0 =>'ESC-DEL'
         return ((-1 == String.fromCharCode(tecla).search(RE)) && (!teclas_ex)) ? e.cancelBubble=true : e.cancelBubble=false;
      }
      else
         return (-1 == String.fromCharCode(tecla).search(RE)) ? e.returnValue=false : e.returnValue=true;
   }
   
   function DisableCtrl(p_event, p_plus_keycode){      
      var vKeyCode = (netscape) ? p_event.which : p_event.keyCode;	  
	  if (p_event.ctrlKey && vKeyCode == p_plus_keycode){
		 if(netscape || mozilla) return p_event.cancelBubble=true;
		 else return p_event.returnValue=false;
	  }else{
		 if(netscape || mozilla) return p_event.cancelBubble=false;
		 else return p_event.returnValue=true;
	  }
   }

   function SoNumero(event)
   {
      validaChar('0-9', event);
      //return (event.keyCode < 48 || event.keyCode > 57) ? event.returnValue=false : event.returnValue=true;
   }
   
   function NumWidthDec(event)
   {
      validaChar('0-9,', event);
      //return (event.keyCode < 48 || event.keyCode > 57) ? event.returnValue=false : event.returnValue=true;
   }
   
   function SemLetras()
   {
      return validaChar('a-zA-ZçÇ') ? event.returnValue=false : event.returnValue=true;
   //   return ((event.keyCode > 65) && (event.keyCode < 122)) ? event.returnValue=false : event.returnValue=true;
   }
//</VALIDAÇÕES DE TECLAS>

function Delete(nome)
{
   if(confirm('Confirma exclusão?'))
   {
      var excluir = get_field('excluir');
      excluir.value = 1;
      Entrar(nome,'Aguarde...');
   }
}

//<SEEKER> Usando no Seeker  <!-- NOVO --> Desenvolvido por Eduardo. Usando no Seeker
   var seekerValue;
   function ValorVelho(valor)
   {
      seekerValue = valor;
   }

   function ValorDif(valor)
   {
      return (seekerValue != valor);
   }
//</SEEKER> Usando no Seeker

function desabilita_lupa_veiculo()
{
   a = top.opener ? top.opener : top;
   a.get_field('bt_lupa_veiculo').disabled = true;
}

function AbilitaTela(obj)
{
   a = top.opener ? top.opener : top;
   var abilita = obj.value;
   with(a.document.forms[0])
   {
      elements['id_empresa'].disabled = abilita;
      elements['sigla_empresa'].disabled = abilita;

      elements['sigla_filial'].disabled = abilita;

      elements['id_filial_dest'].disabled = abilita;
      elements['codigo_filial_dest'].disabled = abilita;

      elements['vlr_mer_min'].disabled = abilita;
      elements['tp_manifesto'].disabled = abilita;
      elements['status'].disabled = abilita;
      elements['suspenso'].disabled = abilita;
      elements['tipo_carro'].disabled = abilita;
      elements['tipo_serv'].disabled = abilita;
   }
}

function PosX(pObj)
{
   if(typeof(pObj.offsetParent) != 'undefined')
   {
      for(var posX=0; pObj; pObj = pObj.offsetParent)
         posX += pObj.offsetLeft;
      return posX;
   }
   else
      return pObj.x;
}

function PosY(pObj)
{
   if(typeof(pObj.offsetParent) != 'undefined')
   {
      for(var posY=0; pObj; pObj = pObj.offsetParent)
         posY += pObj.offsetTop;
      return posY;
   }
   else
      return pObj.y;
}

function abilita_travamento() //usado em seeker->exec_script_name
{
   a = top.opener ? top.opener : top;
   with(a.document.forms[0])
   {
      elements['id_travamento'].disabled = !elements['id_rastreador'].value;
      elements['codigo_travamento'].disabled = !elements['id_rastreador'].value;
      elements['descricao_travamento'].disabled = !elements['id_rastreador'].value;
      elements['bt_lupa_travamento'].disabled = !elements['id_rastreador'].value;
      elements['codigo_travamento'].style.background = (!elements['id_rastreador'].value) ? "#EEEEEE" : "#FFFFFF";
      elements['descricao_travamento'].style.background = (!elements['id_rastreador'].value) ? "#EEEEEE" : "#EEEEEE";
   }
}
function CadastraTelefone(campos,id_filial,numero,id_tipo_telefone) //usado em seeker->exec_script_name
{
   titulo = '';
   win = (top.opener ? top.opener : top);
   for(var i = 0; i < campos.length; i++)
   {
      win.document.forms[0].elements[campos[i]].value = '';
   }
   for(var i=0; i < win.document.forms[0].elements.length; i++)
   {
      if(win.document.forms[0].elements[i].type == 'button' ||
         win.document.forms[0].elements[i].type == 'submit' ||
         win.document.forms[0].elements[i].type == 'reset')
      {
         if(win.document.forms[0].elements[i].id != '9')
         {
            win.document.forms[0].elements[i].disabled = false;
         }
      }
   }
   window.open('../../sistemas/cadastro/telefone.php?id_filial='+id_filial+'&focus='+campos[0]+'&numero='+numero+'&id_tipo_telefone='+id_tipo_telefone+'&PHPSESSID='+PHPSESSID,titulo,'status=no,top=0,left=0,width=620,height=180,scrollbars=no');
}
function AtualizaVeiculo() //usado em seeker->exec_script_name
{
   a = top.opener ? top.opener : top;
   with(a.document.forms[0])
   {
      a.veiculo(elements['nrofrota'].value)
   }
}
function AtualizaPortador() //usado em seeker->exec_script_name
{
   a = top.opener ? top.opener : top;
   with(a.document.forms[0])
   {
      a.portador(elements['nome_portador'].value)
   }
}

//      <!-- NOVO --> Desenvolvido por Eduardo.
function format_cep(p_obj)
{
   p_obj.value = replace(p_obj.value,'-','');
   if ((p_obj.value.length < 8) && (p_obj.value != ""))
   {
      alert('Cep Inválido!');
       p_obj.value = '';
      p_obj.focus();
      return false;
   }
   else if(p_obj.value.length > 7)
   {
      p_obj.value = p_obj.value.substr(0,5) + '-' + p_obj.value.substr(5,3);
      return true;
   }
}

function mudabotao()
{
   var confirma = get_field('confirma');
   confirma.value = 0;
   document.forms[0].elements['salvar'].value = "   Salvar";
}

function get_field(p_name_field)
{
   var v_form = getFormByElement(p_name_field);
   return v_form.elements[p_name_field];
}

function get_date(p_name_field_dt, p_name_field_hr) //40207
{
   var data = document.forms[0].elements[p_name_field_dt].value;
   var dd = data.substr(0, 2)/1;
   var mm = data.substr(3, 2)-1;
   var aaaa = data.substr(6, 4)/1;
   
   if(p_name_field_hr != undefined)
   {
      var hora = document.forms[0].elements[p_name_field_hr].value;
      var hr = hora.substr(0, 2)/1;
      var mi = hora.substr(3, 2)/1;

      var v_data = new Date(aaaa, mm, dd, hr, mi);
   }
   else
      var v_data = new Date(aaaa, mm, dd);

   return v_data;
}

function get_data(dia, mes, ano)
{
   var v_data = new Date (ano / 1,
                     mes - 1,
                     dia / 1);
   return v_data;
}

function diff_data(dt_ini,dt_fim)
{
   var v_dt_ini =  get_date(dt_ini);
   var v_dt_fim =  get_date(dt_fim);
   var v_diff = (v_dt_fim - v_dt_ini) / 77760000;
   return v_diff;
}

function caracter_is_number(valor)
{
   var i = 0;
   for (i=0; i<10 ; i++)
   {
      if (valor == i)
      {
         return true;
      }
   }
   return false;
}

function seeker(p_name_obj,p_value)
{
   var v_obj = this.document.forms[0].elements[p_name_obj];

   if (!v_obj.length)
   {
      if (v_obj.value == p_value)
      {
         return true;
      }
      else
      {
         return false;
      }
   }
   else
   {
      for (var i=0; i < v_obj.length; i++)
      {
         if (v_obj[i].value == p_value)
         {
            return true;
         }
      }
      return false;
   }
}

//DANIEL SAMBINELLI
//VERIFICA SE TODOS OS CARACTERES SAO NÚMEROS
function is_number(valor)
{
   valor = valor.toString().replace( ".", "" );
   valor = valor.toString().replace( ",", "" );

   for (var i=0; i<valor.length; i++)
   {
      if ( !caracter_is_number( valor.substr(i,1) ) )
      {
         return false;
      }
   }
   return true;
}


function validate_number(obj)
{
   if ( !is_number(obj.value) )
   {
      alert('Número inválido!');
      obj.value='';
   }
}

//DANIEL SAMBINELLI
//VALIDA ANO DENTRO DE UM INTERVALO
function Valida_ano(ano)
{
   if (ano == '')
   {
      return true;
   }
   // [23/02/2010][LBOTARDO]: Substituida função getYear() por getFullYear() pois a getYear() não funcionava corretamente no FireFox
   if (!is_number(ano) || ((ano < (new Date()).getFullYear()-100) || (ano > (new Date()).getFullYear()+10)))
   {
      return false;
   }
   else
   {
      return true;
   }
}

//DANIEL SAMBINELLI
//FAZ A MÁSCARA DE CAMPOS
function Formata(objForm, strField, sMask, evtKeyPress) {
   var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;

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

   sValue = strField.value;

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

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

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

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

      i++;
   }

   strField.value = sCod;

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

//DANIEL SAMBINELLI
//VALIDA DATA PERMITINDO NULA
function valida_data_nor(p_data){

   var str = p_data.value;

   if (str != '')
    {

      dia = (str.substring(0,2));
      mes = (str.substring(3,5));
      ano = (str.substring(6,10));

      dt_invalid = false;
      // verifica o dia valido para cada mes
      if ((dia < 1)||(dia < 1 || dia > 30) && (  mes == 4 || mes == 6 || mes == 9 || mes == 11 ) || dia > 31) {
         dt_invalid = true;
      }

      // verifica se o mes e valido
      if (mes < 1 || mes > 12 ) {
         dt_invalid = true;
      }

      // verifica se e ano bissexto
      if (mes == 2 && ( dia < 1 || dia > 29 || ( dia > 28 && (parseInt(ano / 4) != ano / 4)))) {
         dt_invalid = true;
      }

      if (ano.length < 4) {
         dt_invalid = true;
      }

      if (dt_invalid) {
         alert(" Data inválida!");
         p_data.value = '';
         return false;
      }
   }
}


//DANIEL SAMBINELLI
//VALIDA DATA MES/ANO PERMITINDO NULA
function valida_data_mes_ano (obj) {

   var str = obj.value;

    if (str != '')
    {
      mes = (str.substr(0,2));
      ano = (str.substr(3,7));

      situacao = "";
      // verifica se o mes e valido
      if (mes < 01 || mes > 12 ) {
         situacao = "falsa";
      }

      if ((ano > 2050) || (ano < 1900 )) {
         situacao = "falsa";
      }
      if (situacao == "falsa") {
         alert(' Data inválida!');
         obj.value = '';
         return false;
      }
   }
  }


//DANIEL SAMBINELLI
//FAZ A MÁSCARA DE MES/ANO
function MaskDataMesAno(this_data)
{
   if (this_data.value == '')
   {
      return false;
   }

   var v_data = null;
   v_data = this_data.value;
   v_data = replace (v_data,'/','');
   v_data = replace (v_data,'-','');

   if (v_data.length ==4 || v_data.length == 6)
   {
      if (v_data.length == 4)
      {
         v_data = v_data.substr(0,2) + '20' + v_data.substr(2,2);
      }
      this_data.value = v_data.substr(0,2) + '/' + v_data.substr(2,4);
      valida_data_mes_ano(this_data);
   }
   else
   {
      alert(' Data inválida!');
      this_data.value = '';
   }
}


function compara_numero(obj_ini,obj_fim,descricao)
{
   if (obj_ini.value != '' || obj_fim.value != '')
   {
      if (obj_ini.value == '')
      {
         alert('Favor informar ' + descricao + ' inicial!');
         obj_ini.focus();
         return false;
      }

      if (obj_fim.value == '')
      {
         alert('Favor informar ' + descricao + ' final!');
         obj_fim.focus();
         return false;
      }

      var v_ini = obj_ini.value;
      var v_fim = obj_fim.value;

      v_ini = replace(v_ini,'.','');
      v_ini = replace(v_ini,',','.');

      v_fim = replace(v_fim,'.','');
      v_fim = replace(v_fim,',','.');

      v_ini = v_ini * 1;
      v_fim = v_fim * 1;

      if (v_ini > v_fim)
      {
         alert(descricao + ' final deve ser maior que ' + descricao + ' inicial!');
         obj_fim.focus();
         return false;
      }
   }
   return true;
}

function valida_data(dt_ini, dt_fim, dias, msg_campo, msg_periodo)
{
   var f_dt_ini = get_field(dt_ini);
   var f_dt_fim = get_field(dt_fim);
   var v_dt_ini =  get_date(dt_ini);
   var v_dt_fim =  get_date(dt_fim);
   var v_msg;

   if(f_dt_ini.value == '')
   {
      v_msg = 'Favor informar a data ';
      v_msg = v_msg + msg_campo;
      v_msg = v_msg + ' início!'
      alert(v_msg);
      f_dt_ini.focus();
      return false;
   }

   if(f_dt_fim.value == '')
   {
      v_msg = 'Favor informar a data ';
      v_msg = v_msg + msg_campo;
      v_msg = v_msg + ' fim!'
      alert(v_msg);
      f_dt_fim.focus();
      return false;
   }

   if(v_dt_ini > v_dt_fim)
   {
      alert('Data início deve ser maior que a data fim!');
      f_dt_ini.focus();
      return false;
   }

   v_dt_ini.setDate (v_dt_ini.getDate() + dias);


   if (f_dt_ini.value != '' && f_dt_fim.value != '' && (v_dt_fim >= v_dt_ini) )
   {
      var vmsg = (msg_periodo != undefined) ? msg_periodo : 'O período deve ser entre '+ dias +' dias!';
      alert(vmsg);
      f_dt_fim.focus();
      return false;
   }

   return true;
}


function valida_valor(p_vlr_inicio,p_vlr_fim,p_msg_campo,p_obrigatio)
{
   vlr_inicio = get_field(p_vlr_inicio);
   vlr_fim = get_field(p_vlr_fim);

   if(vlr_inicio.value == '' && vlr_fim.value != '')
   {
      alert('Favor informar o valor início ' + p_msg_campo + '!');
      vlr_inicio.focus();
      return false;
   }

   if(vlr_inicio.value != '' && vlr_fim.value == '')
   {
      alert('Favor informar o valor fim ' + p_msg_campo + '!');
      vlr_fim.focus();
      return false;
   }

   if (vlr_inicio.value != '' && vlr_fim.value != '')
   {
      p_obrigatio = 1;
   }

   if (p_obrigatio == 1)
   {

      if (vlr_inicio.value == '')
      {
         alert('Favor informar o valor início ' + p_msg_campo + '!');
         vlr_inicio.focus();
         return false;
      }

      if (vlr_fim.value == '')
      {
         alert('Favor informar o valor fim ' + p_msg_campo + '!');
         vlr_fim.focus();
         return false;
      }

      v_vlr_inicio = vlr_inicio.value;
      v_vlr_fim = vlr_fim.value;

      v_vlr_inicio = replace(v_vlr_inicio,'.','');
      v_vlr_inicio = replace(v_vlr_inicio,',','.');
      v_vlr_inicio = v_vlr_inicio / 1;

      v_vlr_fim = replace(v_vlr_fim,'.','');
      v_vlr_fim = replace(v_vlr_fim,',','.');
      v_vlr_fim = v_vlr_fim / 1;

      if (v_vlr_inicio > v_vlr_fim)
      {
         alert('Valor início ' + p_msg_campo + ' deve ser menor que o valor final ' + p_msg_campo + '!');
         vlr_inicio.focus();
         return false;
      }
   }

   return true;
}

function up_date (p_data,nro_dia)
{
   p_data.setDate ( p_data.getDate()+nro_dia);
   return p_data;
}

function imp_html_div(info, name){
   var ie=document.all
   var dom=document.getElementById
   var ns4=document.layers

   if(ie)
   {
      document.all[name].innerHTML = info;
   }
   else if(ns4)
   {
      document.layers[name].document.open();
      document.layers[name].document.write(info);
      document.layers[name].document.close();
   }
   else if(dom)
   {
      document.getElementById(name).innerHTML = info;
   }
}


function top_imp_html_div(info,name)
{
   var ie=document.all
   var dom=document.getElementById
   var ns4=document.layers

   if(ie)
      top.document.all[name].innerHTML = info;
   else if(ns4)
   {
      top.document.layers[name].document.open();
      top.document.layers[name].document.write(info);
      top.document.layers[name].document.close();
   }
   else if(dom)
      top.document.getElementById(name).innerHTML= info;
}

function top_opener_imp_html_div(info,name)
{
   var ie=document.all
   var dom=document.getElementById
   var ns4=document.layers

   if(ie)
   {
      top.opener.document.all[name].innerHTML = info;
   }
   else if(ns4)
   {
      top.opener.document.layers[name].document.open();
      top.opener.document.layers[name].document.write(info);
      top.opener.document.layers[name].document.close();
   }
   else if(dom)
   {
      top.opener.document.getElementById(name).innerHTML= info;
   }
}

function Restaurar(nome_botao)
{
   document.forms[0].reset();
}

function Limpar(nome_botao, p_param) //40207
{
   var p_param = (p_param != undefined) ? p_param : '';
   var a = document.location;

   if(p_param && (a.search.indexOf('?') >= 0))
      p_param = p_param.replace('?', '&');

   document.location = 'http://'+a.host+a.pathname+a.search+p_param;
}

function Entrar(nome_botao, msg, e)
{
   var info;
   var v_form = getFormByElement(nome_botao);

   info = msg ? msg : 'Aguarde estamos efetuando a pesquisa...';

   imp_html_div(info, 'mensagem');
   v_form.elements[nome_botao].disabled = true;
   v_form.submit();
   this.document.body.style.cursor = 'wait';
}

function Entrar2(nome_botao, msg, pForm)
{
   var form = (pForm != undefined) ? pForm : document.forms[0];
   var info = msg   ? msg   : 'Aguarde estamos efetuando a pesquisa...';

   imp_html_div(info, 'mensagem');
   form.elements[nome_botao].disabled = true;
   form.submit();
   this.document.body.style.cursor = 'wait';
}

function Entrar2Janela( nome_botao, msg, link ){

   var info;
   if (msg == '')
   {
      info = 'Aguarde estamos efetuando a pesquisa...'
   }
   else
   {
      info = msg;
   }

   imp_html_div (info,'mensagem');
   document.forms[0].elements[nome_botao].disabled = true;
   AbreJanela(link,500,500,'Produção');
}

/*------------------------------------------------------------------------------
                    
------------------------------------------------------------------------------*/
function pad(Objeto,tamanho,caracter,posicao)
{
   if (Objeto.value != ''){
      var v_qtd, string;
      v_qtd = tamanho - Objeto.value.length;
      string = '';
      for (var indice=0; indice < v_qtd; indice++){
          string = string + caracter;
      }

      if (posicao == "L"){
         string = string + Objeto.value;
      }else if (posicao == "R"){
         string = Objeto.value +  string;
      }

      Objeto.value = string;
   }
}

function spad(valor,tamanho,caracter,posicao)
{
   if (valor != ''){
      var v_qtd, string;
      v_qtd = tamanho - valor.length;
      string = '';
      for (var indice=0; indice < v_qtd; indice++){
          string = string + caracter;
      }

      if (posicao == "L"){
         string = string + valor;
      }else if (posicao == "R"){
         string = valor +  string;
      }
   }
   return string;
}

/*------------------------------------------------------------------------------
                    Mudar a cor do foco na entrada e saida
------------------------------------------------------------------------------*/
function Menu(Objeto){
   Objeto.style.background = "#FFFFFF";
   Objeto.style.border= "1px solid #FFFFFF";
   Objeto.style.color= "#9E9E9E";
   Objeto.style.font= "bold 11px Arial, sans-serif";
   Objeto.style.cursor= "hand";
}

function MenuSobre(Objeto){
   Objeto.style.background = "#FFFFFF";
   Objeto.style.border= "1px solid #FF6600";
   Objeto.style.color= "#9E9E9E";
   Objeto.style.font= "bold 11px Arial, sans-serif";
   Objeto.style.cursor= "hand";
}

function SetReadOnly (Objeto, p_value)
{
   Objeto.readonly = p_value;
   if (p_value)
   {
      Objeto.style.background = "#EFEFEF";
      Objeto.style.color= "#999999";
   }
   else
   {
      Objeto.style.background = "#FFFFFF";
      Objeto.style.color= "#000000";
   }
}

var OldEntradaBgColor = ''; //21406
function Entrada(Objeto, pChangeBg)
{
   OldEntradaBgColor = Objeto.style.backgroundColor;
   var vChangeBg = (pChangeBg != undefined) ? pChangeBg : true;
   
   if(vChangeBg && (!ie7 || Objeto.type != 'select-one'))
      Objeto.style.backgroundColor = "#99ffcc";
   Objeto.style.border = "1px solid #BFBFBF";
   
   if((Objeto.value != '') && (Objeto.type == 'text'))
      Objeto.select();
      
}

function Saida(Objeto)
{
   Objeto.style.backgroundColor = OldEntradaBgColor;
   Objeto.style.border = "1px solid #BFBFBF";
   //if (mozilla)
   //   alert('mozilla');
//   Objeto.style.color = "#000000";
}

var OldRowBgColor = '';
function RowLigth(pObj, pLiga)
{
   if(pLiga)
   {
      OldRowBgColor = pObj.bgColor;
      pObj.bgColor = '#DBDBDB';
   }
   else
      pObj.bgColor = OldRowBgColor;
}

function FuncLink(link){
   var aplicacao = document.forms[0].elements['aplicacao'].value;
   document.location = link + '?aplicacao=' + aplicacao + "&PHPSESSID="+PHPSESSID;
}

/*------------------------------------------------------------------------------
Pega a posição que uma string se encontra(Usado muito para formatação de número)
------------------------------------------------------------------------------*/
function position (valor, caracter)
{
   var pos; var index;
   for (index=0; index!=valor.length; index++){
      if (valor.substr(index,1) == caracter){
         pos = index;
         return pos;
      }
   }
   return 0;
}
/*------------------------------------------------------------------------------
            Funcão que faz replace em uma string de modo simples
------------------------------------------------------------------------------*/
function replace(str, str_search, str_replace){
   var index;
   var str_start;
   var str_end;
   var str_end_len
    str = str + '';
   for (index=0; index!=str.length; index++)
   {
      if (str.substr(index,str_search.length) == str_search)
      {
         str_start = str.substr(0,index);
         str_end_len = index + str_search.length;
         str_end = str.substr(str_end_len,str.length);
         str = str_start + str_replace + str_end;
         index=0;
      }
   }
   return str;
}
/*------------------------------------------------------------------------------
          Ao passar o mause em cima da linha da tabela muda de cor
------------------------------------------------------------------------------*/

function tag_tr(tag,cor){
   //alert(cor);
   tag.bgColor = cor;
}

function tag_tr_click(tag,cor){
   tag.bgColor = cor;
}
/*----------------------------------------------------------------------------*/
//                     Função que usa o Tab como Enter
/*----------------------------------------------------------------------------*/
var Proximo;
Proximo = 0;
/*----------------------------------------------------------------------------*/
function SearchFocus(event)
{
   var v_form = getFormByElement(event.srcElement.name);
   for(var index=0; index < v_form.elements.length; index++)
   {
      if(v_form.elements[index].id == 1)
      {
         index++;
         return index;
      }
   }
   return 0;
}
/*----------------------------------------------------------------------------*/
function EscEnter(DnEvents)
{
   var find = 1;
   var key;
   var ie=document.all
   var dom=document.getElementById
   var ns4=document.layers
   var v_form = null;
   
   if(!mozilla && event && (event.srcElement != null))
   {
      v_form = getFormByElement(event.srcElement.name);
      key = (netscape) ? DnEvents.which : window.event.keyCode;
   }      
   else
      v_form = document.forms[0];
   
   if(DnEvents)
   {
      event = DnEvents;
   }

   if(key == 13 || (key == 9 && !event.shiftKey))
   {
      Proximo = SearchFocus(event);
      if((Proximo >= 0) && (Proximo != v_form.elements.length))
      {
         while(find == 1)
         {
            if(!v_form.elements[Proximo])
               Proximo = 0;
            if(v_form.elements[Proximo].type == 'hidden')
               Proximo++;
            else if(v_form.elements[Proximo].readOnly)
               Proximo++;
            else if(v_form.elements[Proximo].style.display == 'none')
               Proximo++;               
            else if(v_form.elements[Proximo].disabled)
               Proximo++;
            else if(v_form.elements[Proximo].id == '5')
               Proximo++;
            else
               find = 0;
         }
         //if (Proximo < 0) Proximo = 0;
         //if (Proximo > v_form.elements.length) Proximo = v_form.elements.length;

         if(Proximo <= v_form.elements.length)
         {
         	try {
	            v_form.elements[Proximo].focus();
	            if(v_form.elements[Proximo].type == 'text')
	               v_form.elements[Proximo].select();         	
         	} catch(e) {
         	}

         }
      }
      return false;
   }
   else if(key == 27 || (key == 9 && event.shiftKey))
   {
      Proximo--;
      if((Proximo >= 0) && (Proximo != v_form.elements.length))
      {
         while(find == 1)
         {
            if(!v_form.elements[Proximo])
               Proximo = SearchFocus(event);

            if(v_form.elements[Proximo].type == 'hidden')
               Proximo--;
            else if(v_form.elements[Proximo].readOnly)
               Proximo--;
            else if(v_form.elements[Proximo].disabled)
               Proximo--;
            else if(v_form.elements[Proximo].id == '5')
               Proximo--;
            else
               find = 0;
         }

         //if (Proximo < 0) Proximo = 0;
         //if (Proximo > v_form.elements.length) Proximo = v_form.elements.length;

         if(v_form.elements[Proximo])
         {
            v_form.elements[Proximo].focus();
            if(v_form.elements[Proximo].type == 'text')
               v_form.elements[Proximo].select();
         }
      }
      return false;
   }
}
/*----------------------------------------------------------------------------*/
function EntradaTextare(){
   document.onkeydown = '';
   if (netscape) document.captureEvents();
}
/*----------------------------------------------------------------------------*/
function SaidaTextare(){
   document.onkeydown = EscEnter;
   if (netscape) document.captureEvents(Event.KEYDOWN|Event.KEYUP);
}
/*----------------------------------------------------------------------------*/
function Logon()
{
   var usuario = document.forms[0].elements['usuario'];
   var senha = document.forms[0].elements['senha'];

   if(usuario.value == '')
   {
     alert('Favor informar o usuário!');
     usuario.focus();
     return false;
   }

   if(senha.value == '')
   {
     alert('Favor informar a senha!');
     senha.focus();
     return false;
   }

   Entrar('entrar','Aguarde...');
}


function AddCnpj()
{
   var id_cliente = document.forms[0].elements['id_cliente'];
   var save = document.forms[0].elements['save'];
   var cnpj_cliente = document.forms[0].elements['cnpj_cliente'];

   if (id_cliente.value == '' && cnpj_cliente.value != "")
   {
      alert('Aguarde enquanto os dados estão sendo carregados!');
      cnpj_cliente.focus();
      return false;
   }

   if (id_cliente.value == '')
   {
      alert('Favor informar o cliente!');
      cnpj_cliente.focus();
      return false;
   }

   save.value = 0;
   Entrar('add', 'Aguarde...');
}

function ExCnpj(cgc_cpf,id_usuario)
{
   var str;
   str = "../senha/ExCnpj.php?cgc_cpf=" + cgc_cpf + "&id_usuario=" + id_usuario + "&PHPSESSID="+PHPSESSID;
   this.ifrExCnpj.location=str;
}

function AprovaSenha()
{
   var save = document.forms[0].elements['save'];
   var status = document.forms[0].elements['status'];

   if (status.value == '')
   {
      alert('Favor informar o status!');
      status.focus();
      return false;
   }

   save.value = 1;
   Entrar('salvar','Aguarde...');
}

function CadastroSenha()
{
   var usuario = document.forms[0].elements['usuario'];
   var senha = document.forms[0].elements['senha'];
   var confirma_senha = document.forms[0].elements['confirma_senha'];
   var email = document.forms[0].elements['email'];
   var save = document.forms[0].elements['save'];
   var nome_contato = document.forms[0].elements['nome_contato'];
   var ddd = document.forms[0].elements['ddd'];
   var nro_telefone = document.forms[0].elements['nro_telefone'];
   var no_cnpj = document.forms[0].elements['no_cnpj'];

   if (usuario.value == '')
   {
      alert('Favor informar o usuário!');
      usuario.focus();
      return false;
   }

   if (senha.value == '')
   {
      alert('Favor informar a senha!');
      senha.focus();
      return false;
   }

   if (confirma_senha.value == '')
   {
      alert('Favor informar a confirmaçao da senha!');
      confirma_senha.focus();
      return false;
   }

   if (senha.value.length < 8)
   {
      alert ('Senha tem que ter 8 caracter!');
      senha.focus();
      return false;
   }

   if (confirma_senha.value.length < 8)
   {
      alert ('Confirmação da senha tem que ter 8 caracter!');
      confirma_senha.focus();
      return false;
   }

   if (senha.value != confirma_senha.value)
   {
      alert ('Senha não confere com a senha de confirmação!');
      confirma_senha.value = '';
      senha.focus();
      return false;
   }

   if (nome_contato.value == '')
   {
      alert('Favor informar o seu nome!');
      nome_contato.focus();
      return false;
   }

   if (ddd.value == '')
   {
      alert('Favor informar o ddd!');
      ddd.focus();
      return false;
   }

   if (nro_telefone.value == '')
   {
      alert('Favor informar o número do telefone!');
      nro_telefone.focus();
      return false;
   }

   if (email.value == '')
   {
      alert('Favor informar o e-mail!');
      email.focus();
      return false;
   }
   else
   {
      if (!ValidaEmail(email))
      {
         return false;
      }
   }

   if (no_cnpj.value == 1)
   {
      alert('Favor informar o cnpj ou clique no botão "Adicionar"!');
      return false;
   }

   save.value = 1;
   Entrar('salvar','Aguarde...');

}

function ValidaEsqueciSenha()
{
   var id_pessoal = document.forms[0].elements['id_pessoal'].value;
   var chapa_pessoal = document.forms[0].elements['chapa_pessoal'];

   if (id_pessoal == '')
   {
      alert('Favor informar a matrícula ou o nome!');
      chapa_pessoal.focus();
      return false;
   }

   Entrar('enviar','Aguarde...');
}


function ValidaTrocaSenha(){
   var usuario = document.forms[0].elements['usuario'];
   var senha = document.forms[0].elements['senha'];
   var nova_senha = document.forms[0].elements['nova_senha'];
   var confirma_senha = document.forms[0].elements['confirma_senha'];


   if (usuario.value == ""){
     alert ('Favor preencher o usuário!');
     usuario.focus();
     return false;
   }else if (senha.value == ""){
     alert ('Favor preencher a senha!');
     senha.focus();
     return false;
   }else if (nova_senha.value == ""){
     alert ('Favor preencher a nova senha!');
     nova_senha.focus();
     return false;
   }else if (confirma_senha.value == ""){
     alert ('Favor preencher a confirmação da senha!');
     confirma_senha.focus();
     return false;
   }else if (nova_senha.value.length < 8){
     alert ('Nova senha tem que ter 8 caracter!');
     nova_senha.focus();
     nova_senha.select();
     return false;
   }else if (confirma_senha.value.length < 8){
     alert ('Confirmação da senha tem que ter 8 caracter!');
     confirma_senha.focus();
     confirma_senha.select();
     return false;
   }else if (senha.value == nova_senha.value){
     alert ('Senha não pode ser igual a nova senha!');
     nova_senha.select();
     nova_senha.focus();
     confirma_senha.value='';
     return false;
   }else if (nova_senha.value != confirma_senha.value){
     alert ('Nova senha não confere com a senha de confirmação!');
     nova_senha.select();
     nova_senha.focus();
     confirma_senha.value='';
     return false;
   }

   Entrar('save','Aguarde...');
}

function ChamaTelaTrocaSenha(){
   var host = window.location.protocol+'//'+window.location.hostname;
   window.open(host+'/sistemas/senha/dSenha.php?PHPSESSID='+PHPSESSID,'TrocaSenha','left=0,top=0,width=650,height=400,scrollbars=yes,resizable=yes');
}

function ChamaTelaEsqueciSenha(tipo){
   var host = window.location.protocol+'//'+window.location.hostname;
   window.open(host+'/sistemas/senha/dEsqueciSenha.php?tipo='+tipo+'&PHPSESSID='+PHPSESSID,'TrocaSenha','left=0,top=0,width=650,height=400,scrollbars=yes,resizable=yes');
}

function OpenWinLoca(modulo)
{
   var host = window.location.protocol+'//'+window.location.hostname;
   window.open(host+'/sistemas/location.php?modulo='+modulo+'&PHPSESSID='+PHPSESSID,'Locat', 'toolbar=yes,location=no,directories=yes,status=no,menubar=yes,scrollbars=yes,resizable=yes,menubar=yes,left=0,top=0,width='+ screen.availwidth +',height='+ screen.availheight);
}

function AbreJanela(link,altura,largura)
{
   link = link+((position(link, '?') > 0) ? '&' : '?')+'PHPSESSID='+PHPSESSID;
   window.open(link, 'AbreJanela', 'toolbar=yes,location=no,directories=yes,status=no,menubar=yes,scrollbars=yes,resizable=yes,menubar=yes,top=0,left=0,width='+ largura +',height='+ altura);
}

function AbreJanela (link,altura,largura,nome_janela)
{
   link = link+((position(link, '?') > 0) ? '&' : '?')+'PHPSESSID='+PHPSESSID;
   window.open(link, nome_janela, 'toolbar=yes,location=no,directories=yes,status=no,menubar=yes,scrollbars=yes,resizable=yes,menubar=yes,top=0,left=0,width='+ largura +',height='+ altura);
}

function AbreJanela (link,altura,largura,nome_janela,top,left)
{
   var url;
   link = link+((position(link, '?') > 0) ? '&' : '?')+'PHPSESSID='+PHPSESSID;

   url = 'toolbar=yes,location=no,directories=yes,status=no,menubar=yes,scrollbars=yes,resizable=yes,menubar=yes,top='+top+',left='+left+',width='+ largura +',height='+ altura;

   window.open(link, nome_janela, url);
}

function AbreJanelaSimple(link,altura,largura,nome_janela)
{
   link = link+((position(link, '?') > 0) ? '&' : '?')+'PHPSESSID='+PHPSESSID;
   newwindow = window.open(link,nome_janela, 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,menubar=no,top=0,left=0,width='+ largura +',height='+ altura+', alwaysRaised=yes');
}

/*------------------------------------------------------------------------------
                   Preenche as casas decimais com 0 (zero)
------------------------------------------------------------------------------*/
function fill_zero(decimal)
{
   var str_zero='';
   var index;
   for(index=0; index!=decimal; index++)
      str_zero = str_zero + '0';
   return str_zero;
}
/*------------------------------------------------------------------------------
                   Completa as casas decimais com 0 (zero)
------------------------------------------------------------------------------*/
function complete_zero(str_lenght, decimal)
{
   var index;
   var valor = '';
   for(index=str_lenght; index!=decimal; index++)
   {
      valor = valor + '0';
   }
   return valor;
}
/*------------------------------------------------------------------------------
            Dá um replace quando o usuário digita ".", adiciona o 
          ponto no número e trava a digitação
------------------------------------------------------------------------------*/
function add_point(valor, size, decimal){
   var found; var pos;
   valor.value = replace(valor.value,".",",");
   pos = position(valor.value,',');
   if(pos != 0)
   {
      valor.maxlength = pos + 1 + decimal;
      valor.value = valor.value.substr(0,valor.maxlength-1);
   }
   else
   {
      valor.maxlength = size + 1 + decimal;
      valor.value = valor.value.substr(0,valor.maxlength-1);
      if(valor.value.length == size)
         valor.value = valor.value + ',';
   }
}
/*------------------------------------------------------------------------------
Formata o número conforme o tamanho com o número de casas decimais no OnkeyPress
------------------------------------------------------------------------------*/
function format_number (valor, size, decimal){
   var str_valor = valor.value;
   var start_decimal;
   var pos;
   var index;
   var soma;
   var nro_zero;
   var str_decimal;
   //-- ----------------------------------------------------
   str_valor = replace(valor.value, '.', '');
   //-- ----------------------------------------------------
   if (str_valor.substr(0,1) == ',')
   {
      str_valor = '0'+str_valor;
   }
   pos = position (str_valor, ',');
   //-- ----------------------------------------------------

   if (!is_number(str_valor))
   {
      alert('Número inválido!');
      valor.value = '';
      return false;
   }

   if (pos > 0){
      index = pos;
      soma = 1;
      while (index != 0){
         if (soma == 3){
            str_valor = str_valor.substring(0,index-1) + '.' + str_valor.substring(index-1,str_valor.length);
            soma = 0;
         }
         soma++;
         index = index - 1;
      }
      if (str_valor.substr(0,1) == '.'){
         str_valor = str_valor.substring(1,str_valor.length);
      }
      pos = position (str_valor, ',');
      start_decimal = str_valor.substr(pos+1,decimal);
      nro_zero = complete_zero(start_decimal.length,decimal);
      str_valor = str_valor + nro_zero
      //valor.value = str_valor + nro_zero;
   }else{
      if (valor.value != ''){
         nro_zero = fill_zero(decimal);
         str_valor = str_valor + ',' + nro_zero;
         pos = position (str_valor, ',');
         index = pos;
         soma = 1;
         while (index != 0){
            if (soma == 3){
               str_valor = str_valor.substring(0,index-1) + '.' + str_valor.substring(index-1,str_valor.length);
               soma = 0;
            }
            soma++;
            index = index - 1;
         }
         if (str_valor.substr(0,1) == '.'){
            str_valor = str_valor.substring(1,str_valor.length);
         }
         //valor.value = str_valor;
      }
   }
   if (decimal == 0)
   {
      str_valor = replace(str_valor, ',', '');
   }
   valor.value = str_valor;
} 

/*------------------------------------------------------------------------------
                     Formata o número
------------------------------------------------------------------------------*/
function FormatNumber(str, size, decimal){
   var start_decimal;
   var pos;
   var index;
   var soma;
   var nro_zero;
   var str_decimal;
   //-- ----------------------------------------------------
   str = replace(str,'.',',');
   //-- ----------------------------------------------------
   pos = position(str, ',');
   //-- ----------------------------------------------------
   if (pos > 0){
      index = pos;
      soma = 1;
      while (index != 0){
         if (soma == 3){
            str = str.substring(0,index-1) + '.' + str.substring(index-1,str.length);
            soma = 0;
         }
         soma++;
         index = index - 1;
      }
      if (str.substr(0,1) == '.'){
         str = str.substring(1,str.length);
      }
      pos = position (str, ',');
      start_decimal = str.substr(pos+1,decimal);
      nro_zero = complete_zero(start_decimal.length,decimal);
      str = str + nro_zero;

      start_decimal = str.substr(pos+1,str.length);
      if (start_decimal > 5){
         start_decimal = str.substr(pos+decimal,1)  / 1;
         //start_decimal = start_decimal + 1;
         str = str.substr(0,pos+decimal) + start_decimal;
      }else{
         str = str.substr(0,pos+decimal+1);
      }
   }else{
      if (str != ''){
         nro_zero = fill_zero(decimal);
         str = str + ',' + nro_zero;
         pos = position (str, ',');
         index = pos;
         soma = 1;
         while (index != 0){
            if (soma == 3){
               str = str.substring(0,index-1) + '.' + str.substring(index-1,str.length);
               soma = 0;
            }
            soma++;
            index = index - 1;
         }
         if (str.substr(0,1) == '.'){
            str = str.substring(1,str.length);
         }
         start_decimal = str.substr(pos+1,str.length);
         if (start_decimal > 5){
            start_decimal = str.substr(pos+decimal,1)  / 1;
            start_decimal = start_decimal + 1;
            str = str.substr(0,pos+decimal) + start_decimal;
         }else{
            str = str.substr(0,pos+decimal+1);
         }
      }
   }
   return str;
} 


function AllCheck(objeto,nome)
{
   var c = this.document.forms[0].elements[nome];
   var i = 0;

   if (!c.length)
   {
      if (objeto.checked)
      {
         c.checked = true;
      }
      else
      {
         c.checked = false;
      }
   }
   else
   {
      for (i=0 ; i < c.length; i++){
         if (objeto.checked)
         {
            c[i].checked = true;
         }
         else
         {
            c[i].checked = false;
         }
      }
   }
}

function InvertCheck(cnome)
{
   var c = this.document.forms[0].elements[cnome];
   var i = 0;
   for (i=0 ; i < c.length; i++){
      if (c[i].checked)
      {
         c[i].checked = false;
      }
      else
      {
         c[i].checked = true;
      }
   }
}

function ValidaClassificados(){
   var id = document.forms['form'].elements['id'];
   var titulo = document.forms['form'].elements['titulo'];
   var email = document.forms['form'].elements['email'];
   var anuncio = document.forms['form'].elements['anuncio'];
   var n_dias = document.forms['form'].elements['n_dias'];
   var filial = document.forms['form'].elements['filial'];
   var telefone = document.forms['form'].elements['telefone'];
   var departamento = document.forms['form'].elements['dpto'];
   var nome = document.forms['form'].elements['nome'];

   if (titulo.value == ''){
      alert('Favor informar o título!');
      titulo.focus();
      return false;
   }else if (n_dias.value == '' && id.value == ''){
      alert('Favor informar o nº de dias!');
      n_dias.focus();
      return false;
   }else if (anuncio.value == ''){
      alert('Favor informar o anuncio!');
      anuncio.focus();
      return false;
   }else if (nome.value == ''){
      alert('Favor informar o nome!');
      nome.focus();
      return false;
   }else if (departamento.value == ''){
      alert('Favor informar o departamento!');
      departamento.focus();
      return false;
   }else if (email.value == ''){
      alert('Favor informar o email!');
      email.focus();
      return false;
   }else if (telefone.value == ''){
      alert('Favor informar o telefone!');
      telefone.focus();
      return false;

   }else{
      document.forms[0].submit();
   }
}

function ValidaNoticias(){
   var id = document.FormEditor.elements['id'];
   var titulo = document.FormEditor.elements['titulo'];
   var subtitulo = document.FormEditor.elements['subtitulo'];
   var nro_dia = document.FormEditor.elements['nro_dia'];

   if (titulo.value == ''){
      alert('Favor informar o título!');
      titulo.focus();
      return false;
   }

   if (subtitulo.value == ''){
      alert('Favor informar o subtítulo!');
      subtitulo.focus();
      return false;
   }

   if (nro_dia.value == ''){
      alert('Favor informar o dias!');
      nro_dia.focus();
      return false;
   }
   // Busca o valor para o body da notícia
   set_value();
   if (document.FormEditor.body.value == '')
   {
      alert('Favor informar a notícia!');
      return false;
   }

   document.FormEditor.save.disabled = true;
   document.FormEditor.submit();
}

function CadSenhaInt()
{
   var id_pessoal = document.forms[0].elements['id_pessoal'];
   var chapa_pessoal = document.forms[0].elements['chapa_pessoal'];
   var id_empresa = document.forms[0].elements['id_empresa'];
   var sigla_empresa = document.forms[0].elements['sigla_empresa'];
   var id_filial = document.forms[0].elements['id_filial'];
   var codigo_filial = document.forms[0].elements['codigo_filial'];
   var save = document.forms[0].elements['save'];

   if (id_pessoal.value == '')
   {
      alert('Favor informar a chapa!');
      chapa_pessoal.focus();
      return false;
   }

   if (id_empresa.value == '')
   {
      alert('Favor informar a empresa!');
      sigla_empresa.focus();
      return false;
   }

   if (id_filial.value == '')
   {
      alert('Favor informar a empresa!');
      codigo_filial.focus();
      return false;
   }

   save.value = 1;
   Entrar('salvar','Aguarde..');
}

function EsqSenha()
{
   var usuario = document.forms[0].elements['usuario'];
   var buscar = document.forms[0].elements['buscar'];

   if (usuario.value == '')
   {
      alert('Favor indormar o usuário!');
      usuario.focus();
      return false;
   }

   buscar.value = 1;
   Entrar('pesquisar','Aguarde...');
}

function Carregando()
{
   for (var i=0; i < document.forms[0].elements.length; i++)
   {
      if (document.forms[0].elements[i].type == 'button' ||
         document.forms[0].elements[i].type == 'submit' ||
         document.forms[0].elements[i].type == 'reset')
      {
         if((!document.forms[0].elements[i].disabled &&
            document.forms[0].elements[i].id != '5')
            ||(document.forms[0].elements[i].name.search(/[bt_lupa]/) >= 0))
         {
            document.forms[0].elements[i].disabled = true;
         }
      }
   }
}

function Carregado()
{
   var a = parent;
   for (var i=0; i < a.document.forms[0].elements.length; i++)
   {
      if(a.document.forms[0].elements[i].type == 'button' ||
         a.document.forms[0].elements[i].type == 'submit' ||
         a.document.forms[0].elements[i].type == 'reset')
      {
//         if((win.document.forms[0].elements[i].id != '9') || (win.document.forms[0].elements[i].name.search(/[bt_lupa]/) >= 0))
         if(a.document.forms[0].elements[i].id != '9')
         {
            a.document.forms[0].elements[i].disabled = false;
         }
      }
   }
}

/*function Carregando()
{
   for (var i=0; i < document.forms[0].elements.length; i++)
   {
      if (document.forms[0].elements[i].type == 'button' ||
         document.forms[0].elements[i].type == 'submit' ||
         document.forms[0].elements[i].type == 'reset')
      {
         if (!document.forms[0].elements[i].disabled &&
            document.forms[0].elements[i].id != '5')
         {
            document.forms[0].elements[i].disabled = true;
         }
      }
   }
}

function Carregado()
{
   if (top.opener)
   {
      var v_ret = top.opener.document.forms[0];
   }
   else if (top)
   {
      var v_ret = top.document.forms[0];
   }
   else
   {
      var v_ret = document.forms[0];
   }

   with(v_ret)
   {
      for (var i=0; i < elements.length; i++)
      {
         if (elements[i].type == 'button' ||
             elements[i].type == 'submit' ||
             elements[i].type == 'reset')
         {
            if (elements[i].id != '9') elements[i].disabled = false;
         }
      }
   }
}*/

function LimpaSeeker()
{
   for(var i=0; i < document.forms[0].elements.length; i++)
   {
      if(document.forms[0].elements[i].type == 'button' ||
         document.forms[0].elements[i].type == 'submit' ||
         document.forms[0].elements[i].type == 'reset')
      {
         if(document.forms[0].elements[i].id != '9')
         {
            document.forms[0].elements[i].disabled = false;
         }
      }
   }
}

function CarregadoLupa()
{
   var a = (top.opener.top ? top.opener.top : parent);
   for(var i=0; i < a.document.forms[0].elements.length; i++)
   {
      if(a.document.forms[0].elements[i].type == 'button' ||
         a.document.forms[0].elements[i].type == 'submit' ||
         a.document.forms[0].elements[i].type == 'reset')
      {
         if(a.document.forms[0].elements[i].id != '9')
            a.document.forms[0].elements[i].disabled = false;
      }
   }
}

if (document.domain == 'di.tanet.com.br' || document.domain == 'intranet.tanet.com.br' || document.domain == 'di.talog.com.br' || document.domain == 'intranet.talog.com.br' || document.domain == 'as-intranet.tanet.com.br')
{
   var v_home = 'http://'+ document.domain +'/home/index.php?PHPSESSID'+PHPSESSID;
   var v_logout = 'http://'+ document.domain +'/';
}
else
{
   var v_home = 'http://'+ document.domain +'/sistemas/logon/list_app.php?PHPSESSID'+PHPSESSID;
   var v_logout = 'http://'+ document.domain +'/logon.php';
}

function Home()
{
   if(document.domain == 'di.tanet.com.br' || document.domain == 'intranet.tanet.com.br' || document.domain == 'di.talog.com.br' || document.domain == 'intranet.talog.com.br' || document.domain == 'intranet-teste.tanet.com.br' || document.domain == 'as-intranet.tanet.com.br')
   {
      document.location.href = "http://"+ document.domain +"/home/index.php?PHPSESSID="+PHPSESSID;
   }
   else if(document.location.toString().search(/list_app.php/i) >= 0)
   {
      Logout();
   }
   else
   {
      document.location.href = "http://"+document.domain+"/sistemas/logon/list_app.php?PHPSESSID="+PHPSESSID;
   }
}

function Logout()
{
   document.location.href = "http://"+document.domain;
}

function AbrePDF()
{
   AbreJanela('../../libext/report/call_report_pdf.php',500,500,'Performace');
}

function OpenExcel()
{
   AbreJanela('../../libext/report/call_excel.php',500,500,'Performace');
}

/*function KillSession(sid,serial)
{
   var str;
   str = "?sid=" + sid;
   str = str + "&serial=" + serial;
   AbreJanela("http://di.tanet.com.br/libext/monitor/kill.php" + str,1,1,'Kill');
}*/

function BuscaEndereco(p_id)
{
   alert(p_id);
   win.document.location.href = "../../sistemas/dep_comprovantes/dDevCanhoto.php?id=" + p_id + "&PHPSESSID="+PHPSESSID;
}


function lista_cliente(name_object,p_show_msg)
{
   var id = get_field('id_' + name_object);
   var cnpj = get_field('cnpj_' + name_object);

   if(id.value == '')
   {
      alert('Favor informar o cliente!');
      cnpj.focus();
      return false;
   }

   var razao_social = get_field('razao_social_' + name_object);

   var id_lista = get_field('id_lista_' + name_object +'[]');
   var cnpj_lista = get_field('cnpj_lista_' + name_object+'[]');
   var razao_social_lista = get_field('razao_social_lista_' + name_object+'[]');

   var str_html = null;

   str_html = '<table width="530" border="0" cellspacing="0" cellpadding="0">';
   str_html = str_html + '<tr>';
   str_html = str_html + '<td width="32%" class=caixa_titulo>';
   str_html = str_html + 'CNPJ';
   str_html = str_html + '</td>';
   str_html = str_html + '<td width="58%" class=caixa_titulo>';
   str_html = str_html + 'Nome';
   str_html = str_html + '</td>';
   str_html = str_html + '<td width="10%" class=caixa_titulo>';
   str_html = str_html + 'Excluir';
   str_html = str_html + '</td>';
   str_html = str_html + '</tr>';

   //alert(id_lista.length);

   if(!id_lista.length)
   {
      str_html = str_html + '<tr>';
      str_html = str_html + '<td width="32%" class=caixa_resultado>';
      str_html = str_html + '<input type="hidden" name="id_lista_' + name_object + '[]" value="'+ id.value +'">';
      str_html = str_html + '<input type="hidden" name="cnpj_lista_' + name_object + '[]" value="'+ cnpj.value +'">';
      str_html = str_html + '<input type="hidden" name="razao_social_lista_' + name_object + '[]" value="'+ razao_social.value +'">';
      str_html = str_html + cnpj.value;
      str_html = str_html + '</td>';
      str_html = str_html + '<td width="58%" class=caixa_resultado>';
      str_html = str_html + razao_social.value;
      str_html = str_html + '</td>';
      str_html = str_html + '<td width="10%" class=caixa_resultado>';
      str_html = str_html + '<div align="center">';
      str_html = str_html + '<a href="javascript:ex_lista_cliente(\''+name_object+'\','+id.value+');">';
      str_html = str_html + '<img src="../../libext/images/excluir1.gif" width="14" height="15" border="0">';
      str_html = str_html + '</a>';
      str_html = str_html + '</div>';
      str_html = str_html + '</td>';
      str_html = str_html + '</tr>';
   }
   else
   {
      var achou = false;
      for (var i=0; i < id_lista.length-1; i++)
      {
         //alert(razao_social_lista[i].value);
         str_html = str_html + '<tr>';
         str_html = str_html + '<td width="32%" class=caixa_resultado>';
         str_html = str_html + '<input type="hidden" name="id_lista_' + name_object + '[]" value="'+ id_lista[i].value +'">';
         str_html = str_html + '<input type="hidden" name="cnpj_lista_' + name_object + '[]" value="'+ cnpj_lista[i].value +'">';
         str_html = str_html + '<input type="hidden" name="razao_social_lista_' + name_object + '[]" value="'+ razao_social_lista[i].value +'">';
         str_html = str_html + cnpj_lista[i].value;
         str_html = str_html + '</td>';
         str_html = str_html + '<td width="58%" class=caixa_resultado>';
         str_html = str_html + razao_social_lista[i].value;
         str_html = str_html + '</td>';
         str_html = str_html + '<td width="10%" class=caixa_resultado>';
         str_html = str_html + '<div align="center">';
         str_html = str_html + '<a href="javascript:ex_lista_cliente(\''+name_object+'\','+id_lista[i].value+');">';
         str_html = str_html + '<img src="../../libext/images/excluir1.gif" width="14" height="15" border="0">';
         str_html = str_html + '</a>';
         str_html = str_html + '</div>';
         str_html = str_html + '</td>';
         str_html = str_html + '</tr>';
         if (id.value == id_lista[i].value)
         {
            achou = true;
         }
      }

      if (!achou)
      {
         str_html = str_html + '<tr>';
         str_html = str_html + '<td width="32%" class=caixa_resultado>';
         str_html = str_html + '<input type="hidden" name="id_lista_' + name_object + '[]" value="'+ id.value +'">';
         str_html = str_html + '<input type="hidden" name="cnpj_lista_' + name_object + '[]" value="'+ cnpj.value +'">';
         str_html = str_html + '<input type="hidden" name="razao_social_lista_' + name_object + '[]" value="'+ razao_social.value +'">';
         str_html = str_html + cnpj.value;
         str_html = str_html + '</td>';
         str_html = str_html + '<td width="58%" class=caixa_resultado>';
         str_html = str_html + razao_social.value;
         str_html = str_html + '</td>';
         str_html = str_html + '<td width="10%" class=caixa_resultado>';
         str_html = str_html + '<div align="center">';
         str_html = str_html + '<a href="javascript:ex_lista_cliente(\''+name_object+'\','+id.value+');">';
         str_html = str_html + '<img src="../../libext/images/excluir1.gif" width="14" height="15" border="0">';
         str_html = str_html + '</a>';
         str_html = str_html + '</div>';
         str_html = str_html + '</td>'
         str_html = str_html + '</tr>';
      }
      else
      {
         if (p_show_msg)
         {
            alert('Registro já está inserido!');
         }
      }
   }
   str_html = str_html + '</table>';
   imp_html_div(str_html,'div_lista_' + name_object);
   return true;
}

function ex_lista_cliente(name_object,id_valor)
{
   var id_lista = get_field('id_lista_' + name_object +'[]');
   var cnpj_lista = get_field('cnpj_lista_' + name_object+'[]');
   var razao_social_lista = get_field('razao_social_lista_' + name_object+'[]');

   str_html = '<table width="530" border="0" cellspacing="0" cellpadding="0">';
   str_html = str_html + '<tr>';
   str_html = str_html + '<td width="32%" class=caixa_titulo>';
   str_html = str_html + 'CNPJ';
   str_html = str_html + '</td>';
   str_html = str_html + '<td width="58%" class=caixa_titulo>';
   str_html = str_html + 'Nome';
   str_html = str_html + '</td>';
   str_html = str_html + '<td width="10%" class=caixa_titulo>';
   str_html = str_html + 'Excluir';
   str_html = str_html + '</td>';
   str_html = str_html + '</tr>';


   var nao_passei = true;
   for (var i=0; i < id_lista.length-1; i++)
   {
      if (id_valor != id_lista[i].value)
      {
         str_html = str_html + '<tr>';
         str_html = str_html + '<td width="32%" class=caixa_resultado>';
         str_html = str_html + '<input type="hidden" name="id_lista_' + name_object + '[]" value="'+ id_lista[i].value +'">';
         str_html = str_html + '<input type="hidden" name="cnpj_lista_' + name_object + '[]" value="'+ cnpj_lista[i].value +'">';
         str_html = str_html + '<input type="hidden" name="razao_social_lista_' + name_object + '[]" value="'+ razao_social_lista[i].value +'">';
         str_html = str_html + cnpj_lista[i].value;
         str_html = str_html + '</td>';
         str_html = str_html + '<td width="58%" class=caixa_resultado>';
         str_html = str_html + razao_social_lista[i].value;
         str_html = str_html + '</td>';
         str_html = str_html + '<td width="10%" class=caixa_resultado>';
         str_html = str_html + '<div align="center">';
         str_html = str_html + '<a href="javascript:ex_lista_cliente(\''+name_object+'\','+id_lista[i].value+');">';
         str_html = str_html + '<img src="../../libext/images/excluir1.gif" width="14" height="15" border="0">';
         str_html = str_html + '</a>';
         str_html = str_html + '</div>';
         str_html = str_html + '</td>'
         str_html = str_html + '</tr>';
         nao_passei = false;
      }

   }

   if (nao_passei)
   {
      str_html = '';
   }

   str_html = str_html + '</table>';
   imp_html_div(str_html,'div_lista_' + name_object);
}



function ValidaEmail(obj)
{
   var ER = /^([\w+\.\-])+\@(([a-zA-Z\d+\-])+\.)+([a-zA-Z\d+]{2,6})+$/;
   if(!ER.test(obj.value) && (obj.value != ''))
   {
      alert('E-Mail inválido!');
      obj.focus();
      return false;
   }
   return true;
}


//DANIEL SAMBINELLI
//VALIDA CPF
function ValidaCpf(cpf)
{
   var i;
   var c = cpf.substr(0,9);
   var dv = cpf.substr(9,2);
   var d1 = 0;

   for (i = 0; i < 9; i++)
   {
      d1 += c.charAt(i)*(10-i);
   }
      if (d1 == 0){
          return false;
      }
   d1 = 11 - (d1 % 11);

   if (d1 > 9) d1 = 0;

   if (dv.charAt(0) != d1)
   {
      return false;
   }

   d1 *= 2;
   for (i = 0; i < 9; i++)
   {
      d1 += c.charAt(i)*(11-i);
   }
   d1 = 11 - (d1 % 11);
   if (d1 > 9) d1 = 0;
   if (dv.charAt(1) != d1)
   {
      return false;
   }
   return true;
}


function submit_page(p_nro_page,p_qtd_record)
{
   var nro_page = get_field('nro_page');
   var qtd_record = get_field('qtd_record');
   nro_page.value = p_nro_page;
   qtd_record.value = p_qtd_record;
   if(clear != undefined)
      clear = 0;
   document.forms[0].submit();
}

// Usada no seeker de busca de característica
function CallAddCaracteristica()
{
   var id_contrato_cliente = document.forms[0].elements['id_contrato_cliente'].value;
   window.open("../../../libext/seeker/caract_docto_fiscal.php?id_contrato=" + id_contrato_cliente,'topo','top=0,left=0width=580,height=325,scrollbars=yes');
}

function CallDeleteCaracteristica()
{
   document.forms[0].elements['id_caract_docto_fiscal'].value = '';
   document.forms[0].elements['descr_caract_docto_fiscal'].value = '';
}

function CarregaCaracteristica(id,descricao)
{
   var a = (top.opener ? top.opener : top);
   a.document.forms[0].elements['id_caract_docto_fiscal'].value = id;
   a.document.forms[0].elements['descr_caract_docto_fiscal'].value = descricao;
   top.close();
}

// function disable_uf() --> usada no relatório de simulação de frete
function disable_uf(nome)
{
   a = top.opener ? top.opener : top;

   a.document.forms[0].elements['uf_orig'].value = (a.document.forms[0].elements['id_uf_cid_orig'].value != '') ? a.document.forms[0].elements['id_uf_cid_orig'].value : "";
   a.document.forms[0].elements['uf_orig'].style.background = (a.document.forms[0].elements['id_uf_cid_orig'].value != '') ? "#EEEEEE" : "#ffffff";
   a.document.forms[0].elements['uf_orig'].disabled = (a.document.forms[0].elements['id_uf_cid_orig'].value != '') ? true : false;

   a.document.forms[0].elements['uf_dest'].value = (a.document.forms[0].elements['id_uf_cid_dest'].value != '') ? a.document.forms[0].elements['id_uf_cid_dest'].value : "";
   a.document.forms[0].elements['uf_dest'].style.background = (a.document.forms[0].elements['id_uf_cid_dest'].value != '') ? "#EEEEEE" : "#ffffff";
   a.document.forms[0].elements['uf_dest'].disabled = (a.document.forms[0].elements['id_uf_cid_dest'].value != '') ? true : false;
}
//Eduardo Deixa ComboboxEditalvel.
  /*----------------------------------------------
  The Common function used for all dropdowns are:
  -----------------------------------------------
  -- function fnKeyDownHandler(getdropdown, e)
  -- function fnLeftToRight(getdropdown)
  -- function fnRightToLeft(getdropdown)
  -- function fnDelete(getdropdown)
  -- function FindKeyCode(e)
  -- function FindKeyChar(e)
  -- function fnSanityCheck(getdropdown)

  --------------------------- Subrata Chakrabarty */

  function fnKeyDownHandler(getdropdown, e)
  {
    fnSanityCheck(getdropdown);

    var vEventKeyCode = FindKeyCode(e);

    // Press left/right arrow keys
    if(vEventKeyCode == 37)
    {
    fnLeftToRight(getdropdown);
    }
    if(vEventKeyCode == 39)
    {
    fnRightToLeft(getdropdown);
    }

    // Delete key pressed
    if(vEventKeyCode == 46)
    {
    fnDelete(getdropdown);
    }

    // backspace key pressed
    if(vEventKeyCode == 8 || vEventKeyCode==127)
    {
    if(e.which) //Netscape
    {
      //e.which = ''; //this property has only a getter.
    }
    else //Internet Explorer
    {
      //To prevent backspace from activating the -Back- button of the browser
      e.keyCode = '';
      if(window.event.keyCode)
      {
      window.event.keyCode = '';
      }
    }
    return true;
    }
  }

  function fnLeftToRight(getdropdown)
  {
    getdropdown.style.direction = "ltr";
  }

  function fnRightToLeft(getdropdown)
  {
    getdropdown.style.direction = "rtl";
  }

  function fnDelete(getdropdown)
  {
    if(getdropdown.options.length != 0)    // if dropdown is not empty
    {
    if (getdropdown.options.selectedIndex == vEditableOptionIndex_A)    // if option the Editable field
    {
      getdropdown.options[getdropdown.options.selectedIndex].text = '';
      getdropdown.options[getdropdown.options.selectedIndex].value = '';
    }
    }
  }

  function FindKeyCode(e)
  {
    if(e.which)
    {
    keycode=e.which;  //Netscape
    }
    else
    {
    keycode=e.keyCode; //Internet Explorer
    }

    //alert("FindKeyCode"+ keycode);
    return keycode;
  }

  function FindKeyChar(e)
  {
    keycode = FindKeyCode(e);
    if((keycode==8)||(keycode==127))
    {
    character="backspace"
    }
    else if((keycode==46))
    {
    character="delete"
    }
    else
    {
    character=String.fromCharCode(keycode);
    }
    //alert("FindKey"+ character);
    return character;
  }

  function fnSanityCheck(getdropdown)
  {
    if(vEditableOptionIndex_A>(getdropdown.options.length-1))
    {
    alert("PROGRAMMING ERROR: The value of variable vEditableOptionIndex_... cannot be greater than (length of dropdown - 1)");
    return false;
    }
  }

  /*----------------------------------------------
  Dropdown specific global variables are:
  -----------------------------------------------
  1) vEditableOptionIndex_A   --> this needs to be set by Programmer!! See explanation.
  2) vEditableOptionText_A    --> this needs to be set by Programmer!! See explanation.
  3) vPreviousSelectIndex_A
  4) vSelectIndex_A
  5) vSelectChange_A

  --------------------------- Subrata Chakrabarty */

  /*----------------------------------------------
  The dropdown specific functions
  (which manipulate dropdown specific global variables)
  used by all dropdowns are:
  -----------------------------------------------
  1) function fnChangeHandler_A(getdropdown)
  2) function fnKeyPressHandler_A(getdropdown, e)
  3) function fnKeyUpHandler_A(getdropdown, e)

  --------------------------- Subrata Chakrabarty */

  /*------------------------------------------------
  IMPORTANT: Global Variable required to be SET by programmer
  -------------------------- Subrata Chakrabarty  */

  var vEditableOptionIndex_A = 0;

  // Give Index of Editable option in the dropdown.
  // For eg.
  // if first option is editable then vEditableOptionIndex_A = 0;
  // if second option is editable then vEditableOptionIndex_A = 1;
  // if third option is editable then vEditableOptionIndex_A = 2;
  // if last option is editable then vEditableOptionIndex_A = (length of dropdown - 1).
  // Note: the value of vEditableOptionIndex_A cannot be greater than (length of dropdown - 1)

  var vEditableOptionText_A = "--?--";

  // Give the default text of the Editable option in the dropdown.
  // For eg.
  // if the editable option is <option ...>--?--</option>,
  // then set vEditableOptionText_A = "--?--";

  /*------------------------------------------------
  Global Variables required for
  fnChangeHandler_A(), fnKeyPressHandler_A() and fnKeyUpHandler_A()
  for Editable Dropdowns
  -------------------------- Subrata Chakrabarty  */

  var vPreviousSelectIndex_A = 0;
  // Contains the Previously Selected Index, set to 0 by default

  var vSelectIndex_A = 0;
  // Contains the Currently Selected Index, set to 0 by default

  var vSelectChange_A = 'MANUAL_CLICK';
  // Indicates whether Change in dropdown selected option
  // was due to a Manual Click
  // or due to System properties of dropdown.

  // vSelectChange_A = 'MANUAL_CLICK' indicates that
  // the jump to a non-editable option in the dropdown was due
  // to a Manual click (i.e.,changed on purpose by user).

  // vSelectChange_A = 'AUTO_SYSTEM' indicates that
  // the jump to a non-editable option was due to System properties of dropdown
  // (i.e.,user did not change the option in the dropdown;
  // instead an automatic jump happened due to inbuilt
  // dropdown properties of browser on typing of a character )

  /*------------------------------------------------
  Functions required for  Editable Dropdowns
  -------------------------- Subrata Chakrabarty  */

  function fnChangeHandler_A(getdropdown)
  {
    fnSanityCheck(getdropdown);

    vPreviousSelectIndex_A = vSelectIndex_A;
    // Contains the Previously Selected Index

    vSelectIndex_A = getdropdown.options.selectedIndex;
    // Contains the Currently Selected Index

    if ((vPreviousSelectIndex_A == (vEditableOptionIndex_A)) && (vSelectIndex_A != (vEditableOptionIndex_A))&&(vSelectChange_A != 'MANUAL_CLICK'))
    // To Set value of Index variables - Subrata Chakrabarty
    {
      getdropdown[(vEditableOptionIndex_A)].selected=true;
      vPreviousSelectIndex_A = vSelectIndex_A;
      vSelectIndex_A = getdropdown.options.selectedIndex;
      vSelectChange_A = 'MANUAL_CLICK';
      // Indicates that the Change in dropdown selected
      // option was due to a Manual Click
    }
  }

  function fnKeyPressHandler_A(getdropdown, e)
  {
    fnSanityCheck(getdropdown);

    keycode = FindKeyCode(e);
    keychar = FindKeyChar(e);

    // Check for allowable Characters
    // The various characters allowable for entry into Editable option..
    // may be customized by minor modifications in the code (if condition below)
    // (you need to know the keycode/ASCII value of the  character to be allowed/disallowed.
    // - Subrata Chakrabarty

    if ((keycode>47 && keycode<59)||(keycode>62 && keycode<127) ||(keycode==32))
    {
      var vAllowableCharacter = "yes";
    }
    else
    {
      var vAllowableCharacter = "no";
    }

    //alert(window); alert(window.event);

    if(getdropdown.options.length != 0)
    // if dropdown is not empty
      if (getdropdown.options.selectedIndex == (vEditableOptionIndex_A))
      // if selected option the Editable option of the dropdown
      {

        var vEditString = getdropdown[vEditableOptionIndex_A].value;

        // make Editable option Null if it is being edited for the first time
        if((vAllowableCharacter == "yes")||(keychar=="backspace"))
        {
          if (vEditString == vEditableOptionText_A)
            vEditString = "";
        }
        if (keychar=="backspace")
        // To handle backspace - Subrata Chakrabarty
        {
          vEditString = vEditString.substring(0,vEditString.length-1);
          // Decrease length of string by one from right

          vSelectChange_A = 'MANUAL_CLICK';
          // Indicates that the Change in dropdown selected
          // option was due to a Manual Click

        }
        //alert("EditString2:"+vEditString);

        if (vAllowableCharacter == "yes")
        // To handle addition of a character - Subrata Chakrabarty
        {
          vEditString+=String.fromCharCode(keycode);
          // Concatenate Enter character to Editable string

          // The following portion handles the "automatic Jump" bug
          // The "automatic Jump" bug (Description):
          //   If a alphabet is entered (while editing)
          //   ...which is contained as a first character in one of the read-only options
          //   ..the focus automatically "jumps" to the read-only option
          //   (-- this is a common property of normal dropdowns
          //    ..but..is undesirable while editing).

          var i=0;
          var vEnteredChar = String.fromCharCode(keycode);
          var vUpperCaseEnteredChar = vEnteredChar;
          var vLowerCaseEnteredChar = vEnteredChar;


          if(((keycode)>=97)&&((keycode)<=122))
          // if vEnteredChar lowercase
            vUpperCaseEnteredChar = String.fromCharCode(keycode - 32);
            // This is UpperCase


          if(((keycode)>=65)&&((keycode)<=90))
          // if vEnteredChar is UpperCase
            vLowerCaseEnteredChar = String.fromCharCode(keycode + 32);
            // This is lowercase

          if(e.which) //For Netscape
          {
            // Compare the typed character (into the editable option)
            // with the first character of all the other
            // options (non-editable).

            // To note if the jump to the non-editable option was due
            // to a Manual click (i.e.,changed on purpose by user)
            // or due to System properties of dropdown
            // (i.e.,user did not change the option in the dropdown;
            // instead an automatic jump happened due to inbuilt
            // dropdown properties of browser on typing of a character )

            for (i=0;i<=(getdropdown.options.length-1);i++)
            {
              if(i!=vEditableOptionIndex_A)
              {
                var vReadOnlyString = getdropdown[i].value;
                var vFirstChar = vReadOnlyString.substring(0,1);
                if((vFirstChar == vUpperCaseEnteredChar)||(vFirstChar == vLowerCaseEnteredChar))
                {
                  vSelectChange_A = 'AUTO_SYSTEM';
                  // Indicates that the Change in dropdown selected
                  // option was due to System properties of dropdown
                  break;
                }
                else
                {
                  vSelectChange_A = 'MANUAL_CLICK';
                  // Indicates that the Change in dropdown selected
                  // option was due to a Manual Click
                }
              }
            }
          }
        }

        // Set the new edited string into the Editable option
        getdropdown.options[vEditableOptionIndex_A].text = vEditString;
        getdropdown.options[vEditableOptionIndex_A].value = vEditString;

        return false;
      }
    return true;
  }

  function fnKeyUpHandler_A(getdropdown, e)
  {
    fnSanityCheck(getdropdown);

    if(e.which) // Netscape
    {
      if(vSelectChange_A == 'AUTO_SYSTEM')
      {
        // if editable dropdown option jumped while editing
        // (due to typing of a character which is the first character of some other option)
        // then go back to the editable option.
        getdropdown[(vEditableOptionIndex_A)].selected=true;
      }

      var vEventKeyCode = FindKeyCode(e);
      // if [ <- ] or [ -> ] arrow keys are pressed, select the editable option
      if((vEventKeyCode == 37)||(vEventKeyCode == 39))
      {
        getdropdown[vEditableOptionIndex_A].selected=true;
      }
    }
  }
  
  function findPos(obj) {
      var curleft = curtop = 0;
      if (obj.offsetParent) {
         do {
               curleft+= obj.offsetLeft;
               curtop+= obj.offsetTop;
         } while (obj = obj.offsetParent);         
      }
      var vCorr = [];
      vCorr['left'] = curleft;
      vCorr['top'] = curtop;
      return vCorr;
   }

  
function DateDiff(p_date_one, p_date_two) {
	var diff = new Date();
	diff.setTime(Math.abs(p_date_one.getTime() - p_date_two.getTime()));
	
	timediff = diff.getTime();
	
	weeks = Math.floor(timediff / (1000 * 60 * 60 * 24 * 7));
	timediff -= weeks * (1000 * 60 * 60 * 24 * 7);
	
	days = Math.floor(timediff / (1000 * 60 * 60 * 24)); 
	timediff -= days * (1000 * 60 * 60 * 24);
	
	hours = Math.floor(timediff / (1000 * 60 * 60)); 
	timediff -= hours * (1000 * 60 * 60);
	
	mins = Math.floor(timediff / (1000 * 60)); 
	timediff -= mins * (1000 * 60);
	
	secs = Math.floor(timediff / 1000); 
	timediff -= secs * 1000;
	  
	var vResult = [];
	vResult['weeks'] = weeks;
	vResult['days'] = days;
	vResult['hours'] = hours;
	vResult['mins'] = mins;
	vResult['secs'] = secs;
	return vResult; 
}

function sleep(naptime) {
  naptime = naptime * 1000;
  var sleeping = true;
  var now = new Date();
  var alarm;
  var startingMSeconds = now.getTime();

  while(sleeping){
	 alarm = new Date();
	 alarmMSeconds = alarm.getTime();
	 if(alarmMSeconds - startingMSeconds > naptime){ 
		sleeping = false; 
	}
  }
}
/*-------------------------------------------------------------------------------------------- Subrata Chakrabarty */

/**
 * 
 * @author rsantos
 * @chamado 55107
 * @date 03/12/2009
 * 
 */
function ShowHide_Versao(p_obj, p_id_controle_versao, p_id_usuario){
	var v_tr = jQuery('#tr_' + p_id_controle_versao);
	if (v_tr.css('display') == 'none'){
		jQuery.blockUI('<br><h3><img src="../../libext/images/busy.gif" /> Aguarde...</h3>');
	
		jQuery.ajax({
           type: 'POST',
           url: '../../libext/versao.php',
           data: 'action=detalhe&id_controle_versao='+p_id_controle_versao+'&id_usuario=' + p_id_usuario,
           success: function(p_html){
              var v_td = jQuery('#td_'+p_id_controle_versao);
              var v_div = jQuery('#div_'+p_id_controle_versao);
              
              jQuery.unblockUI();
              
              v_div.html(p_html);
              jQuery(p_obj).attr('class','IcoMinus');
              v_tr.show();
              v_div.slideDown('slow');
           }
        });
	}else{
		jQuery('#div_'+p_id_controle_versao).slideUp('slow', function(){
			v_tr.hide();
			jQuery(p_obj).attr('class','IcoMore');
		});
	}
}