/**
*  
*
*  Copyright (c) 2004-2008 by Perkus Zapf - PZM Empreendimentos  <perkus@4atecnologia.com.br>
*   http://www.4atecnologia.com.br 
  
*  Checkout AUTHORS file for more information on the developers
*
*  This library is free software; you can redistribute it and/or
*  modify it under the terms of the GNU Lesser General Public
*  License as published by the Free Software Foundation; either
*  version 2.1 of the License, or (at your option) any later version.
*
*  This library is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*  Lesser General Public License for more details.
*
*  You should have received a copy of the GNU Lesser General Public
*  License along with this library; if not, write to the Free Software
*  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
*  USA
*
*/
//**************************Funcoes Ajax********************************************
var aguardando = false;	// indica se há uma consulta em processamento

var CbId;//Variavel global para o objeto de retorno text de ajax.

//Trata aresposta para get text - retorno de string
function GetRetTextAjx(){
	if(ajax.readyState == 4){
		if(ajax.status == 200){ // trata a resposta do servidor
			var resposta = ajax.responseText;
			Aviso(false);
			AjaxShowDadosTextDIV(resposta);
		} else {
			alert("Problema na comunicação com o objeto XMLHttpRequest.");
		}
	}
}

//Trata aresposta para get edit
function GetRetEditAjx(){
	if(ajax.readyState == 4){
		if(ajax.status == 200){ // trata a resposta do servidor
			var resposta = ajax.responseXML;
			Aviso(false);
			AjaxShowDadosEdit(resposta);
		} else {
			alert("Problema na comunicação com o objeto XMLHttpRequest.");
		}
	}
}

// ------- Trata a resposta do servidor para os DBComboBox-------
function trataResposta(){
	if(ajax.readyState == 4){
		if(ajax.status == 200){ // trata a resposta do servidor
			var resposta = ajax.responseXML;
			Aviso(false);
			AjaxShowDados(resposta);
		} else {
			alert("Problema na comunicação com o objeto XMLHttpRequest.");
		}
	}
}

// cria a lista de sugestões na tabela HTML
function AjaxShowDados(dados) {
	
	var dataArray = dados.getElementsByTagName("selecao");

	if(dataArray.length-1 > 0) {
		for(var i=1; i<dataArray.length; i++) {
		   var item = dataArray[i];
		
			var codigo    =  item.getElementsByTagName("cod")[0].firstChild.nodeValue;
			var descricao =  item.getElementsByTagName("nome")[0].firstChild.nodeValue;
		    var ctid      =  item.getElementsByTagName("ctid")[0].firstChild.nodeValue;

			//cria um novo option dinamicamente  
			var novo = document.createElement("option");
			    //atribui um ID a esse elemento
			    novo.setAttribute("id", "opcoes");
				//atribui um valor
			    novo.value = codigo;
				//atribui um texto
			    novo.text  = descricao;
				//finalmente adiciona o novo elemento
 			   if (codigo == CbId) {novo.selected = true;};
			   
           eval('document.frmDados.'+ctid+'.options.add(novo)');

		}
//		document.frmDados.SOC_DCOMP.value = CbId;
	}else {
		   var item = dataArray[0];
		
			var codigo    =  item.getElementsByTagName("cod")[0].firstChild.nodeValue;
			var descricao =  item.getElementsByTagName("nome")[0].firstChild.nodeValue;
		    var ctid      =  item.getElementsByTagName("ctid")[0].firstChild.nodeValue;		
	};
if (CbId == null) eval('O_'+ctid+'.innerHTML = "Todos os Itens"');  

}

// Mostra Resultado XML
function AjaxShowDadosEdit(dados) {
	
	var dataArray = dados.getElementsByTagName("selecao");

 	    var item = dataArray[0];
		var descricao=  item.getElementsByTagName("nome")[0].firstChild.nodeValue;
		var ctid     =  item.getElementsByTagName("ctid")[0].firstChild.nodeValue;		

  eval('document.frmDados.'+ctid+'.value = '+"'"+descricao+"'");  
};

// Mostra Resultado Text
function AjaxShowDadosTextDIV(dados) {
  eval(CbId+'.innerHTML = '+"'"+dados+"'");  
};


// exibe ou oculta o aviso "Processando..."
function Aviso(exibir) {
	aguardando = exibir;
	var aviso =  document.getElementById('aviso'); 
	if(exibir)
		aviso.style.visibility='visible';
	else
		aviso.style.visibility='hidden';
		
}

//*********************************End Ajax Functions*************************************************

function Enviar()
{
	document.frmDados.submit();
};

function Gerar()
{
 	document.frmDados.GERAR.value = 1;
	document.frmDados.submit();
};

function IMG_BTN(IB)
{
  document.frmDados.IMG_BTN.value = IB;
  document.frmDados.submit();
};


function ShowHideDropDown(Visivel)
{
	var Tipo;
	var Valor = Visivel ? '' : 'none';
	var Obj = new Enumerator(window.document.all);	
	
	for(;!Obj.atEnd();Obj.moveNext())
	{
		Tipo = Obj.item().type + '';			
		if(Tipo.substr(0,6) == "select") Obj.item().style.display = Valor;
	};
};

    function ColoriBack(quem,cor)
    {
        quem.style.backgroundColor = cor;
    };
    
	function MostraMenu(Menu,Complemento,sub,qualsub)
	{
	    
	    if (Complemento != 0)
	      {
			Menu.style.display = "Block";
			Complemento.style.display = "Block";
	      }
	    else
	      {
			Menu.style.display = "Block";  
	      };
	    if (sub == 1)
	    {
	        qualsub.style.display = "Block";
	    };
	};
	
	function EscondeMenu(Menu,Complemento,sub,qualsub)
	{
		if (Complemento != 0)
			{
				Menu.style.display = "None";
				Complemento.style.display = "None";
			}
		else
		    {
		    	Menu.style.display = "None";
		    };
		if (sub == 1)
		{
		    qualsub.style.display = "None";
		};
	};

	function esconde_Sub(Menu_Pai,descolori,Menu_Filho)
	{
	   ColoriBack(descolori,'#EFEFEF');
	   Menu_Pai.style.display = 'none';
	   Menu_Filho.style.display = 'none';
	};
	
	
	
// JavaScript Document
function _ResetForm()
{
  document.frmDados.reset;
};

function LayShow(NOME)
{
  //parent.mainBottom['GuiaBtn'].src="imagens/guiabtnativ.gif"; 
  parent.mainFrame[NOME].style.visibility="visible";
};

function LayHide(NOME)
{
  //parent.mainBottom['GuiaBtn'].src="imagens/guiabtn.gif";
  parent.mainFrame[NOME].style.visibility="hidden";
};

function _fDef()
{
 //Rotina default para Propriedades de Evento nulos
};
//Fecha a janela do browser.
function PZM_CLOSE_WINDOW()
{
     //window.alert("Obrigado por utilizar xxxx.");
	 window.close();   
};
   
//Mostra a Data e Hora no Controle <pendule>
function ShowHora(){
 if (!document.layers&&!document.all)
 return
 var Digital=new Date()
 var hours=Digital.getHours()
 var minutes=Digital.getMinutes()
 var seconds=Digital.getSeconds()
 if (hours==0)
 hours=12
 if (minutes<=9)
 minutes="0"+minutes
 if (seconds<=9)
 seconds="0"+seconds

lheure="<font color=white> Hora: "+hours+":"+minutes+":"
 +seconds+"</font>"
if (document.layers){
document.layers.pendule.document.write(lheure)
document.layers.pendule.document.close()
}
else if (document.all)
pendule.innerHTML=lheure
setTimeout("ShowHora()",1000)
}

function login(){
	if (Consistir()){
		document.frmLogin.Evento.value = 1;
		document.frmLogin.submit();
	};
};

function Consistir(){
	if(document.frmLogin.txtLogin.value == '')
	{
		alert("Informe sua Matricula");
		document.frmLogin.txtLogin.select();
		return false;
	};

	if(document.frmLogin.txtSenha.value == '')
	{
		alert("Informe sua Senha");
		document.frmLogin.txtSenha.select();
		return false;
	};
	
	return true;	
};

function txtSenha_onkeypress(){
	if(window.event.keyCode == 13) 
		login();		
}

function OpenPopupForm(ParentObj, Page)
{
   window.open(Page, ParentObj, 'HEIGHT=560, WIDTH=770,toolbars=0,scrollbars=1,status=0, resizable=1')   
};

function PesquisaDef(ParentObj, Page)
{
   window.open(Page, 'SubDef', 'HEIGHT=560, WIDTH=770,toolbars=0,scrollbars=1,status=0, resizable=1')   
};

function PesquisaEmp(ParentObj, Page)
{
   window.open(Page+document.frmDados.ORG_ID.value, ParentObj, 'HEIGHT=525, WIDTH=750,toolbars=0,scrollbars=1,resizable=1')   
};

function PesquisaDiv(ParentObj, Page)
{
   window.open(Page+document.frmDados.ORG_ID.value+'&EMP_ID='+document.frmDados.EMP_ID.value, ParentObj, 'HEIGHT=525, WIDTH=750,toolbars=0,scrollbars=1,resizable=1')   
};

function PesquisaOED(ParentObj, Page, NV)
{
  if (NV == '0') 
  { window.open(Page+'&ORG_ID='+document.frmDados.ORG_ID.value+'&EMP_ID='+document.frmDados.EMP_ID.value+'&DIV_ID='+document.frmDados.EMP_ID.value, ParentObj, 'HEIGHT=525, WIDTH=750,toolbars=0,scrollbars=1,resizable=1');}
  else if (NV == '1') 
  { window.open(Page+'&EMP_ID='+document.frmDados.EMP_ID.value+'&DIV_ID='+document.frmDados.EMP_ID.value, ParentObj, 'HEIGHT=525, WIDTH=750,toolbars=0,scrollbars=1,resizable=1');}
  else if (NV == '2') 
  { window.open(Page+'&DIV_ID='+document.frmDados.EMP_ID.value, ParentObj, 'HEIGHT=525, WIDTH=750,toolbars=0,scrollbars=1,resizable=1');}
  else if (NV == '3') 
  { window.open(Page, ParentObj, 'HEIGHT=525, WIDTH=750,toolbars=0,scrollbars=1,resizable=1');};    
};

function ExportarOrg(ID, NOME)
{
  window.opener.frmDados['ORG_ID'].value = ID;
  window.opener.frmDados['ORG_DSC_BR'].value = NOME;
  self.close();
};

function ExportarEmpresa(ID, NOME)
{
  window.opener.frmDados['EMP_ID'].value = ID;
  window.opener.frmDados['EMP_DSC_BR'].value = NOME;
  self.close();
};
function ExportarDiv(ID, NOME)
{
  window.opener.frmDados['DIV_ID'].value = ID;
  window.opener.frmDados['DIV_DSC_BR'].value = NOME;
  self.close();
};
function ExportarAno(ID)
{
  window.opener.frmDados['CTRL_ANO'].value = ID;
  self.close();
};
function ExportarMes(ID, NOME, ANO)
{
  window.opener.frmDados['MES_ID'].value   = ID;
  window.opener.frmDados['MES_COD'].value  = NOME;
  window.opener.frmDados['CTRL_ANO'].value = ANO;
  self.close();
};

function ExportarUsu(ID, LOGIN, NOME)
{
  window.opener.frmDados['USU_ID'].value = ID;
  window.opener.frmDados['USU_LOGIN'].value = LOGIN;  
  window.opener.frmDados['USU_NOME'].value = NOME;
  
  self.close();
};

function ExportarPais(ID, NOME)
{
  window.opener.frmDados['PAI_ID'].value = ID;
  window.opener.frmDados['PAI_DESC'].value = NOME;  
  
  self.close();
};

function ExportarUf(ID, NOME, PAIS)
{
  window.opener.frmDados['UF_ID'].value = ID;
  window.opener.frmDados['UF_DESC'].value = NOME;  
  window.opener.frmDados['PAI_ID'].value = PAIS;    
  
  self.close();
};

function ExportarMun(ID, COD, NOME)
{
  window.opener.frmDados['MUN_ID'].value = ID;
  window.opener.frmDados['MUN_COD'].value = COD;
  window.opener.frmDados['MUN_DESC'].value = NOME;  
  
  self.close();
};

//Seleciona o campo para facilitar a editar
function SelText(Campo){Campo.select();};

//Seta 0 para checkbox deselecionado
function SetCheckBox(Obj)
{
 if (Obj.value != 1)
 {
  Obj.value = 0;
 };
 return;
};


function NumericMask(){
	if((window.event.keyCode < 48 || window.event.keyCode > 57) && window.event.keyCode != 8 && window.event.keyCode != 13) 
		window.event.keyCode = 0;
};


function CharMask(){
//	if (document.event.keyCode == 39) 
//		document.event.keyCode = 0;
};

//Mascara para forçar digitação No formato de Data dd/mm/yyyy.
function DateMask(Obj)
{
   var Pos = Obj.value.length;
   var Tecla = window.event.keyCode;
       
   if((Tecla < 48 || Tecla > 57) && Tecla != 8) 
   {
       if(Tecla == 47)
       {
           if(Pos == 2 || Pos == 5) 
               return;
           else
               window.event.keyCode = 0;
       }       
       else
           window.event.keyCode = 0;
               
       return;
   }
       
   if(Pos == 2 || Pos == 5) Obj.value = Obj.value + '/';
};

//Máscara para forçar digitação numérica podendo ter casas decimais.
function FloatMask()
{
   var C = window.event.keyCode;
	//alert(C);&& C != 44 		
   if((C < 48 || C > 57) && C != 45 && C != 8 && C != 46) window.event.keyCode = 0;
};

//Ultimo dia do mês 
function LastDay(Mes)
{
   var Meses = new Array(12);
   Meses[1] = 31;
   Meses[2] = 29;
   Meses[3] = 31;
   Meses[4] = 30;
   Meses[5] = 31;
   Meses[6] = 30;
   Meses[7] = 31;
   Meses[8] = 31;
   Meses[9] = 30;
   Meses[10] = 31;
   Meses[11] = 30;
   Meses[12] = 31;
   return Meses[parseInt(Mes,10)];
};

//Retorna se o valor digitado é uma data válida TRUE ou não FALSE
function IsDate(Data)
{
   var Dia, Mes, Ano;
   var Pos1, Pos, B1, B2;
       
   Pos = Data.indexOf('/');
   Dia = Data.substr(0,Pos);
   B1 = Data.substr(Pos,1);
   Pos1 = Pos + 1;         
   Pos = Data.indexOf('/',Pos1);
   Mes = Data.substr(Pos1,Pos - Pos1);
   B2 = Data.substr(Pos,1);    
   Ano = Data.substr(Pos + 1);

    if(Ano.length == 2)
    {
        if(parseInt(Ano,10) < 30)
            Ano = parseInt(Ano,10) + 2000;
        else
            Ano = parseInt(Ano,10) + 1900;
    }
   
   if(B1 != '/' || B2 != '/' || isNaN(Dia) || isNaN(Mes) || isNaN(Ano))
   {
       return false;
   }
   else
   {           
       if((parseInt(Mes,10) > 12) || (parseInt(Dia,10) > LastDay(Mes)) || (Ano == 0)) return false;
   };
   
   return !(parseInt(Ano,10) < 1900 || parseInt(Ano,10) > 2079);
};

//funcao jump de combobox
function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

////////////listass////////////////
function AddMod(ACE)
{ 
  var i=0;
  
  while (i < document.frmDados.LST_MOD_ORI.length)
  { 
   if (document.frmDados.LST_MOD_ORI.options[i].selected)
   {
     var newElement = document.createElement("OPTION");
	 newElement.text  = document.frmDados.LST_MOD_ORI.options[i].text;
	 newElement.value = document.frmDados.LST_MOD_ORI.options[i].value;
	 newElement.id    = ACE;
     document.frmDados.LST_MOD_DEST.options.add(newElement);
	 document.frmDados.LST_MOD_ORI.options.remove(i);	 
     i--;
	 if (i < 0) i=0;
   }else { i++;};
  };

  return true;
}

function RemMod()
{
 var i=0; 
     
  while (i < document.frmDados.LST_MOD_DEST.length)
  { 
   if (document.frmDados.LST_MOD_DEST.options[i].selected)
   {
     var newElement = document.createElement("OPTION");
	 newElement.text  = document.frmDados.LST_MOD_DEST.options[i].text;
	 newElement.value = document.frmDados.LST_MOD_DEST.options[i].value;
     document.frmDados.LST_MOD_ORI.options.add(newElement);
	 document.frmDados.LST_MOD_DEST.options.remove(i);
     i--;
	 if (i < 0) i=0;
   }else { i++;};
  };    
  return true;
}
//change diretory
function ChangeDir()
{
 var i=0; 
     
  while (i < document.frmDados.LST_FILE_DIR.length)
  { 
   if (document.frmDados.LST_FILE_DIR.options[i].selected)
   {
     /*var newElement = document.createElement("OPTION");
	 newElement.text  = document.frmDados.LST_MOD_DEST.options[i].text;
	 newElement.value = document.frmDados.LST_MOD_DEST.options[i].value;
     document.frmDados.LST_MOD_ORI.options.add(newElement);
	 document.frmDados.LST_MOD_DEST.options.remove(i);*/
	 alert(document.frmDados.LST_FILE_DIR.options[i].value);
   };
   i++;
  };    
  return true;
}
//////////////////////////////////////////////////////////////
///                Funcoes de Grid de Dados
//////////////////////////////////////////////////////////////
function SelCell(obj, cor)
{	
  obj.id   = obj.bgColor;
  if (cor != "0") 
  {
    obj.style.backgroundColor = cor;
  }
  else
  {
	obj.style.backgroundColor = '#97CBFF';  
  };  
};

function DSelCell(obj)
{
  obj.style.backgroundColor  = obj.id;
};

//Seleciona alterando a cor de fundo de edits. E8F2FD
function ESelCell(obj, cor)
{	
  if (cor != '0') 
  {
    obj.style.backgroundColor = cor;
  }
  else
  {
	obj.style.backgroundColor = '#FFFFCC';  
  };  

};

//Deseleciona alterando a cor de fundo de edits.
function EDSelCell(obj, cor)
{
  if (cor != '0') 
  {	
    obj.style.backgroundColor = cor;
  }
  else
  {
	obj.style.backgroundColor = '#FFFFFF';  
  };  
};



function Detalhe(page)
{
  if (page != "") alert(page);
};

function TitleSelCell(obj, cor)
{
  obj.id   = obj.bgColor;
  if (cor != "0") 
  {
    obj.style.backgroundColor = cor;
  };  
};

function TitleDSelCell(obj)
{
  obj.style.backgroundColor  = obj.id;
};

function ChangeOrder(CAMPO)
{
  document.frmDados.ED_ORDER_BY.value = CAMPO;
  document.frmDados.submit();
};

function ChangeSubOrder(CAMPO)
{
  document.frmDados.SUB_ED_ORDER_BY.value = CAMPO;
  document.frmDados.submit();
};

function DBChange(COMP)
{
 var i=0; 
     
  while (i < document.frmDados[COMP].length)
  { 
   if (document.frmDados[COMP].options[i].selected)
   {
     document.frmDados.COD.value = document.frmDados[COMP].options[i].id;
    };
   i++;
  };    
};


function FrmMain(PAGE, UPST, PGST)
{
  parent.mainFrame.location = PAGE; 
  
  if (UPST ==true ) parent.bottomFrame.location = PGST;
  
};
function FrmLeft(PAGE)
{
  parent.LeftFrame.location = PAGE; 
};
function FrmBotton(PAGE)
{
  parent.bottonFrame.location = PAGE; 
};

function FrmPage(PAGE)
{
  location = PAGE; 
};

//Valida a senha de acordo com os criterios de seguranca para senha forte
function CheckSkillAcesso()
{
   var vpstr, ppos, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10;
   	
	//Checa se a senha tem no minimo 8 digitos
	if( document.frmDados.USU_SENHA_NEW.value.length < 8)
	{
		alert("A Senha deve ter no mínimo 8 digitos.");
		document.frmDados.USU_SENHA_NEW.select();
		return false;
	};
	
    vpstr = document.frmDados.XMLBASESTR.value.split(";");
	
	//Checa se existe mais de 02 dois caracteres iguais consecutivos.
	
	
	//Checa se existe numeros sequenciais = 1234567890
	
	
	//Checa se existe caracteres sequenciais = abcdefg
	
	
	return true;
};

function SelCheckAll(theElement)
{
     var theForm = theElement.form, z = 0;
	 for(z=0; z<theForm.length;z++)
	 {if(theForm[z].type == 'checkbox') //&& theForm[z].name != 'checkall')
	    {theForm[z].checked = theElement.checked;}
     }
}
