Index: trunk/workflow/inc/local/classes/class.wf_location.php
===================================================================
--- trunk/workflow/inc/local/classes/class.wf_location.php	(revision 3167)
+++ trunk/workflow/inc/local/classes/class.wf_location.php	(revision 5307)
@@ -161,8 +161,10 @@
 		$result = $this->db->query($sql, array($state_id));
 		$output = array();
+		if (is_object($result)) {
 		while ($row = $result->fetchRow())
 			$output[] = $row;
 
 		$this->citiesFromState[$state_id] = $output;
+		}
 		return $output;
 	}
Index: trunk/workflow/inc/local/classes/class.wf_report.php
===================================================================
--- trunk/workflow/inc/local/classes/class.wf_report.php	(revision 5307)
+++ trunk/workflow/inc/local/classes/class.wf_report.php	(revision 5307)
@@ -0,0 +1,43 @@
+<?php
+
+require_once(PHPGW_SERVER_ROOT.SEP.'workflow'.SEP.'inc'.SEP.'report'.SEP.'includes'.SEP.'classes'.SEP.'Listagem.class.php');
+
+class wf_report
+{
+
+	var $db;
+	
+	var $listagem;
+	/**
+	 * Construtor da classe wf_log
+	 * @param array/string $logTypes Array ou String com o(s) tipo(s) de log(s) que deverï¿œ(ï¿œo) ser criado(s)
+	 * @return object Objeto do tipo wf_log
+	 * @access public
+	 */
+	public function wf_report()
+	{
+		$this->db = &Factory::getInstance('WorkflowObjects')->getDBWorkflow()->Link_ID->_connectionID;
+	    
+		$this->listagem = new Listagem('wf_report','wf_report',$this->db);
+		$this->listagem->setUrlBasePath($GLOBALS['phpgw_info']['server']['webserver_url'] . "/workflow/inc/report");
+	}
+	
+	function loadReport($idlisting) {
+		$this->listagem->carregarIDListagem($idlisting);
+	}
+	function setParam($param_name,$value) {
+		$this->listagem->setParametro($param_name,$value);
+	}
+	function getHTML() {
+		ob_start();
+		$this->listagem->desenhar(); 
+		$html = ob_get_contents();
+		ob_end_clean();
+		return $html;
+	}
+	
+	function getClass() {
+		return $this->listagem;
+	}
+	
+}
Index: trunk/workflow/inc/class.reports.inc.php
===================================================================
--- trunk/workflow/inc/class.reports.inc.php	(revision 5307)
+++ trunk/workflow/inc/class.reports.inc.php	(revision 5307)
@@ -0,0 +1,123 @@
+<?php
+/**************************************************************************\
+* eGroupWare                                                 *
+* http://www.egroupware.org                                                *
+* --------------------------------------------                             *
+*  This program is free software; you can redistribute it and/or modify it *
+*  under the terms of the GNU General Public License as published by the   *
+*  Free Software Foundation; either version 2 of the License, or (at your  *
+*  option) any later version.                                              *
+\**************************************************************************/
+
+$lib_folder = dirname(__FILE__) . SEP . 'report' . SEP;
+
+require_once(dirname(__FILE__) . SEP . 'class.ui_ajaxinterface.inc.php');
+require_once($lib_folder . 'xajax/xajax.inc.php');
+include($lib_folder . 'includes/php/listagem/cad_listagem.xajax.php');
+include($lib_folder . 'includes/classes/Formulario.class.php');
+include($lib_folder . 'includes/classes/Listagem.class.php');
+
+/**
+* Monta a interface inicial da Lista de Controle de Acesso
+*
+* @package Workflow
+* @author Jair Pereira - pereira.jair@gmail.com
+* @license http://www.gnu.org/copyleft/gpl.html GPL
+*/
+class reports extends ui_ajaxinterface
+{
+	/**
+	* Relaciona os mï¿œtodos pï¿œblicos da classe
+	*
+	* @var array $public_functions
+	* @access private
+	*/
+	var $public_functions = array(
+		'form'	=> true,
+		'view'	=> true,
+	);
+
+	/**
+	* Verifica permissï¿œo do usuï¿œrio atual para rodar a lista de controle de acesso
+	* Caso nï¿œo tenha permissï¿œo, emite mensagem e encerra execuï¿œï¿œo
+	*
+	* @return void
+	* @access public
+	*/
+	function reports()
+	{
+		if (!Factory::getInstance('workflow_acl')->checkWorkflowAdmin($GLOBALS['phpgw_info']['user']['account_id']))
+		{
+			$GLOBALS['phpgw']->common->phpgw_header();
+			echo parse_navbar();
+			echo lang('access not permitted');
+			$GLOBALS['phpgw']->log->message('F-Abort, Unauthorized access to workflow.reports.form');
+			$GLOBALS['phpgw']->log->commit();
+			$GLOBALS['phpgw']->common->phpgw_exit();
+		}
+	}
+
+	/**
+	* Monta a pï¿œgina inicial da interface de controle de acesso, a partir do template, e
+	* executa o mï¿œtodo inicial JavaScript para preencher dadas
+	*
+	* @return void
+	* @access public
+	*/
+	function form()
+	{
+		$GLOBALS['phpgw_info']['flags']['app_header'] = $GLOBALS['phpgw_info']['apps']['workflow']['title'] . ' - ' . lang('Reports');
+		$GLOBALS['phpgw_info']['flags'] = array('noheader' => false, 'nonavbar' => false, 'currentapp' => 'workflow');
+		$smarty = Factory::getInstance('workflow_smarty');
+
+		$javaScripts = $this->get_common_js();
+		$css = $this->get_common_css();
+
+		$smarty->assign('header', $smarty->expressoHeader);
+		$smarty->assign('footer', $smarty->expressoFooter);
+		$smarty->assign('txt_loading', lang("loading"));
+		$smarty->assign('javaScripts', $javaScripts);
+		
+		$lib_folder = dirname(__FILE__) . SEP . 'report' . SEP;
+		
+		ob_start();
+		include($lib_folder . 'cad_listagem.php');
+		$html = ob_get_contents();
+		ob_end_clean();
+		
+		$smarty->assign('css', $css);
+		$smarty->assign('reports_content', $html);
+		
+		$smarty->display('reports.tpl');
+		
+	}
+	
+	function view()
+	{
+		$GLOBALS['phpgw_info']['flags']['app_header'] = $GLOBALS['phpgw_info']['apps']['workflow']['title'] . ' - ' . lang('Reports');
+		$GLOBALS['phpgw_info']['flags'] = array('noheader' => false, 'nonavbar' => false, 'currentapp' => 'workflow');
+		$smarty = Factory::getInstance('workflow_smarty');
+
+		$javaScripts = $this->get_common_js();
+		$css = $this->get_common_css();
+
+		$smarty->assign('header', $smarty->expressoHeader);
+		$smarty->assign('footer', $smarty->expressoFooter);
+		$smarty->assign('txt_loading', lang("loading"));
+		$smarty->assign('javaScripts', $javaScripts);
+		
+		$lib_folder = dirname(__FILE__) . SEP . 'report' . SEP;
+		
+		ob_start();
+		include($lib_folder . 'includes/php/listagem/lst_view.php');
+		$html = ob_get_contents();
+		ob_end_clean();
+		
+		$smarty->assign('css', $css);
+		$smarty->assign('reports_content', $html);
+		
+		$smarty->display('reports.tpl');
+		
+	}
+}
+?>
Index: trunk/workflow/inc/report/downloads.php
===================================================================
--- trunk/workflow/inc/report/downloads.php	(revision 5307)
+++ trunk/workflow/inc/report/downloads.php	(revision 5307)
@@ -0,0 +1,32 @@
+<?
+session_start();
+include 'includes/classes/Download.class.php';
+
+$pathURL = $_GET['arquivo']; 
+
+$baseDir = '/tmp/';
+$baseRef = 'true';
+
+$pathFile = str_replace($baseDir , '', $pathURL);
+
+$pathPartes = explode('/', $pathFile) ;
+
+$pathDirFinal = $pathPartes[0];
+
+
+$fileDown = '';
+for($i = 1; $i < (count($pathPartes)); $i++){
+   $fileDown = ($fileDown != '') ? $fileDown . '/' : $fileDown ;
+   $fileDown .= $pathPartes[$i];
+}
+ 
+$down = new Download($baseDir, $baseRef );
+$down->doDownload($baseDir . $pathDirFinal);
+
+if($down->getSysError() != ''){
+    echo $down->getSysDebug();  
+    echo $down->getSysError();
+}
+
+
+ ?>
Index: trunk/workflow/inc/report/cad_listagem.php
===================================================================
--- trunk/workflow/inc/report/cad_listagem.php	(revision 5307)
+++ trunk/workflow/inc/report/cad_listagem.php	(revision 5307)
@@ -0,0 +1,204 @@
+<?
+
+$BASE_URL = "index.php?menuaction=workflow.reports.form";
+$BASE_URL_VIEW = "index.php?menuaction=workflow.reports.view";
+ 
+$conn = &Factory::getInstance('WorkflowObjects')->getDBWorkflow()->Link_ID->_connectionID;
+ini_set("soap.wsdl_cache_enabled", "0"); //Limpa o cache
+
+$abaMenu = (isset($_POST['abaMenu'])) ? $_POST['abaMenu'] : $_GET['abaMenu'];
+$abaMenu = ($abaMenu != '') ? $abaMenu : 'pesquisa';
+$acao = (isset($_POST['acao'])) ? $_POST['acao'] : $_GET['acao'];
+
+$lstoid = (isset($_POST['lstoid'])) ? $_POST['lstoid'] : $_GET['lstoid'];
+$FrmCadListagem_acao = (isset($_POST['FrmCadListagem_acao'])) ? $_POST['FrmCadListagem_acao'] : $_GET['FrmCadListagem_acao'];
+
+if ($FrmCadListagem_acao == "editar") { $abaMenu = "cadastro"; }
+
+$habilitasincronizacao = $_SESSION['funcao']['webservice_listagem_sincronizacao'];
+
+?>
+<html>
+<head>
+  <link type="text/css" rel="stylesheet" href="./workflow/inc/report/includes/css/base_form.css">
+  <link type="text/css" rel="stylesheet" href="./workflow/inc/report/includes/css/calendar.css">
+  <script language="Javascript" type="text/javascript" src="./workflow/inc/report/includes/js/jquery-1.3.2.js"></script>
+  <script language="Javascript" type="text/javascript" src="./workflow/inc/report/includes/js/calendar.js"></script>
+  <script language="Javascript" type="text/javascript" src="./workflow/inc/report/includes/js/mascaras.js"></script>
+  <script language="Javascript" type="text/javascript" src="./workflow/inc/report/includes/js/auxiliares.js"></script>  
+  <script language="Javascript" type="text/javascript" src="./workflow/inc/report/includes/js/validacoes.js"></script>
+  <script language="Javascript" type="text/javascript" src="./workflow/inc/report/includes/js/FormularioUtil.js"></script>
+  <script>
+  function mudaAba(aba){
+    $id('hidden_id_abaMenu').value = aba;
+    document.frm.submit();
+  }
+  </script>
+  <script>
+  function ExibirMensagem(msg) {
+  	$id('div_msg').innerHTML = msg;
+  }
+function adiciona_option(idcampo,valor,nome){
+    posicao = document.getElementById(idcampo).length;
+    document.getElementById(idcampo).options[posicao] = new Option(nome, valor);
+}
+function remover_options(idcampo){
+ tamanho = document.getElementById(idcampo).length;
+ for(i=0 ; i<tamanho ; i++){
+     document.getElementById(idcampo).options[0] = null;
+ }
+
+}
+function selecionaTipoIndicador(tipo,imagem) {
+	remover_options('id_lsiimagem');
+    
+    if ((tipo == "Q") || (tipo == "R") || (tipo == "T")) {
+    	adiciona_option("id_lsiimagem",'','---');
+        adiciona_option("id_lsiimagem",'3' ,'Amarelo - 1');
+        adiciona_option("id_lsiimagem",'17','Amarelo - 2');
+        adiciona_option("id_lsiimagem",'20','Azul - 1');
+        adiciona_option("id_lsiimagem",'10','Azul - 2');
+        adiciona_option("id_lsiimagem",'2' ,'Azul - 3');
+        adiciona_option("id_lsiimagem",'19','Azul - 4');
+        adiciona_option("id_lsiimagem",'22','Cinza - 1');
+        adiciona_option("id_lsiimagem",'5' ,'Cinza - 2');
+        adiciona_option("id_lsiimagem",'14','Cinza - 3');
+        adiciona_option("id_lsiimagem",'18','Laranja - 1');
+        adiciona_option("id_lsiimagem",'16','Laranja - 2');
+        adiciona_option("id_lsiimagem",'13','Preto');
+        adiciona_option("id_lsiimagem",'12','Rosa');
+        adiciona_option("id_lsiimagem",'11','Roxo');
+        adiciona_option("id_lsiimagem",'21','Verde - 1');
+        adiciona_option("id_lsiimagem",'15','Verde - 2');
+        adiciona_option("id_lsiimagem",'1' ,'Verde - 3');
+        adiciona_option("id_lsiimagem",'4' ,'Vermelho');
+    }
+    if (tipo == "I") {
+        adiciona_option("id_lsiimagem",'','---');
+    	adiciona_option("id_lsiimagem",'filePdf','Arquivo de PDF');
+        adiciona_option("id_lsiimagem",'fileTxt','Arquivo de Texto');
+        adiciona_option("id_lsiimagem",'folhaBranca','Arquivo em Branco');
+        adiciona_option("id_lsiimagem",'i_attach','Arquivo Anexo');
+        adiciona_option("id_lsiimagem",'lupaMais','Prï¿œ-Visualizar (Lupa)');
+        adiciona_option("id_lsiimagem",'mais','Sinal Mais');
+        adiciona_option("id_lsiimagem",'menos','Sinal Menos');
+        adiciona_option("id_lsiimagem",'v','V - Existe');
+        adiciona_option("id_lsiimagem",'x','X - Excluido');
+        adiciona_option("id_lsiimagem",'x1','X 1 - Excluï¿œdo');
+        adiciona_option("id_lsiimagem",'pasta1','Pasta 1');
+        adiciona_option("id_lsiimagem",'pasta2','Pasta 2');
+        adiciona_option("id_lsiimagem",'pasta3','Pasta 3');
+    }
+    document.getElementById("id_lsiimagem").value = imagem;
+}
+
+function liberar_campo(idcampo) {
+    document.getElementById(idcampo).style.backgroundColor = '#FFFFFF';
+    document.getElementById(idcampo).disabled = "";
+}
+function bloquear_campo(idcampo) {
+	document.getElementById(idcampo).style.backgroundColor = '#E0E0E0';
+    document.getElementById(idcampo).disabled = "true";
+}
+function limpar_campo(idcampo) {
+	document.getElementById(idcampo).value = "";
+}
+function nowrapCheck(checked) {
+	  if (checked) { 
+        limpar_campo('not_id_lslcwidth'); 
+        bloquear_campo('not_id_lslcwidth'); 
+      } else { 
+        liberar_campo('not_id_lslcwidth'); 
+      }
+}
+
+  </script>
+</head>
+<body>
+ 
+<div align="center">
+<br />
+
+<table width="98%" class="tableMoldura">
+<br>
+<tr class="tableTitulo">
+    <td><h1>Cadastro de Relatórios</h1></td>
+</tr>
+<tr>
+        <td><br><span id="div_msg" class="msg"><?=$msg?></span></td>
+</tr>
+<tr>
+    <td align="center">
+    
+    <form action="<?=$_PHP_SELF?>" method="post" name="frm" id="frm">
+
+    <input type="hidden" name="abaMenu" id="hidden_id_abaMenu" value="<?=$abaMenu?>"/>
+    <input type="hidden" name="acao" id="hidden_id_abaMenu" value="<?=$acao?>"/>
+    <input type="hidden" name="lstoid" id="hidden_id_lstoid" value="<?=$lstoid?>"/>
+    
+    <table width="98%">
+            <tr>
+                <td align="left" id="navPrincipal">
+        
+        <table>
+            <tr>
+                <td align="center" id="tabnav">
+                    <a href="javascript:void(null);" onclick="window.location.href='<?=$BASE_URL?>';" <? if($abaMenu == 'pesquisa'){ echo 'class="active"'; }?>>Pesquisa</a>
+                </td>
+                <? if (($lstoid != "") || ($lstoid == "" && $FrmCadListagem_acao == "editar") ||  ($FrmCadListagem_acao == "atualizar_listagem")) { ?>
+                <td align="center" id="tabnav">
+                    <a href="javascript:void(null);" onclick="javascript:mudaAba('cadastro');" <? if($abaMenu == 'cadastro'){ echo 'class="active"'; }?>>Cadastro</a>
+                </td>
+                <? } ?>
+                <? if (($lstoid != "") ||  ($FrmCadListagem_acao == "atualizar_listagem")) { ?>
+                <td align="center" id="tabnav">
+                    <a href="javascript:void(null);" onclick="javascript:mudaAba('colunas');" <? if($abaMenu == 'colunas'){ echo 'class="active"'; }?>>Colunas</a>
+                </td>
+                <td align="center" id="tabnav">
+                    <a href="javascript:void(null);" onclick="javascript:mudaAba('indicadores');" <? if($abaMenu == 'indicadores'){ echo 'class="active"'; }?>>Indicadores</a>
+                </td>
+                <td align="center" id="tabnav">
+                    <a href="javascript:void(null);" onclick="javascript:mudaAba('parametros');" <? if($abaMenu == 'parametros'){ echo 'class="active"'; }?>>Parametros</a>
+                </td>
+                <td align="center" id="tabnav">
+                    <a href="javascript:void(null);" onclick="javascript:mudaAba('preview');" <? if($abaMenu == 'preview'){ echo 'class="active"'; }?>>Pre-Visualizacao</a>
+                </td>
+                <? if ($habilitasincronizacao) { ?>
+                <td align="center" id="tabnav">
+                    <a href="javascript:void(null);" onclick="javascript:mudaAba('sincronizar');" <? if($abaMenu == 'sincronizar'){ echo 'class="active"'; }?>>Sincronizacao</a>
+                </td> 
+                <? } ?>
+                <? } ?>
+            </tr>
+        </table>
+        
+                </td>
+            </tr>
+        </table>
+    
+      </form>
+    </td>
+</tr>
+
+<tr>
+    <td align="center">
+    <?
+    //echo $abaMenu;
+    switch($abaMenu){
+        case 'pesquisa' : include 'includes/php/listagem/lst_pesquisa.php'; break;
+        case 'cadastro' : include 'includes/php/listagem/lst_cadastro.php'; break;
+        case 'colunas' : include 'includes/php/listagem/lst_colunas.php';   break;
+        case 'parametros' : include 'includes/php/listagem/lst_parametros.php';   break;
+        case 'indicadores' : include 'includes/php/listagem/lst_indicadores.php';   break;
+        case 'preview' : include 'includes/php/listagem/lst_preview.php';   break;
+        case 'sincronizar' : include 'includes/php/listagem/lst_sincronizacao.php';   break;
+    }
+    ?>
+    </td>
+</tr>
+</table>
+    
+</div>
+
+</body>
+</html>
Index: trunk/workflow/inc/report/includes/php/listagem/lst_pesquisa.php
===================================================================
--- trunk/workflow/inc/report/includes/php/listagem/lst_pesquisa.php	(revision 5307)
+++ trunk/workflow/inc/report/includes/php/listagem/lst_pesquisa.php	(revision 5307)
@@ -0,0 +1,107 @@
+<?php
+
+$form           = new Formulario("FrmCadListagem");
+
+$acao = $_POST['FrmCadListagem_acao'];
+if ($acao == "") { $acao = $_GET['acao']; }
+$lstoid = $_POST['lstoid'];
+if ($lstoid == "") { $lstoid = $_GET['lstoid']; }
+
+$lstnome = $_POST['lstnome'];
+
+//FORMULï¿œRIO DE PESQUISA
+$form->setAction($BASE_URL);
+$form->adicionarCampo("lstnome","lstnome","Procurar por:","Procurar Por",$lstnome,false);
+$form->adicionarQuadro("quadro1","Pesquisa");
+$form->adicionarSubmit("quadro1","btn_pesquisar","Pesquisar","pesquisar");
+$form->adicionarSubmit("quadro1","btn_novo","Novo","editar");
+
+
+if ($form->isSubmit("pesquisar")) {
+//LISTAGEM
+$sql = "select 
+            lstoid, 
+            lstidlistagem, 
+            lstnome, 
+            lstdescricao, 
+            lstexclusao
+        from 
+            listagem.listagem 
+        where 
+            lstnome ilike '%$lstnome%' or  
+            lstdescricao ilike '%$lstnome%' or 
+            lstidlistagem ilike '%$lstnome%' 
+        order by 
+            lstidlistagem";
+
+$res = pg_query($conn,$sql);
+
+if ($habilitasincronizacao) {
+   $addcol = "<td align='center' colspan=2><h3>Sincronizado</h3></td>";
+   $addcol .= "<td align='center'><h3>Status</h3></td>";    
+}
+
+$tr .= "<table class='tableMoldura'>
+                <tr class='tableSubTitulo'><td colspan=6><h2>Listagens</h2></td></tr>
+                <tr class='tableTituloColunas'>
+                    <td><h3>ID Listagem</h3></td>
+                    <td><h3>Nome</h3></td>
+                    <td><h3>Descricao</h3></td>
+                    <td><h3>Visualizar</h3></td>
+                    $addcol
+                </tr>";
+                
+        $qtd = pg_num_rows($res);
+        if ($qtd == 0) { $msgres = "Nenhum Resultado Encontrado."; } else { $msgres = "$qtd resultado(s) encontrado(s)."; }
+        while ($listagen = pg_fetch_object($res)) {
+            
+            if ($habilitasincronizacao) {
+            
+                $xmlversao = verificaVersao(array( "$listagen->lstidlistagem" ));
+                $versao = new SimpleXMLElement($xmlversao);
+                
+                $sincronizado = $versao->listagem[0]->sincronizado;
+                
+                if ($sincronizado == "1") {
+                	$iconsincronizado = "<img src='./images/indicadores/redondos/apf/ap01.jpg'>";
+                    $linksincronizado = "";
+                } else {
+                	$iconsincronizado = "<img src='./images/indicadores/redondos/apf/ap03.jpg'>";
+                    $linksincronizado = "<a href='" . $BASE_URL . "&acao=editar&abaMenu=sincronizar&lstoid=" . $listagen->lstoid . "'>[ Sincronizar ]</a>";
+                } 
+                $exclusao = $listagen->lstexclusao;
+                
+                if ($exclusao) {
+                	$iconstatus = "<span style='color:#990000;'>Inativo</span>";
+                } else {
+                	$iconstatus = "Ativo";
+                }
+                
+                
+                $addcoluna = "<td align='center'>" . $iconsincronizado . "</td><td align='center' nowrap>$linksincronizado</td>";
+                
+                $addcoluna .= "<td align='center'>" . $iconstatus . "</td>";  
+            
+            }
+            
+            $class = ( $class == "tdc" ) ? "tde" : "tdc";
+            $tr .= "<tr class='$class'>";
+            $tr .= "<td><a href='" . $BASE_URL . "&acao=editar&abaMenu=cadastro&lstoid=" . $listagen->lstoid . "'>" . $listagen->lstidlistagem . "</a></td>";
+            $tr .= "<td>" . $listagen->lstnome . "</td>"; 
+            $tr .= "<td>" . $listagen->lstdescricao . "</td><td align='center'><a href='$BASE_URL_VIEW&idlistagem=" . $listagen->lstidlistagem . "'>[Visualizar]</a></td>$addcoluna";
+            
+            $tr .= "</tr>";
+        }
+        
+        $tr .= "<tr class='tableRodapeModelo1'><td colspan=6 align='center'><h3>$msgres</h3></td></tr>";
+        $tr .= "</table>";
+
+
+}
+$form->desenhar();
+
+
+echo $tr;
+
+
+?>
Index: trunk/workflow/inc/report/includes/php/listagem/lst_view.php
===================================================================
--- trunk/workflow/inc/report/includes/php/listagem/lst_view.php	(revision 5307)
+++ trunk/workflow/inc/report/includes/php/listagem/lst_view.php	(revision 5307)
@@ -0,0 +1,95 @@
+<?php
+
+$conn = &Factory::getInstance('WorkflowObjects')->getDBWorkflow()->Link_ID->_connectionID;
+
+$BASE_URL = "index.php?menuaction=workflow.reports.view";
+
+$lstoid = $_POST['lstoid'];
+if ($lstoid == "") { $lstoid = $_GET['lstoid']; }
+
+$lstidlistagem = $_POST['idlistagem'];
+if ($lstidlistagem == "") { $lstidlistagem = $_GET['idlistagem']; }
+
+if ($lstoid != "") { 
+	$sql = "select lstidlistagem, lstnome from listagem.listagem where lstoid = $lstoid";
+	$res = pg_query($conn,$sql);
+	$dados= pg_fetch_array($res);
+	$lstidlistagem = $dados["lstidlistagem"];
+} else {
+	$sql = "select lstoid, lstidlistagem, lstnome from listagem.listagem where lstidlistagem = '$lstidlistagem'";
+	$res = pg_query($conn,$sql);
+	$dados= pg_fetch_array($res);
+	$lstidlistagem = $dados["lstidlistagem"];
+	$lstoid = $dados["lstoid"];
+}
+
+$form           = new Formulario("FrmCadListagem");
+$form->setAction($BASE_URL);
+$listagem = new Listagem($lstidlistagem,"",$conn);
+$listagem->setDebug(true);
+$listagem->setUrlBasePath($GLOBALS['phpgw_info']['server']['webserver_url'] . "/workflow/inc/report");
+$listagem->carregarIDListagem($lstidlistagem);
+
+$sql_par = "select 
+                lspoid,
+                lsplstoid,
+                lspidparametro,
+                lsptitulo,
+                lsptipo,
+                lspvalor_padrao,
+                lspobrigatorio 
+            from 
+                listagem.listagem_parametro 
+            where 
+                lsplstoid = $lstoid 
+            order by lspoid ";
+$resu_par = pg_query($conn,$sql_par);
+
+$form->adicionarHidden("lstoid",$lstoid);
+$form->adicionarHidden("abaMenu",$abaMenu);
+$form->adicionarHidden("acao","editar");
+$exibeform = false;
+
+while ($parametro = pg_fetch_object($resu_par)) {
+    $idparametro = $parametro->lspidparametro;
+    $titulo = $parametro->lsptitulo;
+
+    
+    if ($titulo == "") { 
+    	$titulo = $idparametro;
+    }
+    $tipo = $parametro->lsptipo;
+    $obrigatorio = ($parametro->lspobrigatorio == "t") ? true : false;
+    $valor_padrao = $parametro->lspvalor_padrao;
+    
+    $exibeform = true;    
+    
+    $valor = $_POST[$idparametro];
+    if ($tipo == "data") {
+    	$valor = $_POST[$idparametro . "_inicio"];
+    }
+    if (($valor == "") && ((!isset($_POST[$idparametro])) && (!isset($_POST[$idparametro . "_inicio"])))) { $valor = $valor_padrao; }
+    
+    if ($obrigatorio) { $titulo .= " *"; }
+
+    $form->adicionarCampo($idparametro,$tipo,$titulo. ":",$idparametro . ":",$valor,$obrigatorio);
+    
+    $listagem->setParametro($idparametro,$valor);
+    
+    $addobr = "";
+    if ($obrigatorio) { $addobr = " //OBRIGATÓRIO"; }
+    
+    $adicionarcodigo .= "\$report->setParam('$idparametro',\$$valor_$idparametro);$addobr<br>";
+}
+
+if ($exibeform) {
+    $form->adicionarQuadro("quadro1","Formulário de Pesquisa");
+    $form->adicionarSubmit("quadro1","btn_cadastrar","Pesquisar","pesquisar");
+    $form->desenhar();
+}
+
+
+echo "<center>";
+$listagem->desenhar();
+
+?>
Index: trunk/workflow/inc/report/includes/php/listagem/lst_parametros.php
===================================================================
--- trunk/workflow/inc/report/includes/php/listagem/lst_parametros.php	(revision 5307)
+++ trunk/workflow/inc/report/includes/php/listagem/lst_parametros.php	(revision 5307)
@@ -0,0 +1,163 @@
+<?php
+
+$form           = new Formulario("FrmCadListagem");
+$form->setAction($BASE_URL);
+$listagem       = new Listagem("listResultado","Parâmetros",$conn);
+$listagem->setUrlBasePath($GLOBALS['phpgw_info']['server']['webserver_url'] . "/workflow/inc/report");
+
+
+$lspoid = (isset($_POST['lspoid'])) ? $_POST['lspoid'] : $_GET['lspoid'];
+
+if ($acao == "excluir") {
+    $sql = "delete from listagem.listagem_parametro where lspoid = $lspoid ";
+    pg_query($conn,$sql);
+    
+    //ATUALIZA A VERSÃO DA LISTAGEM PARA MANTER O PROCESSO DE SINCRONIZAÇÃO
+    atualizarVersao($conn,$lstoid);
+    $msg = "Parâmetro Excluído com sucesso!";
+}
+
+if ($form->isSubmit("atualizar_parametro",true)) {
+    
+    $lspidparametro         = $_POST['lspidparametro'];
+    $lspidparametro = str_replace("{","",$lspidparametro);
+    $lspidparametro = str_replace("}","",$lspidparametro);
+    
+    $lsptitulo              = $_POST['lsptitulo'];
+    $lspvalor_padrao        = $_POST['lspvalor_padrao'];
+    $lsptipo                = $_POST['lsptipo'];
+    
+    $lspobrigatorio = (isset($_POST['lspobrigatorio'])) ? true: false;
+
+    $flspobrigatorio = ($lspobrigatorio) ?  "'t'" : "'f'"; 
+    
+    if ($lspoid == "") {
+        
+        $sqlver = "select lspoid from listagem.listagem_parametro where lspidparametro = '$lspidparametro' and lsplstoid = '$lstoid'";
+        $res = pg_query($sqlver);
+        $qtd = pg_num_rows($res);
+        
+        if ($qtd == 0) {
+            $sql = "insert into 
+                        listagem.listagem_parametro ( 
+                        
+                        lsplstoid,
+                        lspidparametro,
+                        lsptipo,
+                        lspvalor_padrao,
+                        lspobrigatorio,
+                        lsptitulo
+                    ) values (
+                        $lstoid,
+                        '$lspidparametro',
+                        '$lsptipo',
+                        '$lspvalor_padrao',
+                        $flspobrigatorio,
+                        '$lsptitulo'
+                    );";
+            $res = pg_query($conn,$sql);
+            
+            //ATUALIZA A VERSÃO DA LISTAGEM PARA MANTER O PROCESSO DE SINCRONIZAÇÃO
+            atualizarVersao($conn,$lstoid);
+            
+            $msg=  "Coluna adicionada com Sucesso!";
+        } else {
+            $msg = "Identificador de Coluna já está adicionado a essa listagem.";
+        }
+        
+    } else {
+        $sql = "update 
+                    listagem.listagem_parametro 
+                set lspidparametro = '$lspidparametro',
+                    lsptitulo = '$lsptitulo',  
+                    lsptipo='$lsptipo', 
+                    lspvalor_padrao = '$lspvalor_padrao', 
+                    lspobrigatorio = $flspobrigatorio
+                where lspoid = $lspoid ";
+                
+       //ATUALIZA A VERSÃO DA LISTAGEM PARA MANTER O PROCESSO DE SINCRONIZAÇÃO
+       atualizarVersao($conn,$lstoid);
+       
+       $res = pg_query($conn,$sql);
+       $msg=  "Coluna atualizada com Sucesso!";
+       $lspoid = "";
+       $acao = "editar";
+    }
+}
+
+if ($acao == "editar") {
+    if ($lspoid != "") {
+        $sql = "select * from listagem.listagem_parametro where lspoid = $lspoid ";
+        $res = pg_query($sql);
+        $dados = pg_fetch_object($res);
+        
+        $lspidparametro = $dados->lspidparametro;
+        $lspvalor_padrao =  $dados->lspvalor_padrao;
+        $lsptitulo =  $dados->lsptitulo;
+        $lsptipo = $dados->lsptipo;
+        $lspobrigatorio = ($dados->lspobrigatorio == "t") ? true: false;
+
+    } else {
+        $lspidparametro = "";
+        $lspvalor_padrao = "";
+        $lsptipo = "";
+        $lsptitulo = "";
+        $lspobrigatorio = false;
+        
+    }
+}
+
+
+if(isset($lstoid{0})){
+
+    $form->adicionarHidden("lstoid",$lstoid); 
+    $form->adicionarHidden("lspoid",$lspoid); 
+    $form->adicionarHidden("abaMenu",$abaMenu);
+    $form->adicionarHidden("acao","editar");
+    $form->adicionarCampo("lspidparametro","lspidparametro","ID do Parâmetro:","Identificador da Coluna",$lspidparametro,true,"20","","Identificador do Parâmetro. (Não usar {}).");
+    $form->adicionarCampo("lsptitulo","lsptitulo","Título do Parâmetro:","Título do Parâmetro",$lsptitulo,true,"20","","");
+    
+    $arrTipoColunas = array ( ''      => '---' ,
+                              'text'      => 'Texto' ,
+                              'int'       => 'Número' ,
+                              'data'      => 'Data' 
+           );
+    $form->adicionarSelect("lsptipo","Tipo:","Tipo do Parâmetro",$lsptipo,$arrTipoColunas,true);
+    
+    $form->adicionarCampo("lspvalor_padrao","lspvalor_padrao","Valor para Testes:","Valor para Testes",$lspvalor_padrao,false,"","","Valor usado nos testes para faciltar a consulta.");
+    
+    $arrCheckBlank[] = array('t', ' Parâmetro Obrigatório.', $lspobrigatorio);
+    $form->adicionarCheckBox("lspobrigatorio","",$arrCheckBlank,false);
+    
+      
+    $form->adicionarQuadro("quadro2","Cadastro de Parâmetros");
+    $form->adicionarSubmit("quadro2","btn_cadastrar","Atualizar","atualizar_parametro");
+    
+    
+
+    //LISTAGEM DE PARÂMETROS
+    $sql = "SELECT *, case when lsptipo = 'int' then 'Número' when lsptipo = 'text' then 'Texto' when lsptipo = 'data' then 'Data' end as novo_tipo FROM listagem.listagem_parametro WHERE lsplstoid=$lstoid order by lspoid";
+    $listagem->carregar($sql);
+    
+    $listagem->adicionarIndicador("indobrigatorio","({lspobrigatorio} == 't')","I","v","Parâmetro Obrigatório");
+    
+    $listagem->adicionarColuna("lspidparametro","Parâmetro","{lspidparametro}","text","left","200px");
+    $listagem->adicionarColuna("lsptitulo","Título","{lsptitulo}","text","left","200px");
+    $listagem->adicionarColuna("lsptipo","Tipo","{novo_tipo}","text","left","200px");
+    $listagem->adicionarColuna("lspvalor_padrao","Valor de testes","{lspvalor_padrao}","text","left","200px");
+    $listagem->adicionarColuna("lspobrigatorio","Obrigatório","{indobrigatorio}","text","center","50px");
+    $listagem->adicionarColuna("lspoid","Excluir","[Excluir]","text","center","50px");
+    $listagem->adicionarLink("lspoid",$BASE_URL . "&abaMenu=parametros&lstoid=$lstoid&lspoid={lspoid}&acao=excluir");
+    $listagem->adicionarLink("lspidparametro",$BASE_URL . "&abaMenu=parametros&lstoid=$lstoid&lspoid={lspoid}&acao=editar");
+    $listagem->setMensagemRegistrosEncontrados("parâmetros(s) cadastrado(s)");
+    $listagem->setMostrarLegendaTopo(false);
+    $listagem->setMostrarLegendaRodape(true);
+}
+
+if ($msg != "") {
+    echo "<script>ExibirMensagem('$msg')</script>";
+}
+$form->desenhar();
+$listagem->desenhar();
+echo "<div id='div_result_colunas'></div>";
+?>
Index: trunk/workflow/inc/report/includes/php/listagem/lst_cadastro.php
===================================================================
--- trunk/workflow/inc/report/includes/php/listagem/lst_cadastro.php	(revision 5307)
+++ trunk/workflow/inc/report/includes/php/listagem/lst_cadastro.php	(revision 5307)
@@ -0,0 +1,352 @@
+<?php
+
+$form           = new Formulario("FrmCadListagem");
+$form->setAction($BASE_URL);
+$listagem       = new Listagem("listResultado","Listagens",$conn);
+$listagem->setUrlBasePath($GLOBALS['phpgw_info']['server']['webserver_url'] . "/workflow/inc/report");
+
+$acao = $_POST['FrmCadListagem_acao'];
+if ($acao == "") { $acao = $_GET['acao']; }
+if ($acao == "") { $acao = $_POST['acao']; }
+$lstoid = $_POST['lstoid'];
+if ($lstoid == "") { $lstoid = $_GET['lstoid']; }
+
+
+    if ($acao == "alterarStatus") {
+        $lstidlistagem = $_POST['lstidlistagem'];
+        $novostatus = $_POST['novostatus'];
+        $ret = atualizaStatus(array("$lstidlistagem"),$novostatus);
+        $msg = "Status Alterado com Sucesso!"; 
+        $acao = "editar";
+    }
+        
+
+    if (($acao == "editar") || ($form->isSubmit("atualizar_listagem",true))) {
+
+        $lstidlistagem = $_POST['lstidlistagem'];
+        $lstversao = $_POST['lstversao'];
+        $lstnome = $_POST['lstnome'];
+        $lsttitulo = $_POST['lsttitulo'];
+        $lstsql = $_POST['lstsql'];
+        
+        $lstmsg_totalizador = $_POST['lstmsg_totalizador'];
+        $lstmsg_subtotalizador = $_POST['lstmsg_subtotalizador'];
+        $lstmsg_registrosencontrados = $_POST['lstmsg_registrosencontrados'];
+        $lstmsg_nenhumresultado = $_POST['lstmsg_nenhumresultado'];
+        $lstdescricao = $_POST['lstdescricao'];
+        
+        $lstagrupamento_campo = $_POST['lstagrupamento_campo'];
+        $lstagrupamento_titulo = $_POST['lstagrupamento_titulo'];
+        $lstexclusao = $_POST['lstexclusao'];
+        
+        if ($lstmsg_totalizador == "")           { $lstmsg_totalizador = "TOTAL:"; }
+        if ($lstmsg_subtotalizador == "")        { $lstmsg_subtotalizador = "SUB-TOTAL:"; }
+        if ($lstmsg_registrosencontrados == "")  { $lstmsg_registrosencontrados = "registro(s) encontrado(s)."; }
+        if ($lstmsg_nenhumresultado == "")       { $lstmsg_nenhumresultado = "Nenhum resultado encontrado."; }
+        if ($lsttitulo == "")       { $lsttitulo = "Resultado da Pesquisa."; }
+        
+        if ($lstoid == "") {
+              $lstexibe_resultados = true;
+              $lstexibe_header = true;
+              $lstexibe_totalizadores = true;
+              $lstexibe_subtotais = true;
+              $lstexibe_qtdregistros = true;
+              $lstexibe_legendatopo = true;
+              $lstexibe_titagrupamento = true;
+              $lstexibe_agrupamento_alfabetico = false;
+              $lstexclusao = true;
+        }
+        
+        $arrOpcVisualizacao[] = array('lstexibe_resultados', ' Exibir resultados na tela.', $lstexibe_resultados);
+        $arrOpcVisualizacao[] = array('lstexibe_header', ' Exibir titulos das colunas', $lstexibe_header);
+        $arrOpcVisualizacao[] = array('lstexibe_totalizadores', ' Exibir totalizadores', $lstexibe_totalizadores);
+        $arrOpcVisualizacao[] = array('lstexibe_subtotais', ' Exibir sub-totalizadores', $lstexibe_subtotais);
+        $arrOpcVisualizacao[] = array('lstexibe_qtdregistros', ' Exibir Quantidade de registros encontrados', $lstexibe_qtdregistros);
+        $arrOpcVisualizacao[] = array('lstexibe_checkbox', ' Exibir colunas com checkbox.', $lstexibe_checkbox);
+        $arrOpcVisualizacao[] = array('lstexibe_csv', ' Gerar CSV', $lstexibe_csv);
+        $arrOpcVisualizacao[] = array('lstexibe_legendatopo', ' Exibir legenda no topo', $lstexibe_legendatopo);
+        $arrOpcVisualizacao[] = array('lstexibe_legendarodape', ' Exibir legenda no rodape', $lstexibe_legendarodape);
+        $arrOpcVisualizacao[] = array('lstexibe_titagrupamento', ' Re-exibir titulos de agrupamento', $lstexibe_titagrupamento);
+        $arrOpcVisualizacao[] = array('lstexibe_agrupamento_alfabetico', ' Exibir agrupamento alfabetico', $lstexibe_agrupamento_alfabetico);
+        $arrOpcVisualizacao[] = array('lstexclusao', ' Ativa', $lstexclusao);
+        foreach ($arrOpcVisualizacao as $opc) {
+            $$opc[0] = "false";
+        }
+        $opcvisualizacao = $_POST['opcvisualizacao'];
+        if (is_array($opcvisualizacao)) {
+            foreach ($opcvisualizacao as $opc) {
+                $$opc = "true";
+            }
+        }
+        
+        if ($lstexclusao == "false") {
+        	$flstexclusao = "now()";
+        }
+        if ($lstexclusao == "true") {
+        	$flstexclusao = "null";
+        }
+        
+        if (($acao == "editar") && ($lstoid != "")) {
+            $sql = "select 
+                        lstoid,
+                        lstversao,
+                        lstidlistagem,
+                        lstdescricao,
+                        lstnome,
+                        lsttitulo,
+                        lstsql,
+                        lstexibe_header,
+                        lstexibe_totalizadores,
+                        lstexibe_subtotais,
+                        lstexibe_qtdregistros,
+                        lstexibe_checkbox,
+                        lstexibe_csv,
+                        lstexibe_legendatopo,
+                        lstexibe_legendarodape,
+                        lstexibe_titagrupamento,
+                        lstexibe_agrupamento_alfabetico,
+                        lstagrupamento_campo,
+                        lstagrupamento_titulo,
+                        lstmsg_totalizador,
+                        lstmsg_subtotalizador,
+                        lstmsg_registrosencontrados,
+                        lstmsg_nenhumresultado,
+                        lstexclusao,
+                        lstexibe_resultados
+                    from 
+                        listagem.listagem 
+                    where 
+                        lstoid = $lstoid";
+            $res = pg_query($sql);
+            $linha = pg_fetch_object($res);
+            $lstidlistagem = "";
+            foreach ($linha as $chave => $valor) {
+                if ($valor == "f") { 
+                    $valor = false;
+                } 
+                if ($valor == "t") { 
+                    $valor = true;
+                }
+              //  $$chave= str_replace("[-]","'",$valor);;
+                $$chave=  html_entity_decode($valor, ENT_QUOTES);
+            } 
+            if ($lstexclusao == "") {
+            	$f_lstexclusao = true;
+            } else {
+            	$f_lstexclusao = false;
+            }
+            
+            //$lstsql = str_replace("[-]","'",$lstsql);
+            unset ($arrOpcVisualizacao);
+            $arrOpcVisualizacao[] = array('lstexibe_resultados', ' Exibir resultados na tela.', $lstexibe_resultados);
+            $arrOpcVisualizacao[] = array('lstexibe_header', ' Exibir titulos das colunas', $lstexibe_header);
+            $arrOpcVisualizacao[] = array('lstexibe_totalizadores', ' Exibir totalizadores', $lstexibe_totalizadores);
+            $arrOpcVisualizacao[] = array('lstexibe_subtotais', ' Exibir sub-totalizadores', $lstexibe_subtotais);
+            $arrOpcVisualizacao[] = array('lstexibe_qtdregistros', ' Exibir Quantidade de registros encontrados', $lstexibe_qtdregistros);
+            $arrOpcVisualizacao[] = array('lstexibe_checkbox', ' Exibir colunas com checkbox.', $lstexibe_checkbox);
+            $arrOpcVisualizacao[] = array('lstexibe_csv', ' Gerar CSV', $lstexibe_csv);
+            $arrOpcVisualizacao[] = array('lstexibe_legendatopo', ' Exibir legenda no topo', $lstexibe_legendatopo);
+            $arrOpcVisualizacao[] = array('lstexibe_legendarodape', ' Exibir legenda no rodape', $lstexibe_legendarodape);
+            $arrOpcVisualizacao[] = array('lstexibe_titagrupamento', ' Re-exibir titulos de agrupamento', $lstexibe_titagrupamento);
+            $arrOpcVisualizacao[] = array('lstexibe_agrupamento_alfabetico', ' Exibir agrupamento alfabetico', $lstexibe_agrupamento_alfabetico);
+            
+            
+            $arrOpcVisualizacao[] = array('lstexclusao', ' Ativa', $f_lstexclusao);
+            
+            $lstexclusao = $linha->lstexclusao;
+
+        }
+
+        if ($acao == "atualizar_listagem") {
+            
+            if ($lstoid != "") {
+                 $sql = "select 
+                            lstidlistagem
+                        from 
+                            listagem.listagem 
+                        where 
+                            lstoid = $lstoid";
+                $res = pg_query($sql);
+                $linha = pg_fetch_object($res);
+                
+                $lstidlistagem = $linha->lstidlistagem;
+            
+            }
+            
+            //$lstsql = str_replace("\\'","[-]",$lstsql);
+            //$lstsql = str_replace("'","[-]",$lstsql);
+            
+            $lstdescricao = htmlspecialchars($lstdescricao,ENT_QUOTES);
+            $lstnome = htmlspecialchars($lstnome,ENT_QUOTES);
+            $lstsql = htmlspecialchars($lstsql,ENT_QUOTES);
+            
+            try {
+                pg_query($conn,"BEGIN;");
+                if ($lstoid == "") {
+                    
+                    $sql = "INSERT INTO listagem.listagem (  lstidlistagem,
+                                                    lstnome,
+                                                    lsttitulo,
+                                                    lstsql,
+                                                    lstexibe_header,
+                                                    lstexibe_totalizadores,
+                                                    lstexibe_qtdregistros,
+                                                    lstexibe_subtotais,
+                                                    lstexibe_checkbox,
+                                                    lstexibe_csv,
+                                                    lstexibe_legendatopo,
+                                                    lstexibe_legendarodape,
+                                                    lstexibe_titagrupamento,
+                                                    lstmsg_totalizador,
+                                                    lstmsg_subtotalizador,
+                                                    lstmsg_registrosencontrados,
+                                                    lstmsg_nenhumresultado, 
+                                                    lstversao,
+                                                    lstagrupamento_campo,
+                                                    lstagrupamento_titulo,
+                                                    lstdescricao,
+                                                    lstexibe_agrupamento_alfabetico,
+                                                    lstexibe_resultados,
+                                                    lstexclusao
+                                            ) 
+                                            VALUES 
+                                                (   '$lstidlistagem',
+                                                    '$lstnome',
+                                                    '$lsttitulo',
+                                                    '$lstsql',
+                                                    $lstexibe_header,
+                                                    $lstexibe_totalizadores,
+                                                    $lstexibe_qtdregistros,
+                                                    $lstexibe_subtotais,
+                                                    $lstexibe_checkbox,
+                                                    $lstexibe_csv,
+                                                    $lstexibe_legendatopo,
+                                                    $lstexibe_legendarodape,
+                                                    $lstexibe_titagrupamento,
+                                                    '$lstmsg_totalizador',
+                                                    '$lstmsg_subtotalizador',
+                                                    '$lstmsg_registrosencontrados',
+                                                    '$lstmsg_nenhumresultado',
+                                                    1,
+                                                    '$lstagrupamento_campo',
+                                                    '$lstagrupamento_titulo',
+                                                    '$lstdescricao',
+                                                    $lstexibe_agrupamento_alfabetico,
+                                                    $lstexibe_resultados,
+                                                    $flstexclusao
+                                            )";
+                                                   
+                                              //     echo $sql;
+                    $result = pg_query($conn,$sql);
+                    if (!$result) { throw new Exception("ERRO: Inserindo listagem."); }
+                    
+                    $sql = "SELECT max(lstoid) as lstoid from listagem.listagem ";
+                    $result = pg_query($conn,$sql);
+                    
+                    $dados  = pg_fetch_array($result);
+                    $lstoid = $dados['lstoid'];
+                    
+                    echo "<script>document.frm.lstoid.value='$lstoid';</script>";
+                    $acao = "editar";
+                                    
+                    $msg = "Registro Inserido com Sucesso!";
+    
+                } else {
+                    
+                    $sql = "UPDATE listagem.listagem SET 
+                                                lstnome = '$lstnome',
+                                                lsttitulo = '$lsttitulo',  
+                                                lstsql = '$lstsql',
+                                                lstexibe_header = $lstexibe_header,
+                                                lstexibe_totalizadores = $lstexibe_totalizadores,
+                                                lstexibe_qtdregistros = $lstexibe_qtdregistros,
+                                                lstexibe_subtotais = $lstexibe_subtotais,
+                                                lstexibe_checkbox = $lstexibe_checkbox,
+                                                lstexibe_csv = $lstexibe_csv, 
+                                                lstexibe_legendatopo = $lstexibe_legendatopo,
+                                                lstexibe_legendarodape = $lstexibe_legendarodape,
+                                                lstexibe_titagrupamento = $lstexibe_titagrupamento,
+                                                lstexibe_agrupamento_alfabetico = $lstexibe_agrupamento_alfabetico,
+                                                lstmsg_totalizador = '$lstmsg_totalizador',
+                                                lstmsg_subtotalizador  = '$lstmsg_subtotalizador',
+                                                lstmsg_registrosencontrados = '$lstmsg_registrosencontrados',
+                                                lstmsg_nenhumresultado = '$lstmsg_nenhumresultado',
+                                                lstversao = lstversao + 1,
+                                                lstagrupamento_campo = '$lstagrupamento_campo',
+                                                lstagrupamento_titulo = '$lstagrupamento_titulo',
+                                                lstdescricao = '$lstdescricao',
+                                                lstexibe_resultados = $lstexibe_resultados,
+                                                lstexclusao = $flstexclusao
+                                        WHERE lstoid = $lstoid";
+                    $result = pg_query($conn,$sql);
+                    if (!$result) { throw new Exception("ERRO: Inserindo listagem."); }
+                    $msg = "Registro Atualizado com Sucesso!";
+                }
+                
+                pg_query($conn,"COMMIT;");
+            
+            } catch (exception $e) {
+            	$msg = $e->getMessage();
+                pg_query($conn,"ROLLBACK;");
+            }
+            
+        }
+        
+        $lstsql =  html_entity_decode($lstsql, ENT_QUOTES);
+        $lstnome =  html_entity_decode($lstnome, ENT_QUOTES);
+        $lstdescricao =  html_entity_decode($lstdescricao, ENT_QUOTES);
+        
+        $form->adicionarHidden("lstoid",$lstoid);
+        $form->adicionarHidden("abaMenu",$abaMenu);
+        $form->adicionarHidden("acao","editar");
+        $form->adicionarCampo("lstidlistagem","lstidlistagem","ID da Listagem","Identificador da Listagem",$lstidlistagem,true);
+        
+        $form->adicionarCampo("lstnome","lstnome","Nome:","Nome:",$lstnome,true,"80");
+        
+        $form->adicionarTextarea("lstdescricao","Descricao:",$lstdescricao,true,"80","8");
+        $form->adicionarSubtitulo("Consulta");
+        
+        $form->adicionarTextarea("lstsql","",$lstsql,true,"120","15");
+        
+        $form->adicionarSubtitulo("Opcoes de Visualizacao");
+        $form->adicionarCheckBox("opcvisualizacao","",$arrOpcVisualizacao,false);
+
+        $form->adicionarSubtitulo("Agrupamento");
+        $form->adicionarCampo("lstagrupamento_campo","lstagrupamento_campo","Campo de Agrupamento:","Campo de Agrupamento:",$lstagrupamento_campo,false,"","","Campo que sera usado para agrupar os sub-totalizadores (Nao usar {}).");
+        $form->adicionarCampo("lstagrupamento_titulo","lstagrupamento_titulo","Titulo do Agrupamento:","Titulo do Agrupamento:",$lstagrupamento_titulo,false,"50","300","Ex.: Cliente: {clinome}");
+        
+        $form->adicionarSubtitulo("Mensagens Personalizadas");
+        $form->adicionarCampo("lsttitulo","lsttitulo","Titulo:","Titulo:",$lsttitulo,true,"50");
+        $form->adicionarCampo("lstmsg_totalizador","lstmsg_totalizador","Mensagem Totalizador:","Mensagem Totalizador:",$lstmsg_totalizador,true);
+        $form->adicionarCampo("lstmsg_subtotalizador","lstmsg_subtotalizador","Mensagem Sub-Totalizador:","Mensagem Sub-Totalizador:",$lstmsg_subtotalizador,true);
+        $form->adicionarCampo("lstmsg_registrosencontrados","lstmsg_registrosencontrados","Mensagem Registros Encontrados:","Mensagem Registros Encontrados:",$lstmsg_registrosencontrados,true);
+        $form->adicionarCampo("lstmsg_nenhumresultado","lstmsg_nenhumresultado","Mensagem Nenhum Resultado:","Mensagem Nenhum Resultado:",$lstmsg_nenhumresultado,true);
+        $form->agruparCampos("lstmsg_totalizador,lstmsg_subtotalizador;lstmsg_registrosencontrados,lstmsg_nenhumresultado");
+
+        if ($lstexclusao) {
+            $novostatus = "1";
+            $titulo = "Ativar";
+        } else {
+            $novostatus = "0";
+            $titulo = "Inativar";
+        }
+        $form->adicionarHidden("novostatus",$novostatus);
+
+        $form->adicionarQuadro("quadro1","Cadastro de Listagem");
+        
+        $form->adicionarSubmit("quadro1","btn_cadastrar","Atualizar","atualizar_listagem");
+        /*if ($lstoid != "") {
+            $form->adicionarSubmit("quadro1","btn_status",$titulo,"alterarStatus");
+        }*/
+
+    }
+    
+if ($msg != "") {
+    echo "<script>ExibirMensagem('$msg')</script>";
+}
+$form->desenhar();
+
+if ($lstoid) {
+	echo "<script>bloquear_campo('id_lstidlistagem');</script>";
+}
+?>
Index: trunk/workflow/inc/report/includes/php/listagem/lst_preview.php
===================================================================
--- trunk/workflow/inc/report/includes/php/listagem/lst_preview.php	(revision 5307)
+++ trunk/workflow/inc/report/includes/php/listagem/lst_preview.php	(revision 5307)
@@ -0,0 +1,133 @@
+<?php
+
+$sql = "select lstidlistagem, lstnome from listagem.listagem where lstoid = $lstoid";
+$res = pg_query($conn,$sql);
+$dados= pg_fetch_array($res);
+$lstidlistagem = $dados["lstidlistagem"];
+
+$form           = new Formulario("FrmCadListagem");
+$form->setAction($BASE_URL);
+$listagem = new Listagem($idlistagem,"",$conn);
+$listagem->setDebug(true);
+$listagem->setUrlBasePath($GLOBALS['phpgw_info']['server']['webserver_url'] . "/workflow/inc/report");
+$listagem->carregarIDListagem($lstidlistagem);
+
+$sql_par = "select 
+                lspoid,
+                lsplstoid,
+                lspidparametro,
+                lsptitulo,
+                lsptipo,
+                lspvalor_padrao,
+                lspobrigatorio 
+            from 
+                listagem.listagem_parametro 
+            where 
+                lsplstoid = $lstoid 
+            order by lspoid ";
+$resu_par = pg_query($conn,$sql_par);
+
+$form->adicionarHidden("lstoid",$lstoid);
+$form->adicionarHidden("abaMenu",$abaMenu);
+$form->adicionarHidden("acao","editar");
+$exibeform = false;
+
+while ($parametro = pg_fetch_object($resu_par)) {
+    $idparametro = $parametro->lspidparametro;
+    $titulo = $parametro->lsptitulo;
+
+    
+    if ($titulo == "") { 
+    	$titulo = $idparametro;
+    }
+    $tipo = $parametro->lsptipo;
+    $obrigatorio = ($parametro->lspobrigatorio == "t") ? true : false;
+    $valor_padrao = $parametro->lspvalor_padrao;
+    
+    $exibeform = true;    
+    
+    $valor = $_POST[$idparametro];
+    if ($tipo == "data") {
+    	$valor = $_POST[$idparametro . "_inicio"];
+    }
+    if (($valor == "") && ((!isset($_POST[$idparametro])) && (!isset($_POST[$idparametro . "_inicio"])))) { $valor = $valor_padrao; }
+    
+    if ($obrigatorio) { $titulo .= " *"; }
+
+    $form->adicionarCampo($idparametro,$tipo,$titulo. ":",$idparametro . ":",$valor,$obrigatorio);
+    
+    $listagem->setParametro($idparametro,$valor);
+    
+    $addobr = "";
+    if ($obrigatorio) { $addobr = " //OBRIGATÓRIO"; }
+    
+    $adicionarcodigo .= "\$report->setParam('$idparametro',\$$valor_$idparametro);$addobr<br>";
+}
+
+if ($exibeform) {
+    $form->adicionarQuadro("quadro1","Formulário de Pesquisa");
+    $form->adicionarSubmit("quadro1","btn_cadastrar","Pesquisar","pesquisar");
+    $form->desenhar();
+}
+
+
+
+$html = "<center>
+            <table class='tableMoldura'>
+               <tr class='tableSubTitulo'><td><h2>CÓDIGO FONTE:</h2></td></tr>
+               <tr><td>
+                <br>
+                <div style='margin: 10px;'>
+                \$report = Factory::newInstance('wf_report');<br>
+                \$report->loadReport('$lstidlistagem');<br>$adicionarcodigo
+                \$html_report = \$report->getHTML();<br>
+                \$this->addViewVar('report_result', \$html_report);
+                <br><br>
+                </div>
+                </td></tr>
+            </table>
+</center>";
+
+echo $html;
+
+$listagem->desenhar();
+$consulta = $listagem->getSQL();
+
+
+$res = pg_query($conn,"EXPLAIN " . $consulta);
+if (pg_num_rows($res)) {
+    $tr .= "<table class='tableMoldura'>
+                    <tr class='tableSubTitulo'><td colspan=5><h2>EXPLAIN</h2></td></tr>
+                    <tr class='tableTituloColunas'>
+                        <td><h3>Possíveis problemas encontrados no plano de consulta</h3></td>
+                    </tr>";
+    
+            $qtd = 0;
+            $qtd1 = 0;
+            while ($plan = pg_fetch_array($res)) {
+                $qtd1 = $qtd1+1;
+                if ((stristr($plan["QUERY PLAN"],"Seq Scan")) || ($qtd1 == 1)) {
+                    $class = ( $class == "tdc" ) ? "tde" : "tdc";
+                    $tr .= "<tr class='$class'>";
+                    $tr .= "<td>" .$plan["QUERY PLAN"]. "</td>";
+                    $tr .= "</tr>";
+                    $qtd = $qtd + 1;
+                }
+            }
+            if ($qtd == 0) { $msgres = "Nenhum Resultado Encontrado."; } else { $msgres = "$qtd resultado(s) encontrado(s)."; }
+            $tr .= "<tr class='tableRodapeModelo1'><td colspan=5 align='center'><h3>$msgres</h3></td></tr>";
+            $tr .= "</table>";
+}
+
+echo "<center><table class='tableMoldura'>
+                   <tr class='tableSubTitulo'><td><h2>CONSULTA EXECUTADA:</h2></td></tr>
+                   <tr><td>
+                    <br>
+                    <div style='margin: 10px;'>
+                    $consulta
+                    </div>
+    <br><center>$tr</center>
+                    </td></tr>
+                </table></center>";
+
+?>
Index: trunk/workflow/inc/report/includes/php/listagem/lst_sincronizacao.php
===================================================================
--- trunk/workflow/inc/report/includes/php/listagem/lst_sincronizacao.php	(revision 5307)
+++ trunk/workflow/inc/report/includes/php/listagem/lst_sincronizacao.php	(revision 5307)
@@ -0,0 +1,96 @@
+<?
+
+          
+$sql = "select lstidlistagem from listagem where lstoid = $lstoid";
+$res = pg_query($sql);
+$linha = pg_fetch_object($res);          
+$idlistagem = $linha->lstidlistagem;
+
+$listas = array("$idlistagem");
+$retorno = utf8_decode(verificaVersao($listas,false));
+
+if ($retorno) {
+    
+    //echo $retorno;
+$resposta = new SimpleXMLElement($retorno);
+
+    
+foreach ($resposta->listagem as $listagem) {
+        //echo $listagem->lstidlistagem . ":" . $listagem->sincronizado . "<br>";
+        //print_r($listagem->dependencias);
+        
+        $versao_desenvolvimento = $listagem->versaoTESTES;
+        $versao_producao = $listagem->versaoPRODUCAO;
+        
+        $tr .= "<table class='tableMoldura'>
+                <tr class='tableSubTitulo'><td colspan=3><h2>Módulos dependentes desta listagem em producao.</h2></td></tr>
+                <tr class='tableTituloColunas'><td><h3>Arquivo</h3></td><td align='center'><h3>Data Primeiro Acesso</h3></td><td align='center'><h3>Data Último Acesso</h3></td></tr>";
+        foreach ($listagem->dependencias as $dep) {
+            if (is_object($dep)) {
+            	foreach ($dep as $dependencia) {
+                    $class = ( $class == "tdc" ) ? "tde" : "tdc";
+                    $tr .= "<tr class='$class'>";
+                    $tr .= "<td>" . $dependencia->arquivo . "</td><td align='center'>" . date("d/m/Y H:i",strtotime($dependencia->dt_cadastro)) ."</td><td align='center'>" . date("d/m/Y H:i",strtotime($dependencia->dt_acesso)) . "</td>";
+                    $tr .= "</tr>";
+            	}
+            } else {
+            	$tr .= "<tr class='tableRodapeModelo1'><td colspan=3 align='center'><h3>Nenhum Resultado Encontrado.</h3></td></tr>";
+            }
+        }
+        $tr .= "</table>";
+        
+        if ($versao_desenvolvimento == "0") {
+            $versao_desenvolvimento = "NÃO EXISTE.";
+        } 
+        
+        if ($versao_producao == "0") {
+        	$versao_producao = "NÃO EXISTE.";
+        } 
+        
+        if ($listagem->sincronizado == "1") {
+        	$html_botoes = "<div id='botoes_sincronizacao' style='margin: 10px; width: 60px; float: left;'><br><br><br><img src='./images/icones/v.gif'></div>";
+        } else {
+        	$html_botoes = "<div id='botoes_sincronizacao' style='margin: 10px; width: 60px; float: left;'><br><br><img src='./images/icones/t3/cetaDireita.jpg' style='cursor: pointer;' onclick=\"if (confirm('Deseja Realmente Sincronizar?')) { xajax_sincronizar('$idlistagem','1'); } \"><br><br><img src='./images/icones/t3/cetaEsquerda.jpg' style='cursor: pointer;' onclick=\"if (confirm('Deseja Realmente Sincronizar?')) { xajax_sincronizar('$idlistagem','2'); } \"></div>";
+        }
+}
+
+
+
+$html = "<center>
+            <table class='tableMoldura'>
+               <tr class='tableSubTitulo'><td><h2>Sincronização de Servidores</h2></td></tr>
+               <tr><td align='center'>
+                <div style='text-align: center; width: 100%;'>
+                <div style='margin: 10px; width: 300px; border: 1px solid #E0E0E0; float: left;'>
+                    <img src='./images/icones/databaseGrande.gif' style='float: left;'>
+                    <br><br><br>
+                    <h2>DESENVOLVIMENTO</h2>
+                    <br>
+                    <br>
+                    <h2>VERSÃO:<span id='versao_desenvolvimento'>$versao_desenvolvimento</span></h2> 
+                    <div style='clear: both;'></div>
+                </div>
+                $html_botoes
+                <div style='margin: 10px; width: 300px; border: 1px solid #E0E0E0; float: left;'>
+                    <img src='./images/icones/databaseGrande.gif' style='float: left;'>
+                    <br><br><br>
+                    <h2>PRODUCAO</h2>
+                    <br>
+                    <br>
+                    <h2>VERSÃO:<span id='versao_producao'>$versao_producao</span></h2> 
+                    <div style='clear: both;'></div>
+                </div>
+                <div style='clear: both;'></div>
+</div>
+                </td></tr>
+            </table>
+
+$tr
+</center>";
+            
+}
+
+echo $html;
+
+  
+?>
Index: trunk/workflow/inc/report/includes/php/listagem/cad_listagem.xajax.php
===================================================================
--- trunk/workflow/inc/report/includes/php/listagem/cad_listagem.xajax.php	(revision 5307)
+++ trunk/workflow/inc/report/includes/php/listagem/cad_listagem.xajax.php	(revision 5307)
@@ -0,0 +1,221 @@
+<?php
+
+//require_once ('./xajax/xajax.inc.php');
+
+$xajax = new xajax();
+$xajax->registerFunction('selecionarTipoColuna');
+$xajax->registerFunction('sincronizar');
+
+$xajax->setCharEncoding('ISO-8859-1');
+$xajax->decodeUTF8InputOn();
+
+$xajax->processRequests();
+
+// Funes XAJAX
+function selecionarTipoColuna($tipo) {
+    global $conn;
+    $objResponse = new xajaxResponse();
+    
+    $objResponse->addScript("formUtilOcultaCampos('lslccalculada,lslccheckbox');");
+    
+    if ($tipo == "int") {
+        $objResponse->addScript("formUtilExibeCampos('lslccalculada,lslccheckbox,lslctotalizador_condicao,lslcsubtotalizador_condicao,lslccheckbox_condicao');");
+    }
+    
+    if ($tipo == "moeda") {
+        $objResponse->addScript("formUtilExibeCampos('lslccalculada,lslctotalizador_condicao,lslcsubtotalizador_condicao');");
+    }
+    
+    if ($tipo == "hora") {
+        $objResponse->addScript("formUtilExibeCampos('lslccalculada,lslctotalizador_condicao,lslcsubtotalizador_condicao');");
+    }
+    
+    return $objResponse->getXML();
+}
+
+
+function sincronizar($idlistagem,$conexao = "1") {
+    global $conn;
+    $objResponse = new xajaxResponse();
+    
+    $xml_params = '<?xml version="1.0" encoding="ISO-8859-1"?>
+    <raiz xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+        <sincronizaVersao>
+            <lstidlistagem>'. $idlistagem . '</lstidlistagem>
+            <conexao>'. $conexao . '</conexao>
+        </sincronizaVersao>
+    </raiz>';
+    
+     $xml_params = utf8_encode($xml_params);
+     
+     
+     $server_url = "http://url_servidor/webservice/cad_listagem_sincronizacao/cadListagem_server.php?wsdl";
+
+    $client = new SoapClient(   $server_url,
+                            array(  'trace' => 1, 'exceptions' => 1,'soap_version' => SOAP_1_1));
+                                    
+    try {
+
+        $save_result = $client->sincronizar($xml_params);
+        
+        $objResponse->addAssign("botoes_sincronizacao","innerHTML","<br><br><br><img src='./images/icones/v.gif'>");
+        
+        if ($conexao == "1") {
+            $objResponse->addScript("document.getElementById('versao_producao').innerHTML = document.getElementById('versao_labirinto').innerHTML;");
+        } else {
+            $objResponse->addScript("document.getElementById('versao_desenvolvimento').innerHTML = document.getElementById('versao_producao').innerHTML;");
+        }
+
+        $objResponse->addScript("ExibirMensagem('Sincronizacao Efetuada com sucesso.')");
+        $objResponse->addAlert('Sincronizacao Efetuada com sucesso.');
+        
+    } catch (SoapFault $e){
+        $objResponse->addAlert("FALHOU! SOAP Fault: ".$e->getMessage());
+    } 
+    
+    
+    return $objResponse->getXML();
+}
+
+function atualizaStatus($listagems,$status,$debug = false) {
+    $versoes = "";
+    foreach ($listagems as $listagem) {
+       $versoes .= '
+    <atualizaStatus>
+        <lstidlistagem>' . $listagem . '</lstidlistagem>
+        <status>' . $status . '</status>
+    </atualizaStatus>';   
+    }
+    
+    $xml_params='<?xml version="1.0" encoding="ISO-8859-1"?>
+<raiz xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' . $versoes . '
+</raiz>';
+    //$xml_params = utf8_encode($xml_params);
+    
+    //echo $xml_params;
+
+	 $server_url = "http://url_servidor/webservice/cad_listagem_sincronizacao/cadListagem_server.php?wsdl";
+
+    $client = new SoapClient(   $server_url,
+                            array(  'trace' => 1, 'exceptions' => 1,'soap_version' => SOAP_1_1));
+                                    
+    try {
+
+        $save_result = $client->atualizaStatus($xml_params);
+        
+
+        if ($debug) { 
+            echo "<hr>";
+            echo "<pre>\n\n";
+            echo "Request Cabeï¿œalho:\n";
+            echo htmlspecialchars($client->__getLastRequestHeaders())."\n";
+            echo "</pre>";
+            
+            echo "<pre>\n\n";
+            echo "Request:\n";
+            echo htmlspecialchars($client->__getLastRequest())."\n";
+            echo "</pre>";
+            echo "<hr>";
+            
+            echo "<pre>\n\n";
+            echo "Retorno Cabeï¿œalho:\n";
+            echo htmlspecialchars($client->__getLastResponseHeaders())."\n";
+            echo "</pre>";
+            
+            echo "<pre>\n\n";
+            echo "Retorno:\n";
+            echo htmlspecialchars($client->__getLastResponse())."\n";
+            echo "</pre>";
+            
+            echo "<br>ENVIO FINALIZADO!<br>";
+        }
+        
+        return $save_result;
+        
+    } catch (SoapFault $e){
+        echo "<br>FALHOU! SOAP Fault: ".$e->getMessage()."<br>";        
+    } 
+}
+
+
+function verificaVersao($listagems,$debug = false) {
+    $versoes = "";
+    foreach ($listagems as $listagem) {
+       $versoes .= '
+    <verificaVersao>
+        <lstidlistagem>' . $listagem . '</lstidlistagem>
+    </verificaVersao>';   
+    }
+    
+    $xml_params='<?xml version="1.0" encoding="ISO-8859-1"?>
+<raiz xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' . $versoes . '
+</raiz>';
+    //$xml_params = utf8_encode($xml_params);
+    
+    //echo $xml_params;
+    
+    $server_url = "http://url_servidor/webservice/cad_listagem_sincronizacao/cadListagem_server.php?wsdl";
+
+    $client = new SoapClient(   $server_url,
+                            array(  'trace' => 1, 'exceptions' => 1,'soap_version' => SOAP_1_1));
+                                    
+    try {
+
+        $save_result = $client->verificaVersao($xml_params);
+        
+
+        if ($debug) { 
+            echo "<hr>";
+            echo "<pre>\n\n";
+            echo "Request Cabecalho:\n";
+            echo htmlspecialchars($client->__getLastRequestHeaders())."\n";
+            echo "</pre>";
+            
+            echo "<pre>\n\n";
+            echo "Request:\n";
+            echo htmlspecialchars($client->__getLastRequest())."\n";
+            echo "</pre>";
+            echo "<hr>";
+            
+            echo "<pre>\n\n";
+            echo "Retorno Cabecalho:\n";
+            echo htmlspecialchars($client->__getLastResponseHeaders())."\n";
+            echo "</pre>";
+            
+            echo "<pre>\n\n";
+            echo "Retorno:\n";
+            echo htmlspecialchars($client->__getLastResponse())."\n";
+            echo "</pre>";
+            
+            echo "<br>ENVIO FINALIZADO!<br>";
+        }
+        
+        return $save_result;
+        
+    } catch (SoapFault $e){
+        echo "<br>FALHOU! SOAP Fault: ".$e->getMessage()."<br>";        
+    } 
+}
+
+function atualizarVersao($conn,$lstoid) {
+	$sql = "update listagem.listagem set lstversao = lstversao + 1 where lstoid = $lstoid";
+    $res = pg_query($conn,$sql);
+    return ($res);
+}
+
+function retornaParametros($sql) {
+    $sqlparametros = array();
+    $abre_chaves = explode("{",$sql);
+    foreach ($abre_chaves as $chave) {
+        $_chaves = array();
+        if (stristr($chave,"}")) {
+            $_chaves = explode("}",$chave);
+            $sqlparametros[] = $_chaves[0];
+        }
+    }
+    return $sqlparametros;
+}
+
+$xajax->printJavascript("workflow/inc/report/");
+
+?>
Index: trunk/workflow/inc/report/includes/php/listagem/lst_colunas.php
===================================================================
--- trunk/workflow/inc/report/includes/php/listagem/lst_colunas.php	(revision 5307)
+++ trunk/workflow/inc/report/includes/php/listagem/lst_colunas.php	(revision 5307)
@@ -0,0 +1,354 @@
+<?php
+
+$form           = new Formulario("FrmCadListagem");
+$form->setAction($BASE_URL);
+$listagem       = new Listagem("listResultado","Colunas",$conn);
+$listagem->setUrlBasePath($GLOBALS['phpgw_info']['server']['webserver_url'] . "/workflow/inc/report");
+
+$lslcoid = (isset($_POST['lslcoid'])) ? $_POST['lslcoid'] : $_GET['lslcoid'];
+
+if ($acao == "excluir") {
+	$sql = "delete from listagem.listagem_coluna where lslcoid = $lslcoid ";
+    pg_query($conn,$sql);
+    $msg = "Coluna Excluída com sucesso!";
+}
+
+if ($form->isSubmit("atualizar_coluna",true)) {
+    
+    $lslcidcoluna         = $_POST['lslcidcoluna'];
+    $lslcidcoluna = str_replace("{","",$lslcidcoluna);
+    $lslcidcoluna = str_replace("}","",$lslcidcoluna);
+    
+    $lslctitulo           = $_POST['lslctitulo'];
+    $lslctipo             = $_POST['lslctipo'];
+    $lslchtml             = $_POST['lslchtml'];
+    $lslcalign            = $_POST['lslcalign'];
+    $lslcwidth            = $_POST['lslcwidth'];
+    $lslclink             = $_POST['lslclink'];
+    $lslclink_condicao    = $_POST['lslclink_condicao'];
+    $lslcordem            = $_POST['lslcordem'];
+    
+    //print_r($_POST['lslclink_blank']);
+    $lslclink_blank = (isset($_POST['lslclink_blank'])) ? true: false;
+    $lslcnowrap =  (isset($_POST['lslcnowrap'])) ? true: false;
+    $lslcvisivel =  (isset($_POST['lslcvisivel'])) ? true: false;
+    $lslcexibe_csv = (isset($_POST['lslcexibe_csv'])) ? true: false;
+    $lslccheckbox = (isset($_POST['lslccheckbox'])) ? true: false;
+    $lslccalculada = (isset($_POST['lslccalculada'])) ? true: false;
+    
+    $flslclink_blank = ($lslclink_blank) ?  "'t'" : "'f'"; 
+    $flslcnowrap = ($lslcnowrap) ?  "'t'" : "'f'"; 
+    $flslcexibe_csv = ($lslcexibe_csv) ?  "'t'" : "'f'"; 
+    $flslcvisivel = ($lslcvisivel) ?  "'t'" : "'f'";
+    $flslccheckbox = ($lslccheckbox) ?  "'t'" : "'f'"; 
+    $flslccalculada = ($lslccalculada) ?  "'t'" : "'f'";  
+    
+    try {
+        pg_query($conn,"BEGIN;");
+       if ($lslcoid == "") {
+            
+            $lslcidcoluna =  htmlspecialchars($lslcidcoluna, ENT_QUOTES);
+            $lslctitulo =  htmlspecialchars($lslctitulo, ENT_QUOTES);
+            $lslchtml =  htmlspecialchars($lslchtml, ENT_QUOTES);
+            $lslclink =  htmlspecialchars($lslclink, ENT_QUOTES);
+            $lslclink_condicao =  htmlspecialchars($lslclink_condicao, ENT_QUOTES);    
+            
+            $sqlver = "select lslcoid from listagem.listagem_coluna where lslcidcoluna = '$lslcidcoluna' and lslclstoid = '$lstoid'";
+            $res = pg_query($sqlver);
+            $qtd = pg_num_rows($res);
+    
+            if ($qtd == 0) {
+                $sql = "insert into 
+                            listagem.listagem_coluna ( 
+                            
+                            lslclstoid,
+                            lslcidcoluna,
+                            lslctipo,
+                            lslctitulo,
+                            lslchtml,
+                            lslcalign,
+                            lslcexibe_csv,
+                            lslcvisivel,
+                            lslccheckbox,
+                            lslccalculada,
+                            lslcnowrap,
+                            lslcordem,
+                            lslclink,
+                            lslclink_condicao,
+                            lslcwidth
+                        ) values (
+                        
+                            $lstoid,
+                            '$lslcidcoluna',
+                            '$lslctipo',
+                            '$lslctitulo',
+                            '$lslchtml',
+                            '$lslcalign',
+                            $flslcexibe_csv,
+                            $flslcvisivel,
+                            $flslccheckbox,
+                            $flslccalculada,
+                            $flslcnowrap,
+                            $lslcordem,
+                            '$lslclink',
+                            '$lslclink_condicao',
+                            '$lslcwidth'
+                        );";
+                 //       echo $sql;
+                $res = pg_query($conn,$sql);
+                
+                //atualizarVersao($conn,$lstoid);
+                if (!$res) { throw new Exception("Incluindo nova coluna."); }
+                
+                $msg=  "Coluna adicionada com Sucesso!";
+                
+            } else {
+                $msg = "Identificador de Coluna já está adicionado a essa listagem.";
+            }
+            
+        } else {
+            $sql = "update 
+                        listagem.listagem_coluna 
+                    set lslcidcoluna = '$lslcidcoluna', 
+                        lslctipo='$lslctipo', 
+                        lslctitulo = '$lslctitulo', 
+                        lslchtml = '$lslchtml',
+                        lslcalign = '$lslcalign',
+                        lslcwidth = '$lslcwidth',
+                        lslcexibe_csv = $flslcexibe_csv,
+                        lslcvisivel = $flslcvisivel,
+                        lslccalculada = $flslccalculada,
+                        lslccheckbox = $flslccheckbox,
+                        lslcnowrap = $flslcnowrap,
+                        lslcordem = $lslcordem,
+                        lslclink = '$lslclink',
+                        lslclink_condicao = '$lslclink_condicao',
+                        lslclink_blank = $flslclink_blank
+                    where lslcoid = $lslcoid
+    
+     ";
+           $res = pg_query($conn,$sql);
+           if (!$res) { throw new Exception("Atualizando informações da coluna."); }
+           
+           //atualizarVersao($conn,$lstoid);
+           
+           $msg=  "Coluna atualizada com Sucesso!";
+           $lslcoid = "";
+           $acao = "editar";
+        }
+        
+        pg_query($conn,"COMMIT;");
+    
+     } catch (exception $e) {
+                $msg = "ERRO: " . $e->getMessage();
+                pg_query($conn,"ROLLBACK;");
+     }
+}
+
+if ($acao == "editar") {
+    if ($lslcoid != "") {
+        $sql = "select 
+                    lslcoid,
+                    lslclstoid,
+                    lslcidcoluna,
+                    lslcordem,
+                    lslctipo,
+                    lslctitulo,
+                    lslchtml,
+                    lslcalign,
+                    lslcwidth,
+                    lslcnowrap,
+                    lslcvisivel,
+                    lslcexibe_csv,
+                    lslccalculada,
+                    lslccheckbox,
+                    lslclink,
+                    lslclink_condicao,
+                    lslclink_blank,
+                    lslctotalizador_condicao,
+                    lslcsubtotalizador_condicao,
+                    lslccheckbox_condicao
+                from 
+                    listagem.listagem_coluna 
+                where 
+                    lslcoid = $lslcoid ";
+        $res = pg_query($sql);
+        $dados = pg_fetch_object($res);
+        $lslcidcoluna = $dados->lslcidcoluna;
+        $lslctitulo = $dados->lslctitulo;
+        $lslctipo = $dados->lslctipo;
+        $lslchtml = $dados->lslchtml;
+        $lslcalign = $dados->lslcalign;
+        $lslcwidth = $dados->lslcwidth;
+        $lslclink = $dados->lslclink;
+        $lslclink_condicao = $dados->lslclink_condicao;
+        $lslclink_blank = ($dados->lslclink_blank == "t") ? true: false;
+        $lslcnowrap = ($dados->lslcnowrap == "t") ? true: false;
+        $lslcvisivel = ($dados->lslcvisivel == "t") ? true: false;
+        $lslcexibe_csv = ($dados->lslcexibe_csv == "t") ? true: false;
+        $lslccheckbox = ($dados->lslccheckbox == "t") ? true: false;
+        $lslccalculada = ($dados->lslccalculada == "t") ? true: false;
+        $lslcordem = $dados->lslcordem;
+    } else {
+    	$lslcidcoluna = "";
+        $lslctitulo = "";
+        $lslctipo = "";
+        $lslchtml = "";
+        $lslcalign = "";
+        $lslcwidth = "";
+        $lslclink = "";
+        $lslclink_condicao = "";
+        $lslclink_blank = false;
+        $lslcnowrap = false;
+        $lslcvisivel = true;
+        $lslcexibe_csv = true;
+        $lslccheckbox = false;
+        $lslccalculada = false;
+        $lslcordem = "";
+    }
+}
+
+
+if(isset($lstoid{0})){
+
+
+    $lslcidcoluna       =  html_entity_decode($lslcidcoluna, ENT_QUOTES);
+    $lslctitulo         =  html_entity_decode($lslctitulo, ENT_QUOTES);
+    $lslchtml           =  html_entity_decode($lslchtml, ENT_QUOTES);
+    $lslclink           =  html_entity_decode($lslclink, ENT_QUOTES);
+    $lslclink_condicao  =  html_entity_decode($lslclink_condicao, ENT_QUOTES);
+    
+
+    $form->adicionarHidden("lstoid",$lstoid); 
+    $form->adicionarHidden("lslcoid",$lslcoid); 
+    $form->adicionarHidden("abaMenu",$abaMenu);
+    $form->adicionarHidden("acao","editar");
+    $form->adicionarCampo("lslcidcoluna","lslcidcoluna","ID da Coluna:","Identificador da Coluna",$lslcidcoluna,true,"20");
+    $form->adicionarCampo("lslctitulo","lslctitulo","Titulo da Coluna:","Titulo da Coluna",$lslctitulo,true,"","","");
+    
+    $arrTipoColunas = array ( 
+                              ''      => '---' ,
+                              'text'      => 'Texto' ,
+                              'int'       => 'Número' ,
+                              'data'      => 'Data' ,
+                              'hora'      => 'Hora' ,
+                              'moeda'     => 'Moeda' 
+           );
+    $form->adicionarSelect("lslctipo","Tipo:","Tipo da Coluna",$lslctipo,$arrTipoColunas,true);
+    $form->adicionarCampoAcao("lslctipo","onchange","xajax_selecionarTipoColuna(this.value);");
+    
+    $form->adicionarCampo("lslchtml","lslchtml","Html da Listagem:","Html da Listagem",$lslchtml,true,"","","campo que será exibido entre chaves. Ex: {nomedocampo}");
+
+    $arrTipoAlign = array ( 
+                            ''      => '---' ,
+                            'left'   => 'Esquerda',
+                            'center' => 'Centralizado',
+                            'right'  => 'Direita' );
+    $form->adicionarSelect("lslcalign","Alinhamento (align):","Alinhamento da Coluna",$lslcalign,$arrTipoAlign,true);
+
+    $form->adicionarCampo("lslcwidth","lslcwidth","Tamanho (width):","Tamanho da Coluna",$lslcwidth,false,"10","","Ex: (100px ou 50%)");
+    $form->adicionarCampo("lslcordem","lslcordem","Ordem:","Ordem da Coluna",$lslcordem,true,"10","","Ordem que a coluna irá aparecer.");
+    
+    $form->adicionarSubTitulo("Coluna com Link");
+    $form->adicionarCampo("lslclink","lslclink","URL:","URL",$lslclink,false,"40","","Ex.: arquivo.php?acao=editar&codigo={codigo} OU javascript:editar({codigo});");
+
+    $form->adicionarCampo("lslclink_condicao","lslclink_condicao","Link Condição:","Link Condição",$lslclink_condicao,false,"","","Condição para exibir o link. Ex: (({meustatus} == 1) && ({tipo} > 200)) OU 1 para sempre exibir.");
+    
+    $arrCheckBlank[] = array('t', ' Abrir em uma nova janela.', $lslclink_blank);
+    $form->adicionarCheckBox("lslclink_blank","",$arrCheckBlank,false);
+
+    //$form->agruparCampos("lslclink,lslclink_blank",true);
+    
+    $form->adicionarSubTitulo("Outras Opções");
+    $arrCheckNowRap[] = array('t', ' Não habilitar quebra de linha (nowrap)', $lslcnowrap);
+    $form->adicionarCheckBox("lslcnowrap","",$arrCheckNowRap,false);
+    $form->adicionarCampoAcao("lslcnowrap","onchange","nowrapCheck(this.checked);");
+
+    $arrCheckVisivel[] = array('t', ' Coluna é Visível ', $lslcvisivel);
+    $form->adicionarCheckBox("lslcvisivel","",$arrCheckVisivel,false);
+
+    $arrCheckCSV[] = array('t', ' Exibir coluna no arquivo CSV:', $lslcexibe_csv);
+    $form->adicionarCheckBox("lslcexibe_csv","",$arrCheckCSV,false);
+
+    $arrCheckCalculada[] = array('t', ' Coluna é calculada, com Totalizador e Sub-Totalizador', $lslccalculada);
+    $form->adicionarCheckBox("lslccalculada","",$arrCheckCalculada,false);
+
+    $arrCheckCheck[] = array('t', ' Possui Checkbox para seleção de itens.', $lslccheckbox);
+    $form->adicionarCheckBox("lslccheckbox","",$arrCheckCheck,false);
+   
+    
+    $form->adicionarQuadro("quadro2","Cadastro de Colunas");
+    
+    if ($lslcoid == "") {
+    	$titbotao = "Adicionar";
+    } else {
+    	$titbotao = "Atualizar";
+    }
+    
+    $form->adicionarSubmit("quadro2","btn_cadastrar",$titbotao,"atualizar_coluna");
+    
+    
+    //LISTAGEM DE COLUNAS
+    $sql = "SELECT 
+                lslcoid,
+                lslclstoid,
+                lslcidcoluna,
+                lslcordem,
+                lslctipo,
+                lslctitulo,
+                lslchtml,
+                lslcalign,
+                lslcwidth,
+                lslcnowrap,
+                lslcvisivel,
+                lslcexibe_csv,
+                lslccalculada,
+                lslccheckbox,
+                lslclink,
+                lslclink_condicao,
+                lslclink_blank,
+                lslctotalizador_condicao,
+                lslcsubtotalizador_condicao,
+                lslccheckbox_condicao, 
+                case when lslctipo = 'int' then 'Número' when lslctipo = 'hora' then 'Hora' when lslctipo = 'text' then 'Texto' when lslctipo = 'data' then 'Data' when lslctipo = 'moeda' then 'Moeda' end as novo_tipo  
+            FROM 
+                listagem.listagem_coluna 
+            WHERE 
+                lslclstoid=$lstoid 
+            order by lslcordem";
+    $listagem->carregar($sql);
+    
+    $listagem->adicionarIndicador("indvisivel","({lslcvisivel} == 't')","I","v","Coluna Visível");
+    $listagem->adicionarIndicador("indcsv","({lslcexibe_csv} == 't')","I","v","Exibir no CSV");
+    $listagem->adicionarIndicador("indnowrap","({lslcnowrap} == 't')","I","v","Não habilitar quebra de Linha");
+    $listagem->adicionarIndicador("indcalculada","({lslccalculada} == 't')","I","v","Coluna Calculada");
+    
+    $listagem->adicionarColuna("lslcidcoluna","Coluna","{lslcidcoluna}","text","left","100px");
+    $listagem->adicionarColuna("lslctitulo","Titulo","{lslctitulo}","text","left","100px");
+    $listagem->adicionarColuna("lslchtml","Html","{lslchtml}","text","left","100px");
+    $listagem->adicionarColuna("lslctipo","Tipo","{novo_tipo}","text","left","50px");
+    $listagem->adicionarColuna("lslcwidth","Tamanho","{lslcwidth}","text","left","50px");
+    $listagem->adicionarColuna("lslcvisivel","Visível","{indvisivel}","text","center","10px");
+    $listagem->adicionarColuna("lslcexibe_csv","CSV","{indcsv}","text","center","10px");
+    $listagem->adicionarColuna("lslcnowrap","Nowrap","{indnowrap}","text","center","10px");
+    $listagem->adicionarColuna("lslccalculada","Calculada","{indcalculada}","text","center","10px");
+    $listagem->adicionarColuna("lslcordem","Ordem","{lslcordem}","text","right","50px");
+    
+    $listagem->adicionarColuna("lslcoid","Excluir","[Excluir]","text","center","20px");
+    $listagem->adicionarLink("lslcoid",$BASE_URL . "&abaMenu=colunas&lstoid=$lstoid&lslcoid={lslcoid}&acao=excluir");
+    $listagem->adicionarLink("lslcidcoluna",$BASE_URL . "&abaMenu=colunas&lstoid=$lstoid&lslcoid={lslcoid}&acao=editar");
+    $listagem->setMensagemRegistrosEncontrados("coluna(s) cadastrada(s)");
+    $listagem->setMostrarLegendaTopo(false);
+    $listagem->setMostrarLegendaRodape(false);
+}
+
+if ($msg != "") {
+    echo "<script>ExibirMensagem('$msg')</script>";
+}
+echo "<script>xajax_selecionarTipoColuna('');</script>";
+if ($lscnowrap != "") {
+    echo "<script>nowrapCheck('$lslcnowrap');</script>";
+}
+$form->desenhar();
+$listagem->desenhar();
+?>
Index: trunk/workflow/inc/report/includes/php/listagem/lst_indicadores.php
===================================================================
--- trunk/workflow/inc/report/includes/php/listagem/lst_indicadores.php	(revision 5307)
+++ trunk/workflow/inc/report/includes/php/listagem/lst_indicadores.php	(revision 5307)
@@ -0,0 +1,185 @@
+<?php
+
+$form           = new Formulario("FrmCadListagem");
+$form->setAction($BASE_URL);
+$listagem       = new Listagem("listResultado","Indicadores",$conn);
+$listagem->setUrlBasePath($GLOBALS['phpgw_info']['server']['webserver_url'] . "/workflow/inc/report");
+
+
+$lsioid = (isset($_POST['lsioid'])) ? $_POST['lsioid'] : $_GET['lsioid'];
+
+if ($acao == "excluir_indicador") {
+    $sql = "delete from listagem.listagem_indicador where lsioid = $lsioid ";
+    pg_query($conn,$sql);
+    $msg = "Parâmetro Excluído com sucesso!";
+}
+
+if ($form->isSubmit("atualizar_parametro",true)) {
+    
+    
+    $lsiidindicador = $_POST['lsiidindicador'];
+    $lsiidindicador = str_replace("{","",$lsiidindicador);
+    $lsiidindicador = str_replace("}","",$lsiidindicador);
+    
+    $lsitipo = $_POST['lsitipo'];
+    $lsiimagem = $_POST['lsiimagem'];
+    $lsilegenda = $_POST['lsilegenda'];
+    $lsilegenda_csv = $_POST['lsilegenda_csv'];
+    $lsicondicao = $_POST['lsicondicao'];
+    
+    
+    try {
+
+        pg_query($conn,"BEGIN;");
+        
+        $lsilegenda =  htmlspecialchars($lsilegenda, ENT_QUOTES);
+        $lsilegenda_csv =  htmlspecialchars($lsilegenda_csv, ENT_QUOTES);
+        $lsicondicao =  htmlspecialchars($lsicondicao, ENT_QUOTES);    
+        
+        if ($lsioid == "") {
+    
+            
+                $sql = "insert into 
+                            listagem.listagem_indicador ( 
+                            lsilstoid,
+                            lsiidindicador,
+                            lsitipo,
+                            lsiimagem,
+                            lsilegenda,
+                            lsilegenda_csv,
+                            lsicondicao
+                        ) values (
+                            $lstoid,
+                            '$lsiidindicador',
+                            '$lsitipo',
+                            '$lsiimagem',
+                            '$lsilegenda',
+                            '$lsilegenda_csv',
+                            '$lsicondicao'
+                        );";
+    
+    			echo $sql;
+                $res = pg_query($conn,$sql);
+                //ATUALIZA A VERSÃO DA LISTAGEM PARA MANTER O PROCESSO DE SINCRONIZAÇÃO
+                //atualizarVersao($conn,$lstoid);
+                
+                $msg=  "Indicador adicionado com Sucesso!";
+           
+        } else {
+            $sql = "update 
+                        listagem.listagem_indicador
+                    set lsiidindicador = '$lsiidindicador',
+                        lsitipo = '$lsitipo',
+                        lsiimagem = '$lsiimagem',
+                        lsilegenda = '$lsilegenda',
+                        lsilegenda_csv = '$lsilegenda_csv',
+                        lsicondicao = '$lsicondicao'
+                    where lsioid = $lsioid ";
+    
+           $res = pg_query($conn,$sql);
+           //ATUALIZA A VERSÃO DA LISTAGEM PARA MANTER O PROCESSO DE SINCRONIZAÇÃO
+           //atualizarVersao($conn,$lstoid);
+           $msg=  "Indicador atualizado com Sucesso!";
+           $lsioid = "";
+           $acao = "editar";
+        }
+     pg_query($conn,"COMMIT;");
+    
+     } catch (exception $e) {
+                $msg = "ERRO: " . $e->getMessage();
+                pg_query($conn,"ROLLBACK;");
+     }
+}
+
+if ($acao == "editar") {
+    if ($lsioid != "") {
+        $sql = "select * from listagem.listagem_indicador where lsioid = $lsioid ";
+        $res = pg_query($sql);
+        $dados = pg_fetch_object($res);
+
+        $lsiidindicador = $dados->lsiidindicador;
+        $lsitipo = $dados->lsitipo;
+        $lsiimagem = $dados->lsiimagem;
+        $lsilegenda = $dados->lsilegenda;
+        $lsilegenda_csv = $dados->lsilegenda_csv;
+        $lsicondicao = $dados->lsicondicao;
+
+    } else {
+        $lsiidindicador = "";
+        $lsitipo = "";
+        $lsiimagem = "";
+        $lsilegenda = "";
+        $lsilegenda_csv = "";
+        $lsicondicao = "";
+
+    }
+}
+
+
+if(isset($lstoid{0})){
+    
+    $lsilegenda         =  html_entity_decode($lsilegenda, ENT_QUOTES);
+    $lsilegenda_csv     =  html_entity_decode($lsilegenda_csv, ENT_QUOTES);
+    $lsicondicao        =  html_entity_decode($lsicondicao, ENT_QUOTES);  
+
+    $form->adicionarHidden("lstoid",$lstoid); 
+    $form->adicionarHidden("lsioid",$lsioid); 
+    $form->adicionarHidden("abaMenu",$abaMenu);
+    $form->adicionarHidden("acao","editar");
+    $form->adicionarCampo("lsiidindicador","lsiidindicador","ID do Indicador:","Identificador do Indicador",$lsiidindicador,true,"20","","Identificador do Indicador. (Não usar {}).");
+    
+    $arrTipoIndicador = array (  '' => '---',
+                                 'Q'        => 'Quadrado' ,
+                                 'R'      => 'Redondo' ,
+                                 'T'      => 'Triangulo',
+                                 'I'      => 'Ícone');
+    $form->adicionarSelect("lsitipo","Tipo do Indicador:","Tipo do Indicador:",$lsitipo,$arrTipoIndicador,true);
+    $form->adicionarCampoAcao("lsitipo","onchange","selecionaTipoIndicador(this.value,'$lsiimagem');");
+
+    $arrImagemIndicador = array();
+    $form->adicionarSelect("lsiimagem","Imagem do Indicador:","Imagem do Indicador:",$lsiimagem,$arrImagemIndicador,true,"","150");
+    
+    $form->adicionarCampo("lsilegenda","lsilegenda","Legenda:","Legenda",$lsilegenda,false,"30","","(Deixe em branco para não exibir)");
+    $form->adicionarCampo("lsilegenda_csv","lsilegenda_csv","Legenda CSV:","Legenda",$lsilegenda_csv,false,"30","","Legenda que será exibida no arquivo CSV.");
+    $form->adicionarCampo("lsicondicao","lsicondicao","Condição de Exibição:","Condição",$lsicondicao,false,"50","","Condição para exibir o indicador. Ex: (({meustatus} == 1) && ({tipo} > 200))");
+    
+    $form->adicionarQuadro("quadro2","Cadastro de Indicadores");
+    $form->adicionarSubmit("quadro2","btn_cadastrar","Atualizar","atualizar_parametro");
+
+    //LISTAGEM DE PARÂMETROS
+    $sql = "SELECT * FROM listagem.listagem_indicador WHERE lsilstoid=$lstoid order by lsioid";
+    $res = pg_query($sql);
+    
+    $listagem->carregar($sql);
+    
+    
+    while ($indicador = pg_fetch_object($res)) {
+        $lsioid = $indicador->lsioid;
+        $tipo = $indicador->lsitipo;
+        $imagem = $indicador->lsiimagem;
+        $legenda = $indicador->lsilegenda;
+        $listagem->adicionarIndicador("indicador","({lsioid} == $lsioid)",$tipo,$imagem,$legenda);
+    }
+    
+    $listagem->adicionarColuna("indicador","","{indicador}","text","center","20px");
+    $listagem->adicionarColuna("lsiidindicador","ID do indicador","{lsiidindicador}","text","left","100px");
+    $listagem->adicionarColuna("lsilegenda","Legenda","{lsilegenda}","text","left","200px");
+    $listagem->adicionarColuna("lsilegenda_csv","Legenda CSV","{lsilegenda_csv}","text","left","200px");
+    $listagem->adicionarColuna("lsicondicao","Condição de Exibição","{lsicondicao}","text","left","200px");
+
+    $listagem->adicionarColuna("lsioid","Excluir","[Excluir]","text","center","50px");
+    $listagem->adicionarLink("lsioid",$BASE_URL . "&abaMenu=indicadores&lstoid=$lstoid&lsioid={lsioid}&acao=excluir_indicador");
+    $listagem->adicionarLink("lsiidindicador",$BASE_URL . "&abaMenu=indicadores&lstoid=$lstoid&lsioid={lsioid}&acao=editar");
+    $listagem->setMensagemRegistrosEncontrados("indicadores(s) cadastrado(s)");
+    $listagem->setMostrarLegendaTopo(false);
+    $listagem->setMostrarLegendaRodape(true);
+}
+
+if ($msg != "") {
+    echo "<script>ExibirMensagem('$msg')</script>";
+}
+$form->desenhar();
+$listagem->desenhar();
+echo "<script>selecionaTipoIndicador('$lsitipo','$lsiimagem')</script>";
+echo "<div id='div_result_colunas'></div>";
+?>
Index: trunk/workflow/inc/report/includes/css/calendar.css
===================================================================
--- trunk/workflow/inc/report/includes/css/calendar.css	(revision 5307)
+++ trunk/workflow/inc/report/includes/css/calendar.css	(revision 5307)
@@ -0,0 +1,163 @@
+#calendarDiv
+{
+    position:absolute;
+    width:205px;
+    border:1px solid #006699;
+    padding:1px;
+    background-color: #FFF;
+    font-family:arial;
+    font-size:10px;
+    padding-bottom:20px;
+    visibility:hidden;
+}
+
+#calendarDiv span,#calendarDiv img{
+    float:left;
+}
+
+#calendarDiv .selectBox,#calendarDiv .selectBoxOver
+{
+    line-height:12px;
+    padding:1px;
+    cursor:pointer;
+    padding-left:2px;
+}
+
+#calendarDiv .selectBoxTime,#calendarDiv .selectBoxTimeOver
+{
+    line-height:12px;
+    padding:1px;
+    cursor:pointer;
+    padding-left:2px;
+}
+
+#calendarDiv td
+{
+    padding:3px;
+    margin:0px;
+    font-size:10px;
+}
+
+#calendarDiv .selectBox
+{
+    border:1px solid #D8ECF1;
+    color: #D8ECF1;
+    position:relative;
+}
+
+#calendarDiv .selectBoxOver
+{
+    border:1px solid #FFF;
+    background-color: #006699;
+    color: #FFF;
+    position:relative;
+}
+
+#calendarDiv .selectBoxTime
+{
+    border:1px solid #006699;
+    color: #006699;
+    position:relative;
+}
+
+#calendarDiv .selectBoxTimeOver
+{
+    border:1px solid #EDF7FA;
+    color: #EDF7FA;
+    position:relative;
+}
+
+#calendarDiv .topBar
+{
+    height:16px;
+    padding:2px;
+    background-color: #006699;
+}
+
+#calendarDiv .activeDay
+{	/* Active day in the calendar */
+    color:#FF0000;
+}
+
+#calendarDiv .todaysDate
+{
+    height:17px;
+    line-height:17px;
+    padding:2px;
+    background-color: #D8ECF1;
+    text-align:center;
+    position:absolute;
+    bottom:0px;
+    width:201px;
+}
+
+#calendarDiv .todaysDate div
+{
+    float:left;
+}
+
+#calendarDiv .timeBar
+{
+    height:17px;
+    line-height:17px;
+    background-color: #D8ECF1;
+    width:72px;
+    color:#FFF;
+    position:absolute;
+    right:0px;
+}
+
+#calendarDiv .timeBar div
+{
+    float:left;
+    margin-right:1px;
+}
+
+#calendarDiv .monthYearPicker
+{
+    background-color: #D8ECF1;
+    border:1px solid #AAAAAA;
+    position:absolute;
+    color: #006699;
+    left:0px;
+    top:15px;
+    z-index:1000;
+    display:none;
+}
+
+#calendarDiv #monthSelect
+{
+    width:70px;
+}
+
+#calendarDiv .monthYearPicker div
+{
+    float:none;
+    clear:both;
+    padding:1px;
+    margin:1px;
+    cursor:pointer;
+}
+
+#calendarDiv .monthYearActive
+{
+    background-color:#006699;
+    color: #D8ECF1;
+}
+
+#calendarDiv td
+{
+    text-align:right;
+    cursor:pointer;
+}
+
+#calendarDiv .topBar img
+{
+    cursor:pointer;
+}
+
+#calendarDiv .topBar div
+{
+    float:left;
+    margin-right:1px;
+}
Index: trunk/workflow/inc/report/includes/css/base_form.css
===================================================================
--- trunk/workflow/inc/report/includes/css/base_form.css	(revision 5307)
+++ trunk/workflow/inc/report/includes/css/base_form.css	(revision 5307)
@@ -0,0 +1,600 @@
+/* @file base_form.css*/
+/* @version 10/01/2009 */
+/* @since 13/03/2009 10:29 */
+
+/* ------------------------------------------------------------------------------------------------------------------- */
+html, body, div, span, applet, object, iframe, h1, h2, h3,h4, h5, h6, p, blockquote, pre, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins,
+kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, dl, dt, dd, ol, fieldset, form, label, legend,caption, tbody, tfoot, table, thead, tr, td, a {
+	margin: 0;
+	padding: 0;
+	border: 0;
+	outline: 0;
+	font-weight: inherit;
+	font-style: inherit;
+	font-size: 100%;
+	font-family: inherit;
+	
+}
+:focus { outline: 0;}
+a, a:link, a:visited, a:hover, a:active{text-decoration:none}
+table { border-collapse: separate;border-spacing: 0;}
+th, td { font-weight: normal;}
+img, iframe {border: none; text-decoration:none;}
+/*ol, ul {list-style: none;}*/
+input, textarea, select, button {font-size: 100%;font-family: inherit;}
+select {margin: inherit;}
+hr {margin: 0;padding: 0;border: 0;color: #000;background-color: #000;height: 1px}
+/* ------------------------------------------------------------------------------------------------------------------- */
+
+
+
+
+
+
+
+
+body {
+    margin: 0px 0px 0px 0px;
+    margin-top:0px;
+    font-family: Verdana, Arial, Helvetica, sans-serif;
+    font-size: 11px;
+    font-weight: normal;
+    color: #000000;
+}
+
+img{ border: 0px solid #FFFFFF; }
+
+a {
+    color: #3B5CA1;
+    text-decoration: none;
+    font-family: Verdana, Arial, Helvetica, sans-serif; 
+    font-size: 11px;
+}
+
+a:hover {
+    text-decoration: underline;
+    font-family: Verdana, Arial, Helvetica, sans-serif; 
+    font-size: 11px;
+}
+
+h1{
+    font-family: Verdana, Arial, Helvetica, sans-serif;
+    font-size: 14px;
+    color: #000000;
+    font-weight: bold;
+    white-space : nowrap;
+    text-align: left;
+    display:inline;
+    margin-left: 12px;
+}
+
+h2{
+    font-family: Verdana, Arial, Helvetica, sans-serif;
+    font-size: 12px;
+    color: #000000;
+    font-weight : bold;
+    text-align: left;
+    white-space : nowrap;
+    display:inline;
+    margin-left: 8px;
+    margin-right: 8px;
+}
+
+h3{
+    font-family: Verdana, Arial, Helvetica, sans-serif;
+    font-size: 10px;
+    color: #000000; /*#164C7A;*/
+    font-weight : bold;
+    text-align: left;
+    display:inline;
+    margin-left: 4px;
+
+}
+
+label {
+    font-family: Verdana, Arial, Helvetica, sans-serif;
+    font-size: 11px;
+    font-weight: normal;
+    margin-left: 8px;
+    margin-right: 8px;
+   /* white-space: nowrap; */
+}
+
+
+
+
+
+
+
+/*********  TABELAS E RESULTADOS *********/
+.tableMoldura{
+    text-align: left;
+    vertical-align: top;
+    border: 1px solid #94ADC2;
+    width:98%;
+    padding: 0px 0px 0px 0px;
+    margin: 0px 0px 10px 0px;
+    clear: left;
+    background-color:#FFFFFF;
+}
+
+.tableTitulo{
+    height: 16px;
+    background-image: url("../../images/fundo.gif");
+    margin-right:3px;
+    height: 20px;
+    
+}
+
+.tableTitulo td {
+	border: 0px solid #FFFFFF;
+	border-bottom: 1px solid #94ADC2;
+}
+
+.tableSubTitulo{
+    height: 14px;
+    /*border: 0px solid #FFFFFF;*/
+	background-color: #E6EAEE;
+	margin-right: 3px;
+	height: 20px;
+}
+
+.tableTituloColunas{   
+    height: 14px;
+    
+	background-color: #BAD0E5;
+    height: 20px;
+	margin: 0px 0px 0px 0px;
+	margin-right:3px;
+}
+
+.tableTituloColunas td{   
+    margin: 4px 0px 4px 0px;
+    border-right: solid 1px #FFFFFF;
+    border-bottom : 1px solid #FFFFFF;
+}
+
+
+.tableRodapeModelo1{
+    background-color: #BAD0E5;
+    margin: 4px 0px 4px 0px;
+    border-bottom: solid 1px #FFFFFF; border-right: solid 1px #FFFFFF; border-left: solid 1px #FFFFFF;
+    height: 20px;
+}
+
+.tableRodapeModelo2{
+    background-color: #B1CBDE;
+    margin: 4px 0px 4px 0px;
+    border-bottom: solid 1px #FFFFFF; border-right: solid 1px #FFFFFF; border-left: solid 1px #FFFFFF;
+    height: 20px;
+}
+
+.tableRodapeModelo3{
+    background-color: #AABFD2;
+    margin: 4px 0px 4px 0px;
+    border-bottom: solid 1px #FFFFFF; border-right: solid 1px #FFFFFF; border-left: solid 1px #FFFFFF;
+    height: 20px;
+}
+
+.tableRodapeModelo1 td { 
+	margin: 4px 0px 4px 0px; 
+	border-bottom: solid 1px #FFFFFF; 
+	border-right: solid 1px #FFFFFF; 
+	border-left: solid 1px #FFFFFF; 
+}
+
+.tableRodapeModelo2 td { 
+    margin: 4px 0px 4px 0px; 
+    border-bottom: solid 1px #FFFFFF; 
+    border-right: solid 1px #FFFFFF; 
+    border-left: solid 1px #FFFFFF; 
+}
+
+.tableRodapeModelo3 td { 
+    margin: 4px 0px 4px 0px; 
+    border-bottom: solid 1px #FFFFFF; 
+    border-right: solid 1px #FFFFFF; 
+    border-left: solid 1px #FFFFFF; 
+}
+
+ table {
+    border-collapse: separate;
+    border-spacing: 0px;
+    margin: 0px 0px 0px 0px;
+    padding: 0px 0px 0px 0px;
+    empty-cells: show !important;
+}
+
+table {
+	max-width: 100%;
+   * border-collapse:collapse !important;
+   * border-spacing:1px 1px !important;
+   _ border-collapse:collapse !important;
+   _ border-spacing:1px 1px  !important; 
+   outline: 0;
+   padding: 0;
+   margin: 0;
+   border: 0;
+}
+
+tr {
+    border-spacing: 0 !important;
+}
+
+tr {
+
+    margin: 0px 0px 0px 0px;
+    padding: 0px 0px 0px 0px;
+}  
+
+td{
+    font-family: Verdana, Arial, Helvetica, sans-serif;
+    font-weight: normal;
+    font-size: 11px;
+
+}
+
+.tdc {
+    font-family: Verdana, Arial, Helvetica, sans-serif;
+    font-size: 11px;
+    color: black;
+    height:16;
+    background-color: #FFFFFF;
+    border: 0px solid #FFFFFF;
+}
+
+.tde {
+    font-family: Verdana, Arial, Helvetica, sans-serif;
+    font-size: 11px;
+    color: black;
+    height:16;
+    background-color: #DEE6F6;
+    border: 0px solid #FFFFFF;
+}
+
+.tdcOver {
+    font-family: Verdana, Arial, Helvetica, sans-serif;
+    font-size: 11px;
+    color: black;
+    height:16;
+    background-color: #F9E5A9 /* #FDF3D9 */;
+    border: 0px solid #FFFFFF;
+    
+}
+
+.tdeOver {
+    font-family: Verdana, Arial, Helvetica, sans-serif;
+    font-size: 11px;
+    color: black;
+    height:16;
+    background-color: #F9E5A9;
+    border: 0px solid #FFFFFF;
+    
+}
+
+.tdc td { 
+	border-right: solid 1px #FFFFFF; 
+	border-bottom: solid 1px #FFFFFF; 
+	padding: 0px 3px 0px 3px ! important;
+}
+
+.tde td { 
+    border-right: solid 1px #FFFFFF; 
+    border-bottom: solid 1px #FFFFFF; 
+    padding: 0px 3px 0px 3px ! important;
+}
+
+.tdcOver td {
+    border-right: solid 1px #FFFFFF; 
+    border-bottom: solid 1px #FFFFFF; 
+    padding: 0px 3px 0px 3px ! important;
+}
+
+.tdeOver td {
+    border-right: solid 1px #FFFFFF; 
+    border-bottom: solid 1px #FFFFFF; 
+    padding: 0px 3px 0px 3px ! important;
+}
+
+.bolaLegenda{
+	font-size:18px;
+}
+
+
+
+
+
+.msg {
+    padding: 0px 10px 0px 10px !important;
+    font-family: Verdana, Arial, Helvetica, sans-serif !important;
+    font-size: 12px !important;
+    color: #643E41 !important;
+    font-weight:bold !important;
+
+}
+
+.msg_help {
+
+    display:inline;
+    font-size:11px; 
+    color:#643E41;	
+}
+
+/****************
+ * Status pendente
+ * Aplicar em elemento span para representar uma legenda
+ */
+.statusA {
+	background-image: url("../../images/indicadores/redondos/ap/ap01.jpg");
+    background-repeat: no-repeat;
+    margin: 3px 3px 3px 3px;
+    padding: 2px 10px 2px 10px;
+	
+}
+.statusAF {
+    background-image: url("../../images/indicadores/redondos/apf/ap01.jpg");
+    background-repeat: no-repeat;
+    margin: 3px 3px 3px 3px;
+    padding: 2px 10px 2px 10px;    
+}
+.statusN {
+    
+    background-image: url("../../images/indicadores/redondos/ap/ap04.jpg");
+    background-repeat: no-repeat;
+    margin: 3px 3px 3px 3px;
+    padding: 2px 10px 2px 10px; 
+    
+}
+.statusNF {
+    
+    background-image: url("../../images/indicadores/redondos/apf/ap04.jpg");
+    background-repeat: no-repeat;
+    margin: 3px 3px 3px 3px;
+    padding: 2px 10px 2px 10px;
+
+    
+}
+.statusP {
+    
+    background-image: url("../../images/indicadores/redondos/ap/ap03.jpg");
+    background-repeat: no-repeat;
+    margin: 3px 3px 3px 3px;
+    padding: 2px 10px 2px 10px;
+    
+}
+.statusPF {
+    
+    background-image: url("../../images/indicadores/redondos/apf/ap03.jpg");
+    background-repeat: no-repeat;
+    margin: 3px 3px 3px 3px;
+    padding: 2px 10px 2px 10px;
+    
+}
+.statusM {
+    
+    background-image: url("../../images/indicadores/redondos/ap/ap02.jpg");
+    background-repeat: no-repeat;
+    margin: 3px 3px 3px 3px;
+    padding: 2px 10px 2px 10px;
+    
+}
+.statusMF {
+    background-image: url("../../images/indicadores/redondos/apf/ap02.jpg");
+    background-repeat: no-repeat;
+    margin: 3px 3px 3px 3px;
+    padding: 2px 10px 2px 10px;
+}
+.statusC {
+    background-image: url("../../images/indicadores/redondos/ap/ap05.jpg");
+    background-repeat: no-repeat;
+    margin: 4px 4px 4px 4px;
+    padding: 2px 10px 3px 10px;
+}
+.statusCF {
+    background-image: url("../../images/indicadores/redondos/apf/ap05.jpg");
+    background-repeat: no-repeat;
+    margin: 4px 4px 4px 4px;
+    padding: 2px 10px 3px 10px;
+}
+
+/*********  FORMULARIOS  *********/
+
+.botao { 
+    font-family: Verdana, Arial, Helvetica, sans-serif; 
+    background-image: URL("../../images/fd_tr_principal.gif");
+    vertical-align: middle;
+    font-size: 9pt; 
+    text-align:center ;
+    border-color: #000000;  
+    border-style:outset; 
+    border: 1px solid #999999; 
+    padding: 0px 0px 0px 0px;
+    font-size: 8pt;
+    color:#000000;
+    height: 20px;
+}
+.files { 
+    font-family: Verdana, Arial, Helvetica, sans-serif; 
+    background-image: URL("../../images/fd_tr_principal.gif");
+    vertical-align: middle;
+    font-size: 9pt; 
+    border-color: #000000;  
+    border-style:outset; 
+    border: 1px solid #999999; 
+    padding: 0px 0px 0px 0px;
+    font-size: 8pt;
+    color:#000000;
+    height: 20px;
+}
+.msg{
+    font-family: Verdana, Arial, Helvetica, sans-serif;
+    font-size: 12px;
+    color:#996666;
+    font-weight : bold;
+    text-align: left;
+    white-space : nowrap;
+    margin-left:5px;
+}
+
+.radio, .checkbox {
+    color: #000000;
+    font-family: Verdana, Arial, Helvetica, sans-serif;
+    font-size: 10pt;
+    background-color: #FFFFFF;
+    height: auto;
+    border: 0px solid #FFFFFF;
+    margin: 1px 0px 1px 0px;
+}
+
+.inputError {
+    background-color:#FFFFC0;
+}
+.inputNormal {
+    background-color:#FFFFFF;
+}
+
+input {
+    color: #000000;
+    font-family: Verdana, Arial, Helvetica, sans-serif;
+    font-size: 10pt;
+    background-color: #ffffff;
+    height : 20px;
+    border: 1px solid #C0C0C0;
+    margin: 1px 0px 1px 0px;
+}
+
+select {
+    color: #000000;
+    font-family: Verdana, Arial, Helvetica, sans-serif;
+    font-size: 10pt;
+    background-color: #FFFFFF;
+    border: 1px solid #C0C0C0;
+    margin: 1px 0px 1px 0px;
+}
+
+textarea {
+    color: #000000;
+    font-family: Verdana, Arial, Helvetica, sans-serif;
+    font-size: 10pt;
+    background-color: #FFFFFF;
+    border: 1px solid #C0C0C0;
+    margin: 1px 0px 1px 0px;
+}
+
+
+
+
+
+
+/* Abas */
+
+#navPrincipal {
+    border-bottom: 1px solid #94ADC2;
+}
+  
+
+#tabnav {
+    
+    margin: 0;
+    position: relative;
+    margin: 0; 
+    padding: 0;
+    padding-top: 10px;
+
+}
+    
+#tabnav a:link {
+    float: left;
+    font-size: 10px;
+    line-height: 14px;
+    padding: 5px 10px 5px 10px;
+    margin-right: 3px;
+    border: 1px solid #ccc;
+    border-bottom: 1px solid #FFFFFF !important; 
+    text-decoration: none;
+    background-image: url("../../images/fundo.gif");  
+    font-weight: normal;
+    white-space: nowrap;
+    
+}
+
+   
+#tabnav a:link.active, #tabnav a:visited.active {
+        
+	border: 1px solid #94ADC2 !important; 
+	border-bottom: 1px solid #FFFFFF !important; 
+	background-image: url("../../images/fundo_over3.jpg");
+	color: #000000;
+	white-space: nowrap
+}
+
+
+#tabnav a:hover {
+    background-image: url("../../images/fundo_over2.jpg");
+    border-bottom: 1px solid #FFFFFF !important; 
+    background-repeat: repeat-x;
+    color: #000000;
+    font-weight: normal;
+    white-space: nowrap
+}
+ 
+.aba_disabled {
+	float: left;
+    font-size: 10px;
+    line-height: 14px;
+    padding: 5px 10px 5px 10px;
+    margin-right: 3px;
+    border: 1px solid #ccc;
+    border-bottom: 1px solid #FFFFFF !important; 
+    text-decoration: none;
+    background-image: url("../../images/fundo.gif");  
+    font-weight: normal;
+    color: #C5CACD;
+    white-space: nowrap;
+}
+
+/*USADO NA CLASSE DE LISTAGEM*/
+.div_visivel{
+    
+    position: absolute;
+    top:2px;  
+    width:250px;  
+    background-color: #F0F0F0;
+    border: 1px solid #000000;
+    padding: 5px;
+    
+}
+
+/* Usado no help comment */
+#helpComment{
+    position:absolute;
+    width:300px;
+    border:1px solid #94ADC2;
+    padding:1px;
+    background-color:#eff3f7;
+    font-family:arial;
+    font-size:10px;
+    visibility:hidden;
+}
+
+#helpCommentSeta{
+    position:absolute;
+}
+
+#helpComment .cell-mensagem{
+    padding:5px;
+    color: black;
+    font-family: Verdana, Arial, Helvetica, sans-serif;
+    font-size:11px;
+}
+
+#helpComment .cell-topo-mensagem{
+    padding-left:5px;
+    background-color: #DFEAF3;
+    /*border-bottom: 1px solid #E0E0E0; */
+    color: black;
+    font-family:arial;
+    font-size:11px;
+    font-weight:bold;
+    height:18px;
+}
Index: trunk/workflow/inc/report/includes/js/auxiliares.js
===================================================================
--- trunk/workflow/inc/report/includes/js/auxiliares.js	(revision 5307)
+++ trunk/workflow/inc/report/includes/js/auxiliares.js	(revision 5307)
@@ -0,0 +1,720 @@
+/**
+ * Funï¿œï¿œo:     	$id(nomeCampo)
+ * Autor:      	Ricardo Andre Pikussa
+ * Data:		12/12/2008
+ * Descriï¿œï¿œo:	Funï¿œï¿œo utilizada para retornar as propriedades de um campo via getElementById(nomeCampo) 
+ * Chamada:		$id('nomeCampo'); ou $id('nomeCampo').value; 
+ *     
+ */
+function $id(nomeCampo)
+{
+    return document.getElementById(nomeCampo);
+}
+
+function trim(str){
+    return str.replace(/^\s+|\s+$/g,"");
+}
+
+//gerencia o efeito amarelo que aparece nas mensagens ao usuario
+var tempo_fade;
+function fade(percent,container,topercent) {
+	if(!topercent){
+		topercent = 100;
+	}
+	
+    clearTimeout(tempo_fade);
+    
+    if($id(container)){
+    
+	    $id(container).style.backgroundColor = "rgb(100%, 100%, "+percent+"%)";
+	    
+	    percent += 10;
+	    
+	    if(percent<=topercent){
+	        tempo_fade = setTimeout("fade("+percent+",'"+container+"',"+topercent+")", 100/*ms*/);
+	    }
+	
+	    if(percent > topercent){
+	    	$id(container).style.backgroundColor = "#FFFFC0";
+	    	return true;	
+	    }
+    }
+    
+}
+
+//gera a mensagem ao usuario
+function cria_msg_html(container,mensagem){
+    $id(container).innerHTML = "";
+    if(mensagem!=""){
+    	$id(container).innerHTML = mensagem;
+        fade(0,container);
+    }
+    return;
+}
+
+// funcao para mudar a cor de background de um campos
+function muda_cor(id_campo){
+	document.getElementById(id_campo).style.backgroundColor = "#FFFFC0";
+}
+// funcao para remover a cor de background de um campos
+function remove_cor(id_campo){
+    
+    if(document.getElementById(id_campo).readOnly == true){
+     
+        document.getElementById(id_campo).style.backgroundColor = "#F0F0F0";
+      
+    }else{
+
+	   document.getElementById(id_campo).style.backgroundColor = "";
+	   
+	}
+}
+
+//limpa todos os backgrounds dos inputs
+function limpaCores(){
+	
+	for(i=0;i<document.forms.length;i++){
+		
+		for (j=0; j<document.forms[i].elements.length ;j++){
+			
+			/* limpando os inputs txt */
+			if(document.forms[i].elements[j].type == 'text'){
+				if(document.forms[i].elements[j].id){
+					remove_cor(document.forms[i].elements[j].id);
+				}
+			}
+			/* limpando os selects */
+			if(document.forms[i].elements[j].type == 'select-one'){
+				if(document.forms[i].elements[j].id){
+					remove_cor(document.forms[i].elements[j].id);
+				}
+			}
+			/* limpando os textarea */
+			if(document.forms[i].elements[j].type == 'textarea'){
+				if(document.forms[i].elements[j].id){
+					remove_cor(document.forms[i].elements[j].id);
+				}
+			}
+			
+		}
+		
+		/* limpando os checkboxes e radios*/
+	ckbox_a_div = document.getElementsByTagName('div');
+		
+		for(x=0;x<ckbox_a_div.length;x++){
+		
+			if(ckbox_a_div[x].id){
+				remove_cor(ckbox_a_div[x].id);
+			}
+		}
+	}
+}
+
+// funcao para criar um div dinamico
+function criarDiv(id, html, width, height, left, top, classe) {
+	
+   var newdiv = document.createElement('div');
+   newdiv.setAttribute('id', id);
+   
+   if (width) {
+       newdiv.style.width = width;
+   }
+   
+   if (height) {
+       newdiv.style.height = height;
+   }
+   
+   if ((left || top) || (left && top)) {
+       newdiv.style.position = "absolute";
+       
+       if (left) {
+           newdiv.style.left = left;
+       }
+       
+       if (top) {
+           newdiv.style.top = top;
+       }
+   }
+   
+   newdiv.style.color = "#643E41";
+   newdiv.style.fontFamily = "Verdana";
+   newdiv.style.fontSize = "12px";
+   newdiv.style.fontWeight = "bold";
+   newdiv.style.verticalAlign = "middle";
+   
+   if (classe) {
+   		newdiv.setAttribute('class',classe);
+   		alert(classe);
+   }
+   
+   
+   if (html) {
+       newdiv.innerHTML = html;
+   } else {
+       //newdiv.innerHTML = "ops...";
+   }
+   
+   document.body.appendChild(newdiv);
+
+} 
+
+// Funï¿œï¿œo para criar o div de mensagem padrï¿œo
+function criaAlerta(mensagem){
+    
+    if(!document.getElementById("mess")){
+                
+        criarDiv('mess', '<table height=\"32\" width=\"100%\" valign=\"middle\"><tr onclick=\"removeDiv(\'mess\');\"><td class="\msg\" width=\"96%\" heigth=\"100%\">&nbsp;<font color=\"#CD0000\">' + mensagem + '</font></td><td width=\"4%\"><img width=\"15\" height=\"15\" src=\"images/X.jpg\"></img></td></tr></table>', '100%', '34', '0', '0');
+        alinhaDiv('mess');
+        id_interval = setInterval("alinhaDiv('mess')",500);
+        fade(0,'mess',80);
+                
+    }else{
+    
+        fade(0,'mess',80);
+    }
+}
+// Funï¿œï¿œo para remover div de alerta
+function removeAlerta(){
+    removeDiv('mess');
+}
+
+// funcao para remover um div dinamico
+function removeDiv(id){
+	
+	tmp = document.getElementById(id);
+	if(tmp){
+		document.body.removeChild(tmp);
+	}
+}
+
+// funcao para alinhar um div ao topo
+var id_interval ;
+
+function alinhaDiv(id){
+	if(document.getElementById(id)){
+				
+		if(navigator.appName == "Microsoft Internet Explorer"){
+			var new_top = document.body.scrollTop;
+		}else{
+			var new_top = window.pageYOffset;
+		}
+		new_top = parseFloat(new_top);
+		
+		b = new_top; 
+	
+		document.getElementById(id).style.marginTop = b+'px';
+		
+	}else{
+		clearInterval(id_interval);
+	}
+}
+
+//funcao para alinhar um div a direita
+var id_interval_dir ;
+
+function alinhaDivDir(id){
+	
+	var tamanho_util = getWidth();
+	
+	document.getElementById(id).style.display = '';
+	
+	if(document.getElementById(id).style.display == ''){
+		
+		document.getElementById(id).style.display = 'none';
+		document.getElementById(id).style.marginLeft = '0px';
+				
+		if(navigator.appName == "Microsoft Internet Explorer"){
+			var new_dir = document.body.scrollLeft;
+		}else{
+			var new_dir = window.pageXOffset;
+		}
+		new_dir = parseFloat(new_dir);
+		tamanho_util = parseFloat(tamanho_util);
+		
+		b = new_dir+tamanho_util-360 ;
+		
+		document.getElementById(id).style.marginLeft = b+'px';
+		
+		document.getElementById(id).style.display = '';
+		
+	}
+}
+
+function retiraAspas (evtKeyPress) {
+    
+	var nTecla=0;
+	if (document.all) {
+	
+		nTecla = evtKeyPress.keyCode;
+
+	} else {
+		nTecla = evtKeyPress.which;
+	}
+	if (nTecla == 34 || nTecla == 39) {
+		return false;
+	} else {
+		return true;
+	}
+}
+
+// Funï¿œï¿œo para alterar o style width de um selectbox
+function expandirSelect(sel,width) {
+    
+    if(width){
+        sel.style.width = width+'px';  
+    }else{
+        sel.style.width = 'auto';
+    }
+}
+
+//Detect if the browser is IE or not.
+//If it is not IE, we assume that the browser is NS.
+var IE = document.all?true:false;
+
+//If NS -- that is, !IE -- then set up for mouse capture
+if (!IE) document.captureEvents(Event.MOUSEMOVE);
+
+//Set-up to use getMouseXY function onMouseMove
+//document.onmousemove = getMouseXY;
+
+//Temporary variables to hold mouse x-y pos.s
+var tempX = 0;
+var tempY = 0;
+
+// Funï¿œï¿œo principal para pegar posiï¿œï¿œo Y do mouse
+function getMouseY(e) {
+	
+	if (IE) { // grab the x-y pos.s if browser is IE
+		
+		tempY = event.clientY + document.body.scrollTop;
+		
+	}else{  // grab the x-y pos.s if browser is NS
+
+		tempY = e.pageY;
+	}  
+	// catch possible negative values in NS4
+
+	if (tempY < 0){tempY = 0;}  
+	// show the position values in the form named Show
+	// in the text fields named MouseX and MouseY
+	//document.frm.MouseX.value = tempX
+	//document.frm.MouseY.value = tempY
+	
+	return tempY;
+}
+
+// Funï¿œï¿œo principal para pegar posiï¿œï¿œo X do mouse
+function getMouseX(e) {
+	
+	if (IE) { // grab the x-y pos.s if browser is IE
+		
+		tempX = event.clientX + document.body.scrollLeft;
+
+	}else{  // grab the x-y pos.s if browser is NS
+
+		tempX = e.pageX;
+	}  
+	// catch possible negative values in NS4
+	if (tempX < 0){tempX = 0;}
+	// show the position values in the form named Show
+	// in the text fields named MouseX and MouseY
+	//document.frm.MouseX.value = tempX
+	//document.frm.MouseY.value = tempY
+	
+	return tempX;
+}
+
+function ListagemExibeOcultaColuna(id_listagem, id_campo){
+
+    var i = 0;
+    var continua = true;
+    
+    while(continua == true){
+
+        if(document.getElementById('td_'+id_campo+'_'+i)){
+
+            if(document.getElementById(id_listagem + '_ck_visivel_' + id_campo).checked == true){
+                
+        		document.getElementById('td_'+id_campo+'_'+i).style.display = '';
+                    
+        	}else{
+                
+        		document.getElementById('td_'+id_campo+'_'+i).style.display = 'none';
+        	}
+
+            i++;
+            
+        }else{
+            
+            continua = false;
+        }
+    }
+
+    if(document.getElementById('td_tit_'+id_campo)){
+
+        if(document.getElementById(id_listagem+'_ck_visivel_'+id_campo).checked == true){
+            
+            document.getElementById('td_tit_'+id_campo).style.display = '';
+                
+        }else{
+            
+            document.getElementById('td_tit_'+id_campo).style.display = 'none';
+        }
+    }
+
+    if(document.getElementById('total_'+id_campo)){
+
+        if(document.getElementById(id_listagem+'_ck_visivel_'+id_campo).checked == true){
+            
+            document.getElementById('total_'+id_campo).style.display = '';
+                
+        }else{
+            
+            document.getElementById('total_'+id_campo).style.display = 'none';
+        }
+    }
+    
+    i = 1;
+    continua = true;
+
+    while(continua == true){
+
+        if(document.getElementById('subtotal_'+id_campo+'_'+i)){
+
+            if(document.getElementById(id_listagem+ '_ck_visivel_'+id_campo).checked == true){
+                
+                document.getElementById('subtotal_'+id_campo+'_'+i).style.display = '';
+                    
+            }else{
+                
+                document.getElementById('subtotal_'+id_campo+'_'+i).style.display = 'none';
+            }
+
+            i++;
+            
+        }else{
+            
+            if (i == 1) {
+            	i++;
+            } else {
+              continua = false;
+            }
+        }
+    }
+
+
+    document.getElementById(id_listagem+'_div_visivel').style.display = ''; 
+    document.getElementById(id_listagem+'_div_visivel_load').style.display = 'none';
+    
+    //setTimeout("alinhaDivDir('"+id_listagem+"_div_visivel')",1000);
+
+}
+
+function getWidth(){
+
+	if(window.innerWidth){
+		//alert('window.width='+window.innerWidth);
+		return window.innerWidth; /* For non-IE */
+	}
+	if(document.documentElement.clientWidth){
+		//alert('document.element='+document.documentElement.clientWidth);
+		return document.documentElement.clientWidth; /* IE 6+ (Standards Compilant Mode) */
+	}
+	if(document.body.clientWidth){
+		//alert('document.body='+document.body.clientWidth);
+		return document.body.clientWidth; /* IE 4 Compatible */
+	}
+	if(window.screen.width){
+		//alert('screen.width='+window.screen.width);
+		return window.screen.width; /* Others (It is not browser window size, but screen size) */
+	}
+	
+	return false;
+
+}
+
+function ListagemShowHide(event,id_listagem,id){
+
+	//alinhaDivDir(id_listagem + '_div_visivel');
+	 
+	var y = getMouseY(event);
+	//var x = getMouseX(event);
+	
+    if(document.getElementById(id_listagem+'_div_visivel').style.display == 'none'){
+    	
+    	id_interval_dir = setInterval("alinhaDivDir('"+id_listagem+"_div_visivel')",100);
+    	//id_interval_dir2 = setInterval("alinhaDivDir('"+id_listagem+"_div_visivel_load')",100);
+    	
+    	document.getElementById(id_listagem+'_div_visivel').style.display = '';
+
+        document.getElementById(id_listagem+'_div_visivel').style.marginTop = parseInt(y) - 200 + 'px';
+        document.getElementById(id_listagem+'_div_visivel_load').style.marginTop = parseInt(y) -200 + 'px';
+        
+        //document.getElementById(id_listagem+'_div_visivel').style.marginLeft = '2%'; //parseInt(x) -260 + 'px';
+        //document.getElementById(id_listagem+'_div_visivel_load').style.marginLeft = '2%'; //parseInt(x) -260 + 'px';
+        
+    	//document.getElementById(id).setAttribute("src","./images/icones/menosTransparente.gif");
+        
+    }else{
+    	
+    	//alert('limpou intervalo');
+    	clearInterval(id_interval_dir);
+    	//clearInterval(id_interval_dir2);
+    	
+    	document.getElementById(id_listagem+'_div_visivel').style.display = 'none';
+    	//document.getElementById(id).setAttribute("src","./images/icones/maisTransparente.gif");
+    	
+    }
+}
+
+function ListagemSelecionachecks(check,qtdtotal,prefixo){
+	
+	for (var i=0;i<qtdtotal;i++)  {
+		if(document.getElementById(prefixo+i)){
+			document.getElementById(prefixo+i).checked=check;
+		}
+	}
+}
+
+//FUNï¿œï¿œES DA COMBO ESPECIAL.
+function CE_pesquisar(idcodigo,idnome,funcao) {
+    var nome = document.getElementById(idnome);
+    var codigo = document.getElementById(idcodigo);
+    var botao = document.getElementById("bt_pesquisar_" + idcodigo);
+    var palavra = nome.value;
+    botao.disabled = true;
+    if (botao.value == 'Pesquisar') {
+        if(palavra != ""){
+            if(palavra.length>2){
+                xajax_CE_pesquisar_combo(idcodigo,idnome,funcao,nome.value);
+                document.getElementById('div_img_pesquisa_' +idcodigo).style.display = "inline";
+            }else{
+            	criaAlerta("Digite no mï¿œnimo 3 caracteres para procurar.");
+            }
+        }else{
+        	criaAlerta("Digite no mï¿œnimo 3 caracteres para procurar.");
+            document.getElementById('result_pesq_' + idcodigo).innerHTML = "";
+        }
+    } else {
+        CE_bloquear(false,idcodigo,idnome);
+    }
+}
+function CE_selecionar(selecao,idcodigo,idnome){
+    var nome = document.getElementById(idnome);
+    var codigo = document.getElementById(idcodigo);
+    var botao = document.getElementById("bt_pesquisar_" + idcodigo);
+    var funcao_selecionar = document.getElementById(idcodigo + "_funcao_selecionar");
+    var funcao_limpar = document.getElementById(idcodigo + "_funcao_limpar");
+    botao.disabled = false;
+    if(selecao !="|"){
+        var valor = selecao.split("|");
+        codigo.value=valor[0];
+        nome.value=valor[1];
+        CE_bloquear(true,idcodigo,idnome);
+        if (funcao_selecionar.value != "") {
+        	eval(funcao_selecionar.value);
+        }
+        document.getElementById('result_pesq_' + idcodigo).innerHTML = "";
+    }else{
+        return false;
+    }
+}
+
+function CE_bloquear(bloqueio,idcodigo,idnome) {
+    var nome = document.getElementById(idnome);
+    var codigo = document.getElementById(idcodigo);
+    var botao = document.getElementById("bt_pesquisar_" + idcodigo);
+    var funcao_limpar = document.getElementById(idcodigo + "_funcao_limpar");
+    if (bloqueio) {
+        nome.style.background = "#F0F0F0";
+        nome.readOnly = true;
+        botao.value = 'Limpar';
+        botao.disabled = false;
+    } else {
+        nome.style.background = "#FFFFFF";
+        codigo.value="";
+        nome.value="";
+        nome.readOnly = false;
+        botao.value = 'Pesquisar'; 
+        botao.disabled = false;
+        if (funcao_limpar.value != "") {
+        	eval(funcao_limpar.value);
+        }
+    }
+}
+
+// Funï¿œï¿œes e variï¿œveis utilizadas para criaï¿œï¿œo do Help Comment
+var help_offsetTop  = 0; 
+var help_offsetLeft = 0;
+
+var lastObj     = false;
+var helpCommentDiv = false;
+
+var MSIE = false;
+if(navigator.userAgent.indexOf('MSIE')>=0 && navigator.userAgent.indexOf('Opera')<0)MSIE=true;
+
+function mostrarHelpComment(inputObj,msg,lado,titulo){
+
+    if(!helpCommentDiv){
+    
+        criarHelpComment(msg,inputObj,lado,titulo);
+
+    }else{
+
+    	if(helpCommentDiv.style.display=='block'){
+        
+            fecharHelpComment();
+
+            if(lastObj == inputObj){
+
+            	return false;
+                
+            }else{
+                
+            	criarHelpComment(msg,inputObj,lado,titulo);
+            }
+        }
+    }
+}
+function escreveConteudo(msg,titulo){
+
+
+    var calTable = document.createElement('TABLE');
+    calTable.width = '100%';
+    calTable.cellSpacing = '0';
+    helpCommentDiv.appendChild(calTable);
+
+    var calTBody = document.createElement('TBODY');
+    calTable.appendChild(calTBody);
+
+    if(titulo){
+
+        var row = calTBody.insertRow(-1);
+        
+       // var cell = row.insertCell(-1);
+        //cell.align = 'right';
+        //cell.width = '15';
+        //cell.className = 'cell-topo-mensagem';
+        
+        var cell = row.insertCell(-1);
+        cell.innerHTML = titulo;
+        cell.className = 'cell-topo-mensagem';
+        
+        //var cell = row.insertCell(-1);
+        //cell.width = '15';
+        //cell.align = 'right';
+        //cell.innerHTML = '<img OnMouseOver="document.body.style.cursor=\'pointer\';" OnMouseOut="document.body.style.cursor=\'default\';" OnClick="fecharHelpComment(); document.body.style.cursor=\'default\';" src="images/fileclose.gif">';
+        //cell.className = 'cell-topo-mensagem';
+    }
+    
+    var row = calTBody.insertRow(-1);
+    var cell = row.insertCell(-1);
+
+    //if(titulo){
+    //	cell.colSpan = '2';
+    //}
+    
+    cell.innerHTML = msg
+    cell.className = 'cell-mensagem';
+
+}
+
+function getTopPos(inputObj){
+
+    var returnValue = inputObj.offsetTop + inputObj.offsetHeight;
+    while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetTop;
+    return returnValue + help_offsetTop;
+}
+
+function getleftPos(inputObj){
+
+    var returnValue = inputObj.offsetLeft;
+    while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetLeft;
+    return returnValue + help_offsetLeft;
+}
+
+function fecharHelpComment(){
+
+	if(document.getElementById('helpComment')){
+
+		document.body.removeChild(helpCommentDiv);
+        helpCommentDiv = false;
+        document.body.removeChild(helpCommentDivSeta);
+    }
+}
+
+function criarHelpComment(msg,inputObj,lado,titulo){
+
+    lastObj = inputObj;
+    
+    // Configuraï¿œï¿œo do lado que vai ser desenhado
+    if(lado == ''){
+    	alert('Erro ao selecionar lado');
+    	return false;
+    }
+    
+    if(lado == 'D'){
+    	
+    	var divLeftPos = 32;
+    	var divTopPos  = 21;
+    	
+    	var divSetaLeftPos = 20;
+    	var divSetaTopPos  = 15;
+    	
+    	if(titulo){
+    		var imgSeta = '<img src="images/hbseta_t.gif">';
+    	}else{
+    		var imgSeta = '<img src="images/hbseta.gif">';
+    	}
+    }
+    
+    if(lado == 'E'){
+    	
+    	if (MSIE == true){
+    		
+    		var divLeftPos = -314;
+	    	var divTopPos  = 21 ;
+	    	
+    	}else{
+    	
+	    	var divLeftPos = -318;
+	    	var divTopPos  = 21 ;
+    	}
+    	
+    	var divSetaLeftPos = -15;
+    	var divSetaTopPos  = 15 ;
+    	
+    	if(titulo){
+    		divLeftPos = divLeftPos + 1;
+    		var imgSeta = '<img src="images/hbseta2_t.gif">';
+    	}else{
+    		var imgSeta = '<img src="images/hbseta2.gif">';
+    	}
+    }
+    
+    // Div principal
+    helpCommentDiv = document.createElement('DIV');
+    helpCommentDiv.id = 'helpComment';
+    helpCommentDiv.style.zIndex = 1000;
+
+    document.body.appendChild(helpCommentDiv);
+
+    helpCommentDiv.style.visibility = 'visible';   
+    helpCommentDiv.style.display = 'block';
+    helpCommentDiv.style.left = getleftPos(inputObj) + divLeftPos + 'px';
+    helpCommentDiv.style.top = getTopPos(inputObj) - divTopPos + 'px';
+
+    escreveConteudo(msg,titulo);
+
+    // Div da seta
+    helpCommentDivSeta = document.createElement('DIV');
+    helpCommentDivSeta.id = 'helpCommentSeta';
+    helpCommentDivSeta.style.zIndex = 2000;
+    helpCommentDivSeta.innerHTML = imgSeta;
+
+    document.body.appendChild(helpCommentDivSeta);
+
+    helpCommentDivSeta.style.left = getleftPos(inputObj)  + divSetaLeftPos + 'px';
+    helpCommentDivSeta.style.top = getTopPos(inputObj) - divSetaTopPos + 'px';
+    
+}
Index: trunk/workflow/inc/report/includes/js/calendar.js
===================================================================
--- trunk/workflow/inc/report/includes/js/calendar.js	(revision 5307)
+++ trunk/workflow/inc/report/includes/js/calendar.js	(revision 5307)
@@ -0,0 +1,1682 @@
+/************************************************************************************************************
+JS Calendar
+Copyright (C) September 2006  DTHMLGoodies.com, Alf Magne Kalleland
+
+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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+Dhtmlgoodies.com., hereby disclaims all copyright interest in this script
+written by Alf Magne Kalleland.
+
+Alf Magne Kalleland, 2006
+Owner of DHTMLgoodies.com
+	
+************************************************************************************************************/	
+
+/* Update log:
+(C) www.dhtmlgoodies.com, September 2005
+
+Version 1.2, November 8th - 2005 - Added <iframe> background in IE
+Version 1.3, November 12th - 2005 - Fixed top bar position in Opera 7
+Version 1.4, December 28th - 2005 - Support for Spanish and Portuguese
+Version 1.5, January  18th - 2006 - Fixed problem with next-previous buttons after a month has been selected from dropdown
+Version 1.6, February 22nd - 2006 - Added variable which holds the path to images.
+Format todays date at the bottom by use of the todayStringFormat variable
+Pick todays date by clicking on todays date at the bottom of the calendar
+Version 2.0	 May, 25th - 2006	  - Added support for time(hour and minutes) and changing year and hour when holding mouse over + and - options. (i.e. instead of click)
+Version 2.1	 July, 2nd - 2006	  - Added support for more date formats(example: d.m.yyyy, i.e. one letter day and month).
+
+*/
+var languageCode = 'pt-br';
+
+var calendar_display_time = true;
+
+// Format of current day at the bottom of the calendar
+// [todayString] = the value of todayString
+// [dayString] = day of week (examle: mon, tue, wed...)
+// [UCFdayString] = day of week (examle: Mon, Tue, Wed...) ( First letter in uppercase)
+// [day] = Day of month, 1..31
+// [monthString] = Name of current month
+// [year] = Current year
+var todayStringFormat = '[todayString] [UCFdayString]. [day]. [monthString] [year]';
+var pathToImages = 'images/'; // Relative to your HTML file
+var speedOfSelectBoxSliding = 200; // Milliseconds between changing year and hour when holding mouse over "-" and "+" - lower value = faster
+var intervalSelectBox_minutes = 5; // Minute select box - interval between each option (5 = default)
+var calendar_offsetTop = 0; // Offset - calendar placement - You probably have to modify this value if you're not using a strict doctype
+var calendar_offsetLeft = 0; // Offset - calendar placement - You probably have to modify this value if you're not using a strict doctype
+var calendarDiv = false;
+
+var MSIE = false;
+var Opera = false;
+if(navigator.userAgent.indexOf('MSIE')>=0 && navigator.userAgent.indexOf('Opera')<0)MSIE=true;
+if(navigator.userAgent.indexOf('Opera')>=0)Opera=true;
+
+
+switch(languageCode){
+    case "pt-br":  /* Brazilian portuguese (pt-br) */
+        var monthArray = ['Janeiro','Fevereiro','Mar&ccedil;o','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'];
+        var monthArrayShort = ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'];
+        var dayArray = ['Seg','Ter','Qua','Qui','Sex','S&aacute;b','Dom'];
+        var weekString = 'Sem.';
+        var todayString = 'Hoje &eacute;';
+    break;
+}
+
+var daysInMonthArray = [31,28,31,30,31,30,31,31,30,31,30,31];
+var currentMonth;
+var currentYear;
+var currentHour;
+var currentMinute;
+var calendarContentDiv;
+var returnDateTo;
+var returnFormat;
+var activeSelectBoxMonth;
+var activeSelectBoxYear;
+var activeSelectBoxHour;
+var activeSelectBoxMinute;
+
+var iframeObj = false;
+//// fix for EI frame problem on time dropdowns 09/30/2006
+var iframeObj2 =false;
+function EIS_FIX_EI1(where2fixit)
+{
+    if(!iframeObj2)return;
+    iframeObj2.style.display = 'block';
+    iframeObj2.style.height =document.getElementById(where2fixit).offsetHeight+1;
+    iframeObj2.style.width=document.getElementById(where2fixit).offsetWidth;
+    iframeObj2.style.left=getleftPos(document.getElementById(where2fixit))+1-calendar_offsetLeft;
+    iframeObj2.style.top=getTopPos(document.getElementById(where2fixit))-document.getElementById(where2fixit).offsetHeight-calendar_offsetTop;
+}
+
+function EIS_Hide_Frame()
+{
+    if(iframeObj2)iframeObj2.style.display = 'none';}
+    //// fix for EI frame problem on time dropdowns 09/30/2006
+    var returnDateToYear;
+    var returnDateToMonth;
+    var returnDateToDay;
+    var returnDateToHour;
+    var returnDateToMinute;
+
+    var inputYear;
+    var inputMonth;
+    var inputDay;
+    var inputHour;
+    var inputMinute;
+    var calendarDisplayTime = false;
+
+    var selectBoxHighlightColor = '#D60808'; // Highlight color of select boxes
+    var selectBoxRolloverBgColor = '#E2EBED'; // Background color on drop down lists(rollover)
+
+    var selectBoxMovementInProgress = false;
+    var activeSelectBox = false;
+
+function cancelCalendarEvent()
+{
+    return false;
+}
+function isLeapYear(inputYear)
+{
+    if(inputYear%400==0||(inputYear%4==0&&inputYear%100!=0)) return true;
+    return false;	
+}
+var activeSelectBoxMonth = false;
+var activeSelectBoxDirection = false;
+
+function highlightMonthYear()
+{
+    if(activeSelectBoxMonth)activeSelectBoxMonth.className='';
+    activeSelectBox = this;
+
+    if(this.className=='monthYearActive')
+    {
+        this.className='';	
+    }
+    else
+    {
+        this.className = 'monthYearActive';
+        activeSelectBoxMonth = this;
+    }
+
+    if(this.innerHTML.indexOf('-')>=0 || this.innerHTML.indexOf('+')>=0)
+    {
+        if(this.className=='monthYearActive')
+        selectBoxMovementInProgress = true;
+        else
+        selectBoxMovementInProgress = false;
+        if(this.innerHTML.indexOf('-')>=0)activeSelectBoxDirection = -1; else activeSelectBoxDirection = 1;	
+    }
+    else selectBoxMovementInProgress = false;
+}
+
+function showMonthDropDown()
+{
+    if(document.getElementById('monthDropDown').style.display=='block')
+    {
+        document.getElementById('monthDropDown').style.display='none';	
+        //// fix for EI frame problem on time dropdowns 09/30/2006
+        EIS_Hide_Frame();
+    }
+    else
+    {
+        document.getElementById('monthDropDown').style.display='block';		
+        document.getElementById('yearDropDown').style.display='none';
+        document.getElementById('hourDropDown').style.display='none';
+        document.getElementById('minuteDropDown').style.display='none';
+        if (MSIE)
+        {
+            EIS_FIX_EI1('monthDropDown')
+        }
+        //// fix for EI frame problem on time dropdowns 09/30/2006
+    }
+}
+
+function showYearDropDown()
+{
+    if(document.getElementById('yearDropDown').style.display=='block')
+    {
+        document.getElementById('yearDropDown').style.display='none';
+        //// fix for EI frame problem on time dropdowns 09/30/2006
+        EIS_Hide_Frame();
+    }
+    else
+    {
+        document.getElementById('yearDropDown').style.display='block';
+        document.getElementById('monthDropDown').style.display='none';
+        document.getElementById('hourDropDown').style.display='none';
+        document.getElementById('minuteDropDown').style.display='none';
+        if (MSIE)
+        {
+            EIS_FIX_EI1('yearDropDown')
+        }
+        //// fix for EI frame problem on time dropdowns 09/30/2006
+    }
+}
+
+function showHourDropDown()
+{
+    if(document.getElementById('hourDropDown').style.display=='block')
+    {
+        document.getElementById('hourDropDown').style.display='none';	
+        //// fix for EI frame problem on time dropdowns 09/30/2006
+        EIS_Hide_Frame();
+    }
+    else
+    {
+        document.getElementById('hourDropDown').style.display='block';	
+        document.getElementById('monthDropDown').style.display='none';	
+        document.getElementById('yearDropDown').style.display='none';	
+        document.getElementById('minuteDropDown').style.display='none';	
+        if (MSIE)
+        {
+            EIS_FIX_EI1('hourDropDown')
+        }
+        //// fix for EI frame problem on time dropdowns 09/30/2006
+    }
+
+}
+
+function showMinuteDropDown()
+{
+    if(document.getElementById('minuteDropDown').style.display=='block')
+    {
+        document.getElementById('minuteDropDown').style.display='none';	
+        //// fix for EI frame problem on time dropdowns 09/30/2006
+        EIS_Hide_Frame();
+    }
+    else
+    {
+        document.getElementById('minuteDropDown').style.display='block';	
+        document.getElementById('monthDropDown').style.display='none';	
+        document.getElementById('yearDropDown').style.display='none';	
+        document.getElementById('hourDropDown').style.display='none';	
+        if (MSIE)
+        {
+            EIS_FIX_EI1('minuteDropDown')
+        }
+        //// fix for EI frame problem on time dropdowns 09/30/2006
+    }
+}
+
+function selectMonth()
+{
+    document.getElementById('calendar_month_txt').innerHTML = this.innerHTML
+    currentMonth = this.id.replace(/[^\d]/g,'');
+    document.getElementById('monthDropDown').style.display='none';
+    //// fix for EI frame problem on time dropdowns 09/30/2006
+    EIS_Hide_Frame();
+    for(var no=0;no<monthArray.length;no++)
+    {
+        document.getElementById('monthDiv_'+no).style.color='';	
+    }
+    this.style.color = selectBoxHighlightColor;
+    activeSelectBoxMonth = this;
+    writeCalendarContent();
+}
+
+function selectHour()
+{
+    document.getElementById('calendar_hour_txt').innerHTML = this.innerHTML
+    currentHour = this.innerHTML.replace(/[^\d]/g,'');
+    document.getElementById('hourDropDown').style.display='none';
+    //// fix for EI frame problem on time dropdowns 09/30/2006
+    EIS_Hide_Frame();
+    if(activeSelectBoxHour)
+    {
+        activeSelectBoxHour.style.color='';
+    }
+    activeSelectBoxHour=this;
+    this.style.color = selectBoxHighlightColor;
+    }
+
+function selectMinute()
+{
+    document.getElementById('calendar_minute_txt').innerHTML = this.innerHTML
+    currentMinute = this.innerHTML.replace(/[^\d]/g,'');
+    document.getElementById('minuteDropDown').style.display='none';
+    //// fix for EI frame problem on time dropdowns 09/30/2006
+    EIS_Hide_Frame();
+    if(activeSelectBoxMinute)
+    {
+        activeSelectBoxMinute.style.color='';
+    }
+    activeSelectBoxMinute=this;
+    this.style.color = selectBoxHighlightColor;
+    }
+
+
+function selectYear()
+{
+    document.getElementById('calendar_year_txt').innerHTML = this.innerHTML
+    currentYear = this.innerHTML.replace(/[^\d]/g,'');
+    document.getElementById('yearDropDown').style.display='none';
+    //// fix for EI frame problem on time dropdowns 09/30/2006
+    EIS_Hide_Frame();
+    if(activeSelectBoxYear)
+    {
+        activeSelectBoxYear.style.color='';
+    }
+    activeSelectBoxYear=this;
+    this.style.color = selectBoxHighlightColor;
+    writeCalendarContent();
+}
+
+function switchMonth()
+{
+    if(this.src.indexOf('left')>=0)
+    {
+        currentMonth=currentMonth-1;;
+        if(currentMonth<0)
+        {
+            currentMonth=11;
+            currentYear=currentYear-1;
+        }
+    }
+    else
+    {
+        currentMonth=currentMonth+1;;
+        if(currentMonth>11)
+        {
+            currentMonth=0;
+            currentYear=currentYear/1+1;
+        }
+    }
+    writeCalendarContent();
+}
+
+function createMonthDiv()
+{
+    var div = document.createElement('DIV');
+    div.className='monthYearPicker';
+    div.id = 'monthPicker';
+
+    for(var no=0;no<monthArray.length;no++)
+    {
+        var subDiv = document.createElement('DIV');
+        subDiv.innerHTML = monthArray[no];
+        subDiv.onmouseover = highlightMonthYear;
+        subDiv.onmouseout = highlightMonthYear;
+        subDiv.onclick = selectMonth;
+        subDiv.id = 'monthDiv_' + no;
+        subDiv.style.width = '56px';
+        subDiv.onselectstart = cancelCalendarEvent;		
+        div.appendChild(subDiv);
+        if(currentMonth && currentMonth==no)
+        {
+            subDiv.style.color = selectBoxHighlightColor;
+            activeSelectBoxMonth = subDiv;
+        }
+    }
+    return div;
+}
+
+function changeSelectBoxYear(e,inputObj)
+{
+    if(!inputObj)inputObj =this;
+    var yearItems = inputObj.parentNode.getElementsByTagName('DIV');
+    if(inputObj.innerHTML.indexOf('-')>=0)
+    {
+        var startYear = yearItems[1].innerHTML/1 -1;
+        if(activeSelectBoxYear)
+        {
+            activeSelectBoxYear.style.color='';
+        }
+    }
+    else
+    {
+        var startYear = yearItems[1].innerHTML/1 +1;
+        if(activeSelectBoxYear)
+        {
+            activeSelectBoxYear.style.color='';
+        }
+    }
+    for(var no=1;no<yearItems.length-1;no++)
+    {
+        yearItems[no].innerHTML = startYear+no-1;	
+        yearItems[no].id = 'yearDiv' + (startYear/1+no/1-1);	
+    }
+    if(activeSelectBoxYear)
+    {
+        activeSelectBoxYear.style.color='';
+        if(document.getElementById('yearDiv'+currentYear))
+        {
+            activeSelectBoxYear = document.getElementById('yearDiv'+currentYear);
+            activeSelectBoxYear.style.color=selectBoxHighlightColor;;
+        }
+    }
+}
+
+function changeSelectBoxHour(e,inputObj)
+{
+    if(!inputObj) inputObj = this;
+    var hourItems = inputObj.parentNode.getElementsByTagName('DIV');
+    if(inputObj.innerHTML.indexOf('-')>=0)
+    {
+        var startHour = hourItems[1].innerHTML/1 -1;
+        if(startHour<0)startHour=0;
+        if(activeSelectBoxHour)
+        {
+            activeSelectBoxHour.style.color='';
+        }
+    }
+    else
+    {
+        var startHour = hourItems[1].innerHTML/1 +1;
+        if(startHour>14)startHour = 14;
+        if(activeSelectBoxHour)
+        {
+            activeSelectBoxHour.style.color='';
+        }
+    }
+    var prefix = '';
+    for(var no=1;no<hourItems.length-1;no++)
+    {
+        if((startHour/1 + no/1) < 11)prefix = '0'; else prefix = '';
+        hourItems[no].innerHTML = prefix + (startHour+no-1);
+        hourItems[no].id = 'hourDiv' + (startHour/1+no/1-1);
+    }
+    if(activeSelectBoxHour)
+    {
+        activeSelectBoxHour.style.color='';
+        if(document.getElementById('hourDiv'+currentHour))
+        {
+            activeSelectBoxHour = document.getElementById('hourDiv'+currentHour);
+            activeSelectBoxHour.style.color=selectBoxHighlightColor;;
+        }
+    }
+}
+
+function updateYearDiv()
+{
+    var div = document.getElementById('yearDropDown');
+    var yearItems = div.getElementsByTagName('DIV');
+    for(var no=1;no<yearItems.length-1;no++)
+    {
+        yearItems[no].innerHTML = currentYear/1 -6 + no;
+        if(currentYear==(currentYear/1 -6 + no))
+        {
+            yearItems[no].style.color = selectBoxHighlightColor;
+            activeSelectBoxYear = yearItems[no];
+        }
+        else
+        {
+            yearItems[no].style.color = '';
+        }
+    }
+}
+
+function updateMonthDiv()
+{
+    for(no=0;no<12;no++)
+    {
+        document.getElementById('monthDiv_' + no).style.color = '';
+    }
+    document.getElementById('monthDiv_' + currentMonth).style.color = selectBoxHighlightColor;
+    activeSelectBoxMonth = 	document.getElementById('monthDiv_' + currentMonth);
+}
+
+
+function updateHourDiv()
+{
+    var div = document.getElementById('hourDropDown');
+    var hourItems = div.getElementsByTagName('DIV');
+
+    var addHours = 0;
+    if((currentHour/1 -6 + 1)<0)
+    {
+        addHours = (currentHour/1 -6 + 1)*-1;
+    }
+    for(var no=1;no<hourItems.length-1;no++)
+    {
+        var prefix='';
+        if((currentHour/1 -6 + no + addHours) < 10)prefix='0';
+        hourItems[no].innerHTML = prefix +  (currentHour/1 -6 + no + addHours);	
+        if(currentHour==(currentHour/1 -6 + no))
+        {
+            hourItems[no].style.color = selectBoxHighlightColor;
+            activeSelectBoxHour = hourItems[no];
+        }
+        else
+        {
+        hourItems[no].style.color = '';
+        }
+    }
+}
+
+function updateMinuteDiv()
+{
+    for(no=0;no<60;no+=intervalSelectBox_minutes)
+    {
+        var prefix = '';
+        if(no<10)prefix = '0';
+        document.getElementById('minuteDiv_' + prefix + no).style.color = '';
+    }
+    if(document.getElementById('minuteDiv_' + currentMinute))
+    {
+        document.getElementById('minuteDiv_' + currentMinute).style.color = selectBoxHighlightColor;
+        activeSelectBoxMinute = document.getElementById('minuteDiv_' + currentMinute);
+    }
+}
+
+function createYearDiv()
+{
+    if(!document.getElementById('yearDropDown'))
+    {
+        var div = document.createElement('DIV');
+        div.className='monthYearPicker';
+    }
+    else
+    {
+        var div = document.getElementById('yearDropDown');
+        var subDivs = div.getElementsByTagName('DIV');
+        for(var no=0;no<subDivs.length;no++)
+        {
+            subDivs[no].parentNode.removeChild(subDivs[no]);	
+        }
+    }
+    var d = new Date();
+    if(currentYear)
+    {
+        d.setFullYear(currentYear);
+    }
+    var startYear = d.getFullYear()/1 - 5;
+    var subDiv = document.createElement('DIV');
+    subDiv.innerHTML = '&nbsp;&nbsp;- ';
+    subDiv.onclick = changeSelectBoxYear;
+    subDiv.onmouseover = highlightMonthYear;
+    subDiv.onmouseout = function()
+    {
+        selectBoxMovementInProgress = false;
+    }
+    ;
+    subDiv.onselectstart = cancelCalendarEvent;
+    div.appendChild(subDiv);
+
+    for(var no=startYear;no<(startYear+10);no++)
+    {
+        var subDiv = document.createElement('DIV');
+        subDiv.innerHTML = no;
+        subDiv.onmouseover = highlightMonthYear;
+        subDiv.onmouseout = highlightMonthYear;
+        subDiv.onclick = selectYear;
+        subDiv.id = 'yearDiv' + no;
+        subDiv.onselectstart = cancelCalendarEvent;	
+        div.appendChild(subDiv);
+        if(currentYear && currentYear==no)
+        {
+            subDiv.style.color = selectBoxHighlightColor;
+            activeSelectBoxYear = subDiv;
+        }
+    }
+    var subDiv = document.createElement('DIV');
+    subDiv.innerHTML = '&nbsp;&nbsp;+ ';
+    subDiv.onclick = changeSelectBoxYear;
+    subDiv.onmouseover = highlightMonthYear;
+    subDiv.onmouseout = function()
+    {
+        selectBoxMovementInProgress = false;
+    }
+    ;
+    subDiv.onselectstart = cancelCalendarEvent;
+    div.appendChild(subDiv);
+    return div;
+}
+
+/* This function creates the hour div at the bottom bar */
+
+function slideCalendarSelectBox()
+{
+    if(selectBoxMovementInProgress)
+    {
+        if(activeSelectBox.parentNode.id=='hourDropDown')
+        {
+            changeSelectBoxHour(false,activeSelectBox);
+        }
+        if(activeSelectBox.parentNode.id=='yearDropDown')
+        {
+            changeSelectBoxYear(false,activeSelectBox);
+        }
+    }
+    setTimeout('slideCalendarSelectBox()',speedOfSelectBoxSliding);
+}
+
+function createHourDiv()
+{
+    if(!document.getElementById('hourDropDown'))
+    {
+        var div = document.createElement('DIV');
+        div.className='monthYearPicker';
+    }
+    else
+    {
+        var div = document.getElementById('hourDropDown');
+        var subDivs = div.getElementsByTagName('DIV');
+        for(var no=0;no<subDivs.length;no++)
+        {
+            subDivs[no].parentNode.removeChild(subDivs[no]);
+        }
+    }
+    if(!currentHour)currentHour=0;
+    var startHour = currentHour/1;
+    if(startHour>14)startHour=14;
+
+    var subDiv = document.createElement('DIV');
+    subDiv.innerHTML = '&nbsp;&nbsp;- ';
+    subDiv.onclick = changeSelectBoxHour;
+    subDiv.onmouseover = highlightMonthYear;
+    subDiv.onmouseout = function(){ selectBoxMovementInProgress = false;};	
+    subDiv.onselectstart = cancelCalendarEvent;
+    div.appendChild(subDiv);
+
+    for(var no=startHour;no<startHour+10;no++)
+    {
+        var prefix = '';
+        if(no/1<10)prefix='0';
+        var subDiv = document.createElement('DIV');
+        subDiv.innerHTML = prefix + no;
+        subDiv.onmouseover = highlightMonthYear;
+        subDiv.onmouseout = highlightMonthYear;
+        subDiv.onclick = selectHour;
+        subDiv.id = 'hourDiv' + no;
+        subDiv.onselectstart = cancelCalendarEvent;	
+        div.appendChild(subDiv);
+        if(currentYear && currentYear==no)
+        {
+            subDiv.style.color = selectBoxHighlightColor;
+            activeSelectBoxYear = subDiv;
+        }
+    }
+    var subDiv = document.createElement('DIV');
+    subDiv.innerHTML = '&nbsp;&nbsp;+ ';
+    subDiv.onclick = changeSelectBoxHour;
+    subDiv.onmouseover = highlightMonthYear;
+    subDiv.onmouseout = function(){ selectBoxMovementInProgress = false;};
+    subDiv.onselectstart = cancelCalendarEvent;
+    div.appendChild(subDiv);
+
+    return div;
+}
+/* This function creates the minute div at the bottom bar */
+
+function createMinuteDiv()
+{
+    if(!document.getElementById('minuteDropDown'))
+    {
+        var div = document.createElement('DIV');
+        div.className='monthYearPicker';
+    }
+    else
+    {
+        var div = document.getElementById('minuteDropDown');
+        var subDivs = div.getElementsByTagName('DIV');
+        for(var no=0;no<subDivs.length;no++)
+        {
+            subDivs[no].parentNode.removeChild(subDivs[no]);
+        }
+    }
+    var startMinute = 0;
+    var prefix = '';
+    for(var no=startMinute;no<60;no+=intervalSelectBox_minutes)
+    {
+        if(no<10)prefix='0'; else prefix = '';
+        var subDiv = document.createElement('DIV');
+        subDiv.innerHTML = prefix + no;
+        subDiv.onmouseover = highlightMonthYear;
+        subDiv.onmouseout = highlightMonthYear;
+        subDiv.onclick = selectMinute;
+        subDiv.id = 'minuteDiv_' + prefix +  no;
+        subDiv.onselectstart = cancelCalendarEvent;
+        div.appendChild(subDiv);
+        if(currentYear && currentYear==no)
+        {
+            subDiv.style.color = selectBoxHighlightColor;
+            activeSelectBoxYear = subDiv;
+        }
+    }
+    return div;
+}
+
+function highlightSelect()
+{
+    if(this.className=='selectBoxTime')
+    {
+        this.className = 'selectBoxTimeOver';
+        this.getElementsByTagName('IMG')[0].src = pathToImages + 'down_time_over_cal.gif';
+    }
+    else if(this.className=='selectBoxTimeOver')
+    {
+        this.className = 'selectBoxTime';
+        this.getElementsByTagName('IMG')[0].src = pathToImages + 'down_time_cal.gif';
+    }
+    if(this.className=='selectBox')
+    {
+        this.className = 'selectBoxOver';
+        this.getElementsByTagName('IMG')[0].src = pathToImages + 'down_over_cal.gif';
+    }
+    else if(this.className=='selectBoxOver')
+    {
+        this.className = 'selectBox';
+        this.getElementsByTagName('IMG')[0].src = pathToImages + 'down_cal.gif';
+    }
+}
+
+function highlightArrow()
+{
+    if(this.src.indexOf('over')>=0)
+    {
+        if(this.src.indexOf('left')>=0)this.src = pathToImages + 'left_cal.gif';
+        if(this.src.indexOf('right')>=0)this.src = pathToImages + 'right_cal.gif';
+    }
+    else
+    {
+        if(this.src.indexOf('left')>=0)this.src = pathToImages + 'left_over_cal.gif';
+        if(this.src.indexOf('right')>=0)this.src = pathToImages + 'right_over_cal.gif';
+    }
+}
+
+function highlightClose()
+{
+    if(this.src.indexOf('over')>=0)
+    {
+        this.src = pathToImages + 'close_cal.gif';
+    }
+    else
+    {
+        this.src = pathToImages + 'close_over_cal.gif';	
+    }
+}
+
+function closeCalendar()
+{
+    document.getElementById('yearDropDown').style.display='none';
+    document.getElementById('monthDropDown').style.display='none';
+    document.getElementById('hourDropDown').style.display='none';
+    document.getElementById('minuteDropDown').style.display='none';
+
+    calendarDiv.style.display='none';
+    if(iframeObj){
+    iframeObj.style.display='none';
+    //// //// fix for EI frame problem on time dropdowns 09/30/2006
+    EIS_Hide_Frame();}
+    if(activeSelectBoxMonth)activeSelectBoxMonth.className='';
+    if(activeSelectBoxYear)activeSelectBoxYear.className='';
+}
+
+function writeTopBar()
+{
+    var topBar = document.createElement('DIV');
+    topBar.className = 'topBar';
+    topBar.id = 'topBar';
+    calendarDiv.appendChild(topBar);
+
+    // Left arrow
+    var leftDiv = document.createElement('DIV');
+    leftDiv.style.marginRight = '1px';
+    var img = document.createElement('IMG');
+    img.src = pathToImages + 'left_cal.gif';
+    img.onmouseover = highlightArrow;
+    img.onclick = switchMonth;
+    img.onmouseout = highlightArrow;
+    leftDiv.appendChild(img);	
+    topBar.appendChild(leftDiv);
+    if(Opera)leftDiv.style.width = '16px';
+
+    // Right arrow
+    var rightDiv = document.createElement('DIV');
+    rightDiv.style.marginRight = '1px';
+    var img = document.createElement('IMG');
+    img.src = pathToImages + 'right_cal.gif';
+    img.onclick = switchMonth;
+    img.onmouseover = highlightArrow;
+    img.onmouseout = highlightArrow;
+    rightDiv.appendChild(img);
+    if(Opera)rightDiv.style.width = '16px';
+    topBar.appendChild(rightDiv);
+
+    // Month selector
+    var monthDiv = document.createElement('DIV');
+    monthDiv.id = 'monthSelect';
+    monthDiv.onmouseover = highlightSelect;
+    monthDiv.onmouseout = highlightSelect;
+    monthDiv.onclick = showMonthDropDown;
+    var span = document.createElement('SPAN');
+    span.innerHTML = monthArray[currentMonth];
+    span.id = 'calendar_month_txt';
+    monthDiv.appendChild(span);
+    var img = document.createElement('IMG');
+    img.src = pathToImages + 'down_cal.gif';
+    img.style.position = 'absolute';
+    img.style.right = '0px';
+    monthDiv.appendChild(img);
+    monthDiv.className = 'selectBox';
+    if(Opera)
+    {
+        img.style.cssText = 'float:right;position:relative';
+        img.style.position = 'relative';
+        img.style.styleFloat = 'right';
+    }
+    topBar.appendChild(monthDiv);
+    var monthPicker = createMonthDiv();
+    monthPicker.style.left = '37px';
+    monthPicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px';
+    monthPicker.style.width ='60px';
+    monthPicker.id = 'monthDropDown';
+
+    calendarDiv.appendChild(monthPicker);
+
+    // Year selector
+    var yearDiv = document.createElement('DIV');
+    yearDiv.onmouseover = highlightSelect;
+    yearDiv.onmouseout = highlightSelect;
+    yearDiv.onclick = showYearDropDown;
+    var span = document.createElement('SPAN');
+    span.innerHTML = currentYear;
+    span.id = 'calendar_year_txt';
+    yearDiv.appendChild(span);
+    topBar.appendChild(yearDiv);
+    var img = document.createElement('IMG');
+    img.src = pathToImages + 'down_cal.gif';
+    yearDiv.appendChild(img);
+    yearDiv.className = 'selectBox';
+    if(Opera)
+    {
+        yearDiv.style.width = '50px';
+        img.style.cssText = 'float:right';
+        img.style.position = 'relative';
+        img.style.styleFloat = 'right';
+    }
+    var yearPicker = createYearDiv();
+    yearPicker.style.left = '113px';
+    yearPicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px';
+    yearPicker.style.width = '35px';
+    yearPicker.id = 'yearDropDown';
+    calendarDiv.appendChild(yearPicker);
+
+    var img = document.createElement('IMG');
+    img.src = pathToImages + 'close_cal.gif';
+    img.style.styleFloat = 'right';
+    img.onmouseover = highlightClose;
+    img.onmouseout = highlightClose;
+    img.onclick = closeCalendar;
+    topBar.appendChild(img);
+
+    if(!document.all)
+    {
+        img.style.position = 'absolute';
+        img.style.right = '2px';
+    }
+}
+
+function writeCalendarContent()
+{
+    var calendarContentDivExists = true;
+    if(!calendarContentDiv)
+    {
+        calendarContentDiv = document.createElement('DIV');
+        calendarDiv.appendChild(calendarContentDiv);
+        calendarContentDivExists = false;
+    }
+    currentMonth = currentMonth/1;
+    var d = new Date();
+
+    d.setFullYear(currentYear);
+    d.setDate(1);
+    d.setMonth(currentMonth);
+
+    var dayStartOfMonth = d.getDay();
+    if(dayStartOfMonth==0)dayStartOfMonth=7;
+    dayStartOfMonth--;
+
+    document.getElementById('calendar_year_txt').innerHTML = currentYear;
+    document.getElementById('calendar_month_txt').innerHTML = monthArray[currentMonth];
+    document.getElementById('calendar_hour_txt').innerHTML = currentHour;
+    document.getElementById('calendar_minute_txt').innerHTML = currentMinute;
+
+    var existingTable = calendarContentDiv.getElementsByTagName('TABLE');
+    if(existingTable.length>0)
+    {
+        calendarContentDiv.removeChild(existingTable[0]);
+    }
+
+    var calTable = document.createElement('TABLE');
+    calTable.width = '100%';
+    calTable.cellSpacing = '0';
+    calendarContentDiv.appendChild(calTable);
+
+    var calTBody = document.createElement('TBODY');
+    calTable.appendChild(calTBody);
+    var row = calTBody.insertRow(-1);
+    row.className = 'calendar_week_row';
+    var cell = row.insertCell(-1);
+    cell.innerHTML = weekString;
+    cell.className = 'calendar_week_column';
+    cell.style.backgroundColor = selectBoxRolloverBgColor;
+
+    for(var no=0;no<dayArray.length;no++)
+    {
+        var cell = row.insertCell(-1);
+        cell.innerHTML = dayArray[no]; 
+    }
+
+    var row = calTBody.insertRow(-1);
+    var cell = row.insertCell(-1);
+    cell.className = 'calendar_week_column';
+    cell.style.backgroundColor = selectBoxRolloverBgColor;
+    var week = getWeek(currentYear,currentMonth,1);
+    cell.innerHTML = week;		// Week
+    for(var no=0;no<dayStartOfMonth;no++)
+    {
+        var cell = row.insertCell(-1);
+        cell.innerHTML = '&nbsp;';
+    }
+
+    var colCounter = dayStartOfMonth;
+    var daysInMonth = daysInMonthArray[currentMonth];
+    if(daysInMonth==28)
+    {
+        if(isLeapYear(currentYear)) daysInMonth=29;
+    }
+
+    for(var no=1;no<=daysInMonth;no++)
+    {
+        d.setDate(no-1);
+        if(colCounter>0 && colCounter%7==0)
+        {
+            var row = calTBody.insertRow(-1);
+            var cell = row.insertCell(-1);
+            cell.className = 'calendar_week_column';
+            var week = getWeek(currentYear,currentMonth,no);
+            cell.innerHTML = week; // Week
+            cell.style.backgroundColor = selectBoxRolloverBgColor;
+        }
+        var cell = row.insertCell(-1);
+        if(currentYear==inputYear && currentMonth == inputMonth && no==inputDay)
+        {
+            cell.className='activeDay';
+        }
+        cell.innerHTML = no;
+        cell.onclick = pickDate;
+        colCounter++;
+    }
+
+    if(!document.all){
+        if(calendarContentDiv.offsetHeight)
+        document.getElementById('topBar').style.top = calendarContentDiv.offsetHeight + document.getElementById('timeBar').offsetHeight + document.getElementById('topBar').offsetHeight -1 + 'px';
+        else
+        {
+           document.getElementById('topBar').style.top = '';
+          document.getElementById('topBar').style.bottom = '0px';
+        }
+    }
+
+    if(iframeObj)
+    {
+        if(!calendarContentDivExists)setTimeout('resizeIframe()',350);else setTimeout('resizeIframe()',10);
+    }
+}
+
+function resizeIframe()
+{
+    iframeObj.style.width = calendarDiv.offsetWidth + 'px';
+    iframeObj.style.height = calendarDiv.offsetHeight + 'px' ;
+}
+
+function pickTodaysDate()
+{
+    var d = new Date();
+    currentMonth = d.getMonth();
+    currentYear = d.getFullYear();
+    pickDate(false,d.getDate());
+}
+
+function pickDate(e,inputDay)
+{
+    var month = currentMonth/1 +1;
+    if(month<10)month = '0' + month;
+    var day;
+    if(!inputDay && this)day = this.innerHTML; else day = inputDay;
+
+    if(day/1<10)day = '0' + day;
+    if(returnFormat)
+    {
+        returnFormat = returnFormat.replace('dd',day);
+        returnFormat = returnFormat.replace('mm',month);
+        returnFormat = returnFormat.replace('yyyy',currentYear);
+        returnFormat = returnFormat.replace('hh',currentHour);
+        returnFormat = returnFormat.replace('ii',currentMinute);
+        returnFormat = returnFormat.replace('d',day/1);
+        returnFormat = returnFormat.replace('m',month/1);
+        returnDateTo.value = returnFormat;
+        try
+        {
+            returnDateTo.onchange();
+        }
+        catch(e)
+        {
+        }
+    }
+    else
+    {
+        for(var no=0;no<returnDateToYear.options.length;no++)
+        {
+            if(returnDateToYear.options[no].value==currentYear)
+            {
+                returnDateToYear.selectedIndex=no;
+                break;
+            }
+        }
+        for(var no=0;no<returnDateToMonth.options.length;no++)
+        {
+            if(returnDateToMonth.options[no].value==parseInt(month))
+            {
+                returnDateToMonth.selectedIndex=no;
+                break;
+            }
+        }
+        for(var no=0;no<returnDateToDay.options.length;no++)
+        {
+            if(returnDateToDay.options[no].value==parseInt(day))
+            {
+                returnDateToDay.selectedIndex=no;
+                break;
+            }
+        }
+        if(calendarDisplayTime)
+        {
+            for(var no=0;no<returnDateToHour.options.length;no++)
+            {
+                if(returnDateToHour.options[no].value==parseInt(currentHour))
+                {
+                    returnDateToHour.selectedIndex=no;
+                    break;
+                }
+            }
+            for(var no=0;no<returnDateToMinute.options.length;no++)
+            {
+                if(returnDateToMinute.options[no].value==parseInt(currentMinute))
+                {
+                    returnDateToMinute.selectedIndex=no;
+                    break;
+                }
+            }
+        }
+    }
+    closeCalendar();
+}
+
+// This function is from http://www.codeproject.com/csharp/gregorianwknum.asp
+// Only changed the month add
+function getWeek(year,month,day)
+{
+    day = day/1;
+    year = year/1;
+    month = month/1 + 1; //use 1-12
+    var a = Math.floor((14-(month))/12);
+    var y = year+4800-a;
+    var m = (month)+(12*a)-3;
+    var jd = day + Math.floor(((153*m)+2)/5) + (365*y) + Math.floor(y/4) - Math.floor(y/100) + Math.floor(y/400) - 32045;      // (gregorian calendar)
+    var d4 = (jd+31741-(jd%7))%146097%36524%1461;
+    var L = Math.floor(d4/1460);
+    var d1 = ((d4-L)%365)+L;
+    NumberOfWeek = Math.floor(d1/7) + 1;
+    return NumberOfWeek;
+}
+
+function writeTimeBar()
+{
+    var timeBar = document.createElement('DIV');
+    timeBar.id = 'timeBar';
+    timeBar.className = 'timeBar';	
+    var subDiv = document.createElement('DIV');
+    subDiv.innerHTML = 'Time:';
+    //timeBar.appendChild(subDiv);
+    // Year selector
+    var hourDiv = document.createElement('DIV');
+    hourDiv.onmouseover = highlightSelect;
+    hourDiv.onmouseout = highlightSelect;
+    hourDiv.onclick = showHourDropDown;
+    hourDiv.style.width = '30px';
+    var span = document.createElement('SPAN');		
+    span.innerHTML = currentHour;
+    span.id = 'calendar_hour_txt';
+    hourDiv.appendChild(span);
+    timeBar.appendChild(hourDiv);
+    var img = document.createElement('IMG');
+    img.src = pathToImages + 'down_time_cal.gif';
+    hourDiv.appendChild(img);
+    hourDiv.className = 'selectBoxTime';
+    if(Opera)
+    {
+        hourDiv.style.width = '30px';
+        img.style.cssText = 'float:right';
+        img.style.position = 'relative';
+        img.style.styleFloat = 'right';
+    }
+    var hourPicker = createHourDiv();
+    hourPicker.style.left = '130px';
+    //hourPicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px';
+    hourPicker.style.width = '35px';
+    hourPicker.id = 'hourDropDown';
+    calendarDiv.appendChild(hourPicker);
+
+    // Add Minute picker
+    // Year selector
+    var minuteDiv = document.createElement('DIV');
+    minuteDiv.onmouseover = highlightSelect;
+    minuteDiv.onmouseout = highlightSelect;
+    minuteDiv.onclick = showMinuteDropDown;
+    minuteDiv.style.width = '30px';
+    var span = document.createElement('SPAN');
+    span.innerHTML = currentMinute;
+    span.id = 'calendar_minute_txt';
+    minuteDiv.appendChild(span);
+    timeBar.appendChild(minuteDiv);
+    var img = document.createElement('IMG');
+    img.src = pathToImages + 'down_time_cal.gif';
+    minuteDiv.appendChild(img);
+    minuteDiv.className = 'selectBoxTime';
+    if(Opera)
+    {
+        minuteDiv.style.width = '30px';
+        img.style.cssText = 'float:right';
+        img.style.position = 'relative';
+        img.style.styleFloat = 'right';
+    }
+    var minutePicker = createMinuteDiv();
+    minutePicker.style.left = '167px';
+    //minutePicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px';
+    minutePicker.style.width = '35px';
+    minutePicker.id = 'minuteDropDown';
+    calendarDiv.appendChild(minutePicker);
+
+    return timeBar;
+    }
+
+function writeBottomBar()
+{
+    var d = new Date();
+    var bottomBar = document.createElement('DIV');
+    bottomBar.id = 'bottomBar';
+    bottomBar.style.cursor = 'pointer';
+    bottomBar.className = 'todaysDate';
+    // var todayStringFormat = '[todayString] [dayString] [day] [monthString] [year]';	;;
+
+    var subDiv = document.createElement('DIV');
+    subDiv.onclick = pickTodaysDate;
+    subDiv.id = 'todaysDateString';
+    subDiv.style.width = (calendarDiv.offsetWidth - 95) + 'px';
+    var day = d.getDay();
+    if(day==0)day = 7;
+    day--;
+
+    var bottomString = todayStringFormat;
+    bottomString = bottomString.replace('[monthString]',monthArrayShort[d.getMonth()]);
+    bottomString = bottomString.replace('[day]',d.getDate());
+    bottomString = bottomString.replace('[year]',d.getFullYear());
+    bottomString = bottomString.replace('[dayString]',dayArray[day].toLowerCase());
+    bottomString = bottomString.replace('[UCFdayString]',dayArray[day]);
+    bottomString = bottomString.replace('[todayString]',todayString);
+
+    subDiv.innerHTML = todayString + ': ' + d.getDate() + '. ' + monthArrayShort[d.getMonth()] + ', ' +  d.getFullYear() ;
+    subDiv.innerHTML = bottomString ;
+    bottomBar.appendChild(subDiv);
+
+    var timeDiv = writeTimeBar();
+    bottomBar.appendChild(timeDiv);
+    calendarDiv.appendChild(bottomBar);	
+}
+
+function getTopPos(inputObj)
+{
+    var returnValue = inputObj.offsetTop + inputObj.offsetHeight;
+    while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetTop;
+    return returnValue + calendar_offsetTop;
+}
+
+function getleftPos(inputObj)
+{
+    var returnValue = inputObj.offsetLeft;
+    while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetLeft;
+    return returnValue + calendar_offsetLeft;
+}
+
+function positionCalendar(inputObj)
+{
+    calendarDiv.style.left = getleftPos(inputObj) + 'px';
+    calendarDiv.style.top = getTopPos(inputObj) + 'px';
+    if(iframeObj)
+    {
+        iframeObj.style.left = calendarDiv.style.left;
+        iframeObj.style.top =  calendarDiv.style.top;
+        //// fix for EI frame problem on time dropdowns 09/30/2006
+        iframeObj2.style.left = calendarDiv.style.left;
+        iframeObj2.style.top =  calendarDiv.style.top;
+    }
+}
+
+function initCalendar()
+{
+    if(MSIE)
+    {
+        iframeObj = document.createElement('IFRAME');
+        iframeObj.style.filter = 'alpha(opacity=0)';
+        iframeObj.style.position = 'absolute';
+        iframeObj.border='0px';
+        iframeObj.style.border = '0px';
+        iframeObj.style.backgroundColor = '#FF0000';
+        //// fix for EI frame problem on time dropdowns 09/30/2006
+        iframeObj2 = document.createElement('IFRAME');
+        iframeObj2.style.position = 'absolute';
+        iframeObj2.border='0px';
+        iframeObj2.style.border = '0px';
+        iframeObj2.style.height = '1px';
+        iframeObj2.style.width = '1px';
+        document.body.appendChild(iframeObj2);
+        //// fix for EI frame problem on time dropdowns 09/30/2006
+        // Added fixed for HTTPS
+        iframeObj2.src = 'blank.html';
+        iframeObj.src = 'blank.html';
+        document.body.appendChild(iframeObj);
+    }
+
+    calendarDiv = document.createElement('DIV');
+    calendarDiv.id = 'calendarDiv';
+    calendarDiv.style.zIndex = 1000;
+    slideCalendarSelectBox();
+
+    document.body.appendChild(calendarDiv);
+    writeBottomBar();	
+    writeTopBar();
+    if(!currentYear)
+    {
+        var d = new Date();
+        currentMonth = d.getMonth();
+        currentYear = d.getFullYear();
+    }
+    writeCalendarContent();
+}
+
+function setTimeProperties()
+{
+    if(!calendarDisplayTime)
+    {
+        document.getElementById('timeBar').style.display='none'; 
+        document.getElementById('timeBar').style.visibility='hidden'; 
+        document.getElementById('todaysDateString').style.width = '100%';
+    }
+    else
+    {
+        document.getElementById('timeBar').style.display='block';
+        document.getElementById('timeBar').style.visibility='visible';
+        document.getElementById('hourDropDown').style.top = document.getElementById('calendar_minute_txt').parentNode.offsetHeight + calendarContentDiv.offsetHeight + document.getElementById('topBar').offsetHeight + 'px';
+        document.getElementById('minuteDropDown').style.top = document.getElementById('calendar_minute_txt').parentNode.offsetHeight + calendarContentDiv.offsetHeight + document.getElementById('topBar').offsetHeight + 'px';
+        document.getElementById('minuteDropDown').style.right = '50px';
+        document.getElementById('hourDropDown').style.right = '50px';
+        document.getElementById('todaysDateString').style.width = '115px';
+    }
+}
+
+function calendarSortItems(a,b)
+{
+    return a/1 - b/1;
+}
+
+
+function displayCalendar(inputField,format,buttonObj,displayTime,timeInput)
+{
+    if(displayTime) calendarDisplayTime=true; else calendarDisplayTime = false;
+    if(inputField.value.length==10)
+    {
+        if(!format.match(/^[0-9]*?$/gi))
+        {
+            var items = inputField.value.split(/[^0-9]/gi);
+            var positionArray = new Array();
+            positionArray['m'] = format.indexOf('mm');
+            if(positionArray['m']==-1)positionArray['m'] = format.indexOf('m');
+            positionArray['d'] = format.indexOf('dd');
+            if(positionArray['d']==-1)positionArray['d'] = format.indexOf('d');
+            positionArray['y'] = format.indexOf('yyyy');
+            positionArray['h'] = format.indexOf('hh');
+            positionArray['i'] = format.indexOf('ii');
+            var positionArrayNumeric = Array();
+            positionArrayNumeric[0] = positionArray['m'];
+            positionArrayNumeric[1] = positionArray['d'];
+            positionArrayNumeric[2] = positionArray['y'];
+            positionArrayNumeric[3] = positionArray['h'];
+            positionArrayNumeric[4] = positionArray['i'];
+            positionArrayNumeric = positionArrayNumeric.sort(calendarSortItems);
+            var itemIndex = -1;
+            currentHour = '00';
+            currentMinute = '00';
+            for(var no=0;no<positionArrayNumeric.length;no++)
+            {
+                if(positionArrayNumeric[no]==-1)continue;
+                itemIndex++;
+                if(positionArrayNumeric[no]==positionArray['m'])
+                {
+                    currentMonth = items[itemIndex]-1;
+                    continue;
+                }
+                if(positionArrayNumeric[no]==positionArray['y'])
+                {
+                    currentYear = items[itemIndex];
+                    continue;
+                }
+                if(positionArrayNumeric[no]==positionArray['d'])
+                {
+                    tmpDay = items[itemIndex];
+                    continue;
+                }
+                if(positionArrayNumeric[no]==positionArray['h'])
+                {
+                    currentHour = items[itemIndex];
+                    continue;
+                }
+                if(positionArrayNumeric[no]==positionArray['i'])
+                {
+                    currentMinute = items[itemIndex];
+                    continue;
+                }
+            }
+
+            currentMonth = currentMonth / 1;
+            tmpDay = tmpDay / 1;
+        }
+        else
+        {
+            var monthPos = format.indexOf('mm');
+            currentMonth = inputField.value.substr(monthPos,2)/1 -1;	
+            var yearPos = format.indexOf('yyyy');
+            currentYear = inputField.value.substr(yearPos,4);		
+            var dayPos = format.indexOf('dd');
+            tmpDay = inputField.value.substr(dayPos,2);		
+            var hourPos = format.indexOf('hh');
+            if(hourPos>=0)
+            {
+                tmpHour = inputField.value.substr(hourPos,2);	
+                currentHour = tmpHour;
+            }
+            else
+            {
+            currentHour = '00';
+            }
+            var minutePos = format.indexOf('ii');
+            if(minutePos>=0)
+            {
+                tmpMinute = inputField.value.substr(minutePos,2);	
+                currentMinute = tmpMinute;
+            }
+            else
+            {
+                currentMinute = '00';
+            }
+        }
+    }
+    else
+    {
+        var d = new Date();
+        currentMonth = d.getMonth();
+        currentYear = d.getFullYear();
+        currentHour = '08';
+        currentMinute = '00';
+        tmpDay = d.getDate();
+    }
+    inputYear = currentYear;
+    inputMonth = currentMonth;
+    inputDay = tmpDay/1;
+    if(!calendarDiv)
+    {
+        initCalendar();
+    }
+    else
+    {
+        if(calendarDiv.style.display=='block')
+        {
+            closeCalendar();
+            return false;
+        }
+    writeCalendarContent();
+    }
+    returnFormat = format;
+    returnDateTo = inputField;
+    positionCalendar(buttonObj);
+    calendarDiv.style.visibility = 'visible';	
+    calendarDiv.style.display = 'block';	
+    if(iframeObj)
+    {
+        iframeObj.style.display = '';
+        iframeObj.style.height = '140px';
+        iframeObj.style.width = '195px';
+        iframeObj2.style.display = '';
+        iframeObj2.style.height = '140px';
+        iframeObj2.style.width = '195px';
+    }
+    setTimeProperties();	
+    updateYearDiv();
+    updateMonthDiv();
+    updateMinuteDiv();
+    updateHourDiv();
+}
+
+function displayCalendarSelectBox(yearInput,monthInput,dayInput,hourInput,minuteInput,buttonObj)
+{
+    if(!hourInput)calendarDisplayTime=false; else calendarDisplayTime = true;
+
+    currentMonth = monthInput.options[monthInput.selectedIndex].value/1-1;
+    currentYear = yearInput.options[yearInput.selectedIndex].value;
+    if(hourInput)
+    {
+        currentHour = hourInput.options[hourInput.selectedIndex].value;
+        inputHour = currentHour/1;
+    }
+    if(minuteInput)
+    {
+        currentMinute = minuteInput.options[minuteInput.selectedIndex].value;
+        inputMinute = currentMinute/1;
+    }
+
+    inputYear = yearInput.options[yearInput.selectedIndex].value;
+    inputMonth = monthInput.options[monthInput.selectedIndex].value/1 - 1;
+    inputDay = dayInput.options[dayInput.selectedIndex].value/1;
+
+    if(!calendarDiv)
+    {
+        initCalendar();
+    }
+    else
+    {
+        writeCalendarContent();
+    }
+
+    returnDateToYear = yearInput;
+    returnDateToMonth = monthInput;
+    returnDateToDay = dayInput;
+    returnDateToHour = hourInput; 	
+    returnDateToMinute = minuteInput; 	
+
+    returnFormat = false;
+    returnDateTo = false;
+    positionCalendar(buttonObj);
+    calendarDiv.style.visibility = 'visible';	
+    calendarDiv.style.display = 'block';
+    if(iframeObj)
+    {
+    iframeObj.style.display = '';
+    iframeObj.style.height = calendarDiv.offsetHeight + 'px';
+    iframeObj.style.width = calendarDiv.offsetWidth + 'px';	
+    //// fix for EI frame problem on time dropdowns 09/30/2006
+    iframeObj2.style.display = '';
+    iframeObj2.style.height = calendarDiv.offsetHeight + 'px';
+    iframeObj2.style.width = calendarDiv.offsetWidth + 'px'
+    }
+    setTimeProperties();
+    updateYearDiv();
+    updateMonthDiv();
+    updateHourDiv();
+    updateMinuteDiv();
+}
+
+// colocar no evento onKeyUp passando o objeto como parametro
+function formata_dt(val)
+{
+    var pass = val.value;
+    var expr = /[0123456789]/;
+
+    for (i=0; i<pass.length; i++)
+    {
+        // charAt -> retorna o caractere posicionado no índice especificado
+        var lchar = val.value.charAt(i);
+        var nchar = val.value.charAt(i+1);
+
+        if (i==0)
+        {
+            // search -> retorna um valor inteiro, indicando a posição do inicio da primeira
+            // ocorrência de expReg dentro de instStr. Se nenhuma ocorrencia for encontrada o método retornara -1
+            // instStr.search(expReg);
+            if ((lchar.search(expr) != 0) || (lchar>3))
+            {
+                val.value = "";
+            }
+
+        }
+        else if (i==1)
+        {
+            if (lchar.search(expr) != 0)
+            {
+                // substring(indice1,indice2)
+                // indice1, indice2 -> será usado para delimitar a string
+                var tst1 = val.value.substring(0,(i));
+                val.value = tst1;
+                continue;
+            }
+            if ((nchar != '/') && (nchar != ''))
+            {
+                var tst1 = val.value.substring(0, (i)+1);
+
+                if(nchar.search(expr) != 0) var tst2 = val.value.substring(i+2, pass.length);
+                else var tst2 = val.value.substring(i+1, pass.length);
+
+                val.value = tst1 + '/' + tst2;
+            }
+        }
+        else if (i==4)
+        {
+            if (lchar.search(expr) != 0)
+            {
+                var tst1 = val.value.substring(0, (i));
+                val.value = tst1;
+                continue;
+            }
+
+            if ((nchar != '/') && (nchar != ''))
+            {
+                var tst1 = val.value.substring(0, (i)+1);
+                if(nchar.search(expr) != 0) var tst2 = val.value.substring(i+2, pass.length);
+                else var tst2 = val.value.substring(i+1, pass.length);
+                val.value = tst1 + '/' + tst2;
+            }
+        }
+        if (i>=6)
+        {
+            if (lchar.search(expr) != 0)
+            {
+                var tst1 = val.value.substring(0, (i));
+                val.value = tst1;
+            }
+        }
+    }
+
+    if(pass.length==10)
+    {
+        dia = (val.value.substring(0,2));
+        mes = (val.value.substring(3,5));
+        ano = (val.value.substring(6,10));
+
+        cons = true;
+
+        // verifica se foram digitados números
+        if (isNaN(dia) || isNaN(mes) || isNaN(ano))
+        {
+            alert("Preencha a data somente com números.");
+            val.value = "";
+            val.focus();
+            return false;
+        }
+
+        // verifica o dia valido para cada mes
+        if ((dia < "01")||(dia < "01" || dia > "30") && (mes == "04" || mes == "06" ||  mes == "09" || mes == "11" ) ||  dia > "31")
+        {
+            cons = false;
+        }
+
+        // verifica se o mes e valido
+        if (mes < "01" || mes > "12" )
+        {
+            cons = false;
+        }
+
+        // verifica se e ano bissexto
+        if (mes == "02" && ( dia < "01" || dia > "29" || ( dia > "28" && (parseInt(ano / 4) != ano / 4))))
+        {
+            cons = false;
+        }
+
+        if (cons == false)
+        {
+            alert("A data inserida não é válida: " + val.value);
+            val.value = "";
+            val.focus();
+            return false;
+        }
+    }
+    if(pass.length>10)
+    val.value = val.value.substring(0, 10);
+    return true;
+}
+/**
+* @autor : Ricardo e Rodrigo
+* @data : 28/12/2007
+* @Objetivo : Validar Mes e ano
+* @chamada da função: onKeyUp="formata_mes_ano(this);"
+*/
+function formata_mes_ano(val)
+{
+    var pass = val.value;
+    var expr = /[0123456789]/;
+
+    for (i=0; i<pass.length; i++)
+    {
+        // charAt -> retorna o caractere posicionado no índice especificado
+        var lchar = val.value.charAt(i);
+        var nchar = val.value.charAt(i+1);
+
+        if (i==0)
+        {
+            // search -> retorna um valor inteiro, indicando a posição do inicio da primeira
+            // ocorrência de expReg dentro de instStr. Se nenhuma ocorrencia for encontrada o método retornara -1
+            // instStr.search(expReg);
+            if ((lchar.search(expr) != 0) || (lchar>1))
+            {
+                val.value = "";
+            }
+
+        }
+        else if (i==1)
+        {
+            if (val.value.substring(0, 2)>12)
+            {
+                val.value = val.value.substring(0, (i));
+            }
+            if (lchar.search(expr) != 0)
+            {
+                // substring(indice1,indice2)
+                // indice1, indice2 -> será usado para delimitar a string
+                var tst1 = val.value.substring(0,(i));
+                val.value = tst1;
+                continue;
+            }
+            if ((nchar != '/') && (nchar != ''))
+            {
+                var tst1 = val.value.substring(0, (i)+1);//conferir este valor;
+
+                if(nchar.search(expr) != 0) var tst2 = val.value.substring(i+2, pass.length);
+                else var tst2 = val.value.substring(i+1, pass.length);
+
+                val.value = tst1 + '/' + tst2;
+            }
+        }
+        if (i>=4)
+        {
+            if (lchar.search(expr) != 0)
+            {
+                var tst1 = val.value.substring(0, (i));
+                val.value = tst1;
+            }
+        }
+    }
+
+    if(pass.length==7)
+    {
+        mes = (val.value.substring(0,2));
+        ano = (val.value.substring(3,7));
+
+        cons = true;
+
+        // verifica se foram digitados números
+        if (isNaN(mes) || isNaN(ano))
+        {
+            alert("Preencha a data somente com números.");
+            val.value = "";
+            val.focus();
+            return false;
+        }
+
+        // verifica se o mes e valido
+        if (mes < "01" || mes > "12" )
+        {
+            cons = false;
+        }
+
+        if (cons == false)
+        {
+            alert("A data inserida não é válida: " + val.value);
+            val.value = "";
+            val.focus();
+            return false;
+        }
+    }
+    if(pass.length>7)
+    val.value = val.value.substring(0, 7);
+    return true;
+}
Index: trunk/workflow/inc/report/includes/js/mascaras.js
===================================================================
--- trunk/workflow/inc/report/includes/js/mascaras.js	(revision 5307)
+++ trunk/workflow/inc/report/includes/js/mascaras.js	(revision 5307)
@@ -0,0 +1,504 @@
+
+/* ************************************************************************************************
+Função:     formatar(campo,mascara)
+Autor:      Alex Nunes Wzorek
+Data:       26/08/2008
+Descrição:  Função utilizada para formatar máscaras genéricas em campos text
+          @ - numeros
+          # - demais caracteres
+          OnKeyUp="formatar(this,'###-@@/@@@@')"    
+**************************************************************************************************/ 
+
+function formatar(campo, mask){
+    if(navigator.appName == 'Konqueror') {
+        if(window.event && window.event.toString()  == "[object KeyboardEvent]"){
+            return true;
+        }
+    }
+    //verifica se mascara é para somente números
+    if(mask == '@'){
+        campo.value = campo.value.replace(/\D/g,"");
+        return;
+        /*if(!parseInt(campo.value))
+             campo.value = '';
+        else
+            campo.value = parseInt(campo.value);
+        return '';*/
+    }
+    
+    if(campo.value.length > mask.length){
+            campo.value = campo.value.substring(0,mask.length);
+    }
+    else {
+            var i = campo.value.length -1;
+            var texto = mask.substring(i);
+            if(texto.substring(0,1) != '#'){
+                    for(j=i;j<=mask.length;j++) {
+                            if(mask.substring(j,j+1) == '@'){
+                                    var valida = campo.value.substring(j,j+1);
+                                    if((valida != 0 && valida != 1 && valida != 2 && valida != 3 && valida != 4 && valida != 5 && valida != 6 && valida != 7 && valida != 8 && valida != 9) || valida==" ")
+                                    campo.value = campo.value.substr(0,i);
+                                    break;
+                            }
+                            else {
+                                    if(mask.substring(j,j+1) == '#' || mask.substring(j,j+1) == campo.value.substring(j))	
+                                            break;
+                                    var saida = '#';
+                                    if (mask.substring(j,j+1) != saida)
+                                    {	
+                                            campo.value = campo.value.substring(0,j) + mask.substring(j,j+1) + campo.value.substring(j);
+                                    }
+                            }
+                    }
+            }
+    }
+}
+
+
+/* ************************************************************************************************
+Função:     revalidar(campo,mascara,validacao)
+Autor:      Alex Nunes Wzorek
+Data:       26/08/2008
+Descrição:  Função utilizada para atribuir a máscara e validar campos específicos. 
+          Chama a função formatar(), para evitar erros no caso do usuário colar um valor (ctrl+v)
+          para o campo text.
+          OnBlur="formatar(this,'@@@.@@@.@@@-@@','cpf')"    
+**************************************************************************************************/ 
+
+function revalidar(campo,mask,validacao){
+    campo.style.background = "#FFFFFF";
+        if(mask != ''){
+            var aux = campo.value;
+            campo.value = '';
+            if(mask == '@'){
+                // Alterado por Ricardo - 19/09/2008
+                //if(parseInt(aux))
+                //    campo.value = parseInt(aux);
+                campo.value = aux.replace(/\D/g,"");
+            }
+            else{
+                for(i=0;i<aux.length;i++){
+                        campo.value += aux.substr(i,1);
+                        formatar(campo,mask);
+                }
+            }
+        }
+	switch (validacao) {
+		case 'cnpj':
+			var valor = campo.value;
+				
+			valor = valor.replace (".","").replace (".","").replace ("-","").replace ("/","");
+			
+			var a = [];
+			var b = new Number;
+			var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
+			for (i=0; i<12; i++){
+				a[i] = valor.charAt(i);
+				b += a[i] * c[i+1];
+			}
+			if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
+			b = 0;
+			for (y=0; y<13; y++) {
+				b += (a[y] * c[y]);
+			}
+			if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
+			if ((valor.charAt(12) != a[12]) || (valor.charAt(13) != a[13])){
+				campo.style.background = "#FFFFC0";
+				campo.value = '';
+				return false;	
+			}
+			break; 
+		
+        case 'email':
+
+			if (trim(campo.value) != ""){
+			    var vemail =/^[\w-]+(\.[\w-]+)*@(([\w-]{2,63}\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
+			    if(!vemail.test(campo.value)){
+					campo.style.background = "#FFFFC0";
+					campo.value = '';
+					return false;	
+			    }
+			}    
+			break;
+                        
+
+		case 'cpf':
+		
+			var valor = campo.value.replace('.','').replace('.','').replace('-','');
+			
+			if(valor.length != 11 || valor == "00000000000" || valor == "11111111111" ||
+				valor == "22222222222" || valor == "33333333333" || valor == "44444444444" ||
+				valor == "55555555555" || valor == "66666666666" || valor == "77777777777" ||
+				valor == "88888888888" || valor == "99999999999"){
+				campo.style.background = "#FFFFC0";
+				campo.value = '';
+				return false;
+				break;
+			}
+			
+			soma = 0;
+			for(i = 0; i < 9; i++)
+				soma += parseInt(valor.charAt(i)) * (10 - i);
+			resto = 11 - (soma % 11);
+			if(resto == 10 || resto == 11)
+				resto = 0;
+			if(resto != parseInt(valor.charAt(9))){
+				campo.style.background = "#FFFFC0";
+				campo.value = '';
+				return false;	
+			}
+			soma = 0;
+			for(i = 0; i < 10; i ++)
+				soma += parseInt(valor.charAt(i)) * (11 - i);
+			resto = 11 - (soma % 11);
+			if(resto == 10 || resto == 11)
+				resto = 0;
+			if(resto != parseInt(valor.charAt(10))){
+				campo.style.background = "#FFFFC0";
+				campo.value = '';
+				return false;	
+			}
+			break
+		
+		case 'data':
+		
+			var tam = campo.length;
+			var dia = campo.value.substr(0,2);
+			var mes = campo.value.substr (3,2);
+			var ano = campo.value.substr (6,4);
+			var array_campo = campo.value.split('/');
+			
+			if (array_campo.length < 3) {
+				campo.value = '';
+				campo.style.background = "#FFFFC0";
+				return false;
+			} else {
+				if (array_campo[2].length < 4) {
+					campo.value = '';
+					campo.style.background = "#FFFFC0";
+					return false;
+				}
+			}
+			if (dia > 31 || dia == 0) {
+				campo.value = '';
+				campo.style.background = "#FFFFC0";
+				return false;
+			}
+			if (mes < 1 || mes > 12) {
+				campo.value = '';
+				campo.style.background = "#FFFFC0";
+				return false;
+			}
+
+            var date = new Date();
+            if(ano < (date.getFullYear() - 15) || ano > (date.getFullYear() +15)){
+				campo.style.background = "#FFFFC0";
+				return false;	
+                        }
+                        if(mes == 1 || mes == 3 || mes == 5 || mes == 7 || mes == 8 || mes == 10 || mes == 12){
+                                if  (dia > 31){
+						campo.style.background = "#FFFFC0";
+						campo.value = '';
+						return false;	
+       	            	        }
+                        }
+                        if(mes == 4 || mes == 6 || mes == 9 || mes == 11){
+                                if  (dia > 30){
+						campo.style.background = "#FFFFC0";
+						campo.value = '';
+						return false;	
+				}
+                        }
+                        //verifica bisexto
+                        if(mes == 2 && ( dia > 29 || ( dia > 28 && (parseInt(ano / 4) != ano / 4)))){
+				campo.style.background = "#FFFFC0";
+				campo.value = '';
+				return false;	
+                        }
+                        if(mes > 12 || mes < 1){
+				campo.style.background = "#FFFFC0";
+				campo.value = '';
+				return false;	
+                        }
+            
+			break;
+			
+		case 'hora':
+			
+			var tam = campo.length;
+			var hora = campo.value.substr(0,2);
+			var min = campo.value.substr (3,2);
+			var array_campo = campo.value.split(':');
+			
+			if (array_campo.length < 2) {
+				campo.value = '';
+				campo.style.background = "#FFFFC0";
+				return false;
+			} else {
+				if (array_campo[0].length < 2 || array_campo[1].length < 2) {
+					campo.value = '';
+					campo.style.background = "#FFFFC0";
+					return false;
+				}
+			}
+			if (hora > 23 || hora < 0 ) {
+				campo.value = '';
+				campo.style.background = "#FFFFC0";
+				return false;
+			}
+			if (min < 0 || min > 59) {
+				campo.value = '';
+				campo.style.background = "#FFFFC0";
+				return false;
+			}
+			
+			break;
+		
+		case 'tempo':
+			
+			var tam = campo.length;
+			var hora = campo.value.substr(0,2);
+			var min = campo.value.substr (3,2);
+			var array_campo = campo.value.split(':');
+			
+			if (array_campo.length < 2) {
+				campo.value = '';
+				campo.style.background = "#FFFFC0";
+				return false;
+			} else {
+				if (array_campo[0].length < 2 || array_campo[1].length < 2) {
+					campo.value = '';
+					campo.style.background = "#FFFFC0";
+					return false;
+				}
+			}
+			if (min < 0 || min > 59) {
+				campo.value = '';
+				campo.style.background = "#FFFFC0";
+				return false;
+			}
+			
+			break;
+			
+		case 'mesAno':
+
+			var tam = campo.length;
+			var mes = campo.value.substr (0,2);
+			var ano = campo.value.substr (3,4);
+			var array_campo = campo.value.split('/');
+
+			if (array_campo.length < 2) {
+				campo.value = '';
+				campo.style.background = "#FFFFC0";
+				return false;
+			} else {
+				if (array_campo[1].length < 4) {
+					campo.value = '';
+					campo.style.background = "#FFFFC0";
+					return false;
+				}
+			}
+			if (mes < 1 || mes > 12) {
+				campo.value = '';
+				campo.style.background = "#FFFFC0";
+				return false;
+			}
+
+			var date = new Date();
+			if(ano < (date.getFullYear() - 15) || ano > (date.getFullYear() +15)){
+				campo.style.background = "#FFFFC0";
+				return false;	
+			}
+
+			break;
+	}
+	campo.style.background = "";
+	return true;
+}
+
+/* ************************************************************************************************
+Função:     moeda(campo,casas)
+Autor:      Alex Nunes Wzorek
+Data:       26/08/2008
+Descrição:  Função utilizada para formatar valores monetários com separador de milhar (.) e decimal (,). 
+          O segundo parametro é o número de casas decimais desejado
+          OnKeyUp="moeda(this,2)"    
+**************************************************************************************************/ 
+
+function moeda(campo,casas){
+        if(navigator.appName == 'Konqueror') {
+            if(window.event.toString()  == "[object KeyboardEvent]"){
+                return true;
+            }
+        }
+	var valida = campo.value.substring(campo.value.length-1);	
+	if((valida != 0 && valida != 1 && valida != 2 && valida != 3 && valida != 4 && valida != 5 && valida != 6 && valida != 7 && valida != 8 && valida != 9) || valida == ' '){
+		campo.value = campo.value.substr(0,campo.value.length-1);
+	}
+	campo.value = campo.value.replace('.','').replace(',','.');
+	if(parseFloat(campo.value) < 1){
+		campo.value = parseFloat(campo.value.replace('0.',''));
+	}
+	var zeros = '';
+	if(campo.value.length <= casas){
+		for(i=0;i<casas-campo.value.length;i++){
+			zeros += '0';
+		}
+		campo.value = '0,' + zeros + campo.value;
+	}
+	else{
+		if(campo.value.length > (casas+4)){
+			var decimal = campo.value.substr(campo.value.length-(casas));
+			var inteiro = campo.value.substr(0,campo.value.length-casas).replace(/\./g,'');
+			var milhar = '';
+			for(i=0;i<inteiro.length;){
+				i+=3;
+				if((inteiro.substr(inteiro.length-(i+1),4).length == 4) && ((inteiro.length-(i+1)) >= 0)){
+					milhar =  inteiro.substr(inteiro.length-i,3) + '.' + milhar;
+				}
+				else{
+                                        milhar = inteiro.substr(0,(inteiro.length-(i+1))+4) + '.' + milhar; 
+				}
+			}
+			if(milhar != '')
+				campo.value = milhar.substr(0,milhar.length-1) + ',' +decimal;
+		}
+		else{
+			campo.value = campo.value.substr(0,campo.value.length -casas).replace('.','') + ',' + campo.value.substr(campo.value.length -casas);
+		}	
+	}
+}
+
+/* ************************************************************************************************
+Função:     revalidarMoeda(campo,casas)
+Autor:      Alex Nunes Wzorek
+Data:       26/08/2008
+Descrição:  Função utilizada para formatar valores monetários com separador de milhar (.) e decimal (,). 
+          Chama a função moeda, para formatar valores que possam ter sido colados (ctrl+v) pelo usuario.
+          OnBlur="moeda(this,2)"    
+**************************************************************************************************/
+
+function revalidarMoeda(campo,casas){
+	aux = campo.value;
+	campo.value = '';
+	for(j=0;j<aux.length;j++){
+         	campo.value += aux.substr(j,1);
+		moeda(campo,casas);
+	}
+}
+
+/* ************************************************************************************************
+Função:     milhar(campo)
+Autor:      Ricardo Andre Pikussa
+Data:       26/08/2008
+Descrição:  Função utilizada para formatar valores numerico com separador de milhar (.). 
+         	OnKeyUp="milhar(this);"    
+**************************************************************************************************/ 
+
+function milhar(campo){
+    if(navigator.appName == 'Konqueror') {
+        if(window.event.toString()  == "[object KeyboardEvent]"){
+            return true;
+        }
+    }
+	var valida = campo.value.substring(campo.value.length-1);	
+	if((valida != 0 && valida != 1 && valida != 2 && valida != 3 && valida != 4 && valida != 5 && valida != 6 && valida != 7 && valida != 8 && valida != 9) || valida == ' '){
+		campo.value = campo.value.substr(0,campo.value.length-1);
+	}
+	campo.value = campo.value.replace('.','').replace(',','.');
+	if(parseFloat(campo.value) < 1){
+		campo.value = parseFloat(campo.value.replace('0.',''));
+	}
+		if(campo.value.length >= 3){
+		var decimal = campo.value.substr(campo.value.length);
+		var inteiro = campo.value.substr(0,campo.value.length).replace(/\./g,'');
+		var milhar = '';
+		for(i=0;i<inteiro.length;){
+			i+=3;
+			if((inteiro.substr(inteiro.length-(i+1),4).length == 4) && ((inteiro.length-(i+1)) >= 0)){
+				milhar =  inteiro.substr(inteiro.length-i,3) + '.' + milhar;
+			} else {
+				milhar = inteiro.substr(0,(inteiro.length-(i+1))+4) + '.' + milhar; 
+			}
+		}
+		if(milhar != '')
+			campo.value = milhar.substr(0,milhar.length-1) + decimal;
+	} else {
+		campo.value = campo.value.substr(0,campo.value.length).replace('.','') + campo.value.substr(campo.value.length);
+	}	
+}
+
+/**
+ * Função:     	revalidarMilhar(campo)
+ * Autor:      	Ricardo Andre Pikussa
+ * Data:       	26/08/2008
+ * Descrição:  	Função utilizada para formatar valores numerricos com separador de milhar (.). 
+          		Chama a função milhar, para formatar valores que possam ter sido colados (ctrl+v) pelo usuario.
+ * Chamada:		OnBlur="revalidarMilhar(this);"    
+ */
+function revalidarMilhar(campo){
+	aux = campo.value;
+	campo.value = '';
+	for(j=0;j<aux.length;j++){
+        campo.value += aux.substr(j,1);
+		milhar(campo);
+	}
+}
+
+/**
+ * Função:     retiraCaracteres(campo,upper)
+ * Autor:      Ricardo Andre Pikussa
+ * Data:       12/12/2008
+ * Descrição:  Função utilizada para retiraar caracteres indesejados em campos text
+	Se preciso ela tambem passa os caracteres para caixa alta 
+ * Chamada:		onBlur="retiraCaracteres(this);"
+ */
+function retiraCaracteres(campo, upper) 
+{
+	campo.value = campo.value.replace(/[\'°ºª]/g,"");
+	if (upper == 'true') {
+		campo.value = campo.value.toUpperCase();
+	}
+}
+
+function somenteNumero(campo){
+	
+    var digits = "0123456789.";
+    var campo_temp 
+    
+    for (var i=0;i<campo.value.length;i++){
+    
+    	campo_temp=campo.value.substring(i,i+1)
+    	
+    	if (digits.indexOf(campo_temp)==-1){
+    		
+    		campo.value = campo.value.substring(0,i);
+    		break;
+    	}
+    }
+}
+
+function revalidaSomenteNumero(campo,casas){
+
+	var digits = "0123456789.";
+	var campo_temp; 
+	    
+	for (var i=0;i<campo.value.length;i++){
+	      
+		campo_temp = campo.value.substring(i,i+1)       
+	      
+		if (digits.indexOf(campo_temp)==-1){
+			campo.value = campo.value.substring(0,i);
+            break;
+		}
+	}
+	
+	valor = campo.value;
+	
+	if(valor.length > 0){
+	
+		valor = parseFloat(valor);
+		campo.value = valor.toFixed(casas);
+	}
+}
+
Index: trunk/workflow/inc/report/includes/js/validacoes.js
===================================================================
--- trunk/workflow/inc/report/includes/js/validacoes.js	(revision 5307)
+++ trunk/workflow/inc/report/includes/js/validacoes.js	(revision 5307)
@@ -0,0 +1,557 @@
+/**
+ * Função:     submeter(acao, prefixo)
+ * Data:       12/12/2008
+ * Descrição:  Função utilizada para validar os campos obrigatórios de um formulário
+ 			Foi criada no intuito de agiizar o desenvolvimento de formulários de pesquisa
+ 			Exige que os campos possuam um prefixo passado por parametro e o prefixo deve possuir 4 caracteres
+ 			Exige que o formulario possua o nome frm
+ 			Trabalha validando o preenchimento dos campos onde há o prefixo passado 
+ 			e submete o frm em caso de sucesso, caso contrario alerta e muda a cor de fundo dos campos
+ * Chamada:	onClick="submeter('pesquisar','pesq');"
+ *     
+ */
+ 
+ 
+ /**
+ * Criado em: 04/03/2009
+ * 
+ *	
+ * 	Função. valida(form,acao,submete,obrigatorio);
+ * 
+ * 	@param form = objeto forumlario que deseja validar;
+ * 	@param acao = valor que deseja que seja setado no input de ação
+ * 	@param submete = valor (true ou false) para dizer se o script vai submeter o formulario
+ * 	@param obrigatorio = campo opcional que altera o default de 'nao obrigatorios' com o valor (_not)
+ * 						para 'obrigatorios' com o valor passado
+ * 
+ * 
+ * Script tem como funcionalidade validar todos os inputs do formulario
+ * 
+ *  - Compativel com: Firefox 3, Internet Explorer 7, Konqueror 3.5, Chrome 1.0, Opera 9
+ * 
+ * 	NOTAS IMPORTANTES
+ * 
+ * 	- para o script identificar a acao do form, o input tipo hidden 'acao' deve possuir o um id com o prefixo do form
+ *    em que ele está, da seguinte maneira 'id_form'+'_acao'. Ex: <input type="hidden" id="frm1_acao" name="frm1_acao"> ;
+ * 
+ *  - para o script identificar os blocos de checkboxes, os checkboxes devem estar dentro de um <div> identificado da seguinte forma:
+ * 	  o id do div deve ser composto de 'id_form'+_div_ckbox+'id_qualquer'. Ex: <div id="frm1_div_ckbox_10">
+ * 	  os checkboxes devem estar dentro do div da seguinte maneira:
+ * 	  Ex: <div id="frm1_div_ckbox_10">
+ * 			<input type="checkbox" id="id_qualquer" value="1">
+ * 			<input type="checkbox" id="id_qualquer2" value="2">
+ * 			<input type="checkbox" id="id_qualquer3" value="3">
+ *		  </div> 
+ *
+ *   - para o script identificar os blocos de radio, os radios devem estar dentro de um <div> identificado da seguinte forma:
+ * 	  o id do div deve ser composto de 'id_form'+_div_radio+'id_qualquer'. Ex: <div id="frm1_div_radio_11">
+ * 	  os checkboxes devem estar dentro do div da seguinte maneira:
+ * 	  Ex: <div id="frm1_div_radio_11">
+ * 			<input type="radio" name="rad1" id="id_qualquer1" value="1" >
+ * 			<input type="radio" name="rad1" id="id_qualquer2" value="2">
+ * 			<input type="radio" name="rad1" id="id_qualquer3" value="3">
+ *		  </div> 
+ * 
+ * 
+ * 
+ * 
+ */
+
+
+function submeter(acao, prefixo)
+{
+    var pode_enviar = true;
+    var achou = false;
+    for ( var i = 0; i < document.frm.elements.length; i++ ) {
+        obj = document.frm.elements[i];
+        if (obj.name.substring(0,4) == prefixo && obj.getAttribute('obrigatorio') == 1) {
+            if (obj.type == 'text' || obj.type == 'textarea' || obj.type == 'select') {
+                obj.style.background = "#FFFFFF";
+                if (obj.value == '') {
+                    obj.style.background = "#FDF3D9";
+                    
+                    pode_enviar = false;
+                }
+            }
+        }
+    }
+    if (pode_enviar == true) {
+        $id('acao').value = acao;
+        $id('frm').submit();
+    } else {
+        cria_msg_html('div_msg','Existem campos obrigatórios não preenchidos.');
+        return;
+    }
+}
+
+/* funcao de validar */ 
+function valida(form,acao,submete,obrigatorio){
+   
+    /* declaração de variaveis */
+    var erro = 0;
+    var x = 0 ;
+    var debug = 1;
+    
+    ckbox_a_lista = new Array ;
+    ckbox_a_div = new Array;
+    ckbox_a_error = new Array;
+    
+    /* variavel que seta o sufixo para nao obrigatorio */
+    var n_obri = 'not_';
+    
+    limpaCores();
+    
+    / * alerta de erro se não tiver form informado */
+      if(form.length == 0){
+        alert('ERRO: form inválido informado');
+        return false;
+    }
+    
+    for (i=0; i<form.elements.length ;i++){
+    
+        /* todos os checkboxes de listagem */
+        if(form.elements[i].type == 'checkbox' || form.elements[i].type == 'radio'){
+          
+            if( form.elements[i].className.substr(0,11) == 'obrigatorio'){
+              
+                if(!ckbox_a_lista[form.elements[i].name.substr(0,form.elements[i].name.length-2)]){
+	            
+                    ckbox_a_lista[form.elements[i].name.substr(0,form.elements[i].name.length-2)] = 0;
+	               
+	            }
+                
+                if(document.getElementById( form.elements[i].id ).checked == true){
+                
+                    ckbox_a_lista[form.elements[i].name.substr(0,form.elements[i].name.length-2)] = 1;
+                   
+                }
+
+            }
+              
+        }
+           
+        /* todos os inputs text */
+        if(form.elements[i].type == 'text'){
+          
+            if(debug == 1){
+                / * alerta de erro: se o elemento nao possuir um id ele grita * /
+                if(!form.elements[i].id){
+                    alert('Para validação input '+form.elements[i].name+' precisa possuir um id');
+                }
+            }
+              
+            /*so valida se tiver id*/
+            if(form.elements[i].id){
+                /* verificando se o parametro de string obrigatorio foi passado */
+                if(obrigatorio){
+                    /* verificando se é obrigatorio a partir da string de obrigatorio setada*/              
+                    if( (form.elements[i].id.substr(0,obrigatorio.length)) == obrigatorio){
+                          
+                        if(form.elements[i].value.length < 1){
+                            muda_cor(form.elements[i].id);
+                            erro = 1;
+                        }else{
+                            remove_cor(form.elements[i].id);
+                        }    
+                    }
+                               
+                }else{
+
+                    /* verificando se é obrigatorio */
+                    if( (form.elements[i].id.substr(0,n_obri.length)) != n_obri){
+                                              
+                        if(form.elements[i].value.length < 1){
+                            muda_cor(form.elements[i].id);
+                            erro = 1;
+                        }else{
+                            remove_cor(form.elements[i].id);
+                        }
+                    }
+                }
+            }        
+        } 
+          
+
+        /* todos os selects */
+        if(form.elements[i].type == 'select-one'){
+            
+            if(debug == 1){
+                / * alerta de erro: se o elemento nao possuir um id ele grita * /
+                if(!form.elements[i].id){
+                    alert('Para validação input '+form.elements[i].name+' precisa possuir um id');
+                }
+            }
+            
+            /*so valida se tiver id*/
+            if(form.elements[i].id){
+                  
+                /* verificando se o parametro de string obrigatorio foi passado */
+                if(obrigatorio){
+                    
+                    /* verificando se é obrigatorio a partir da string de obrigatorio setada*/      
+                    if( (form.elements[i].id.substr(0,obrigatorio.length)) == obrigatorio){
+                          
+                        if(form.elements[i].value == 0 || form.elements[i].value == ""){
+                            muda_cor(form.elements[i].id);
+                            erro = 1;
+                        }else{
+                            remove_cor(form.elements[i].id);
+                        }    
+                    }
+                               
+                }else{
+                    
+                    /* verificando se é obrigatorio */
+                    if( (form.elements[i].id.substr(0,n_obri.length)) != n_obri){
+                        if(form.elements[i].value == 0 || form.elements[i].value == ""){
+                            muda_cor(form.elements[i].id);
+                            erro = 1;
+                        }else{
+                            remove_cor(form.elements[i].id);
+                        }               
+                    }
+                }
+            }
+        }
+          
+        /* todos os inputs textarea */
+        if(form.elements[i].type == 'textarea'){
+            if(debug == 1){
+                / * alerta de erro: se o elemento nao possuir um id ele grita * /
+                if(!form.elements[i].id){
+                    alert('Para validação input '+form.elements[i].name+' precisa possuir um id');
+                }
+            }
+            
+            /*so valida se tiver id*/
+            if(form.elements[i].id){
+                  
+                if(obrigatorio){
+                    
+                    /* verificando se é obrigatorio a partir da string de obrigatorio setada*/              
+                    if( (form.elements[i].id.substr(0,obrigatorio.length)) == obrigatorio){
+                        
+                        if(form.elements[i].value.length < 1){
+                            muda_cor(form.elements[i].id);
+                            erro = 1;
+                        }else{
+                            remove_cor(form.elements[i].id);
+                        }    
+                    }
+                               
+                }else{
+                    
+                    /* verificando se é obrigatorio */
+                    if( (form.elements[i].id.substr(0,n_obri.length)) != n_obri){
+                        if(form.elements[i].value.length < 1){
+                            muda_cor(form.elements[i].id);
+                            erro = 1;
+                        }else{
+                            remove_cor(form.elements[i].id);
+                        }
+                    }
+                }
+            }               
+        }
+    } 
+      
+     // olhá só isso
+    for(i_a in ckbox_a_lista){
+      
+        //alert('KEY' + i_a + ' - VALOR ' + ckbox_a_lista[i_a]);
+      
+        if(ckbox_a_lista[i_a] == 0){
+            
+            g=0;
+            while(document.getElementById('td_'+i_a+'_'+g)){
+                muda_cor('td_'+i_a+'_'+g)
+                g++;
+            }
+            erro = 1;
+        
+        }else{
+        
+            if(ckbox_a_lista[i_a] == 1){        
+            
+		        g=0;
+	            while(document.getElementById('td_'+i_a+'_'+g)){
+	                remove_cor('td_'+i_a+'_'+g)
+	                g++;
+	            }
+            
+            }
+	        
+        }
+    }
+      
+
+    / * checkboxes e radios * /
+      
+    // capturando todos os divs
+    ckbox_a_div = document.getElementsByTagName('div');
+      
+    for(i=0;i<ckbox_a_div.length;i++){
+    
+        / * checkboxes e radios* /
+        
+        /* verificando se são obrigatórios e se tem parametro de obrigatorio */
+        if(obrigatorio){
+    
+            // verificando se é o div a ser checado
+            if( ckbox_a_div[i].id.substr(0, (11 + form.id.length + obrigatorio.length )) == obrigatorio+"_"+form.id+"_div_ckbox" || ckbox_a_div[i].id.substr(0, (11 + form.id.length + obrigatorio.length )) == obrigatorio+"_"+form.id+"_div_radio") {
+                
+                if((ckbox_a_div[i].id.substr(0,obrigatorio.length)) == obrigatorio){
+                            
+                    /* verificando se os checkboxes são do mesmo form */    
+                    if( ckbox_a_div[i].id.substr((obrigatorio.length+1),form.id.length) == form.id){
+                            
+                        ckbox_a_child = document.getElementById(ckbox_a_div[i].id).childNodes;
+                        ckbox_a_error[ckbox_a_div[i].id] = 0;
+                              
+                            for(j=0;j<ckbox_a_child.length;j++){
+                                  
+                                if(ckbox_a_child[j].nodeName == "INPUT"){
+                                  
+                                    //CHECKBOX
+                                    if(ckbox_a_child[j].getAttribute("type") == "checkbox"){
+                                        if(document.getElementById(ckbox_a_child[j].id).checked == true){
+                                            ckbox_a_error[ckbox_a_div[i].id] = 1;
+                                            break;            
+                                        }    
+                                    }
+                                    
+                                    //RADIO BUTTON
+                                    if(ckbox_a_child[j].getAttribute("type") == "radio"){
+                                        if(document.getElementById(ckbox_a_child[j].id).checked == true){
+                                            ckbox_a_error[ckbox_a_div[i].id] = 1;
+                                            break;            
+                                        }    
+                                    }
+                                      
+                                }else{
+                                  
+                                    /* Se o CHILD não for do tipo INPUT, ele busca RECURSIVAMENTE ate achar o INPUT */
+                                    if(ckbox_a_child[j].nodeName == "TABLE"){
+                                           
+                                        if(ckbox_a_child[j].hasChildNodes()){
+                                                
+                                            for(t=0;t<ckbox_a_child[j].childNodes.length;t++){
+                                                    
+                                                if(ckbox_a_child[j].childNodes[t].nodeName == "TBODY"){
+                                                    
+                                                    for(q=0;q<ckbox_a_child[j].childNodes[t].childNodes.length;q++){
+                                                        
+                                                        if(ckbox_a_child[j].childNodes[t].childNodes[q].nodeName == "TR"){
+                                                                    
+                                                            for(w=0;w<ckbox_a_child[j].childNodes[t].childNodes[q].childNodes.length;w++){
+                                                                    
+                                                                if(ckbox_a_child[j].childNodes[t].childNodes[q].childNodes[w].nodeName == "TD"){
+                                                                        
+                                                                    for(s=0;s<ckbox_a_child[j].childNodes[t].childNodes[q].childNodes[w].childNodes.length;s++){
+                                                                           
+                                                                        if(ckbox_a_child[j].childNodes[t].childNodes[q].childNodes[w].childNodes[s].nodeName == "INPUT"){
+                                                                           
+                                                                            a_tmp = ckbox_a_child[j].childNodes[t].childNodes[q].childNodes[w].childNodes[s];  
+                                                                               
+                                                                            //CHECKBOX E RADIO
+                                                                            if(a_tmp.getAttribute("type") == "checkbox" || a_tmp.getAttribute("type") == "radio"){
+                                                                                   
+                                                                                if(document.getElementById(a_tmp.id).checked == true){
+                                                                                    ckbox_a_error[ckbox_a_div[i].id] = 1;
+                                                                                }   
+                                                                            }
+                                                                        }
+                                                                    }
+                                                                }
+                                                            }
+                                                        }
+                                                    }
+                                                }
+                                            }
+                                        }                          
+                                    }
+                                }
+                            }
+                              
+                            if(ckbox_a_error[ckbox_a_div[i].id] == 0){
+                                muda_cor(ckbox_a_div[i].id)
+                                erro = 1;
+                            }else{
+                                remove_cor(ckbox_a_div[i].id);
+                            }
+                            
+                            x ++ ;
+                          
+                        }
+                    }
+                }
+                
+            }else{
+                
+                if( ckbox_a_div[i].id.substr(0, (10 + form.id.length )) == form.name+"_div_ckbox" || ckbox_a_div[i].id.substr(0, (10 + form.id.length  )) == form.name+"_div_radio") {
+                
+                    if((ckbox_a_div[i].id.substr(0,n_obri.length)) != n_obri){
+                        
+                        /* verificando se os checkboxes são do mesmo form */    
+                        if( ckbox_a_div[i].id.substr(0,form.id.length) == form.id){
+                            
+                            ckbox_a_child = document.getElementById(ckbox_a_div[i].id).childNodes;
+                            ckbox_a_error[ckbox_a_div[i].id] = 0;
+                            
+                            for(j=0;j<ckbox_a_child.length;j++){
+                              
+                                if(ckbox_a_child[j].nodeName == "INPUT"){
+                                    
+                                    //CHECKBOX
+                                    if(ckbox_a_child[j].getAttribute("type") == "checkbox" || ckbox_a_child[j].getAttribute("type") == "radio"){
+                                        
+                                        if(document.getElementById(ckbox_a_child[j].id).checked == true){
+                                            ckbox_a_error[ckbox_a_div[i].id] = 1;
+                                            break;          
+                                        }   
+                                    }
+                                    /*  //RADIO BUTTON
+                                    if(ckbox_a_child[j].getAttribute("type") == "radio"){
+                                        if(document.getElementById(ckbox_a_child[j].id).checked == true){
+                                            ckbox_a_error[ckbox_a_div[i].id] = 1;
+                                            break;          
+                                        }   
+                                    }*/
+                                    
+                                }else{
+                                  
+                                    if(ckbox_a_child[j].nodeName == "TABLE"){
+                                           
+                                        if(ckbox_a_child[j].hasChildNodes()){
+                                            
+                                            for(t=0;t<ckbox_a_child[j].childNodes.length;t++){
+                                                
+                                                if(ckbox_a_child[j].childNodes[t].nodeName == "TBODY"){
+                                                
+                                                    for(q=0;q<ckbox_a_child[j].childNodes[t].childNodes.length;q++){
+                                                    
+                                                        if(ckbox_a_child[j].childNodes[t].childNodes[q].nodeName == "TR"){
+                                                                
+                                                            for(w=0;w<ckbox_a_child[j].childNodes[t].childNodes[q].childNodes.length;w++){
+                                                                
+                                                                if(ckbox_a_child[j].childNodes[t].childNodes[q].childNodes[w].nodeName == "TD"){
+                                                                    
+                                                                    for(s=0;s<ckbox_a_child[j].childNodes[t].childNodes[q].childNodes[w].childNodes.length;s++){
+                                                                       
+                                                                        if(ckbox_a_child[j].childNodes[t].childNodes[q].childNodes[w].childNodes[s].nodeName == "INPUT"){
+                                                                       
+                                                                            a_tmp = ckbox_a_child[j].childNodes[t].childNodes[q].childNodes[w].childNodes[s];  
+                                                                           
+                                                                            //CHECKBOX E RADIO
+                                                                            if(a_tmp.getAttribute("type") == "checkbox" || a_tmp.getAttribute("type") == "radio"){
+                                                                               
+                                                                                if(document.getElementById(a_tmp.id).checked == true){
+                                                                                    ckbox_a_error[ckbox_a_div[i].id] = 1;
+                                                                                }   
+                                                                            }
+                                                                        }
+                                                                    }
+                                                                }
+                                                            }
+                                                        }
+                                                    }
+                                                }
+                                            }
+                                        }                       
+                                    }
+                                }
+                            }
+
+                            if(ckbox_a_error[ckbox_a_div[i].id] == 0){
+                                muda_cor(ckbox_a_div[i].id)
+                                erro = 1;
+                            }else{
+                                remove_cor(ckbox_a_div[i].id);
+                            }
+                            
+                            x ++ ;
+                            
+                        }
+                    }
+                }
+            }
+        }
+      
+        if(erro == 1){
+          
+            if(!document.getElementById("mess")){
+                criarDiv('mess', '<table height=\"32\" width=\"100%\" valign=\"middle\"><tr onclick=\"removeDiv(\'mess\');\"><td class="\msg\" width=\"96%\" heigth=\"100%\">&nbsp;<font color=\"#CD0000\">Existem campos obrigatórios não preenchidos!</font></td><td width=\"4%\"><img width=\"15\" height=\"15\" src=\"images/X.jpg\"></img></td></tr></table>', '100%', '34', '0', '0');
+                alinhaDiv('mess');
+            }
+          
+            id_interval = setInterval("alinhaDiv('mess')",500);
+                    
+            fade(0,'mess',80);
+            
+            return false;
+          
+        }else{
+          
+            if(document.getElementById("mess")){
+                removeDiv('mess');
+            }
+          
+            / * alerta de erro se nao encontrar input de acao * /
+            if(document.getElementById(form.id+'_acao').length == 0){
+                alert('ERRO: erro ao definir ação. Input '+form.id+'_acao não existe');
+            }
+          
+            document.getElementById(form.id+'_acao').value = acao;
+          
+            /* se o parametro for true é para submeter o form */
+            if(submete == true || submete == 1){
+                form.submit();
+            }else{
+                return true;
+            }
+        }
+}
+
+function diferencaEntreDatas(dataMaior,dataMenor) {
+    Data = dataMaior.replace( " ", "" );
+    dia1 = Data.substring( 0, 2 );
+    dia1 = parseInt(dia1,10)+0;
+    mes1 = Data.substring(3,5);
+    mes1 = parseInt(mes1,10)-1;
+    ano1 = Data.substring(6,10);
+    ano1 = parseInt(ano1,10)+0;
+
+    Data = dataMenor.replace( " ", "" );
+    dia2 = Data.substring( 0, 2 );
+    dia2 = parseInt(dia2,10)+0;
+    mes2 = Data.substring(3,5);
+    mes2 = parseInt(mes2,10)-1;
+    ano2 = Data.substring(6,10);
+    ano2 = parseInt(ano2,10)+0;
+
+    return ( (Date.UTC(ano1,mes1,dia1,0,0,0)-Date.UTC(ano2,mes2,dia2,0,0,0)) / 86400000);
+}
+
+
+function validarPeriodo(dataInicial, dataFinal) {
+    diferenca = diferencaEntreDatas(dataFinal.value,dataInicial.value); 
+    var array_tmp = dataInicial.value.split('/'); 
+    var dia_ini = array_tmp[0]; 
+    var mes_ini = array_tmp[1]; 
+    var ano_ini = parseInt(array_tmp[2]); 
+    
+    if (dataFinal.value.length == 10) {
+        array_tmp = dataFinal.value.split('/'); 
+        var dia_fim = array_tmp[0]; 
+        var mes_fim = array_tmp[1]; 
+        var ano_fim = parseInt(array_tmp[2]); 
+        // diferença de um ano 
+        var ano = diferencaEntreDatas(dataFinal.value,dia_fim+'/'+mes_fim+'/'+(ano_fim-1)); 
+    
+        if((ano_ini!=ano_fim && ano_fim<ano_ini) || (ano_ini==ano_fim && mes_ini>mes_fim) || (ano_ini==ano_fim && mes_ini==mes_fim && dia_ini>dia_fim)){
+            dataFinal.value=""; 
+            return false;
+        }
+    }
+    return true;
+}
Index: trunk/workflow/inc/report/includes/js/FormularioUtil.js
===================================================================
--- trunk/workflow/inc/report/includes/js/FormularioUtil.js	(revision 5307)
+++ trunk/workflow/inc/report/includes/js/FormularioUtil.js	(revision 5307)
@@ -0,0 +1,195 @@
+/*
+ * Funções não liberadas.
+ * 
+*/
+/*
+function showDown(evt) { 
+    evt = (evt) ? evt : ((event) ? event : null); 
+    if (evt) { 
+	   // alert(evt.keyCode);
+		
+        if (navigator.appName=="Netscape") { 
+	            if (evt.which == 116) { 
+	                // When F5 is pressed
+	                cancelKey(evt); 
+	            } else if (evt.ctrlKey && (evt.which == 82)) { 
+	                // When ctrl is pressed with R or N
+	                cancelKey(evt); 
+	            }
+        } else {
+	            if (event.keyCode == 116) { 
+	                // When F5 is pressed
+	                cancelKey(evt); 
+	            } else if (event.ctrlKey && (event.keyCode == 78 || event.keyCode == 82)) { 
+	                // When ctrl is pressed with R or N
+	                cancelKey(evt); 
+	            }
+        }
+    } 
+		
+} 
+ 
+function cancelKey(evt) { 
+    if (evt.preventDefault) { 
+        evt.preventDefault(); 
+        return false; 
+    } else { 
+        evt.keyCode = 0; 
+        evt.returnValue = false; 
+    } 
+} */
+ 
+/*TECLA t NÃO FUNCIONAVA.
+ * if (navigator.appName=="Netscape") document.addEventListener("keypress",showDown,true);
+ * */
+//document.onkeydown  = showDown;
+
+/*
+function iUtilsValidachecks(frm,prefixo){
+    ret = false;
+	for (var i=1;i<frm.elements.length;i++)  {
+      var e = frm.elements[i];
+      if ((e.name.substring(0,prefixo.length + 1)  == (prefixo + "["))){
+        if (e.checked) { ret = true; }
+      }
+    }
+	return ret;
+}
+*/
+function iUtilsSelecionachecks(check,frm,prefixo){
+    for (var i=1;i<frm.elements.length;i++)  {
+      var e = frm.elements[i];
+      if ((e.name.substring(0,prefixo.length + 1)  == (prefixo + "["))){
+        e.checked = check;
+      }
+    }
+}
+
+/*
+function iUtilsMudaOrdem(formpesquisa,acao,novaordem,ordematual,tipo) {
+	  if (novaordem == ordematual) {
+		  if ((tipo == 'desc') || (tipo == '')) {
+	         novotipo = 'asc';
+	      } else {
+	         novotipo = 'desc';
+	      }
+	  } else {
+		  novotipo = 'asc';
+	  }
+	  document.getElementById(formpesquisa.name + "_acao").value = acao;
+	  document.getElementById(formpesquisa.name + "_ordem").value = novaordem;
+	  document.getElementById(formpesquisa.name + "_ordemtipo").value = novotipo;
+	  formpesquisa.submit();
+}
+
+function iUtilsVisibilidadeQuadro(idquadro,visible) {
+	if (visible == true) { 
+    	visibility = ""; 
+    } else { 
+    	visibility = "none"; 
+    }
+	quadro = document.getElementById("quadro_" + idquadro);
+	if (quadro != null) {
+		quadro.style.display = visibility;
+    }
+}
+
+function iUtilsOcultaQuadro(idquadro) {
+	iUtilsVisibilidadeQuadro(idquadro,false)
+}
+
+function iUtilsExibeQuadro(idquadro) {
+	iUtilsVisibilidadeQuadro(idquadro,true)
+}
+*/
+
+
+function formUtilExibeImgAjax(campos) {
+	campos_array = campos.split(",");
+	i = 0;
+	while (i < campos_array.length){
+        img = document.getElementById("imgAjax_" + campos_array[i]);
+			if (img != null) {
+			  img.style.display = "";
+			}
+	    i = i + 1;
+	} 
+	/*img = document.getElementById("imgAjax_" + idcampo);
+	if (img != null) {
+	  img.style.display = "";
+	}*/
+}
+
+function formUtilOcultaImgAjax(campos) {
+	campos_array = campos.split(",");
+	i = 0;
+	while (i < campos_array.length){
+        img = document.getElementById("imgAjax_" + campos_array[i]);
+			if (img != null) {
+			  img.style.display = "none";
+			}
+	    i = i + 1;
+	} 
+}
+
+function formUtilOcultaCampos(campos) {
+   campos_array = campos.split(",");
+   
+   i = 0;
+   while (i < campos_array.length){
+	   formUtilVisibilidadeCampo(campos_array[i],false);
+	   i = i + 1; 
+   }
+}
+
+function formUtilExibeCampos(campos) {
+   campos_array = campos.split(",");
+   i = 0;
+   while (i < campos_array.length){
+	   formUtilVisibilidadeCampo(campos_array[i],true);
+	  i = i + 1; 
+   }
+}
+
+
+function formUtilVisibilidadeCampo(idcampo,visible) {
+    var	campo = null;
+    campo = document.getElementById("id_" + idcampo);
+    if (visible == true) { 
+    	visibility = ""; 
+    } else { 
+    	visibility = "none"; 
+    } 
+    if (campo != null) {
+    	campo.style.display = visibility;
+    } else {
+    	campo = document.getElementById("not_id_" + idcampo);
+    	if (campo) {
+    		campo.style.display = visibility;
+    	}
+    }
+    inforight = document.getElementById("id_info_" + idcampo);
+    if (inforight) {
+    	inforight.style.display = visibility;
+    }
+    label = document.getElementById("id_lbl_" + idcampo);
+    if (label) {
+    	label.style.display = visibility;
+    }
+    ckbox = document.getElementById("not_div_ckbox_" + idcampo);
+    if (ckbox) {
+    	ckbox.style.display = visibility;
+    }
+    ckbox = document.getElementById("div_ckbox_" + idcampo);
+    if (ckbox) {
+    	ckbox.style.display = visibility;
+    }
+    imgcalendar = document.getElementById("id_imgcal_" + idcampo + "_inicio");
+    if (imgcalendar) {
+    	imgcalendar.style.display = visibility;
+    }
+    imgcalendar = document.getElementById("id_imgcal_" + idcampo + "_fim");
+    if (imgcalendar) {
+    	imgcalendar.style.display = visibility;
+    }
+}
Index: trunk/workflow/inc/report/includes/js/jquery-1.3.2.js
===================================================================
--- trunk/workflow/inc/report/includes/js/jquery-1.3.2.js	(revision 5307)
+++ trunk/workflow/inc/report/includes/js/jquery-1.3.2.js	(revision 5307)
@@ -0,0 +1,19 @@
+/*
+ * jQuery JavaScript Library v1.3.2
+ * http://jquery.com/
+ *
+ * Copyright (c) 2009 John Resig
+ * Dual licensed under the MIT and GPL licenses.
+ * http://docs.jquery.com/License
+ *
+ * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)
+ * Revision: 6246
+ */
+(function(){var l=this,g,y=l.jQuery,p=l.$,o=l.jQuery=l.$=function(E,F){return new o.fn.init(E,F)},D=/^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,f=/^.[^:#\[\.,]*$/;o.fn=o.prototype={init:function(E,H){E=E||document;if(E.nodeType){this[0]=E;this.length=1;this.context=E;return this}if(typeof E==="string"){var G=D.exec(E);if(G&&(G[1]||!H)){if(G[1]){E=o.clean([G[1]],H)}else{var I=document.getElementById(G[3]);if(I&&I.id!=G[3]){return o().find(E)}var F=o(I||[]);F.context=document;F.selector=E;return F}}else{return o(H).find(E)}}else{if(o.isFunction(E)){return o(document).ready(E)}}if(E.selector&&E.context){this.selector=E.selector;this.context=E.context}return this.setArray(o.isArray(E)?E:o.makeArray(E))},selector:"",jquery:"1.3.2",size:function(){return this.length},get:function(E){return E===g?Array.prototype.slice.call(this):this[E]},pushStack:function(F,H,E){var G=o(F);G.prevObject=this;G.context=this.context;if(H==="find"){G.selector=this.selector+(this.selector?" ":"")+E}else{if(H){G.selector=this.selector+"."+H+"("+E+")"}}return G},setArray:function(E){this.length=0;Array.prototype.push.apply(this,E);return this},each:function(F,E){return o.each(this,F,E)},index:function(E){return o.inArray(E&&E.jquery?E[0]:E,this)},attr:function(F,H,G){var E=F;if(typeof F==="string"){if(H===g){return this[0]&&o[G||"attr"](this[0],F)}else{E={};E[F]=H}}return this.each(function(I){for(F in E){o.attr(G?this.style:this,F,o.prop(this,E[F],G,I,F))}})},css:function(E,F){if((E=="width"||E=="height")&&parseFloat(F)<0){F=g}return this.attr(E,F,"curCSS")},text:function(F){if(typeof F!=="object"&&F!=null){return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(F))}var E="";o.each(F||this,function(){o.each(this.childNodes,function(){if(this.nodeType!=8){E+=this.nodeType!=1?this.nodeValue:o.fn.text([this])}})});return E},wrapAll:function(E){if(this[0]){var F=o(E,this[0].ownerDocument).clone();if(this[0].parentNode){F.insertBefore(this[0])}F.map(function(){var G=this;while(G.firstChild){G=G.firstChild}return G}).append(this)}return this},wrapInner:function(E){return this.each(function(){o(this).contents().wrapAll(E)})},wrap:function(E){return this.each(function(){o(this).wrapAll(E)})},append:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.appendChild(E)}})},prepend:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.insertBefore(E,this.firstChild)}})},before:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this)})},after:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this.nextSibling)})},end:function(){return this.prevObject||o([])},push:[].push,sort:[].sort,splice:[].splice,find:function(E){if(this.length===1){var F=this.pushStack([],"find",E);F.length=0;o.find(E,this[0],F);return F}else{return this.pushStack(o.unique(o.map(this,function(G){return o.find(E,G)})),"find",E)}},clone:function(G){var E=this.map(function(){if(!o.support.noCloneEvent&&!o.isXMLDoc(this)){var I=this.outerHTML;if(!I){var J=this.ownerDocument.createElement("div");J.appendChild(this.cloneNode(true));I=J.innerHTML}return o.clean([I.replace(/ jQuery\d+="(?:\d+|null)"/g,"").replace(/^\s*/,"")])[0]}else{return this.cloneNode(true)}});if(G===true){var H=this.find("*").andSelf(),F=0;E.find("*").andSelf().each(function(){if(this.nodeName!==H[F].nodeName){return}var I=o.data(H[F],"events");for(var K in I){for(var J in I[K]){o.event.add(this,K,I[K][J],I[K][J].data)}}F++})}return E},filter:function(E){return this.pushStack(o.isFunction(E)&&o.grep(this,function(G,F){return E.call(G,F)})||o.multiFilter(E,o.grep(this,function(F){return F.nodeType===1})),"filter",E)},closest:function(E){var G=o.expr.match.POS.test(E)?o(E):null,F=0;return this.map(function(){var H=this;while(H&&H.ownerDocument){if(G?G.index(H)>-1:o(H).is(E)){o.data(H,"closest",F);return H}H=H.parentNode;F++}})},not:function(E){if(typeof E==="string"){if(f.test(E)){return this.pushStack(o.multiFilter(E,this,true),"not",E)}else{E=o.multiFilter(E,this)}}var F=E.length&&E[E.length-1]!==g&&!E.nodeType;return this.filter(function(){return F?o.inArray(this,E)<0:this!=E})},add:function(E){return this.pushStack(o.unique(o.merge(this.get(),typeof E==="string"?o(E):o.makeArray(E))))},is:function(E){return !!E&&o.multiFilter(E,this).length>0},hasClass:function(E){return !!E&&this.is("."+E)},val:function(K){if(K===g){var E=this[0];if(E){if(o.nodeName(E,"option")){return(E.attributes.value||{}).specified?E.value:E.text}if(o.nodeName(E,"select")){var I=E.selectedIndex,L=[],M=E.options,H=E.type=="select-one";if(I<0){return null}for(var F=H?I:0,J=H?I+1:M.length;F<J;F++){var G=M[F];if(G.selected){K=o(G).val();if(H){return K}L.push(K)}}return L}return(E.value||"").replace(/\r/g,"")}return g}if(typeof K==="number"){K+=""}return this.each(function(){if(this.nodeType!=1){return}if(o.isArray(K)&&/radio|checkbox/.test(this.type)){this.checked=(o.inArray(this.value,K)>=0||o.inArray(this.name,K)>=0)}else{if(o.nodeName(this,"select")){var N=o.makeArray(K);o("option",this).each(function(){this.selected=(o.inArray(this.value,N)>=0||o.inArray(this.text,N)>=0)});if(!N.length){this.selectedIndex=-1}}else{this.value=K}}})},html:function(E){return E===g?(this[0]?this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g,""):null):this.empty().append(E)},replaceWith:function(E){return this.after(E).remove()},eq:function(E){return this.slice(E,+E+1)},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments),"slice",Array.prototype.slice.call(arguments).join(","))},map:function(E){return this.pushStack(o.map(this,function(G,F){return E.call(G,F,G)}))},andSelf:function(){return this.add(this.prevObject)},domManip:function(J,M,L){if(this[0]){var I=(this[0].ownerDocument||this[0]).createDocumentFragment(),F=o.clean(J,(this[0].ownerDocument||this[0]),I),H=I.firstChild;if(H){for(var G=0,E=this.length;G<E;G++){L.call(K(this[G],H),this.length>1||G>0?I.cloneNode(true):I)}}if(F){o.each(F,z)}}return this;function K(N,O){return M&&o.nodeName(N,"table")&&o.nodeName(O,"tr")?(N.getElementsByTagName("tbody")[0]||N.appendChild(N.ownerDocument.createElement("tbody"))):N}}};o.fn.init.prototype=o.fn;function z(E,F){if(F.src){o.ajax({url:F.src,async:false,dataType:"script"})}else{o.globalEval(F.text||F.textContent||F.innerHTML||"")}if(F.parentNode){F.parentNode.removeChild(F)}}function e(){return +new Date}o.extend=o.fn.extend=function(){var J=arguments[0]||{},H=1,I=arguments.length,E=false,G;if(typeof J==="boolean"){E=J;J=arguments[1]||{};H=2}if(typeof J!=="object"&&!o.isFunction(J)){J={}}if(I==H){J=this;--H}for(;H<I;H++){if((G=arguments[H])!=null){for(var F in G){var K=J[F],L=G[F];if(J===L){continue}if(E&&L&&typeof L==="object"&&!L.nodeType){J[F]=o.extend(E,K||(L.length!=null?[]:{}),L)}else{if(L!==g){J[F]=L}}}}}return J};var b=/z-?index|font-?weight|opacity|zoom|line-?height/i,q=document.defaultView||{},s=Object.prototype.toString;o.extend({noConflict:function(E){l.$=p;if(E){l.jQuery=y}return o},isFunction:function(E){return s.call(E)==="[object Function]"},isArray:function(E){return s.call(E)==="[object Array]"},isXMLDoc:function(E){return E.nodeType===9&&E.documentElement.nodeName!=="HTML"||!!E.ownerDocument&&o.isXMLDoc(E.ownerDocument)},globalEval:function(G){if(G&&/\S/.test(G)){var F=document.getElementsByTagName("head")[0]||document.documentElement,E=document.createElement("script");E.type="text/javascript";if(o.support.scriptEval){E.appendChild(document.createTextNode(G))}else{E.text=G}F.insertBefore(E,F.firstChild);F.removeChild(E)}},nodeName:function(F,E){return F.nodeName&&F.nodeName.toUpperCase()==E.toUpperCase()},each:function(G,K,F){var E,H=0,I=G.length;if(F){if(I===g){for(E in G){if(K.apply(G[E],F)===false){break}}}else{for(;H<I;){if(K.apply(G[H++],F)===false){break}}}}else{if(I===g){for(E in G){if(K.call(G[E],E,G[E])===false){break}}}else{for(var J=G[0];H<I&&K.call(J,H,J)!==false;J=G[++H]){}}}return G},prop:function(H,I,G,F,E){if(o.isFunction(I)){I=I.call(H,F)}return typeof I==="number"&&G=="curCSS"&&!b.test(E)?I+"px":I},className:{add:function(E,F){o.each((F||"").split(/\s+/),function(G,H){if(E.nodeType==1&&!o.className.has(E.className,H)){E.className+=(E.className?" ":"")+H}})},remove:function(E,F){if(E.nodeType==1){E.className=F!==g?o.grep(E.className.split(/\s+/),function(G){return !o.className.has(F,G)}).join(" "):""}},has:function(F,E){return F&&o.inArray(E,(F.className||F).toString().split(/\s+/))>-1}},swap:function(H,G,I){var E={};for(var F in G){E[F]=H.style[F];H.style[F]=G[F]}I.call(H);for(var F in G){H.style[F]=E[F]}},css:function(H,F,J,E){if(F=="width"||F=="height"){var L,G={position:"absolute",visibility:"hidden",display:"block"},K=F=="width"?["Left","Right"]:["Top","Bottom"];function I(){L=F=="width"?H.offsetWidth:H.offsetHeight;if(E==="border"){return}o.each(K,function(){if(!E){L-=parseFloat(o.curCSS(H,"padding"+this,true))||0}if(E==="margin"){L+=parseFloat(o.curCSS(H,"margin"+this,true))||0}else{L-=parseFloat(o.curCSS(H,"border"+this+"Width",true))||0}})}if(H.offsetWidth!==0){I()}else{o.swap(H,G,I)}return Math.max(0,Math.round(L))}return o.curCSS(H,F,J)},curCSS:function(I,F,G){var L,E=I.style;if(F=="opacity"&&!o.support.opacity){L=o.attr(E,"opacity");return L==""?"1":L}if(F.match(/float/i)){F=w}if(!G&&E&&E[F]){L=E[F]}else{if(q.getComputedStyle){if(F.match(/float/i)){F="float"}F=F.replace(/([A-Z])/g,"-$1").toLowerCase();var M=q.getComputedStyle(I,null);if(M){L=M.getPropertyValue(F)}if(F=="opacity"&&L==""){L="1"}}else{if(I.currentStyle){var J=F.replace(/\-(\w)/g,function(N,O){return O.toUpperCase()});L=I.currentStyle[F]||I.currentStyle[J];if(!/^\d+(px)?$/i.test(L)&&/^\d/.test(L)){var H=E.left,K=I.runtimeStyle.left;I.runtimeStyle.left=I.currentStyle.left;E.left=L||0;L=E.pixelLeft+"px";E.left=H;I.runtimeStyle.left=K}}}}return L},clean:function(F,K,I){K=K||document;if(typeof K.createElement==="undefined"){K=K.ownerDocument||K[0]&&K[0].ownerDocument||document}if(!I&&F.length===1&&typeof F[0]==="string"){var H=/^<(\w+)\s*\/?>$/.exec(F[0]);if(H){return[K.createElement(H[1])]}}var G=[],E=[],L=K.createElement("div");o.each(F,function(P,S){if(typeof S==="number"){S+=""}if(!S){return}if(typeof S==="string"){S=S.replace(/(<(\w+)[^>]*?)\/>/g,function(U,V,T){return T.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?U:V+"></"+T+">"});var O=S.replace(/^\s+/,"").substring(0,10).toLowerCase();var Q=!O.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!O.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||O.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!O.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!O.indexOf("<td")||!O.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!O.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||!o.support.htmlSerialize&&[1,"div<div>","</div>"]||[0,"",""];L.innerHTML=Q[1]+S+Q[2];while(Q[0]--){L=L.lastChild}if(!o.support.tbody){var R=/<tbody/i.test(S),N=!O.indexOf("<table")&&!R?L.firstChild&&L.firstChild.childNodes:Q[1]=="<table>"&&!R?L.childNodes:[];for(var M=N.length-1;M>=0;--M){if(o.nodeName(N[M],"tbody")&&!N[M].childNodes.length){N[M].parentNode.removeChild(N[M])}}}if(!o.support.leadingWhitespace&&/^\s/.test(S)){L.insertBefore(K.createTextNode(S.match(/^\s*/)[0]),L.firstChild)}S=o.makeArray(L.childNodes)}if(S.nodeType){G.push(S)}else{G=o.merge(G,S)}});if(I){for(var J=0;G[J];J++){if(o.nodeName(G[J],"script")&&(!G[J].type||G[J].type.toLowerCase()==="text/javascript")){E.push(G[J].parentNode?G[J].parentNode.removeChild(G[J]):G[J])}else{if(G[J].nodeType===1){G.splice.apply(G,[J+1,0].concat(o.makeArray(G[J].getElementsByTagName("script"))))}I.appendChild(G[J])}}return E}return G},attr:function(J,G,K){if(!J||J.nodeType==3||J.nodeType==8){return g}var H=!o.isXMLDoc(J),L=K!==g;G=H&&o.props[G]||G;if(J.tagName){var F=/href|src|style/.test(G);if(G=="selected"&&J.parentNode){J.parentNode.selectedIndex}if(G in J&&H&&!F){if(L){if(G=="type"&&o.nodeName(J,"input")&&J.parentNode){throw"type property can't be changed"}J[G]=K}if(o.nodeName(J,"form")&&J.getAttributeNode(G)){return J.getAttributeNode(G).nodeValue}if(G=="tabIndex"){var I=J.getAttributeNode("tabIndex");return I&&I.specified?I.value:J.nodeName.match(/(button|input|object|select|textarea)/i)?0:J.nodeName.match(/^(a|area)$/i)&&J.href?0:g}return J[G]}if(!o.support.style&&H&&G=="style"){return o.attr(J.style,"cssText",K)}if(L){J.setAttribute(G,""+K)}var E=!o.support.hrefNormalized&&H&&F?J.getAttribute(G,2):J.getAttribute(G);return E===null?g:E}if(!o.support.opacity&&G=="opacity"){if(L){J.zoom=1;J.filter=(J.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(K)+""=="NaN"?"":"alpha(opacity="+K*100+")")}return J.filter&&J.filter.indexOf("opacity=")>=0?(parseFloat(J.filter.match(/opacity=([^)]*)/)[1])/100)+"":""}G=G.replace(/-([a-z])/ig,function(M,N){return N.toUpperCase()});if(L){J[G]=K}return J[G]},trim:function(E){return(E||"").replace(/^\s+|\s+$/g,"")},makeArray:function(G){var E=[];if(G!=null){var F=G.length;if(F==null||typeof G==="string"||o.isFunction(G)||G.setInterval){E[0]=G}else{while(F){E[--F]=G[F]}}}return E},inArray:function(G,H){for(var E=0,F=H.length;E<F;E++){if(H[E]===G){return E}}return -1},merge:function(H,E){var F=0,G,I=H.length;if(!o.support.getAll){while((G=E[F++])!=null){if(G.nodeType!=8){H[I++]=G}}}else{while((G=E[F++])!=null){H[I++]=G}}return H},unique:function(K){var F=[],E={};try{for(var G=0,H=K.length;G<H;G++){var J=o.data(K[G]);if(!E[J]){E[J]=true;F.push(K[G])}}}catch(I){F=K}return F},grep:function(F,J,E){var G=[];for(var H=0,I=F.length;H<I;H++){if(!E!=!J(F[H],H)){G.push(F[H])}}return G},map:function(E,J){var F=[];for(var G=0,H=E.length;G<H;G++){var I=J(E[G],G);if(I!=null){F[F.length]=I}}return F.concat.apply([],F)}});var C=navigator.userAgent.toLowerCase();o.browser={version:(C.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[0,"0"])[1],safari:/webkit/.test(C),opera:/opera/.test(C),msie:/msie/.test(C)&&!/opera/.test(C),mozilla:/mozilla/.test(C)&&!/(compatible|webkit)/.test(C)};o.each({parent:function(E){return E.parentNode},parents:function(E){return o.dir(E,"parentNode")},next:function(E){return o.nth(E,2,"nextSibling")},prev:function(E){return o.nth(E,2,"previousSibling")},nextAll:function(E){return o.dir(E,"nextSibling")},prevAll:function(E){return o.dir(E,"previousSibling")},siblings:function(E){return o.sibling(E.parentNode.firstChild,E)},children:function(E){return o.sibling(E.firstChild)},contents:function(E){return o.nodeName(E,"iframe")?E.contentDocument||E.contentWindow.document:o.makeArray(E.childNodes)}},function(E,F){o.fn[E]=function(G){var H=o.map(this,F);if(G&&typeof G=="string"){H=o.multiFilter(G,H)}return this.pushStack(o.unique(H),E,G)}});o.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(E,F){o.fn[E]=function(G){var J=[],L=o(G);for(var K=0,H=L.length;K<H;K++){var I=(K>0?this.clone(true):this).get();o.fn[F].apply(o(L[K]),I);J=J.concat(I)}return this.pushStack(J,E,G)}});o.each({removeAttr:function(E){o.attr(this,E,"");if(this.nodeType==1){this.removeAttribute(E)}},addClass:function(E){o.className.add(this,E)},removeClass:function(E){o.className.remove(this,E)},toggleClass:function(F,E){if(typeof E!=="boolean"){E=!o.className.has(this,F)}o.className[E?"add":"remove"](this,F)},remove:function(E){if(!E||o.filter(E,[this]).length){o("*",this).add([this]).each(function(){o.event.remove(this);o.removeData(this)});if(this.parentNode){this.parentNode.removeChild(this)}}},empty:function(){o(this).children().remove();while(this.firstChild){this.removeChild(this.firstChild)}}},function(E,F){o.fn[E]=function(){return this.each(F,arguments)}});function j(E,F){return E[0]&&parseInt(o.curCSS(E[0],F,true),10)||0}var h="jQuery"+e(),v=0,A={};o.extend({cache:{},data:function(F,E,G){F=F==l?A:F;var H=F[h];if(!H){H=F[h]=++v}if(E&&!o.cache[H]){o.cache[H]={}}if(G!==g){o.cache[H][E]=G}return E?o.cache[H][E]:H},removeData:function(F,E){F=F==l?A:F;var H=F[h];if(E){if(o.cache[H]){delete o.cache[H][E];E="";for(E in o.cache[H]){break}if(!E){o.removeData(F)}}}else{try{delete F[h]}catch(G){if(F.removeAttribute){F.removeAttribute(h)}}delete o.cache[H]}},queue:function(F,E,H){if(F){E=(E||"fx")+"queue";var G=o.data(F,E);if(!G||o.isArray(H)){G=o.data(F,E,o.makeArray(H))}else{if(H){G.push(H)}}}return G},dequeue:function(H,G){var E=o.queue(H,G),F=E.shift();if(!G||G==="fx"){F=E[0]}if(F!==g){F.call(H)}}});o.fn.extend({data:function(E,G){var H=E.split(".");H[1]=H[1]?"."+H[1]:"";if(G===g){var F=this.triggerHandler("getData"+H[1]+"!",[H[0]]);if(F===g&&this.length){F=o.data(this[0],E)}return F===g&&H[1]?this.data(H[0]):F}else{return this.trigger("setData"+H[1]+"!",[H[0],G]).each(function(){o.data(this,E,G)})}},removeData:function(E){return this.each(function(){o.removeData(this,E)})},queue:function(E,F){if(typeof E!=="string"){F=E;E="fx"}if(F===g){return o.queue(this[0],E)}return this.each(function(){var G=o.queue(this,E,F);if(E=="fx"&&G.length==1){G[0].call(this)}})},dequeue:function(E){return this.each(function(){o.dequeue(this,E)})}});
+/*
+ * Sizzle CSS Selector Engine - v0.9.3
+ *  Copyright 2009, The Dojo Foundation
+ *  Released under the MIT, BSD, and GPL Licenses.
+ *  More information: http://sizzlejs.com/
+ */
+(function(){var R=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,L=0,H=Object.prototype.toString;var F=function(Y,U,ab,ac){ab=ab||[];U=U||document;if(U.nodeType!==1&&U.nodeType!==9){return[]}if(!Y||typeof Y!=="string"){return ab}var Z=[],W,af,ai,T,ad,V,X=true;R.lastIndex=0;while((W=R.exec(Y))!==null){Z.push(W[1]);if(W[2]){V=RegExp.rightContext;break}}if(Z.length>1&&M.exec(Y)){if(Z.length===2&&I.relative[Z[0]]){af=J(Z[0]+Z[1],U)}else{af=I.relative[Z[0]]?[U]:F(Z.shift(),U);while(Z.length){Y=Z.shift();if(I.relative[Y]){Y+=Z.shift()}af=J(Y,af)}}}else{var ae=ac?{expr:Z.pop(),set:E(ac)}:F.find(Z.pop(),Z.length===1&&U.parentNode?U.parentNode:U,Q(U));af=F.filter(ae.expr,ae.set);if(Z.length>0){ai=E(af)}else{X=false}while(Z.length){var ah=Z.pop(),ag=ah;if(!I.relative[ah]){ah=""}else{ag=Z.pop()}if(ag==null){ag=U}I.relative[ah](ai,ag,Q(U))}}if(!ai){ai=af}if(!ai){throw"Syntax error, unrecognized expression: "+(ah||Y)}if(H.call(ai)==="[object Array]"){if(!X){ab.push.apply(ab,ai)}else{if(U.nodeType===1){for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&(ai[aa]===true||ai[aa].nodeType===1&&K(U,ai[aa]))){ab.push(af[aa])}}}else{for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&ai[aa].nodeType===1){ab.push(af[aa])}}}}}else{E(ai,ab)}if(V){F(V,U,ab,ac);if(G){hasDuplicate=false;ab.sort(G);if(hasDuplicate){for(var aa=1;aa<ab.length;aa++){if(ab[aa]===ab[aa-1]){ab.splice(aa--,1)}}}}}return ab};F.matches=function(T,U){return F(T,null,null,U)};F.find=function(aa,T,ab){var Z,X;if(!aa){return[]}for(var W=0,V=I.order.length;W<V;W++){var Y=I.order[W],X;if((X=I.match[Y].exec(aa))){var U=RegExp.leftContext;if(U.substr(U.length-1)!=="\\"){X[1]=(X[1]||"").replace(/\\/g,"");Z=I.find[Y](X,T,ab);if(Z!=null){aa=aa.replace(I.match[Y],"");break}}}}if(!Z){Z=T.getElementsByTagName("*")}return{set:Z,expr:aa}};F.filter=function(ad,ac,ag,W){var V=ad,ai=[],aa=ac,Y,T,Z=ac&&ac[0]&&Q(ac[0]);while(ad&&ac.length){for(var ab in I.filter){if((Y=I.match[ab].exec(ad))!=null){var U=I.filter[ab],ah,af;T=false;if(aa==ai){ai=[]}if(I.preFilter[ab]){Y=I.preFilter[ab](Y,aa,ag,ai,W,Z);if(!Y){T=ah=true}else{if(Y===true){continue}}}if(Y){for(var X=0;(af=aa[X])!=null;X++){if(af){ah=U(af,Y,X,aa);var ae=W^!!ah;if(ag&&ah!=null){if(ae){T=true}else{aa[X]=false}}else{if(ae){ai.push(af);T=true}}}}}if(ah!==g){if(!ag){aa=ai}ad=ad.replace(I.match[ab],"");if(!T){return[]}break}}}if(ad==V){if(T==null){throw"Syntax error, unrecognized expression: "+ad}else{break}}V=ad}return aa};var I=F.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(T){return T.getAttribute("href")}},relative:{"+":function(aa,T,Z){var X=typeof T==="string",ab=X&&!/\W/.test(T),Y=X&&!ab;if(ab&&!Z){T=T.toUpperCase()}for(var W=0,V=aa.length,U;W<V;W++){if((U=aa[W])){while((U=U.previousSibling)&&U.nodeType!==1){}aa[W]=Y||U&&U.nodeName===T?U||false:U===T}}if(Y){F.filter(T,aa,true)}},">":function(Z,U,aa){var X=typeof U==="string";if(X&&!/\W/.test(U)){U=aa?U:U.toUpperCase();for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){var W=Y.parentNode;Z[V]=W.nodeName===U?W:false}}}else{for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){Z[V]=X?Y.parentNode:Y.parentNode===U}}if(X){F.filter(U,Z,true)}}},"":function(W,U,Y){var V=L++,T=S;if(!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("parentNode",U,V,W,X,Y)},"~":function(W,U,Y){var V=L++,T=S;if(typeof U==="string"&&!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("previousSibling",U,V,W,X,Y)}},find:{ID:function(U,V,W){if(typeof V.getElementById!=="undefined"&&!W){var T=V.getElementById(U[1]);return T?[T]:[]}},NAME:function(V,Y,Z){if(typeof Y.getElementsByName!=="undefined"){var U=[],X=Y.getElementsByName(V[1]);for(var W=0,T=X.length;W<T;W++){if(X[W].getAttribute("name")===V[1]){U.push(X[W])}}return U.length===0?null:U}},TAG:function(T,U){return U.getElementsByTagName(T[1])}},preFilter:{CLASS:function(W,U,V,T,Z,aa){W=" "+W[1].replace(/\\/g,"")+" ";if(aa){return W}for(var X=0,Y;(Y=U[X])!=null;X++){if(Y){if(Z^(Y.className&&(" "+Y.className+" ").indexOf(W)>=0)){if(!V){T.push(Y)}}else{if(V){U[X]=false}}}}return false},ID:function(T){return T[1].replace(/\\/g,"")},TAG:function(U,T){for(var V=0;T[V]===false;V++){}return T[V]&&Q(T[V])?U[1]:U[1].toUpperCase()},CHILD:function(T){if(T[1]=="nth"){var U=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(T[2]=="even"&&"2n"||T[2]=="odd"&&"2n+1"||!/\D/.test(T[2])&&"0n+"+T[2]||T[2]);T[2]=(U[1]+(U[2]||1))-0;T[3]=U[3]-0}T[0]=L++;return T},ATTR:function(X,U,V,T,Y,Z){var W=X[1].replace(/\\/g,"");if(!Z&&I.attrMap[W]){X[1]=I.attrMap[W]}if(X[2]==="~="){X[4]=" "+X[4]+" "}return X},PSEUDO:function(X,U,V,T,Y){if(X[1]==="not"){if(X[3].match(R).length>1||/^\w/.test(X[3])){X[3]=F(X[3],null,null,U)}else{var W=F.filter(X[3],U,V,true^Y);if(!V){T.push.apply(T,W)}return false}}else{if(I.match.POS.test(X[0])||I.match.CHILD.test(X[0])){return true}}return X},POS:function(T){T.unshift(true);return T}},filters:{enabled:function(T){return T.disabled===false&&T.type!=="hidden"},disabled:function(T){return T.disabled===true},checked:function(T){return T.checked===true},selected:function(T){T.parentNode.selectedIndex;return T.selected===true},parent:function(T){return !!T.firstChild},empty:function(T){return !T.firstChild},has:function(V,U,T){return !!F(T[3],V).length},header:function(T){return/h\d/i.test(T.nodeName)},text:function(T){return"text"===T.type},radio:function(T){return"radio"===T.type},checkbox:function(T){return"checkbox"===T.type},file:function(T){return"file"===T.type},password:function(T){return"password"===T.type},submit:function(T){return"submit"===T.type},image:function(T){return"image"===T.type},reset:function(T){return"reset"===T.type},button:function(T){return"button"===T.type||T.nodeName.toUpperCase()==="BUTTON"},input:function(T){return/input|select|textarea|button/i.test(T.nodeName)}},setFilters:{first:function(U,T){return T===0},last:function(V,U,T,W){return U===W.length-1},even:function(U,T){return T%2===0},odd:function(U,T){return T%2===1},lt:function(V,U,T){return U<T[3]-0},gt:function(V,U,T){return U>T[3]-0},nth:function(V,U,T){return T[3]-0==U},eq:function(V,U,T){return T[3]-0==U}},filter:{PSEUDO:function(Z,V,W,aa){var U=V[1],X=I.filters[U];if(X){return X(Z,W,V,aa)}else{if(U==="contains"){return(Z.textContent||Z.innerText||"").indexOf(V[3])>=0}else{if(U==="not"){var Y=V[3];for(var W=0,T=Y.length;W<T;W++){if(Y[W]===Z){return false}}return true}}}},CHILD:function(T,W){var Z=W[1],U=T;switch(Z){case"only":case"first":while(U=U.previousSibling){if(U.nodeType===1){return false}}if(Z=="first"){return true}U=T;case"last":while(U=U.nextSibling){if(U.nodeType===1){return false}}return true;case"nth":var V=W[2],ac=W[3];if(V==1&&ac==0){return true}var Y=W[0],ab=T.parentNode;if(ab&&(ab.sizcache!==Y||!T.nodeIndex)){var X=0;for(U=ab.firstChild;U;U=U.nextSibling){if(U.nodeType===1){U.nodeIndex=++X}}ab.sizcache=Y}var aa=T.nodeIndex-ac;if(V==0){return aa==0}else{return(aa%V==0&&aa/V>=0)}}},ID:function(U,T){return U.nodeType===1&&U.getAttribute("id")===T},TAG:function(U,T){return(T==="*"&&U.nodeType===1)||U.nodeName===T},CLASS:function(U,T){return(" "+(U.className||U.getAttribute("class"))+" ").indexOf(T)>-1},ATTR:function(Y,W){var V=W[1],T=I.attrHandle[V]?I.attrHandle[V](Y):Y[V]!=null?Y[V]:Y.getAttribute(V),Z=T+"",X=W[2],U=W[4];return T==null?X==="!=":X==="="?Z===U:X==="*="?Z.indexOf(U)>=0:X==="~="?(" "+Z+" ").indexOf(U)>=0:!U?Z&&T!==false:X==="!="?Z!=U:X==="^="?Z.indexOf(U)===0:X==="$="?Z.substr(Z.length-U.length)===U:X==="|="?Z===U||Z.substr(0,U.length+1)===U+"-":false},POS:function(X,U,V,Y){var T=U[2],W=I.setFilters[T];if(W){return W(X,V,U,Y)}}}};var M=I.match.POS;for(var O in I.match){I.match[O]=RegExp(I.match[O].source+/(?![^\[]*\])(?![^\(]*\))/.source)}var E=function(U,T){U=Array.prototype.slice.call(U);if(T){T.push.apply(T,U);return T}return U};try{Array.prototype.slice.call(document.documentElement.childNodes)}catch(N){E=function(X,W){var U=W||[];if(H.call(X)==="[object Array]"){Array.prototype.push.apply(U,X)}else{if(typeof X.length==="number"){for(var V=0,T=X.length;V<T;V++){U.push(X[V])}}else{for(var V=0;X[V];V++){U.push(X[V])}}}return U}}var G;if(document.documentElement.compareDocumentPosition){G=function(U,T){var V=U.compareDocumentPosition(T)&4?-1:U===T?0:1;if(V===0){hasDuplicate=true}return V}}else{if("sourceIndex" in document.documentElement){G=function(U,T){var V=U.sourceIndex-T.sourceIndex;if(V===0){hasDuplicate=true}return V}}else{if(document.createRange){G=function(W,U){var V=W.ownerDocument.createRange(),T=U.ownerDocument.createRange();V.selectNode(W);V.collapse(true);T.selectNode(U);T.collapse(true);var X=V.compareBoundaryPoints(Range.START_TO_END,T);if(X===0){hasDuplicate=true}return X}}}}(function(){var U=document.createElement("form"),V="script"+(new Date).getTime();U.innerHTML="<input name='"+V+"'/>";var T=document.documentElement;T.insertBefore(U,T.firstChild);if(!!document.getElementById(V)){I.find.ID=function(X,Y,Z){if(typeof Y.getElementById!=="undefined"&&!Z){var W=Y.getElementById(X[1]);return W?W.id===X[1]||typeof W.getAttributeNode!=="undefined"&&W.getAttributeNode("id").nodeValue===X[1]?[W]:g:[]}};I.filter.ID=function(Y,W){var X=typeof Y.getAttributeNode!=="undefined"&&Y.getAttributeNode("id");return Y.nodeType===1&&X&&X.nodeValue===W}}T.removeChild(U)})();(function(){var T=document.createElement("div");T.appendChild(document.createComment(""));if(T.getElementsByTagName("*").length>0){I.find.TAG=function(U,Y){var X=Y.getElementsByTagName(U[1]);if(U[1]==="*"){var W=[];for(var V=0;X[V];V++){if(X[V].nodeType===1){W.push(X[V])}}X=W}return X}}T.innerHTML="<a href='#'></a>";if(T.firstChild&&typeof T.firstChild.getAttribute!=="undefined"&&T.firstChild.getAttribute("href")!=="#"){I.attrHandle.href=function(U){return U.getAttribute("href",2)}}})();if(document.querySelectorAll){(function(){var T=F,U=document.createElement("div");U.innerHTML="<p class='TEST'></p>";if(U.querySelectorAll&&U.querySelectorAll(".TEST").length===0){return}F=function(Y,X,V,W){X=X||document;if(!W&&X.nodeType===9&&!Q(X)){try{return E(X.querySelectorAll(Y),V)}catch(Z){}}return T(Y,X,V,W)};F.find=T.find;F.filter=T.filter;F.selectors=T.selectors;F.matches=T.matches})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){(function(){var T=document.createElement("div");T.innerHTML="<div class='test e'></div><div class='test'></div>";if(T.getElementsByClassName("e").length===0){return}T.lastChild.className="e";if(T.getElementsByClassName("e").length===1){return}I.order.splice(1,0,"CLASS");I.find.CLASS=function(U,V,W){if(typeof V.getElementsByClassName!=="undefined"&&!W){return V.getElementsByClassName(U[1])}}})()}function P(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1&&!ac){T.sizcache=Y;T.sizset=W}if(T.nodeName===Z){X=T;break}T=T[U]}ad[W]=X}}}function S(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1){if(!ac){T.sizcache=Y;T.sizset=W}if(typeof Z!=="string"){if(T===Z){X=true;break}}else{if(F.filter(Z,[T]).length>0){X=T;break}}}T=T[U]}ad[W]=X}}}var K=document.compareDocumentPosition?function(U,T){return U.compareDocumentPosition(T)&16}:function(U,T){return U!==T&&(U.contains?U.contains(T):true)};var Q=function(T){return T.nodeType===9&&T.documentElement.nodeName!=="HTML"||!!T.ownerDocument&&Q(T.ownerDocument)};var J=function(T,aa){var W=[],X="",Y,V=aa.nodeType?[aa]:aa;while((Y=I.match.PSEUDO.exec(T))){X+=Y[0];T=T.replace(I.match.PSEUDO,"")}T=I.relative[T]?T+"*":T;for(var Z=0,U=V.length;Z<U;Z++){F(T,V[Z],W)}return F.filter(X,W)};o.find=F;o.filter=F.filter;o.expr=F.selectors;o.expr[":"]=o.expr.filters;F.selectors.filters.hidden=function(T){return T.offsetWidth===0||T.offsetHeight===0};F.selectors.filters.visible=function(T){return T.offsetWidth>0||T.offsetHeight>0};F.selectors.filters.animated=function(T){return o.grep(o.timers,function(U){return T===U.elem}).length};o.multiFilter=function(V,T,U){if(U){V=":not("+V+")"}return F.matches(V,T)};o.dir=function(V,U){var T=[],W=V[U];while(W&&W!=document){if(W.nodeType==1){T.push(W)}W=W[U]}return T};o.nth=function(X,T,V,W){T=T||1;var U=0;for(;X;X=X[V]){if(X.nodeType==1&&++U==T){break}}return X};o.sibling=function(V,U){var T=[];for(;V;V=V.nextSibling){if(V.nodeType==1&&V!=U){T.push(V)}}return T};return;l.Sizzle=F})();o.event={add:function(I,F,H,K){if(I.nodeType==3||I.nodeType==8){return}if(I.setInterval&&I!=l){I=l}if(!H.guid){H.guid=this.guid++}if(K!==g){var G=H;H=this.proxy(G);H.data=K}var E=o.data(I,"events")||o.data(I,"events",{}),J=o.data(I,"handle")||o.data(I,"handle",function(){return typeof o!=="undefined"&&!o.event.triggered?o.event.handle.apply(arguments.callee.elem,arguments):g});J.elem=I;o.each(F.split(/\s+/),function(M,N){var O=N.split(".");N=O.shift();H.type=O.slice().sort().join(".");var L=E[N];if(o.event.specialAll[N]){o.event.specialAll[N].setup.call(I,K,O)}if(!L){L=E[N]={};if(!o.event.special[N]||o.event.special[N].setup.call(I,K,O)===false){if(I.addEventListener){I.addEventListener(N,J,false)}else{if(I.attachEvent){I.attachEvent("on"+N,J)}}}}L[H.guid]=H;o.event.global[N]=true});I=null},guid:1,global:{},remove:function(K,H,J){if(K.nodeType==3||K.nodeType==8){return}var G=o.data(K,"events"),F,E;if(G){if(H===g||(typeof H==="string"&&H.charAt(0)==".")){for(var I in G){this.remove(K,I+(H||""))}}else{if(H.type){J=H.handler;H=H.type}o.each(H.split(/\s+/),function(M,O){var Q=O.split(".");O=Q.shift();var N=RegExp("(^|\\.)"+Q.slice().sort().join(".*\\.")+"(\\.|$)");if(G[O]){if(J){delete G[O][J.guid]}else{for(var P in G[O]){if(N.test(G[O][P].type)){delete G[O][P]}}}if(o.event.specialAll[O]){o.event.specialAll[O].teardown.call(K,Q)}for(F in G[O]){break}if(!F){if(!o.event.special[O]||o.event.special[O].teardown.call(K,Q)===false){if(K.removeEventListener){K.removeEventListener(O,o.data(K,"handle"),false)}else{if(K.detachEvent){K.detachEvent("on"+O,o.data(K,"handle"))}}}F=null;delete G[O]}}})}for(F in G){break}if(!F){var L=o.data(K,"handle");if(L){L.elem=null}o.removeData(K,"events");o.removeData(K,"handle")}}},trigger:function(I,K,H,E){var G=I.type||I;if(!E){I=typeof I==="object"?I[h]?I:o.extend(o.Event(G),I):o.Event(G);if(G.indexOf("!")>=0){I.type=G=G.slice(0,-1);I.exclusive=true}if(!H){I.stopPropagation();if(this.global[G]){o.each(o.cache,function(){if(this.events&&this.events[G]){o.event.trigger(I,K,this.handle.elem)}})}}if(!H||H.nodeType==3||H.nodeType==8){return g}I.result=g;I.target=H;K=o.makeArray(K);K.unshift(I)}I.currentTarget=H;var J=o.data(H,"handle");if(J){J.apply(H,K)}if((!H[G]||(o.nodeName(H,"a")&&G=="click"))&&H["on"+G]&&H["on"+G].apply(H,K)===false){I.result=false}if(!E&&H[G]&&!I.isDefaultPrevented()&&!(o.nodeName(H,"a")&&G=="click")){this.triggered=true;try{H[G]()}catch(L){}}this.triggered=false;if(!I.isPropagationStopped()){var F=H.parentNode||H.ownerDocument;if(F){o.event.trigger(I,K,F,true)}}},handle:function(K){var J,E;K=arguments[0]=o.event.fix(K||l.event);K.currentTarget=this;var L=K.type.split(".");K.type=L.shift();J=!L.length&&!K.exclusive;var I=RegExp("(^|\\.)"+L.slice().sort().join(".*\\.")+"(\\.|$)");E=(o.data(this,"events")||{})[K.type];for(var G in E){var H=E[G];if(J||I.test(H.type)){K.handler=H;K.data=H.data;var F=H.apply(this,arguments);if(F!==g){K.result=F;if(F===false){K.preventDefault();K.stopPropagation()}}if(K.isImmediatePropagationStopped()){break}}}},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(H){if(H[h]){return H}var F=H;H=o.Event(F);for(var G=this.props.length,J;G;){J=this.props[--G];H[J]=F[J]}if(!H.target){H.target=H.srcElement||document}if(H.target.nodeType==3){H.target=H.target.parentNode}if(!H.relatedTarget&&H.fromElement){H.relatedTarget=H.fromElement==H.target?H.toElement:H.fromElement}if(H.pageX==null&&H.clientX!=null){var I=document.documentElement,E=document.body;H.pageX=H.clientX+(I&&I.scrollLeft||E&&E.scrollLeft||0)-(I.clientLeft||0);H.pageY=H.clientY+(I&&I.scrollTop||E&&E.scrollTop||0)-(I.clientTop||0)}if(!H.which&&((H.charCode||H.charCode===0)?H.charCode:H.keyCode)){H.which=H.charCode||H.keyCode}if(!H.metaKey&&H.ctrlKey){H.metaKey=H.ctrlKey}if(!H.which&&H.button){H.which=(H.button&1?1:(H.button&2?3:(H.button&4?2:0)))}return H},proxy:function(F,E){E=E||function(){return F.apply(this,arguments)};E.guid=F.guid=F.guid||E.guid||this.guid++;return E},special:{ready:{setup:B,teardown:function(){}}},specialAll:{live:{setup:function(E,F){o.event.add(this,F[0],c)},teardown:function(G){if(G.length){var E=0,F=RegExp("(^|\\.)"+G[0]+"(\\.|$)");o.each((o.data(this,"events").live||{}),function(){if(F.test(this.type)){E++}});if(E<1){o.event.remove(this,G[0],c)}}}}}};o.Event=function(E){if(!this.preventDefault){return new o.Event(E)}if(E&&E.type){this.originalEvent=E;this.type=E.type}else{this.type=E}this.timeStamp=e();this[h]=true};function k(){return false}function u(){return true}o.Event.prototype={preventDefault:function(){this.isDefaultPrevented=u;var E=this.originalEvent;if(!E){return}if(E.preventDefault){E.preventDefault()}E.returnValue=false},stopPropagation:function(){this.isPropagationStopped=u;var E=this.originalEvent;if(!E){return}if(E.stopPropagation){E.stopPropagation()}E.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=u;this.stopPropagation()},isDefaultPrevented:k,isPropagationStopped:k,isImmediatePropagationStopped:k};var a=function(F){var E=F.relatedTarget;while(E&&E!=this){try{E=E.parentNode}catch(G){E=this}}if(E!=this){F.type=F.data;o.event.handle.apply(this,arguments)}};o.each({mouseover:"mouseenter",mouseout:"mouseleave"},function(F,E){o.event.special[E]={setup:function(){o.event.add(this,F,a,E)},teardown:function(){o.event.remove(this,F,a)}}});o.fn.extend({bind:function(F,G,E){return F=="unload"?this.one(F,G,E):this.each(function(){o.event.add(this,F,E||G,E&&G)})},one:function(G,H,F){var E=o.event.proxy(F||H,function(I){o(this).unbind(I,E);return(F||H).apply(this,arguments)});return this.each(function(){o.event.add(this,G,E,F&&H)})},unbind:function(F,E){return this.each(function(){o.event.remove(this,F,E)})},trigger:function(E,F){return this.each(function(){o.event.trigger(E,F,this)})},triggerHandler:function(E,G){if(this[0]){var F=o.Event(E);F.preventDefault();F.stopPropagation();o.event.trigger(F,G,this[0]);return F.result}},toggle:function(G){var E=arguments,F=1;while(F<E.length){o.event.proxy(G,E[F++])}return this.click(o.event.proxy(G,function(H){this.lastToggle=(this.lastToggle||0)%F;H.preventDefault();return E[this.lastToggle++].apply(this,arguments)||false}))},hover:function(E,F){return this.mouseenter(E).mouseleave(F)},ready:function(E){B();if(o.isReady){E.call(document,o)}else{o.readyList.push(E)}return this},live:function(G,F){var E=o.event.proxy(F);E.guid+=this.selector+G;o(document).bind(i(G,this.selector),this.selector,E);return this},die:function(F,E){o(document).unbind(i(F,this.selector),E?{guid:E.guid+this.selector+F}:null);return this}});function c(H){var E=RegExp("(^|\\.)"+H.type+"(\\.|$)"),G=true,F=[];o.each(o.data(this,"events").live||[],function(I,J){if(E.test(J.type)){var K=o(H.target).closest(J.data)[0];if(K){F.push({elem:K,fn:J})}}});F.sort(function(J,I){return o.data(J.elem,"closest")-o.data(I.elem,"closest")});o.each(F,function(){if(this.fn.call(this.elem,H,this.fn.data)===false){return(G=false)}});return G}function i(F,E){return["live",F,E.replace(/\./g,"`").replace(/ /g,"|")].join(".")}o.extend({isReady:false,readyList:[],ready:function(){if(!o.isReady){o.isReady=true;if(o.readyList){o.each(o.readyList,function(){this.call(document,o)});o.readyList=null}o(document).triggerHandler("ready")}}});var x=false;function B(){if(x){return}x=true;if(document.addEventListener){document.addEventListener("DOMContentLoaded",function(){document.removeEventListener("DOMContentLoaded",arguments.callee,false);o.ready()},false)}else{if(document.attachEvent){document.attachEvent("onreadystatechange",function(){if(document.readyState==="complete"){document.detachEvent("onreadystatechange",arguments.callee);o.ready()}});if(document.documentElement.doScroll&&l==l.top){(function(){if(o.isReady){return}try{document.documentElement.doScroll("left")}catch(E){setTimeout(arguments.callee,0);return}o.ready()})()}}}o.event.add(l,"load",o.ready)}o.each(("blur,focus,load,resize,scroll,unload,click,dblclick,mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,change,select,submit,keydown,keypress,keyup,error").split(","),function(F,E){o.fn[E]=function(G){return G?this.bind(E,G):this.trigger(E)}});o(l).bind("unload",function(){for(var E in o.cache){if(E!=1&&o.cache[E].handle){o.event.remove(o.cache[E].handle.elem)}}});(function(){o.support={};var F=document.documentElement,G=document.createElement("script"),K=document.createElement("div"),J="script"+(new Date).getTime();K.style.display="none";K.innerHTML='   <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';var H=K.getElementsByTagName("*"),E=K.getElementsByTagName("a")[0];if(!H||!H.length||!E){return}o.support={leadingWhitespace:K.firstChild.nodeType==3,tbody:!K.getElementsByTagName("tbody").length,objectAll:!!K.getElementsByTagName("object")[0].getElementsByTagName("*").length,htmlSerialize:!!K.getElementsByTagName("link").length,style:/red/.test(E.getAttribute("style")),hrefNormalized:E.getAttribute("href")==="/a",opacity:E.style.opacity==="0.5",cssFloat:!!E.style.cssFloat,scriptEval:false,noCloneEvent:true,boxModel:null};G.type="text/javascript";try{G.appendChild(document.createTextNode("window."+J+"=1;"))}catch(I){}F.insertBefore(G,F.firstChild);if(l[J]){o.support.scriptEval=true;delete l[J]}F.removeChild(G);if(K.attachEvent&&K.fireEvent){K.attachEvent("onclick",function(){o.support.noCloneEvent=false;K.detachEvent("onclick",arguments.callee)});K.cloneNode(true).fireEvent("onclick")}o(function(){var L=document.createElement("div");L.style.width=L.style.paddingLeft="1px";document.body.appendChild(L);o.boxModel=o.support.boxModel=L.offsetWidth===2;document.body.removeChild(L).style.display="none"})})();var w=o.support.cssFloat?"cssFloat":"styleFloat";o.props={"for":"htmlFor","class":"className","float":w,cssFloat:w,styleFloat:w,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",tabindex:"tabIndex"};o.fn.extend({_load:o.fn.load,load:function(G,J,K){if(typeof G!=="string"){return this._load(G)}var I=G.indexOf(" ");if(I>=0){var E=G.slice(I,G.length);G=G.slice(0,I)}var H="GET";if(J){if(o.isFunction(J)){K=J;J=null}else{if(typeof J==="object"){J=o.param(J);H="POST"}}}var F=this;o.ajax({url:G,type:H,dataType:"html",data:J,complete:function(M,L){if(L=="success"||L=="notmodified"){F.html(E?o("<div/>").append(M.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(E):M.responseText)}if(K){F.each(K,[M.responseText,L,M])}}});return this},serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?o.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password|search/i.test(this.type))}).map(function(E,F){var G=o(this).val();return G==null?null:o.isArray(G)?o.map(G,function(I,H){return{name:F.name,value:I}}):{name:F.name,value:G}}).get()}});o.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(E,F){o.fn[F]=function(G){return this.bind(F,G)}});var r=e();o.extend({get:function(E,G,H,F){if(o.isFunction(G)){H=G;G=null}return o.ajax({type:"GET",url:E,data:G,success:H,dataType:F})},getScript:function(E,F){return o.get(E,null,F,"script")},getJSON:function(E,F,G){return o.get(E,F,G,"json")},post:function(E,G,H,F){if(o.isFunction(G)){H=G;G={}}return o.ajax({type:"POST",url:E,data:G,success:H,dataType:F})},ajaxSetup:function(E){o.extend(o.ajaxSettings,E)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return l.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest()},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(M){M=o.extend(true,M,o.extend(true,{},o.ajaxSettings,M));var W,F=/=\?(&|$)/g,R,V,G=M.type.toUpperCase();if(M.data&&M.processData&&typeof M.data!=="string"){M.data=o.param(M.data)}if(M.dataType=="jsonp"){if(G=="GET"){if(!M.url.match(F)){M.url+=(M.url.match(/\?/)?"&":"?")+(M.jsonp||"callback")+"=?"}}else{if(!M.data||!M.data.match(F)){M.data=(M.data?M.data+"&":"")+(M.jsonp||"callback")+"=?"}}M.dataType="json"}if(M.dataType=="json"&&(M.data&&M.data.match(F)||M.url.match(F))){W="jsonp"+r++;if(M.data){M.data=(M.data+"").replace(F,"="+W+"$1")}M.url=M.url.replace(F,"="+W+"$1");M.dataType="script";l[W]=function(X){V=X;I();L();l[W]=g;try{delete l[W]}catch(Y){}if(H){H.removeChild(T)}}}if(M.dataType=="script"&&M.cache==null){M.cache=false}if(M.cache===false&&G=="GET"){var E=e();var U=M.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+E+"$2");M.url=U+((U==M.url)?(M.url.match(/\?/)?"&":"?")+"_="+E:"")}if(M.data&&G=="GET"){M.url+=(M.url.match(/\?/)?"&":"?")+M.data;M.data=null}if(M.global&&!o.active++){o.event.trigger("ajaxStart")}var Q=/^(\w+:)?\/\/([^\/?#]+)/.exec(M.url);if(M.dataType=="script"&&G=="GET"&&Q&&(Q[1]&&Q[1]!=location.protocol||Q[2]!=location.host)){var H=document.getElementsByTagName("head")[0];var T=document.createElement("script");T.src=M.url;if(M.scriptCharset){T.charset=M.scriptCharset}if(!W){var O=false;T.onload=T.onreadystatechange=function(){if(!O&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){O=true;I();L();T.onload=T.onreadystatechange=null;H.removeChild(T)}}}H.appendChild(T);return g}var K=false;var J=M.xhr();if(M.username){J.open(G,M.url,M.async,M.username,M.password)}else{J.open(G,M.url,M.async)}try{if(M.data){J.setRequestHeader("Content-Type",M.contentType)}if(M.ifModified){J.setRequestHeader("If-Modified-Since",o.lastModified[M.url]||"Thu, 01 Jan 1970 00:00:00 GMT")}J.setRequestHeader("X-Requested-With","XMLHttpRequest");J.setRequestHeader("Accept",M.dataType&&M.accepts[M.dataType]?M.accepts[M.dataType]+", */*":M.accepts._default)}catch(S){}if(M.beforeSend&&M.beforeSend(J,M)===false){if(M.global&&!--o.active){o.event.trigger("ajaxStop")}J.abort();return false}if(M.global){o.event.trigger("ajaxSend",[J,M])}var N=function(X){if(J.readyState==0){if(P){clearInterval(P);P=null;if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}}else{if(!K&&J&&(J.readyState==4||X=="timeout")){K=true;if(P){clearInterval(P);P=null}R=X=="timeout"?"timeout":!o.httpSuccess(J)?"error":M.ifModified&&o.httpNotModified(J,M.url)?"notmodified":"success";if(R=="success"){try{V=o.httpData(J,M.dataType,M)}catch(Z){R="parsererror"}}if(R=="success"){var Y;try{Y=J.getResponseHeader("Last-Modified")}catch(Z){}if(M.ifModified&&Y){o.lastModified[M.url]=Y}if(!W){I()}}else{o.handleError(M,J,R)}L();if(X){J.abort()}if(M.async){J=null}}}};if(M.async){var P=setInterval(N,13);if(M.timeout>0){setTimeout(function(){if(J&&!K){N("timeout")}},M.timeout)}}try{J.send(M.data)}catch(S){o.handleError(M,J,null,S)}if(!M.async){N()}function I(){if(M.success){M.success(V,R)}if(M.global){o.event.trigger("ajaxSuccess",[J,M])}}function L(){if(M.complete){M.complete(J,R)}if(M.global){o.event.trigger("ajaxComplete",[J,M])}if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}return J},handleError:function(F,H,E,G){if(F.error){F.error(H,E,G)}if(F.global){o.event.trigger("ajaxError",[H,F,G])}},active:0,httpSuccess:function(F){try{return !F.status&&location.protocol=="file:"||(F.status>=200&&F.status<300)||F.status==304||F.status==1223}catch(E){}return false},httpNotModified:function(G,E){try{var H=G.getResponseHeader("Last-Modified");return G.status==304||H==o.lastModified[E]}catch(F){}return false},httpData:function(J,H,G){var F=J.getResponseHeader("content-type"),E=H=="xml"||!H&&F&&F.indexOf("xml")>=0,I=E?J.responseXML:J.responseText;if(E&&I.documentElement.tagName=="parsererror"){throw"parsererror"}if(G&&G.dataFilter){I=G.dataFilter(I,H)}if(typeof I==="string"){if(H=="script"){o.globalEval(I)}if(H=="json"){I=l["eval"]("("+I+")")}}return I},param:function(E){var G=[];function H(I,J){G[G.length]=encodeURIComponent(I)+"="+encodeURIComponent(J)}if(o.isArray(E)||E.jquery){o.each(E,function(){H(this.name,this.value)})}else{for(var F in E){if(o.isArray(E[F])){o.each(E[F],function(){H(F,this)})}else{H(F,o.isFunction(E[F])?E[F]():E[F])}}}return G.join("&").replace(/%20/g,"+")}});var m={},n,d=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];function t(F,E){var G={};o.each(d.concat.apply([],d.slice(0,E)),function(){G[this]=F});return G}o.fn.extend({show:function(J,L){if(J){return this.animate(t("show",3),J,L)}else{for(var H=0,F=this.length;H<F;H++){var E=o.data(this[H],"olddisplay");this[H].style.display=E||"";if(o.css(this[H],"display")==="none"){var G=this[H].tagName,K;if(m[G]){K=m[G]}else{var I=o("<"+G+" />").appendTo("body");K=I.css("display");if(K==="none"){K="block"}I.remove();m[G]=K}o.data(this[H],"olddisplay",K)}}for(var H=0,F=this.length;H<F;H++){this[H].style.display=o.data(this[H],"olddisplay")||""}return this}},hide:function(H,I){if(H){return this.animate(t("hide",3),H,I)}else{for(var G=0,F=this.length;G<F;G++){var E=o.data(this[G],"olddisplay");if(!E&&E!=="none"){o.data(this[G],"olddisplay",o.css(this[G],"display"))}}for(var G=0,F=this.length;G<F;G++){this[G].style.display="none"}return this}},_toggle:o.fn.toggle,toggle:function(G,F){var E=typeof G==="boolean";return o.isFunction(G)&&o.isFunction(F)?this._toggle.apply(this,arguments):G==null||E?this.each(function(){var H=E?G:o(this).is(":hidden");o(this)[H?"show":"hide"]()}):this.animate(t("toggle",3),G,F)},fadeTo:function(E,G,F){return this.animate({opacity:G},E,F)},animate:function(I,F,H,G){var E=o.speed(F,H,G);return this[E.queue===false?"each":"queue"](function(){var K=o.extend({},E),M,L=this.nodeType==1&&o(this).is(":hidden"),J=this;for(M in I){if(I[M]=="hide"&&L||I[M]=="show"&&!L){return K.complete.call(this)}if((M=="height"||M=="width")&&this.style){K.display=o.css(this,"display");K.overflow=this.style.overflow}}if(K.overflow!=null){this.style.overflow="hidden"}K.curAnim=o.extend({},I);o.each(I,function(O,S){var R=new o.fx(J,K,O);if(/toggle|show|hide/.test(S)){R[S=="toggle"?L?"show":"hide":S](I)}else{var Q=S.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),T=R.cur(true)||0;if(Q){var N=parseFloat(Q[2]),P=Q[3]||"px";if(P!="px"){J.style[O]=(N||1)+P;T=((N||1)/R.cur(true))*T;J.style[O]=T+P}if(Q[1]){N=((Q[1]=="-="?-1:1)*N)+T}R.custom(T,N,P)}else{R.custom(T,S,"")}}});return true})},stop:function(F,E){var G=o.timers;if(F){this.queue([])}this.each(function(){for(var H=G.length-1;H>=0;H--){if(G[H].elem==this){if(E){G[H](true)}G.splice(H,1)}}});if(!E){this.dequeue()}return this}});o.each({slideDown:t("show",1),slideUp:t("hide",1),slideToggle:t("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(E,F){o.fn[E]=function(G,H){return this.animate(F,G,H)}});o.extend({speed:function(G,H,F){var E=typeof G==="object"?G:{complete:F||!F&&H||o.isFunction(G)&&G,duration:G,easing:F&&H||H&&!o.isFunction(H)&&H};E.duration=o.fx.off?0:typeof E.duration==="number"?E.duration:o.fx.speeds[E.duration]||o.fx.speeds._default;E.old=E.complete;E.complete=function(){if(E.queue!==false){o(this).dequeue()}if(o.isFunction(E.old)){E.old.call(this)}};return E},easing:{linear:function(G,H,E,F){return E+F*G},swing:function(G,H,E,F){return((-Math.cos(G*Math.PI)/2)+0.5)*F+E}},timers:[],fx:function(F,E,G){this.options=E;this.elem=F;this.prop=G;if(!E.orig){E.orig={}}}});o.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(o.fx.step[this.prop]||o.fx.step._default)(this);if((this.prop=="height"||this.prop=="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(F){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var E=parseFloat(o.css(this.elem,this.prop,F));return E&&E>-10000?E:parseFloat(o.curCSS(this.elem,this.prop))||0},custom:function(I,H,G){this.startTime=e();this.start=I;this.end=H;this.unit=G||this.unit||"px";this.now=this.start;this.pos=this.state=0;var E=this;function F(J){return E.step(J)}F.elem=this.elem;if(F()&&o.timers.push(F)&&!n){n=setInterval(function(){var K=o.timers;for(var J=0;J<K.length;J++){if(!K[J]()){K.splice(J--,1)}}if(!K.length){clearInterval(n);n=g}},13)}},show:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.show=true;this.custom(this.prop=="width"||this.prop=="height"?1:0,this.cur());o(this.elem).show()},hide:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(H){var G=e();if(H||G>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var E=true;for(var F in this.options.curAnim){if(this.options.curAnim[F]!==true){E=false}}if(E){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(o.css(this.elem,"display")=="none"){this.elem.style.display="block"}}if(this.options.hide){o(this.elem).hide()}if(this.options.hide||this.options.show){for(var I in this.options.curAnim){o.attr(this.elem.style,I,this.options.orig[I])}}this.options.complete.call(this.elem)}return false}else{var J=G-this.startTime;this.state=J/this.options.duration;this.pos=o.easing[this.options.easing||(o.easing.swing?"swing":"linear")](this.state,J,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};o.extend(o.fx,{speeds:{slow:600,fast:200,_default:400},step:{opacity:function(E){o.attr(E.elem.style,"opacity",E.now)},_default:function(E){if(E.elem.style&&E.elem.style[E.prop]!=null){E.elem.style[E.prop]=E.now+E.unit}else{E.elem[E.prop]=E.now}}}});if(document.documentElement.getBoundingClientRect){o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}var G=this[0].getBoundingClientRect(),J=this[0].ownerDocument,F=J.body,E=J.documentElement,L=E.clientTop||F.clientTop||0,K=E.clientLeft||F.clientLeft||0,I=G.top+(self.pageYOffset||o.boxModel&&E.scrollTop||F.scrollTop)-L,H=G.left+(self.pageXOffset||o.boxModel&&E.scrollLeft||F.scrollLeft)-K;return{top:I,left:H}}}else{o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}o.offset.initialized||o.offset.initialize();var J=this[0],G=J.offsetParent,F=J,O=J.ownerDocument,M,H=O.documentElement,K=O.body,L=O.defaultView,E=L.getComputedStyle(J,null),N=J.offsetTop,I=J.offsetLeft;while((J=J.parentNode)&&J!==K&&J!==H){M=L.getComputedStyle(J,null);N-=J.scrollTop,I-=J.scrollLeft;if(J===G){N+=J.offsetTop,I+=J.offsetLeft;if(o.offset.doesNotAddBorder&&!(o.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(J.tagName))){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}F=G,G=J.offsetParent}if(o.offset.subtractsBorderForOverflowNotVisible&&M.overflow!=="visible"){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}E=M}if(E.position==="relative"||E.position==="static"){N+=K.offsetTop,I+=K.offsetLeft}if(E.position==="fixed"){N+=Math.max(H.scrollTop,K.scrollTop),I+=Math.max(H.scrollLeft,K.scrollLeft)}return{top:N,left:I}}}o.offset={initialize:function(){if(this.initialized){return}var L=document.body,F=document.createElement("div"),H,G,N,I,M,E,J=L.style.marginTop,K='<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';M={position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"};for(E in M){F.style[E]=M[E]}F.innerHTML=K;L.insertBefore(F,L.firstChild);H=F.firstChild,G=H.firstChild,I=H.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(G.offsetTop!==5);this.doesAddBorderForTableAndCells=(I.offsetTop===5);H.style.overflow="hidden",H.style.position="relative";this.subtractsBorderForOverflowNotVisible=(G.offsetTop===-5);L.style.marginTop="1px";this.doesNotIncludeMarginInBodyOffset=(L.offsetTop===0);L.style.marginTop=J;L.removeChild(F);this.initialized=true},bodyOffset:function(E){o.offset.initialized||o.offset.initialize();var G=E.offsetTop,F=E.offsetLeft;if(o.offset.doesNotIncludeMarginInBodyOffset){G+=parseInt(o.curCSS(E,"marginTop",true),10)||0,F+=parseInt(o.curCSS(E,"marginLeft",true),10)||0}return{top:G,left:F}}};o.fn.extend({position:function(){var I=0,H=0,F;if(this[0]){var G=this.offsetParent(),J=this.offset(),E=/^body|html$/i.test(G[0].tagName)?{top:0,left:0}:G.offset();J.top-=j(this,"marginTop");J.left-=j(this,"marginLeft");E.top+=j(G,"borderTopWidth");E.left+=j(G,"borderLeftWidth");F={top:J.top-E.top,left:J.left-E.left}}return F},offsetParent:function(){var E=this[0].offsetParent||document.body;while(E&&(!/^body|html$/i.test(E.tagName)&&o.css(E,"position")=="static")){E=E.offsetParent}return o(E)}});o.each(["Left","Top"],function(F,E){var G="scroll"+E;o.fn[G]=function(H){if(!this[0]){return null}return H!==g?this.each(function(){this==l||this==document?l.scrollTo(!F?H:o(l).scrollLeft(),F?H:o(l).scrollTop()):this[G]=H}):this[0]==l||this[0]==document?self[F?"pageYOffset":"pageXOffset"]||o.boxModel&&document.documentElement[G]||document.body[G]:this[0][G]}});o.each(["Height","Width"],function(I,G){var E=I?"Left":"Top",H=I?"Right":"Bottom",F=G.toLowerCase();o.fn["inner"+G]=function(){return this[0]?o.css(this[0],F,false,"padding"):null};o.fn["outer"+G]=function(K){return this[0]?o.css(this[0],F,false,K?"margin":"border"):null};var J=G.toLowerCase();o.fn[J]=function(K){return this[0]==l?document.compatMode=="CSS1Compat"&&document.documentElement["client"+G]||document.body["client"+G]:this[0]==document?Math.max(document.documentElement["client"+G],document.body["scroll"+G],document.documentElement["scroll"+G],document.body["offset"+G],document.documentElement["offset"+G]):K===g?(this.length?o.css(this[0],J):null):this.css(J,typeof K==="string"?K:K+"px")}})})();
Index: trunk/workflow/inc/report/includes/classes/Listagem.class.php
===================================================================
--- trunk/workflow/inc/report/includes/classes/Listagem.class.php	(revision 5307)
+++ trunk/workflow/inc/report/includes/classes/Listagem.class.php	(revision 5307)
@@ -0,0 +1,2177 @@
+<?php
+/**
+ * Listagem
+ *
+ * Implementaçao de Listagens padroes do sistema.
+ */
+/**
+ * Listagem
+ *
+ * Implementaçao de Listagens padroes do sistema.
+ *
+ *
+ * @author Jair Pereira <pereira.jair@gmail.com>
+ * @since 01/06/2009
+ *
+ * @package Listagem
+ */
+
+include_once("ListagemColuna.class.php");
+include_once("ListagemIndicador.class.php");
+include_once("SqlParser.class.php");
+
+class Listagem {
+     
+    /**
+     * Identificador da Listagem.
+     */
+    private $idlistagem;
+    
+    /**
+     * Tï¿œtulo da Listagem
+     */
+    private $titulo;
+    
+    /**
+     * Array de Colunas.
+     */
+    private $colunas = array();
+    
+    /**
+     * Array de Linhas de Detalhamento.
+     */
+    private $linhasdetalhamento = array();
+    
+    /**
+     * Array de Linhas Agrupadas
+     */
+    private $linhasagrupamento = array();
+    
+    /**
+     * Array de Dados.
+     */
+    private $dados = array();
+    
+    /**
+     * Exibe Header das Tables. (Tï¿œtulos das Colunas).
+     */
+    private $showthead = true;
+    
+    /**
+     * Array de Totalizadores.
+     */
+    private $totalizadores = array();
+    
+    /**
+     * Alterado para Protegido nï¿œo serï¿œ instanciado na classe.
+     */
+    //protected  $form = Formulario;
+    
+    /**
+     * Formulï¿œrio de Pesquisa.
+     */
+    //protected $formpesquisa = Formulario;
+    
+    /**
+     * Agrupar Resultados Alfabeticamente (True ou False)
+     */
+    private $agruparAlfabeticamente = false;
+
+	/**
+	 * Array de Indicadores
+	 */
+    private $arrindicadores = array();
+    
+    /**
+     * Array de Parï¿œmetros
+     */
+    private $arrparametros = array();
+    
+    /**
+     * Array de Agrupamentos
+     */
+    private $arragrupamentos = array();
+    
+    /**
+     * SubListagem.
+     */
+    public $subListagem;
+    
+    /**
+     * Indica se este objeto ï¿œ uma SubListagem.
+     */
+    private $issublist = false;
+    
+    /**
+     * Conexao com o Banco de Dados.
+     */
+    private $conexao;
+    
+    /**
+     * SQL da Listagem.
+     */
+    private $sql;
+    
+    /**
+     * Exibir SubTotalizadores
+     */
+    private $exibesubtotais = false;
+    
+    private $exibedivcolunas = true;
+    
+    /**
+     * Exibir Totalizadores
+     */
+    private $_exibetotalizadores = true;
+    
+    /**
+     * Exibir Quantidade de Registros Encontrados
+     */
+    private $_exibeqtdregistros = true;
+    
+    /**
+     * Modo DEBUG
+     */
+    private $_debug = true;
+    
+    /**
+     * Array de Erros
+     */
+    private $_errors = array();
+    
+    /**
+     * Indica se a Listagem Possui algum checkbox
+     */
+    private $temcheck = false;
+    
+    /**
+     * Repetir Tï¿œtulo do Agrupamento. 
+     */
+    private $_repetirtituloagrupamento = true;
+    
+    /**
+     * Quantidade de Registros da Listagem Principal (Usada somente quando a listagem ï¿œ uma sublistagem.)
+     */
+    private $_qtdregistroslistagemprincipal = 0;
+    
+    /**
+     * Gerar Arquivo CSV.
+     */
+    private $_temarquivocsv = false;
+    
+    
+    /**
+     * Exibir Resultados na tela. (Usado quando somente serï¿œ exibido os resultados em CSV).
+     */
+    private $_exiberesultados = true;
+    
+    /**
+     * Gerar Automaticamente Arquivo CSV.
+     */
+    private $_exibearquivocsv = false;
+    
+    /**
+     * Colunas Arquivo CSV.
+     */
+    private $_colunasarquivo = array();
+    
+    /**
+     * Texto do Arquivo CSV.
+     */
+    private $_txtarquivocsv = "";
+    
+    
+    /**
+     * Array de Totalizadores.
+     */
+    private $arrtotais = array();
+    
+    /**
+     * Array de SubTotalizadores
+     */
+    private $arrsubtotais = array();
+     
+     
+    /**
+     * Mesagem: Nenhum Resultado Encontrado.
+     */
+    public $msgnenhumresultado = "Nenhum resultado encontrado.";
+    
+    /**
+     * Mensagem: registro(s) encontrado(s)
+     */
+    public $msgregistros = "registro(s) encontrado(s).";
+    
+    /**
+     * Mensagem: TOTAL:
+     */
+    public $msgtotalizador = "TOTAL:";
+    
+    /**
+     * Mensagem: SUB-TOTAL;
+     */
+    public $msgsubtotalizador = "SUB-TOTAL:";
+    
+    private $_mostraLegendaTopo = true;
+    
+    private $_mostraLegendaRodape = false;
+    
+    private $_exibelinhasvazias = true;
+    
+    private $_colunascsv;
+    
+    private $_isarray = false;
+    
+    private $_totalizadorprecisao = 2;
+    
+    /*
+     * ID da Listagem. que foi carregado.
+     */
+    private $_lstoid = "";
+    
+    private $_url_base_path;
+    
+    private $_tmp_file_path = "/tmp/";
+    
+     
+    /**
+     * Construï¿œï¿œo da Classe.
+     * 
+     * @idlistagem Identificador da Listagem.
+     * @titulo Tï¿œtulo da Listagem.
+     * @conexao Conexï¿œo com o Banco de Dados.
+     * @subListagem Indica se a Listagem ï¿œ uma SubListagem. (default: false)
+     */
+    public function __construct($idlistagem,$titulo,$conexao,$subListagem = false) {
+        $this->setTitulo($titulo);
+        $this->setIdListagem($idlistagem);
+        if (!$subListagem) {
+            $novoidlistagem = $idlistagem . "_sublist";
+            $this->subListagem = new Listagem($novoidlistagem,"",$conexao,true);
+            $this->subListagem->setMostrarQuantidadeRegistros(false);
+            $this->subListagem->setIdListagem($novoidlistagem); 
+        }
+        $this->setSubListagem($subListagem);
+        $this->setConexao($conexao);
+    }
+    
+    /**
+     * Indica se a Listagem ï¿œ uma SubListagem.
+     * 
+     * @param $value (true,false)
+     */
+    protected function setSubListagem($value) {
+        $this->issublist = $value;
+    }
+    
+    public function setTotalizadorPrecisao($value) {
+        $this->_totalizadorprecisao = $value;
+    }
+    
+    /**
+     * Identificador da Listagem.
+     * 
+     * @param $value (true,false)
+     */
+    public function setIdListagem($value) {
+        $this->idlistagem = $value;
+    }
+    
+    public function setExibirOpcoesDeColunas($value) {
+        $this->exibedivcolunas = $value;
+    }
+    
+    /**
+     * Retorna o Identificador da Listagem.
+     */
+    public function getIdListagem() {
+        return $this->idlistagem;
+    }
+    
+    public function setUrlBasePath($base_path) {
+    	$this->_url_base_path = $base_path;
+    }
+
+    /**
+     * Funï¿œï¿œo Interna para Alterar a Varï¿œavel de Conexï¿œo com o Banco de Dados.
+     * 
+     * @param $conexao
+     * @return unknown_type
+     */
+    protected function setConexao($conexao) {  $this->conexao = $conexao;  }
+     
+    /**
+     * Funï¿œï¿œo Interna para Alterar O SQL que serï¿œ executado na listagem.
+     * 
+     * @param $sql
+     * @return unknown_type
+     */
+    protected function setSQL($sql) {  $this->sql = $sql;  }
+     
+    /**
+     * Funï¿œï¿œo Interna para Recuperar o SQL que serï¿œ executado na listagem.
+     * 
+     * @return unknown_type
+     */
+    public function getSQL() {  return $this->sql;  }
+     
+    /**
+     * Funï¿œï¿œo para Alterar o Tï¿œtulo da Listagem.
+     * 
+     * @param $titulo
+     * @return unknown_type
+     */
+    public function setTitulo($titulo) {  $this->titulo = $titulo;  }
+    
+    /**
+     * Funï¿œï¿œo para Alterar a forma de Exibiï¿œï¿œo da Listagem
+     * 
+     * @param $exiberesultados
+     * @return unknown_type
+     */
+    public function setExibirResultadosTela($exiberesultados) {  $this->_exiberesultados = $exiberesultados;  }
+    
+    /**
+     * Funï¿œï¿œo para Alterar a exibiï¿œï¿œo de linhas que nï¿œo exibem nenhum resultado, (linhas vazias)
+     * 
+     * @param $exiberesultados
+     * @return unknown_type
+     */
+    public function setExibirLinhasVazias($valor) {  $this->_exibelinhasvazias = $valor;  }
+
+    /**
+     * Funï¿œï¿œo para Alterar o Resultado da SQL executada.
+     * 
+     * @param $dados
+     * @return unknown_type
+     */
+    public function setDados($dados) {
+        $this->dados = &$dados;  
+        if (is_resource($this->dados)) {
+            $this->_isarray = false;
+        } else {
+            $this->_isarray = true;
+        }
+    }
+    
+     
+    /**
+     * Funï¿œï¿œo utilizada para Executar o SQL e Carregar os dados a serem listados.
+     * @param $sql
+     * @return unknown_type
+     */
+    public function carregar($sql) {
+        $parser = new SqlParser($sql);
+        $ret_parser = $parser->verificaSql();
+        
+        if ($ret_parser === false) {
+            $msg = $parser->getErro();
+            $this->adicionarErro($msg,true);
+        }
+        
+        $ret_parser = $parser->verificaCondicoes();
+        if ($ret_parser === false) {
+            $msg = $parser->getErro();
+            $this->adicionarErro($msg,true);
+        }
+        $sql = $parser->getSql();
+        
+        try {
+                $this->setSQL($sql);
+                $res  = pg_query($this->conexao,"begin;");
+                $resu = pg_query($this->conexao,$this->sql);
+                $res  = pg_query($this->conexao,"rollback;");
+                if (!$resu) { throw new Exception($this->sql); }
+                $this->setDados($resu);
+                
+                return $resu;
+        
+        } catch (exception $e) {
+             $msg = $e->getMessage();
+             $this->adicionarErro("Erro ao Executar a consulta: $msg",true);
+        }
+        
+    }
+    
+    /**
+     * Funï¿œï¿œo utilizada para Executar o SQL e Carregar os dados a serem listados.
+     * @param $sql
+     * @return unknown_type
+     */
+    public function carregarIDListagem($idlistagem,$previsualizacao = false) {
+
+        $sql = "select 
+                    lstoid,
+                    lstversao,
+                    lstidlistagem,
+                    lstdescricao,
+                    lstnome,
+                    lsttitulo,
+                    lstsql,
+                    lstexibe_header,
+                    lstexibe_totalizadores,
+                    lstexibe_subtotais,
+                    lstexibe_qtdregistros,
+                    lstexibe_checkbox,
+                    lstexibe_csv,
+                    lstexibe_legendatopo,
+                    lstexibe_legendarodape,
+                    lstexibe_titagrupamento,
+                    lstexibe_agrupamento_alfabetico,
+                    lstagrupamento_campo,
+                    lstagrupamento_titulo,
+                    lstmsg_totalizador,
+                    lstmsg_subtotalizador,
+                    lstmsg_registrosencontrados,
+                    lstmsg_nenhumresultado,
+                    lstexclusao,
+                    lstexibe_resultados
+                from 
+                    listagem.listagem 
+                where lstidlistagem = '$idlistagem'";
+        $resu = pg_query($this->conexao,$sql);
+        
+        $this->setIdListagem($idlistagem);
+        
+        $arquivo = $_SERVER['PHP_SELF'];
+        
+        if (stristr($arquivo,"cad_listagem.php")) {
+           $arquivo = "null";
+        }
+
+        if (pg_num_rows($resu)) {
+            $dados = pg_fetch_object($resu);
+            
+            $lstexclusao = $dados->lstexclusao;
+            
+            if (($lstexclusao) && ($arquivo != "null")) {
+            	$this->_debug = true;
+                $this->adicionarErro("Esta Consulta estï¿œ inativada, contate o suporte tï¿œcnico de sistemas.",true);
+            }
+            
+            $lstoid = $dados->lstoid;
+            $this->_lstoid = $lstoid;
+            
+             
+        /*    if ($arquivo != "null") {
+                $sql = "select lsdoid from listagem_dependencia where lsdlstoid = '$lstoid' and lsdarquivo ilike '%$arquivo%'";
+                $res_dependencia = pg_query($this->conexao,$sql);
+                $qtd_dependencia = pg_num_rows($res_dependencia);
+                
+                
+                if ($qtd_dependencia == 0) {
+                	$sql = "insert into listagem_dependencia (lsdlstoid,lsdarquivo,lsdacesso) values ($lstoid,'$arquivo',now())";
+                    $atualiza_dependencia = pg_query($this->conexao,$sql);
+                } else {
+                    $listagem_dependencia = pg_fetch_object($res_dependencia);
+                    $lsdoid = $listagem_dependencia->lsdoid;
+                	$sql = "update listagem_dependencia set lsdacesso = now() where lsdoid = $lsdoid";
+                    $atualiza_dependencia = pg_query($this->conexao,$sql);
+                }
+            }
+            */
+            
+            
+            $sql = html_entity_decode( $dados->lstsql, ENT_QUOTES);
+            
+            $this->sql = $sql;
+            
+           // if ($previsualizacao) { $addsql = " limit 20"; }
+
+            $sql_par = "select 
+                            lspoid,
+                            lsplstoid,
+                            lspidparametro,
+                            lsptipo,
+                            lspvalor_padrao,
+                            lspobrigatorio 
+                        from 
+                            listagem.listagem_parametro 
+                        where 
+                            lsplstoid = $lstoid ";
+            $resu_par = pg_query($this->conexao,$sql_par);
+            
+            while ($parametro = pg_fetch_object($resu_par)) {
+                $idparametro = $parametro->lspidparametro;
+                $tipo = $parametro->lsptipo;
+                //$valor = $parametro->lspvalor;
+                $valor = "";
+                $obrigatorio = $parametro->lspobrigatorio;
+                $valor_padrao = $parametro->lspvalor_padrao;
+                
+                $this->adicionarParametro($idparametro,$tipo,$obrigatorio,$valor,$valor_padrao);
+                
+                if ($previsualizacao) {
+                	$this->setParametro($idparametro,$valor_padrao);
+                }
+            }
+            
+            $sql_par = "select 
+                            lsioid,
+                            lsilstoid,
+                            lsiidindicador,
+                            lsitipo,
+                            lsiimagem,
+                            lsilegenda,
+                            lsilegenda_csv,
+                            lsicondicao 
+                        from 
+                            listagem.listagem_indicador 
+                        where lsilstoid = $lstoid ";
+            $resu_par = pg_query($this->conexao,$sql_par);
+            
+            while ($indicador = pg_fetch_object($resu_par)) {
+                $idindicador = $indicador->lsiidindicador;
+                $tipo        = $indicador->lsitipo;
+                $imagem      = $indicador->lsiimagem;
+                $condicao    = html_entity_decode($indicador->lsicondicao, ENT_QUOTES);
+                $legenda_csv = html_entity_decode($indicador->lsilegenda_csv, ENT_QUOTES);
+                $legenda     = html_entity_decode($indicador->lsilegenda, ENT_QUOTES);
+                
+                
+                if ($legenda_csv == "") { 
+                	$legenda_csv = $legenda;
+                }
+                $this->adicionarIndicador($idindicador,$condicao,$tipo,$imagem,$legenda,$legenda_csv);
+            }
+            
+            
+            $this->setTitulo($dados->lsttitulo);   
+            $this->setMensagemTotalizador($dados->lstmsg_totalizador);
+            $this->setMensagemRegistrosEncontrados($dados->lstmsg_registrosencontrados);           	
+            $this->setMensagemSubTotalizador($dados->lstmsg_subtotalizador);
+            $this->setMensagemNenhumResultado($dados->lstmsg_nenhumresultado);
+            
+            if ($dados->lstagrupamento_campo != "") {
+                if ($dados->lstagrupamento_titulo == "") {
+                	$lstagrupamento_titulo = "{" . $dados->lstagrupamento_campo . "}";
+                } else {
+                	$lstagrupamento_titulo = $dados->lstagrupamento_titulo;
+                }
+                if ($dados->lstexibe_titagrupamento == "t") {
+                    $lstexibe_titagrupamento = true;
+                } else {
+                    $lstexibe_titagrupamento = false;
+                }
+                
+                
+                if ($dados->lstexibe_agrupamento_alfabetico == "t") {
+                	$lstexibe_agrupamento_alfabetico = true;
+                } else {
+                	$lstexibe_agrupamento_alfabetico = false;
+                }
+            	$this->setAgrupamento("{" . $dados->lstagrupamento_campo . "}",$lstagrupamento_titulo,$lstexibe_titagrupamento);
+                $this->setAgruparAlfabeticamente($lstexibe_agrupamento_alfabetico);
+            }
+            
+            if ($dados->lstexibe_csv == "f") {
+                $lstexibe_csv = false;
+            } else {
+                $lstexibe_csv = true;
+            }
+            if ($dados->lstexibe_resultados == "f") {
+                $lstexibe_resultados = false;
+            } else {
+                $lstexibe_resultados = true;
+            }
+            if ($dados->lstexibe_totalizadores == "f") {
+            	$lstexibe_totalizadores = false;
+            } else {
+            	$lstexibe_totalizadores = true;
+            }
+            if ($dados->lstexibe_subtotais == "f") {
+                $lstexibe_subtotais = false;
+            } else {
+                $lstexibe_subtotais = true;
+            }
+            if ($dados->lstexibe_header == "f") { 
+            	$showthead = false;
+            } else {
+            	$showthead = true;
+            }
+            if ($dados->lstexibe_qtdregistros == "f") {
+            	$lstexibe_qtdregistros = false;
+            } else {
+            	$lstexibe_qtdregistros = true;
+            }
+            if ($dados->lstexibe_legendatopo == "f") {
+                $lstexibe_legendatopo = false;
+            } else {
+                $lstexibe_legendatopo = true;
+            }
+            if ($dados->lstexibe_checkbox == "f") {
+                $lstexibe_checkbox = false;
+            } else {
+                $lstexibe_checkbox = true;
+            }
+            if ($dados->lstexibe_legendarodape == "f") {
+                $lstexibe_legendarodape = false;
+            } else {
+                $lstexibe_legendarodape = true;
+            }
+            $this->_exibearquivocsv = $lstexibe_csv;
+            $this->_mostraLegendaTopo = $lstexibe_legendatopo;
+            $this->_mostraLegendaRodape = $lstexibe_legendarodape;
+            $this->exibesubtotais = $lstexibe_subtotais;
+            $this->_exibeqtdregistros = $lstexibe_qtdregistros;
+            $this->showthead = $showthead;
+            $this->_exibetotalizadores = $lstexibe_totalizadores;
+            $this->_exiberesultados = $lstexibe_resultados;
+            
+            
+            
+            $sql_colunas = "select 
+                                lslcoid,
+                                lslclstoid,
+                                lslcidcoluna,
+                                lslcordem,
+                                lslctipo,
+                                lslctitulo,
+                                lslchtml,
+                                lslcalign,
+                                lslcwidth,
+                                lslcnowrap,
+                                lslcvisivel,
+                                lslcexibe_csv,
+                                lslccalculada,
+                                lslccheckbox,
+                                lslclink,
+                                lslclink_condicao,
+                                lslclink_blank,
+                                lslctotalizador_condicao,
+                                lslcsubtotalizador_condicao,
+                                lslccheckbox_condicao
+                            from 
+                                listagem.listagem_coluna 
+                            where 
+                                lslclstoid = $lstoid 
+                            order by lslcordem";
+            $resu_colunas = pg_query($this->conexao,$sql_colunas);
+            
+            while ($coluna = pg_fetch_object($resu_colunas)) {
+               // print_r($coluna);
+                $idcoluna = $coluna->lslcidcoluna;
+                $tipo = $coluna->lslctipo;
+                $titulo = $coluna->lslctitulo;
+                $html = $coluna->lslchtml;
+                $align = $coluna->lslcalign;
+                $width = $coluna->lslcwidth;
+                $condicao_totalizador = $coluna->lslctotalizador_condicao;
+                $condicao_subtotalizador = $coluna->lslcsubtotalizador_condicao;
+                $link = $coluna->lslclink;
+                $link_condicao = $coluna->lslclink_condicao;
+                
+                $idcoluna       =  html_entity_decode($idcoluna, ENT_QUOTES);
+                $titulo         =  html_entity_decode($titulo, ENT_QUOTES);
+                $html           =  html_entity_decode($html, ENT_QUOTES);
+                $link           =  html_entity_decode($link, ENT_QUOTES);
+                $link_condicao  =  html_entity_decode($link_condicao, ENT_QUOTES);
+               
+                if ($coluna->lslccalculada == "t") {
+                    $lslccalculada = true;
+                } else {
+                    $lslccalculada = false;
+                }
+                if ($coluna->lslccheckbox == "t") {
+                    $lslccheckbox = true;
+                } else {
+                    $lslccheckbox = false;
+                }
+                if ($coluna->lslcnowrap == "t") {
+                    $lslcnowrap = true;
+                } else {
+                    $lslcnowrap = false;
+                }
+                if ($coluna->lslcvisivel == "t") {
+                    $lslcvisivel = true;
+                } else {
+                    $lslcvisivel = false;
+                }
+                if ($coluna->lslclink_blank == "t") {
+                    $lslclink_blank = true;
+                } else {
+                    $lslclink_blank = false;
+                }
+                
+                if ($coluna->lslcexibe_csv == "t") {
+                    $lslcexibe_csv = true;
+                } else {
+                    $lslcexibe_csv = false;
+                }
+                
+                if ($lslcexibe_csv) {
+                	$this->_colunascsv .= "$idcoluna,"; 
+                }
+                
+                
+                if (($tipo == "text") || ($tipo == "data") || ($tipo == "hora") || ($tipo == "int") || ($tipo == "moeda")) {
+                    
+                    if (($tipo == "int") && ($lslccheckbox)) {
+                        if ($lstexibe_checkbox) {
+                            $this->adicionarColunaCheckBox($idcoluna,$titulo,$html,$coluna->lslccheckbox_condicao);
+                        }
+                    } else {
+                        //echo "idcoluna: $idcoluna -> $lslcnowrap";
+                        $this->adicionarColuna($idcoluna,$titulo,$html,$tipo,$align,$width,$lslcnowrap,$lslcvisivel);                    	
+                    }
+                           
+                    if ($link != "") {
+                    	$this->adicionarLink($idcoluna,$link,$link_condicao,$lslclink_blank);
+                    }
+                       
+                    if ($lslccalculada) {
+                    	$this->adicionarTotalizador($idcoluna,$condicao_totalizador,$condicao_subtotalizador);
+                    }
+                }
+            }
+            
+        } else {
+        	$this->_debug = true;
+            $this->adicionarErro("Listagem nï¿œo encontrada.");
+        }
+            
+
+    }
+
+    public function getQuantidadeRegistros() {
+        if ($this->_isarray) {
+          $ret = count($this->dados);
+        } else {
+           if (count($this->dados)) {
+                $ret = pg_num_rows($this->dados);
+           } else {
+                $ret = 0;
+           }
+        }
+    //    if ($this->issublist) {
+            if (is_object($this->subListagem)) { 
+                $ret = $ret + $this->subListagem->getQuantidadeRegistros();
+            }
+      //  }
+        return $ret;
+    }
+
+    /**
+     * Funï¿œï¿œo para Alterar a Mensagem de Registros Encontrados.
+     * 
+     * @param $msg
+     */
+    public function setMensagemRegistrosEncontrados($msg) { $this->msgregistros = $msg; }
+    
+    /**
+     * Funï¿œï¿œo para Alterar a Mensagem de Total de Registros Encontrados.
+     * 
+     * @param $msg
+     */
+    public function setMensagemTotalizador($msg) { $this->msgtotalizador = $msg; }
+    
+    /**
+     * Funï¿œï¿œo para Alterar a Mensagem de Sub-Total de Registros Encontrados
+     * 
+     * @param $msg
+     */
+    public function setMensagemSubTotalizador($msg) { $this->msgsubtotalizador = $msg; }
+     
+    /**
+     * Funï¿œï¿œo para Alterar a Mensagem de "Nenhum Resultado Encontrado".
+     * 
+     * @param $msg
+     */
+    public function setMensagemNenhumResultado($msg) { $this->msgnenhumresultado = $msg; }
+
+	/**
+	 * Funï¿œï¿œo que Indica se a Listagem ï¿œ Agrupada Alfabeticamente
+	 * 
+	 * @param value (true ou false)
+	 */
+    public function setAgruparAlfabeticamente($value) {
+        $this->agruparAlfabeticamente = $value;
+    }
+    
+    /**
+     * Funï¿œï¿œo para Alterar a Opï¿œï¿œo de Exibir os Sub-Totais de uma Listagem.
+     * 
+     * @param $value (true ou false)
+     */
+    public function setMostrarSubTotais($value) {
+        $this->exibesubtotais = $value;
+    }
+    
+    public function setMostrarTotal($value) {
+        $this->_exibetotalizadores = $value;
+    }
+    
+    public function setMostrarLegendaTopo($value) {
+        $this->_mostraLegendaTopo = $value;
+    }
+    
+    public function setMostrarLegendaRodape($value) {
+        $this->_mostraLegendaRodape = $value;
+    }
+    
+    
+    /**
+     * Funï¿œï¿œo para Alterar a Opï¿œï¿œo de Exibir a Quantidade de Registros Retornados da Listagem.
+     * 
+     * @param $exibir (true ou false)
+     */
+    public function setMostrarQuantidadeRegistros($exibir) {
+        $this->_exibeqtdregistros = $exibir;
+    }
+
+    /**
+     * Funï¿œï¿œo para adicionar uma Coluna na Listagem.
+     * 
+     * @param $idcoluna
+     * @param $tipo
+     * @param $titulo
+     * @param $html
+     * @param $width
+     * @param $nowrap
+     * @param $valign
+     * @param $visivel
+     * @return unknown_type
+     */
+    function adicionarColuna($idcoluna,$titulo,$html,$tipo = "text",$align = "",$width = "",$nowrap = false,$visivel = true) {
+        $erro = false;
+        if ($this->isColuna($idcoluna)) {
+        	$erro = true;
+        	$this->adicionarErro("addColuna()<br>$idcoluna jï¿œ foi adicionada na Listagem.");
+        }
+        if (!$erro) {
+	        $coluna = new ListagemColuna($idcoluna,$tipo,$titulo,$html,$width,$nowrap,$align);
+	        $coluna->setVisibilidade($visivel);
+	        $coluna->setIdListagem($this->idlistagem);
+	        array_push($this->colunas,$coluna);
+        }
+    }
+    
+    function adicionarColunaCalculada($idcoluna,$tipo,$html,$condicao_total = "1",$condicao_subtotal = "1") {
+    	$erro = false;
+        if ($this->isColuna($idcoluna)) {
+        	$erro = true;
+        	$this->adicionarErro("addColuna()<br>$idcoluna jï¿œ foi adicionada na Listagem.");
+        }
+        if (!$erro) {
+    		$this->adicionarColuna($idcoluna,$tipo,$idcoluna,$html,"",true,"",false);
+    		$this->adicionarTotalizador($idcoluna,$condicao_total,$condicao_subtotal);
+        }
+    }
+    
+    function adicionarLinhaDetalhamento($idlinha,$tipo,$html,$align = "left") {
+        $width = "";
+        $nowrap = false;
+        $valign = $align;
+        $coluna = new ListagemColuna($idlinha,$tipo,"",$html,$width,$nowrap,$valign);
+        array_push($this->linhasdetalhamento,$coluna);
+    }
+     
+    /**
+     * Funï¿œï¿œo para Adicionar uma Coluna com CheckBoxes.
+     * 
+     * @param $idcoluna
+     * @param $titulo
+     * @param $html
+     * @param $condicao
+     * @param $width
+     * @param $nowrap
+     * @param $valign
+     * @return unknown_type
+     */
+    function adicionarColunaCheckBox($idcoluna,$titulo,$value,$condicao = "",$width = "1%",$nowrap = false,$valign = "center") {
+        $tipo = "check";
+        $html = "{" . $value . "}";
+        $coluna = new ListagemColuna($idcoluna,$tipo,$titulo,$html,$width,$nowrap,$valign);
+        $coluna->setCondicao($condicao);
+        $coluna->setIdListagem($this->idlistagem);
+        array_push($this->colunas,$coluna);
+    }
+     
+    /**
+     * Funï¿œï¿œo utilizada Internamente para verificar se o idcoluna passado jï¿œ foi adicionado a listagem.
+     * 
+     * @param $idcoluna
+     * @return unknown_type
+     */
+    protected function isColuna($idcoluna) {
+        $ret = false;
+        foreach ($this->colunas as $i => $col) {
+            if ($col->getIdColuna() == $idcoluna) {
+                $ret = true;
+            }
+        }
+        return $ret;
+    }
+     
+    /**
+     * Adiciona um Link para uma ou mais Colunas.
+     * 
+     * @param $idcolunas (Ids das colunas separados por vï¿œrgula)
+     * @param $link Link para ser redirecionado.
+     * @param $target
+     * @return unknown_type
+     */
+    public function adicionarLink($idcolunas,$link,$condicao = "1",$targetblank = false,$popup = false) {
+        $colunas = explode(",",$idcolunas);
+        foreach ($colunas as $idcoluna) {
+            $erro = false;
+            if (!$this->isColuna($idcoluna)) {
+                $this->adicionarErro("addLink()<br>$idcoluna nï¿œo ï¿œ uma coluna adicionada na Listagem.",false);
+                $erro = true;
+            }
+            if (!$erro) {
+                foreach ($this->colunas as $i => $col) {
+                    if ($col->getIdColuna() == $idcoluna) {
+                        $this->colunas[$i]->setLink($link,$condicao,$targetblank,$popup);
+                    }
+                }
+            }
+        }
+    }
+    
+    public function RemoverColuna($idcolunas){
+    	$colunas = explode(",",$idcolunas);
+        foreach ($colunas as $idcoluna) {
+            $erro = false;
+            if (!$this->isColuna($idcoluna)) {
+                $this->adicionarErro("addColunaCor()<br>$idcoluna nï¿œo ï¿œ uma coluna adicionada na Listagem.",false);
+                $erro = true;
+            }
+            if (!$erro) {
+                foreach ($this->colunas as $i => $col) {
+                    if ($col->getIdColuna() == $idcoluna) {
+                        unset($this->colunas[$i]);
+                    }
+                }
+            }
+        }
+    }
+    
+    
+    public function adicionarCor($idcolunas,$cor,$condicao = "1") {
+        $colunas = explode(",",$idcolunas);
+        $cor = str_replace("#","",$cor);
+        foreach ($colunas as $idcoluna) {
+            $erro = false;
+            if (!$this->isColuna($idcoluna)) {
+                $this->adicionarErro("addColunaCor()<br>$idcoluna nï¿œo ï¿œ uma coluna adicionada na Listagem.",false);
+                $erro = true;
+            }
+            if (!$erro) {
+                foreach ($this->colunas as $i => $col) {
+                    if ($col->getIdColuna() == $idcoluna) {
+                        $this->colunas[$i]->setCor($cor,$condicao);
+                    }
+                }
+            }
+        }
+    }
+     
+    /**
+     * Funï¿œï¿œo para Adicionar um Indicador (Legenda).
+     * 
+     * @param $idindicador Cï¿œdigo Interno de Identificaï¿œï¿œo do Identificador
+     * @param $condicao Condiï¿œï¿œo em PHP para Exibir o Indicador.
+     * @param $tipo R,Q,T (REDONDO,QUADRADO,TRIANGULO)
+     * @param $codigoimagem (1 a 19). 
+     * @param $legenda Legenda
+     * @return unknown_type
+     */
+    function adicionarIndicador($idindicador,$condicao,$tipo = "R",$codigoimagem = "1",$legenda = "",$tamanho = "1") {
+        $Indicador = new ListagemIndicador($idindicador,$condicao,$tipo,$codigoimagem,$legenda,$tamanho);
+        $Indicador->setUrlBasePath($this->_url_base_path);
+        if (!isset($this->arrindicadores[$idindicador])) { $this->arrindicadores[$idindicador] = array(); }
+        array_push($this->arrindicadores[$idindicador],$Indicador);
+    }
+     
+    /**
+     * Funï¿œï¿œo para Desenhar a Listagem.
+     * 
+     * @return HTML
+     */
+    function desenhar() {
+        $html = "";
+        $this->incluiCssJavaScript($this->_url_base_path);
+        if ($this->_lstoid != "") {
+            $this->formataSQLParametros();
+            $sql = $this->getSQL();
+            $sql =  html_entity_decode($sql, ENT_QUOTES);
+            $this->carregar($sql);
+           
+        }
+        
+        if ($this->_exibearquivocsv) {
+            	$this->gerarArquivoXLS($this->_colunascsv);
+        }
+        $this->escreveErros();
+        $this->escreveAbreList();
+        $this->escreveLinhas();
+        $this->escreveFechaList();
+    }
+    
+    function incluiCssJavascript($addpath = "") {
+    	echo "\n\n<script language=\"Javascript\" type=\"text/javascript\" src=\"$addpath/includes/js/mascaras.js\"></script>\n
+<script language=\"Javascript\" type=\"text/javascript\" src=\"$addpath/includes/js/validacoes.js\"></script>\n
+<script language=\"Javascript\" type=\"text/javascript\" src=\"$addpath/includes/js/auxiliares.js\"></script>\n
+<script language=\"Javascript\" type=\"text/javascript\" src=\"$addpath/includes/js/calendar.js\"></script>\n
+<script language=\"Javascript\" type=\"text/javascript\" src=\"$addpath/includes/js/FormularioUtil.js\"></script>\n
+<link rel=\"stylesheet\" href=\"$addpath/includes/css/base_form.css\" media=\"screen\"></link>\n
+<link rel=\"stylesheet\" href=\"$addpath/includes/css/calendar.css\" media=\"screen\"></link>\n\n";
+    	
+    }
+    
+    protected function escreveLegenda() {
+        if ($this->_exiberesultados) {
+        	if (count($this->arrindicadores)) {
+                $colspan=0;
+                
+                echo  "\n\t<table width='100%' class='TableMoldura''>
+       	 			   \n\t\t<tr class='tableSubTitulo'>
+    	               \n\t\t\t<td><h3>Legenda</h3></td>
+    	               \n\t\t</tr>";
+                echo "<tr><td align=left colspan='$colspan'>";
+                foreach ($this->arrindicadores as $idindicador => $indicadores) {
+                    $exibelinha = false;
+                    foreach ($indicadores as $indicador) {
+                         if ($indicador->getLegenda() != "") {
+                            $exibelinha = true;
+                         }
+                    }
+                    if ($exibelinha) {
+                        echo "<br>&nbsp;&nbsp;";
+                        $addlegenda = "";
+                        foreach ($indicadores as $indicador) {
+                            if ($indicador->getLegenda() != "") {
+                                $addlegenda .= str_replace("{indicador_substituirpasta}","",$indicador->getHtml()) . " " . $indicador->getLegenda() . " | ";
+                            }
+                        }
+                        $addlegenda = substr($addlegenda,0,strlen($addlegenda) - 3);
+                        echo $addlegenda;
+                        echo "<br>";
+                    }
+                }
+                echo "<br></td></tr></table>";
+            }
+        }
+    }
+     
+    /**
+     * Funï¿œï¿œo que desenha o cabeï¿œalho da Listagem.
+     *  
+     * @return HTML
+     */
+    protected function escreveAbreList() {
+        $colspan = count($this->colunas);
+        
+        $htmldivs = "";
+        $html_icone = "";
+        
+        if (!$this->issublist) {
+        	if ($this->_mostraLegendaTopo) {
+        		$this->escreveLegenda();
+        	}
+            $addclass= " class='TableMoldura'";
+
+            if ($this->_exiberesultados) {
+            	
+            	if ($this->exibedivcolunas) {
+                $html_icone = '<b>[<img id="'. $this->idlistagem . '_img_visivel" src="' . $this->_url_base_path . '/images/icones/maisTransparente.gif" OnClick="ListagemShowHide(event,\''. $this->idlistagem . '\',\''. $this->idlistagem . '_img_visivel\');" OnMouseOver="this.style.cursor=\'pointer\';" OnMouseOut="this.style.cursor=\'default\';">]</b>';
+                $html_icone_2 = '<b>[<img id="'. $this->idlistagem . '_img_visivel_2" src="' . $this->_url_base_path . '/images/icones/menosTransparente.gif" OnClick="ListagemShowHide(event,\''. $this->idlistagem . '\',\''. $this->idlistagem . '_img_visivel\');" OnMouseOver="this.style.cursor=\'pointer\';" OnMouseOut="this.style.cursor=\'default\';">]</b>';
+
+               // $html_icone .= '&nbsp;&nbsp;<b>[<img id="'. $this->idlistagem . '_img_grafico_visivel" src="images/icones/t1/fileGrafico.jpg" OnClick="ListagemShowHide(event,\''. $this->idlistagem . '\',\''. $this->idlistagem . '_img_grafico_visivel\');" OnMouseOver="this.style.cursor=\'pointer\';" OnMouseOut="this.style.cursor=\'default\';">]</b>';
+                                
+                $cnt = 0;
+                $htmlchecks = "";
+                
+                foreach ($this->colunas as $coluna) {
+                	$titulo = $coluna->getNome();
+                    $idcoluna = $coluna->getIdColuna();
+                    $idlistagem = $this->idlistagem;
+                    $visivel = $coluna->getVisibilidade();
+                    $addvisivel = "";
+                    if ($visivel) { $addvisivel = "checked"; }
+                    
+                    $adddisabled = "";
+                    if ($cnt == 0) { $adddisabled = " disabled"; $cnt = $cnt + 1; }
+                    
+                    $htmlchecks .= '<input type="checkbox" class="checkbox" name="' . $idlistagem . '_ck_visivel_' . $idcoluna . '" id="' . $idlistagem . '_ck_visivel_' . $idcoluna . '" OnClick=" document.getElementById(\'' . $idlistagem . '_div_visivel\').style.display = \'none\'; document.getElementById(\'' . $idlistagem . '_div_visivel_load\').style.display = \'\'; alinhaDivDir(\'' .$idlistagem. '_div_visivel_load\'); setTimeout(\'ListagemExibeOcultaColuna(\\\'' . $idlistagem. '\\\',\\\'' .$idcoluna . '\\\');\')" value="' .$idcoluna . '" ' . $addvisivel .$adddisabled . '> ' . $titulo . '<br>';
+                    
+                }
+                
+
+                $htmldivs = '<div id="' . $idlistagem. '_div_visivel" class="div_visivel" style="display:none;">  
+                                    <table width="100%">          
+                                        <tr>
+                                            <td align="right">' .$html_icone_2. '</td>
+                                        </tr>
+                                        <tr>
+                                            <td style="padding-left:5px;">'
+.$htmlchecks . 
+'
+
+                                            </td>
+                                        </tr>
+                                    </table>
+                                </div>
+                                <div id="' . $idlistagem. '_div_visivel_load" class="div_visivel" style="display:none;">
+                                    <table width="100%">
+                                        <tr>
+                                            <td style="padding-left:5px;">
+                                                <img src="images/progress4.gif"></img> Carregando...
+                                            </td>
+                                        </tr>
+                                    </table>
+                                </div>';
+            
+                   }
+            	}
+        
+            
+        }
+ 
+        echo  "\n\t$htmldivs<table id='Listagem_" . $this->getIdListagem() . "' width='100%'$addclass>
+	             \n\t\t<tr class='tableSubTitulo'>
+	             \n\t\t\t<td  colspan='$colspan'><div style='float: right;'>$html_icone&nbsp;&nbsp;</div><h3>"  . $this->titulo . "</h3></td>
+	             \n\t\t</tr>";
+    }
+    
+    /**
+     * Funï¿œï¿œo que desenha o HTML que fecha a listagem.
+     * 
+     * @return HTML
+     */
+    protected function escreveFechaList() {
+        echo  "\n\t</table>";
+        
+        if (!$this->issublist) {
+        	if ($this->_mostraLegendaRodape) {
+        		$this->escreveLegenda();
+        	}
+        }
+    }
+    
+    public function setAgrupamento($idagrupamento,$titulo = "",$repetirtitulo = false) {
+        $width = "";
+        $nowrap = false;
+        $align = "left";
+      	//$html = "{" . $idagrupamento .  "}";
+      	$html = $idagrupamento;
+        if ($titulo == "") { 
+        	$titulo = "{" . $idagrupamento . "}";
+        	$repetirtitulo = true;
+        }
+        $this->_repetirtituloagrupamento = $repetirtitulo;
+        $tipo = "";
+        $coluna = new ListagemColuna($idagrupamento,$tipo,$titulo,$html,$width,$nowrap,$align);
+        $this->linhasagrupamento = array();
+        array_push($this->linhasagrupamento,$coluna);
+    }
+    
+    public function setParametro($idparametro,$valor) {
+    	foreach ($this->arrparametros as $k => $parametro) {
+    		if ($parametro['idparametro'] == $idparametro) {
+                $this->arrparametros[$k]["valor"] = $valor;
+            }
+    	}
+    }
+    
+    public function adicionarParametro($idparametro,$tipo,$obrigatorio = false,$valor = "",$valortestes = "") {
+        $parametros = array();
+        $parametros["idparametro"] = $idparametro;
+        $parametros["tipo"] = $tipo;
+        $parametros["valor"] = $valor;
+        $parametros["obrigatorio"] = $obrigatorio;
+        $parametros["valor_testes"] = $valortestes;
+        
+        if ($this->_debug) {
+        	if (($tipo != "text") && ($tipo != "int") && ($tipo != "data")) {
+        		$this->adicionarErro("Parï¿œmetro '$idparametro' do tipo '$tipo' nï¿œo ï¿œ vï¿œlido.");
+                return false;
+        	}
+        }
+        
+        if (!$this->isParametro($idparametro)) {
+            array_push($this->arrparametros,$parametros);
+        } else {
+            if ($this->_debug) {
+        	   $this->adicionarErro("Parï¿œmetro '$idparametro' jï¿œ estï¿œ adicionado a Listagem.");
+            }
+        }
+    }
+    
+    public function getSQLParametros() {
+        $sql = $this->sql;
+        $sqlparametros = array();
+        $abre_chaves = explode("{",$sql);
+        foreach ($abre_chaves as $chave) {
+            $_chaves = array();
+            if (stristr($chave,"}")) {
+                $_chaves = explode("}",$chave);
+                $sqlparametros[] = $_chaves[0];
+            }
+        }
+        return $sqlparametros;
+    }
+    
+    protected function formataSQLParametros() {
+        $sql = $this->sql;
+        
+        $parametrosconsulta = $this->getSQLParametros();
+        
+        foreach ($parametrosconsulta as $parametro_consulta) {
+            $achou = false;
+            $achou_consulta = false;
+            foreach ($this->arrparametros as $parametro_base) {
+                if ($parametro_base["idparametro"] == $parametro_consulta) {
+                	$achou = true;
+                }
+                if (in_array($parametro_base["idparametro"],$parametrosconsulta)) {
+                    $par_base = $parametro_base["idparametro"];
+                	$achou_consulta = true;
+                }
+            }
+            if (!$achou) {
+            	$this->_debug=true;
+                $this->adicionarErro("Parï¿œmetro '$parametro_consulta' usado na consulta nï¿œo foi adicionado no cadastro.",true);
+            }
+            if (!$achou_consulta) {
+                $this->_debug=true;
+                $this->adicionarErro("Parï¿œmetro '$par_base' cadastrado nï¿œo ï¿œ usado na consulta.",true);
+            }
+        }
+        
+        
+    	foreach ($this->arrparametros as $parametro) {
+            $idparametro = $parametro["idparametro"];
+            $valor = $parametro["valor"];
+            $obrigatorio = $parametro["obrigatorio"];
+            if (($obrigatorio == "t") && ($valor == "")) { 
+                $this->_debug=true;
+            	$this->adicionarErro("Parï¿œmetro '$idparametro ' ï¿œ obrigatï¿œrio.",true);
+            }
+            if (($parametro["tipo"] == "data") || ($parametro["tipo"] == "text")) {
+            	$valor = "'" . $valor . "'";
+            }
+            if (($obrigatorio == "f") && ($parametro["valor"] == "")) {
+                $valor = "null";
+            }
+    		$sql = str_replace("{" . $idparametro. "}",$valor,$sql);
+    	}
+        $this->sql = $sql;
+    }
+    
+    protected function isParametro($idparametro) {
+    	$ret = false;
+        foreach ($this->arrparametros as $parametro) {
+            if ($parametro['idparametro'] == $idparametro) {
+                $ret = true;
+            }
+        }
+        return $ret;
+    }
+    
+    protected function isTotalizador($idcoluna) {
+        $ret = false;
+        foreach ($this->totalizadores as $totalizador) {
+            if ($totalizador['idcoluna'] == $idcoluna) {
+                $ret = true;
+            }
+        }
+        return $ret;
+    }
+    
+    function adicionarTotalizador($idcolunas,$condicaototal = "1",$condicaosubtotal = "1") {
+        
+        $colunas = explode(",",$idcolunas);
+        foreach ($colunas as $idcoluna) {
+            $erro = false;
+            if (!$this->isColuna($idcoluna)) {
+                $this->adicionarErro("adicionarTotalizador()<br>$idcoluna nï¿œo ï¿œ uma coluna adicionada na Listagem.",false);
+                $erro = true;
+            }
+            if (!$erro) {
+                
+                $totalizador = array();
+                $totalizador["idcoluna"] = $idcoluna;
+                $totalizador["condicaototal"] = $condicaototal;
+                $totalizador["condicaosubtotal"] = $condicaosubtotal;
+                $this->totalizadores[$idcoluna] = $totalizador;
+                
+            }
+        }
+        
+    }
+    
+    protected function escreveArquivo($arquivo) {
+        if ($this->_temarquivocsv) {
+        	fwrite($arquivo, $this->_txtarquivo);
+            $this->_txtarquivo = "";
+        }
+    }
+    
+     
+    /**
+     * Funï¿œï¿œo para desenhar as Linhas da Listagem.
+     * 
+     * @return HTML
+     */
+    protected function escreveLinhas() {
+        $html = "";
+        $colspan = count($this->colunas);
+        $idtd = 0;
+        $handle = "";
+        //$nomeform = $this->formpesquisa->getNome();
+        
+        if ($this->_temarquivocsv) {
+            if (!$this->issublist) {
+                $tmpfname = $this->_tmp_file_path . "Listagem_" . $this->idlistagem . "_" . time() . ".csv";
+                $handle = fopen($tmpfname, "a+");
+            }
+        }
+        
+        if ($this->showthead) {
+            if ($this->_exiberesultados) {
+                echo  "\n\t\t<tr class='tableTituloColunas'>";
+                foreach ($this->colunas as $col) {
+                    $fwidth = $col->getWidth(true);
+                    $addvisivel = "";
+                    if (!$col->getVisibilidade()) {
+                        $addvisivel = " style='display: none;' ";
+                    }
+                   // if ($col->getVisibilidade()) {
+                    	echo  "\n\t\t\t<td id='td_tit_" . $col->getIdColuna() . "' $fwidth align='center'$addvisivel><h3>". $col->getNome() . "</h3></td>";
+                   // }
+                }
+                echo  "\n\t\t</tr>";
+            }
+            if ($this->_temarquivocsv) {
+	            foreach ($this->_colunasarquivo as $idcoluna) {
+		    	   foreach ($this->colunas as $coluna) {
+		    	   	  if ($coluna->getIdColuna() == $idcoluna) {
+		    	   	  	$this->_txtarquivo .= '"' . $coluna->getNome() . '"' . ";";
+		    	   	  }
+		    	   }
+		    	}
+		    	$this->_txtarquivo .= "\n";
+                $this->escreveArquivo($handle);
+                
+            }
+        }
+
+        if (!$this->issublist) {
+            $cnt = 0;
+            $this->subListagem->setQuantidadeRegistrosListagemPrincipal($this->getQuantidadeRegistros());
+        } else {
+            $cnt = $this->getQuantidadeRegistrosListagemPrincipal();
+        }
+        $temcheck = false;
+        if (count($this->dados)) {
+
+            $arrtotais = array();
+            $arrsubtotais = array();
+            $arrsubtotais_todos = array();
+            $lastagrupamento = "";
+            $cntagrupamentos = 0;
+            $arragrupamentos = array();
+            $newagrupamento = "";
+
+            $mostroutituloagrupamento = false;
+
+            if (!$this->_isarray) {
+                pg_result_seek($this->dados, 0);
+            }
+            $class= "";
+            
+            $qtdlinhas = 0;
+            
+            $qtd_registros = $this->getQuantidadeRegistros();
+
+
+            for ($qtd_reg = 1;$qtd_reg <= $qtd_registros; $qtd_reg++) {
+                
+                if ($this->_isarray) {
+                    if ($qtd_reg == 1) {
+                        reset($this->dados); 
+                        $linha = current($this->dados);
+                    } else {
+                        $linha = next($this->dados);
+                    }
+                } else {
+                    $linha = pg_fetch_array($this->dados);
+                }
+            
+                $cnt = $cnt + 1;
+                
+                $qtdlinhas = $qtdlinhas + 1;
+                
+                $class = ( $class == "tdc" ) ? "tde" : "tdc";
+
+                if (count($this->linhasagrupamento)) {
+                    foreach ($this->linhasagrupamento as $coluna) {
+                        $fwidth = $coluna->getWidth(true);
+                        $falign = $coluna->getVAlign(true);
+                        $addnowrap = "";
+                        $align = $coluna->getAlign();
+                        if ($coluna->getNowrap()) { $addnowrap = "nowrap"; }
+                        $htmlcoluna = $coluna->getHtml($linha,$this->arrindicadores,$class,$qtdlinhas - 1);
+                        if ($coluna->getNome() == "") {
+                        	$tituloagrupamento = $htmlcoluna;
+                        } else {
+                        	$tituloagrupamento = $coluna->replaceValorLinha($coluna->getNome(),$linha);
+                        }
+                        
+                        if ($this->agruparAlfabeticamente) {
+                            $tituloagrupamento = strtoupper(substr($tituloagrupamento,0,1));
+                            $newagrupamento = $tituloagrupamento;
+                            $align="center";
+                        } else {
+                        	$newagrupamento = strtoupper($htmlcoluna);
+                        }
+                        
+                        
+                        
+                        //AGRUPAMENTO
+                        $cntcheckspan = 0;
+                        if ($newagrupamento != $lastagrupamento) {
+                            $cntagrupamentos = $cntagrupamentos + 1;
+                            
+                            $arragrupamentos[$cntagrupamentos] = $newagrupamento;
+                            
+                            //TOTALIZADOR SUB-TOTAL DO AGRUPAMENTO.
+                            if ($this->exibesubtotais) {
+                                if (count($this->totalizadores)) {
+                                    if ($cntagrupamentos != 1) {
+                                        if ($this->_exiberesultados) {
+                                            echo   "\n\t\t<tr class='tableRodapeModelo2'>";
+                                        }
+                                        $mostroutotal = false;
+                                        foreach ($this->colunas as $coluna) {
+                                             $idcol = $coluna->getIdColuna();
+                                             if ($this->isTotalizador($coluna->getIdColuna())) {
+                                                 if (!$mostroutotal) { 
+                                                     $addtexto = "<h3>" . $this->msgsubtotalizador . "</h3>"; 
+                                                     $txtarquivotexto = $this->msgsubtotalizador ; 
+                                                     $mostroutotal = true; 
+                                                 } else {
+                                                     $addtexto = "";
+                                                 }
+                                                 if ($cntcheckspan) { 
+                                                   /* for ($j=1; $j< $cntcheckspan; $j++) {
+                                                         echo  "<td id='subtotal_" . $idcol . "_$cntagrupamentos' align='right'>&nbsp;</td>";
+                                                    }*/
+                                                    
+                                                   // echo  "<td id='subtotal_" . $idcol . "_" . $cntagrupamentos . "' align='right'>&nbsp;</td>";
+                                                 	if ($this->_temarquivocsv) {
+	                                                 	for ($j=1; $j<= $cntcheckspan; $j++) {
+	                                                 		if ($j == $cntcheckspan) {
+	                                                 			$this->_txtarquivo .= $txtarquivotexto;
+	                                                 		}
+	                                                 		$this->_txtarquivo .= ";";
+	                                                 	}
+                                                 	} 
+                                                 } 
+                                                 $cntcheckspan = 0;
+                                                 $addvisivel = "";
+                                                 if (!$coluna->getVisibilidade()) {
+                                                     $addvisivel = " style='display: none;' ";
+                                                 }
+                                                 if ($coluna->getTipo() == "hora") {
+                                                      $subtotal_valor = $arrsubtotais[$coluna->getIdColuna()];
+                                                 } else {
+                                                     if ($this->_totalizadorprecisao != 0) {
+                                                         $subtotal_valor = number_format($arrsubtotais[$coluna->getIdColuna()],$this->_totalizadorprecisao,",",".");
+                                                     } else {
+                                                         $subtotal_valor = $arrsubtotais[$coluna->getIdColuna()];
+                                                     }
+                                                 }
+                                                 if ($this->_exiberesultados) {
+                                                    echo  "<td  id='subtotal_" . $idcol . "_$cntagrupamentos' align='right'$addvisivel>$addtexto<h3>" . $subtotal_valor . "</h3>&nbsp;</td>";
+                                                 }
+                                                 $this->_txtarquivo .= $subtotal_valor . ";";
+                                                 $arrsubtotais[$coluna->getIdColuna()] = 0;
+                                                 $arrsubtotais_todos[$cntagrupamentos][$coluna->getIdColuna()] = 0;
+                                             } else {
+                                                 $addvisivel = "";
+                                                 if (!$coluna->getVisibilidade()) {
+                                                    $addvisivel = " style='display: none;' ";
+                                                 }
+                                                 if ($this->_exiberesultados) {
+                                                    echo  "<td id='subtotal_$idcol" . "_" . $cntagrupamentos . "' $addvisivel>&nbsp;</td>";
+                                                 }
+                                             }
+                                        }
+                                       // if ($cntcheckspan) { echo  "<td colspan='$cntcheckspan'>&nbsp;</td>";}
+                                        if ($this->_exiberesultados) {
+                                            echo   "\n\t\t</tr>";
+                                        }
+                                        if ($this->_temarquivocsv) {
+                                        	$this->_txtarquivo .= "\n";
+                                            $this->escreveArquivo($handle);
+                                        }
+                                    }
+                                }
+                            }
+                            
+                            
+                            
+                            if (($this->_repetirtituloagrupamento) || (!$mostroutituloagrupamento)) {
+                                if ($this->_exiberesultados) {
+    	                            echo  "\n\t\t<tr>";
+    	                            echo  "\n\t\t\t<td class='tableSubTitulo' colspan='$colspan' align='$align'><h3>" . $tituloagrupamento . "</h3></td>";
+    	                            echo  "\n\t\t</tr>";
+                                    $class = "tdc";
+                                }
+	                            if ($this->_temarquivocsv) {
+	                            	$this->_txtarquivo .= '"' . $tituloagrupamento . '"' . ";\n";
+	                            }
+	                            $mostroutituloagrupamento = true;
+                            }
+                            
+                        }
+                        
+                    }
+                    
+                }
+                
+                
+                if (count($this->colunas)) {
+                    
+                    $addvisivellinha = "";
+                    if ($this->_exibelinhasvazias == false) {
+                        $exibe_linha = false;
+                        $addvisivellinha = " style='display: none;' ";
+                        foreach ($this->colunas as $coluna) {
+                            $htmlcoluna = $coluna->getHtml($linha,$this->arrindicadores,$class,$idtd);
+                            if (trim($htmlcoluna) != "") {
+                            	$exibe_linha = true;
+                                $addvisivellinha = "";
+                            }
+                        }
+                    }
+                    
+                    //if ($exibe_linha) {
+                        if ($this->_exiberesultados) {
+                            echo  "\n\t\t<tr class='" . $class . "' onmouseout=\"this.className='" . $class . "'\" onmouseover=\"this.className='" . $class . "Over'\" $addvisivellinha>";
+                        }
+                        foreach ($this->colunas as $coluna) {
+                            if ($this->_exiberesultados) {
+                                $fwidth = $coluna->getWidth(true);
+                                $falign = $coluna->getVAlign(true);
+                                $addnowrap = "";
+                                $align = $coluna->getAlign();
+                                if ($coluna->getNowrap()) { $addnowrap = " nowrap"; }
+        
+        						if ($this->issublist) {
+        							$idtd = $cnt -2;
+        						} else {
+        							$idtd = $cnt -1;
+        						}
+                                $htmlcoluna = $coluna->getHtml($linha,$this->arrindicadores,$class,$idtd);
+                                
+                                if (($coluna->getTipo() == "check") && ($htmlcoluna != "")) { $temcheck = true; $this->temcheck = true; }
+                            }
+                            if ($this->isTotalizador($coluna->getIdColuna())) { 
+                                $condicaototal = $this->totalizadores[$coluna->getIdColuna()]["condicaototal"];
+                                $condicaosubtotal = $this->totalizadores[$coluna->getIdColuna()]["condicaosubtotal"];
+                                $htmlvalorcoluna = $coluna->getValorHTML($linha);
+                                if ($condicaototal != "1") { 
+                                    $ret_total = $coluna->validaCondicao($condicaototal,$linha,false);
+                                } else {
+                                    $ret_total = true;
+                                }
+                                
+                                if ($ret_total) {
+                                    $tipo_coluna = $coluna->getTipo();
+                                    if (isset($arrtotais[$coluna->getIdColuna()])) {
+                                        if ($tipo_coluna != "hora") {
+                                            $arrtotais[$coluna->getIdColuna()] += $htmlvalorcoluna;
+                                        } else {
+                                            $arrhoras = array($arrtotais[$coluna->getIdColuna()],$htmlvalorcoluna);
+                                            $arrtotais[$coluna->getIdColuna()] = $this->somaIntervaloHoras($arrhoras);
+                                        }
+                                    } else {
+                                        if ($tipo_coluna != "hora") {
+                                    	    $arrtotais[$coluna->getIdColuna()] = 0;
+                                            $arrtotais[$coluna->getIdColuna()] += $htmlvalorcoluna;
+                                        } else {
+                                            $arrtotais[$coluna->getIdColuna()] = "00:00:00";
+                                            $arrhoras = array($arrtotais[$coluna->getIdColuna()],$htmlvalorcoluna);
+                                            $arrtotais[$coluna->getIdColuna()] = $this->somaIntervaloHoras($arrhoras);
+                                        }
+                                    }
+                                }
+                                if ($condicaosubtotal != "1") { 
+                                    $ret_subtotal = $coluna->validaCondicao($condicaosubtotal,$linha,false);
+                                } else {
+                                	$ret_subtotal = true;
+                                }
+                                if ($ret_subtotal) {
+                                    $tipo_coluna = $coluna->getTipo();
+                                    if (isset($arrsubtotais[$coluna->getIdColuna()])) {
+                                        if ($tipo_coluna != "hora") {
+                                            $arrsubtotais[$coluna->getIdColuna()] +=  $htmlvalorcoluna;
+                                        } else {
+                                            $arrhoras = array($arrsubtotais[$coluna->getIdColuna()],$htmlvalorcoluna);
+                                            $arrsubtotais[$coluna->getIdColuna()] =  $this->somaIntervaloHoras($arrhoras);
+                                        }
+                                    } else {
+                                        if ($tipo_coluna != "hora") {
+                                        	$arrsubtotais[$coluna->getIdColuna()] = 0;
+                                            $arrsubtotais[$coluna->getIdColuna()] +=  $htmlvalorcoluna;
+                                        } else {
+                                            $arrsubtotais[$coluna->getIdColuna()] = "00:00:00";
+                                            $arrhoras = array($arrsubtotais[$coluna->getIdColuna()],$htmlvalorcoluna);
+                                            $arrsubtotais[$coluna->getIdColuna()] =  $this->somaIntervaloHoras($arrhoras);
+                                        }
+                                    }
+                                    if (isset($arrsubtotais_todos[$cntagrupamentos][$coluna->getIdColuna()])) {
+                                        $arrsubtotais_todos[$cntagrupamentos][$coluna->getIdColuna()] += $htmlvalorcoluna;
+                                    } else {
+                                        if ($tipo_coluna != "hora") {
+                                    	   $arrsubtotais_todos[$cntagrupamentos][$coluna->getIdColuna()] = 0;
+                                        } else {
+                                           $arrsubtotais_todos[$cntagrupamentos][$coluna->getIdColuna()] = "00:00:00";
+                                        }
+                                    }
+                                }
+                            }
+                            $addvisivel = "";
+                            if (!$coluna->getVisibilidade()) {
+                            	$addvisivel = " style='display: none;' ";
+                            }
+                            
+                            if ($this->_exiberesultados) {
+                            	echo  "\n\t\t\t<td id='td_" . $coluna->getIdColuna() . "_" . $idtd . "' " . $falign . $fwidth .  " align='$align'" . $addnowrap . $addvisivel .  ">" . nl2br($htmlcoluna)  . "</td>";
+                            }
+                        }
+                        
+                        
+    
+                        //ARQUIVO CSV
+                        if ($this->_temarquivocsv) {
+                        	foreach ($this->_colunasarquivo as $colunaarq) {
+                        		foreach ($this->colunas as $coluna) {
+    					    		if ($coluna->getIdColuna() == $colunaarq) {
+    					    			$htmlarquivo = $coluna->getTextoArquivo($linha,$this->arrindicadores);
+    					    			$this->_txtarquivo .= '"' . $htmlarquivo . '"' . ";";
+    					    		}
+                        		}
+    			    		}
+                        }
+                        if ($this->_exiberesultados) {
+                            echo  "\n\t\t</tr>";
+                        }
+                   // }
+                } else {
+                    $this->adicionarErro("Nenhuma coluna foi adicionada.",true);
+                }
+                
+                                
+                if ($this->_temarquivocsv) {
+                	$this->_txtarquivo .= "\n";
+                    $this->escreveArquivo($handle);
+                }
+                
+                //LINHA ADICIONAL DE OBSERVAï¿œï¿œES, (DETALHAMENTO)
+                if (count($this->linhasdetalhamento)) {
+                    foreach ($this->linhasdetalhamento as $coluna) {
+                        $fwidth = $coluna->getWidth(true);
+                        $falign = $coluna->getVAlign(true);
+                        $addnowrap = "";
+                        $align = $coluna->getAlign();
+                        if ($coluna->getNowrap()) { $addnowrap = " nowrap"; }
+                        $htmlcoluna = "";
+                        $htmlcoluna = $coluna->getHtml($linha,$this->arrindicadores,$class,$qtdlinhas - 1);
+                        
+                        if ($this->_exiberesultados) {
+                            if ($htmlcoluna == "") {
+                                $addvisivel = " style='display: none;' ";
+                            }
+                            echo  "\n\t\t<tr id='tr_" . $coluna->getIdColuna() . "_" . $idtd . "' class='" . $class . "' onmouseout=\"this.className='" . $class . "'\" onmouseover=\"this.className='" . $class . "Over'\"" . $addvisivel. ">";
+                            echo  "\n\t\t\t<td id='td_" . $coluna->getIdColuna() . "_" . $idtd . "' " . $falign . $fwidth . $addnowrap . " align='$align' colspan='" . count($this->colunas) . "'>" . $htmlcoluna  . "</td>";
+                            echo  "\n\t\t</tr>";
+                            
+                        }
+                        if ($this->_temarquivocsv) {
+                        	$htmlarquivo = $coluna->getTextoArquivo($linha,$this->arrindicadores);
+                        	if ($htmlarquivo != "") {
+                        		$this->_txtarquivo .= $htmlarquivo . ";\n";
+                        	}
+	                    }
+                    }
+                    
+                }
+                
+                $lastagrupamento = $newagrupamento;
+                //$lastval = "";
+            }
+        }
+        
+        $this->escreveArquivo($handle);
+
+        if (count($this->totalizadores)) {            
+            if ($this->exibesubtotais) {
+                if ($this->_exiberesultados) {
+                    echo   "\n\t\t<tr class='tableRodapeModelo1'>";
+                }
+                $mostrousubtotal = false;
+                $cntcheckspan = 0;
+                if ($cntagrupamentos != 1) {
+                    $cntagrupamentos = $cntagrupamentos + 1;
+                }
+                foreach ($this->colunas as $coluna) {
+                     $idcol = $coluna->getIdColuna();
+                     if ($this->isTotalizador($coluna->getIdColuna())) {
+                         
+                         if (!$mostrousubtotal) { 
+                             $addtexto = "<h3>" . $this->msgsubtotalizador . "</h3>"; 
+                             $mostrousubtotal = true; 
+                             $txtarquivotexto = $this->msgsubtotalizador;
+                         } else {
+                             $addtexto = "";
+                         }
+                         if ($cntcheckspan) { 
+                            
+                         /*   for ($j=1; $j< $cntcheckspan; $j++) {
+                                 echo  "<td id='subtotal_$idcol' align='right'>&nbsp;</td>";
+                            } 
+                            
+                         	echo  "<td id='subtotal_titulo_$idcol' align='right'>&nbsp;$addtexto</td>";*/
+                         	if ($this->_temarquivocsv) {
+                             	for ($j=1; $j<= $cntcheckspan; $j++) {
+                             		if ($j == $cntcheckspan) {
+                             			$this->_txtarquivo .= $txtarquivotexto;
+                             		}
+                             		$this->_txtarquivo .= ";";
+                             	}
+                         	 } 
+                         } 
+                         $cntcheckspan = 0;
+                         $addvisivel = "";
+                             if (!$coluna->getVisibilidade()) {
+                                $addvisivel = " style='display: none;' ";
+                             }
+                             if ($coluna->getTipo() == "hora") {
+                                $subtotal_valor = $arrsubtotais[$coluna->getIdColuna()];
+                             } else {
+                                 if ($this->_totalizadorprecisao != 0) {
+                                    $subtotal_valor = number_format($arrsubtotais[$coluna->getIdColuna()],$this->_totalizadorprecisao,",",".");
+                                 } else {
+                                    $subtotal_valor = $arrsubtotais[$coluna->getIdColuna()];
+                                 }
+                             }
+                             if ($this->_exiberesultados) {
+                        	   echo  "<td id='subtotal_$idcol" . "_" . $cntagrupamentos . "' align='right'$addvisivel>$addtexto&nbsp;<h3>" . $subtotal_valor . "</h3>&nbsp;</td>";
+                             }
+                             if (in_array($idcol,$this->_colunasarquivo)) {
+                        	   $this->_txtarquivo .= $subtotal_valor . ";";
+                             }
+                     } else {
+                         $addvisivel = "";
+                         if (!$coluna->getVisibilidade()) {
+                            $addvisivel = " style='display: none;' ";
+                         }
+                         if ($this->_exiberesultados) {
+                            echo  "<td id='subtotal_$idcol" . "_" . $cntagrupamentos . "' $addvisivel>&nbsp;</td>";
+                         }
+                         if ($this->_temarquivocsv) {
+                            if (in_array($idcol,$this->_colunasarquivo)) {
+                                $this->_txtarquivo .= ";";
+                            }
+                         }
+                     }
+                }
+                if ($this->_exiberesultados) {
+                    echo   "\n\t\t</tr>";
+                }
+                if ($this->_temarquivocsv) {
+                	$this->_txtarquivo .= "\n";
+                }
+            }
+            
+            
+            
+            if ($this->_exibetotalizadores) {
+                if ($this->_exiberesultados) {
+                    echo   "\n\t\t<tr class='tableRodapeModelo2'>";
+                }
+                $mostroutotal = false;
+                $cntcheckspan = 0;
+                foreach ($this->colunas as $coluna) {
+                     
+
+                     $idcol = $coluna->getIdColuna();
+                     if ($this->isTotalizador($coluna->getIdColuna())) {
+                         if (!$mostroutotal) { 
+                             $addtexto = "<h3>" . $this->msgtotalizador .  "</h3>"; 
+                             $mostroutotal = true; 
+                             $txtarquivotexto = $this->msgtotalizador;
+                         } else {
+                             $addtexto = "";
+                         }
+                         
+                         if ($cntcheckspan) { 
+                            if ($this->_temarquivocsv) {
+                                for ($j=1; $j<= $cntcheckspan; $j++) {
+                                    if ($j == $cntcheckspan) {
+                                        $this->_txtarquivo .= $txtarquivotexto;
+                                    }
+                                    $this->_txtarquivo .= ";";
+                                }
+                            } 
+                         } 
+                         $cntcheckspan = 0;
+                         $addvisivel = "";
+                         if (!$coluna->getVisibilidade()) {
+                            $addvisivel = " style='display: none;' ";
+                         }
+                         if ($coluna->getTipo() == "hora") {
+                            $total_valor = $arrtotais[$coluna->getIdColuna()];
+                         } else {
+                             if ($this->_totalizadorprecisao != 0) {
+                                $total_valor = number_format($arrtotais[$coluna->getIdColuna()],$this->_totalizadorprecisao,",",".");
+                             } else {
+                                $total_valor = $arrtotais[$coluna->getIdColuna()];
+                             }
+                         }
+                         if ($this->_exiberesultados) {
+                            echo  "<td id='total_$idcol' align='right'$addvisivel>$addtexto&nbsp;<h3>" . $total_valor . "</h3></td>";
+                         }
+                         if ($this->_temarquivocsv) {
+                            if (in_array($idcol,$this->_colunasarquivo)) {
+                                $this->_txtarquivo .= $total_valor . ";";
+                            }
+                         }
+                     } else {
+                         $addvisivel = "";
+                         if (!$coluna->getVisibilidade()) {
+                            $addvisivel = " style='display: none;' ";
+                         }
+                         if ($this->_exiberesultados) {
+                            echo  "<td id='total_$idcol' $addvisivel>&nbsp;</td>";
+                         }
+                         if ($this->_temarquivocsv) {
+                            if (in_array($idcol,$this->_colunasarquivo)) {
+                                $this->_txtarquivo .= ";";
+                            }
+                         } 
+                     }
+                }
+                if ($this->_exiberesultados) {
+                    echo   "\n\t\t</tr>";
+                }
+                if ($this->_temarquivocsv) {
+                    $this->_txtarquivo .= "\n";
+                } 
+            }
+        }
+        
+        $this->escreveArquivo($handle);
+        
+        
+        if (!$this->issublist) {
+            if (is_object($this->subListagem)) {
+                if ($this->subListagem->getQuantidadeRegistros()) {
+                	$this->subListagem->gerarArquivoXLS(); 
+                    ob_start();
+                    $this->subListagem->desenhar();
+                    $htmllist = ob_get_contents();
+                    ob_end_clean();
+                    if ($this->_temarquivocsv) {
+                    	$this->_txtarquivo .= $this->subListagem->getTextoArquivoCSV();
+                    }
+                    if ($this->_exiberesultados) {
+                        echo  "<tr><td colspan='$colspan'>";
+                        echo  $htmllist;            
+                        echo  "</td></tr>";
+                    }
+                    if ($this->subListagem->getTemCheckBox()) {
+                        $temcheck = true;
+                        $this->temcheck = true;
+                    }
+                }
+            }
+        }
+        
+        $this->escreveArquivo($handle);
+        
+        
+   /*  
+       EXIBIR OS BOTï¿œES DE + E - PARA QUANDO POSSUIR COLUNAS COM CHECKBOXES. COMENTADO POR QUE Nï¿œO FUNCIONA SE TIVER MAIS DE UM FORMULï¿œRIO NA MESMA JANELA. */  
+        if (!$this->issublist) {
+            if ($temcheck) {
+                if (count($this->colunas)) {
+                    echo   "\n\t\t<tr class='tableRodapeModelo3'>";
+                    $cntcheckspan = 0;
+                    $qtd = $this->getQuantidadeRegistros();
+                    foreach ($this->colunas as $coluna) {
+                        if ($coluna->getTipo() == "check") {
+                            if ($cntcheckspan) { echo  "<td colspan='$cntcheckspan'>&nbsp;</td>";}
+                            $cntcheckspan = 0;
+                            $idlistagem = $this->getIdListagem();
+                            echo  "\n\t\t\t<td align=center nowrap>&nbsp;";
+                            echo  "<input type='button' class='botao' name='btselecionar' onclick=\"ListagemSelecionachecks(1,'" . $qtd. "','" . $coluna->getIdColuna() . "_" . $idlistagem . "_');\" value='&nbsp;+&nbsp;'>&nbsp;";
+                            echo  "<input type='button' class='botao' name='btdesselecionar' onclick=\"ListagemSelecionachecks(0,'" . $qtd. "','" . $coluna->getIdColuna() . "_" . $idlistagem . "_');\" value='&nbsp;-&nbsp;'>&nbsp;";
+                            echo  "\n\t\t\t</td>";
+                        } else {
+                            $cntcheckspan = $cntcheckspan + 1;
+                        }
+                    }
+                    if ($cntcheckspan) { echo  "<td colspan='$cntcheckspan'>&nbsp;</td>";}
+                    echo   "\n\t\t</tr>";
+                }
+            }
+        }
+        
+        
+
+        if ($this->_exibeqtdregistros) {
+            if ($this->_exiberesultados) {
+                echo   "\n\t\t<tr class='tableRodapeModelo3'>\n\t\t\t<td colspan='$colspan' align=center>";
+            }
+            $qtd = $this->getQuantidadeRegistros();
+            if ($cnt == 0) {
+                if ($this->_exiberesultados) {
+                    echo   $this->msgnenhumresultado;
+                }
+            }  else {
+                if ($this->_exiberesultados) {
+                echo   "<b>$qtd</b> " . $this->msgregistros;
+                }
+                if ($this->_temarquivocsv) {
+            		$this->_txtarquivo .= $qtd . " " . $this->msgregistros;
+            	}
+            }
+            if ($this->_exiberesultados) {
+                echo   "</td>\n\t\t</tr>";
+            }
+            
+        }
+        
+        $this->escreveArquivo($handle);
+        
+
+        if ($this->_temarquivocsv) {
+        	if (!$this->issublist) {
+                
+		        
+		        fclose($handle);
+		
+		        $link=$tmpfname;
+		        
+		        if ($cnt != 0) {
+			        echo   "\n\t\t<tr class='tableRodapeModelo3'>\n\t\t\t<td colspan='$colspan' align=center>";
+			        //echo   '<input type="button" name="btn_arquivoxls" value="Versï¿œo em XLS" class="botao" onclick="window.open(\'gera_csv_to_excel.php?arquivocsv=/' . $link . '\');" style="width: 90px;">';
+                    echo   '&nbsp;<input type="button" name="btn_arquivoxls" value="Download CSV" class="botao" onclick="window.open(\'' . $this->_url_base_path . '/downloads.php?arquivo=' . $link . '\');" style="width:120px;">';
+			        echo   "</td>\n\t\t</tr>";
+		        } else {
+		        	if ($this->_exibeqtdregistros) {
+			        	echo   "\n\t\t<tr class='tableRodapeModelo3'>\n\t\t\t<td colspan='$colspan' align=center>";
+				        echo   $this->msgnenhumresultado;
+				        echo   "</td>\n\t\t</tr>";
+		        	}
+		        }
+        	}
+	    /*	//FORMULï¿œRIO
+	        $this->form->addButton("btn_arquivo","Arquivo .XLS");
+			$this->form->addCampoAcao("btn_arquivo","onclick","window.open('gera_csv_to_excel.php?arquivocsv=" . $link . "');");
+			$this->form->addQuadro("quadro_arquivo");
+			$this->form->addQuadroButton("quadro_arquivo","btn_arquivo"); 
+	     */
+        }
+        
+        /*    
+          FORMULï¿œRIO   
+        if (!$this->issublist) {
+            if ($cnt != 0) {
+                if (($temcheck) || ($this->_temarquivocsv)) {
+                    echo "\n\t\t<tr>\n\t\t\t<td colspan='$colspan' align=center style='padding: 0px;'>";
+                    ob_start();
+                    $this->form->desenhaCampos();
+                    $this->form->displayErros();
+                    $htmlform = ob_get_contents();
+        
+                    ob_end_clean();
+                    echo  $htmlform;
+                }
+            }
+            echo   "</td>\n\t\t</tr>";
+            ob_start();
+            $this->form->fechaForm();
+            $htmlform = ob_get_contents();
+            ob_end_clean(); 
+        } */
+        //echo  $htmlform;
+        
+        $this->arrtotais = $arrtotais;
+        $this->arrsubtotais = $arrsubtotais_todos;
+        $this->arragrupamentos = $arragrupamentos;
+        
+        
+    }
+    
+    public function setDebug($value) {
+        $this->_debug = $value;
+    }
+     
+    /**
+     * Funï¿œï¿œo usada internamente para adicionar um erro ao formulï¿œrio.
+     *
+     * @param string $msgerro Mensagem de Erro
+     * @param boolean $fatal Se ï¿œ um erro Fatal = true ()
+     * */
+    protected function adicionarErro($msgerro,$fatal = false) {
+        if ($fatal) { $this->_errors = array(); }
+        $erro = array("msgerro" => $msgerro,"fatal" => $fatal);
+        array_push($this->_errors,$erro);
+         
+        if ($fatal) {
+            $this->escreveErros();
+            exit;
+        }
+         
+    }
+
+
+    /**
+     * Funï¿œï¿œo usada para exibir os erros.
+     *
+     * */
+    protected function escreveErros() {
+        if ($this->_debug) {
+            if (count($this->_errors)) {
+                echo "<style type='text/css'>
+                         #erros { background: #BAD0E5; color: #000000; font-size: 12px; Verdana,Arial,Helvetica,sans-serif; font-weight: bold; margin: 15px; padding: 0px; padding-top: 3px; padding-bottom: 3px;  text-align: left; } " .
+                        " .erro { background: #E6EAEE; color: #000000; font-size: 12px; Verdana,Arial,Helvetica,sans-serif; font-weight: bold; margin: 2px; padding: 5px; text-align: left; }" .
+                        "</style>";
+                echo "<div id='erros'>";
+                foreach ($this->_errors as $erro) {
+                    echo "<div class=erro>";
+
+                    if ($erro["fatal"]) {
+                        $addmsg = "<span style='color: #990000;'><b>ERRO:</b></span> ";
+                    } else {
+                        $addmsg = "ERRO: ";
+                    }
+                    echo $addmsg . $erro["msgerro"];
+                    echo "</div>";
+                }
+                echo "</div>";
+            }
+        } else {
+            echo "MODO DEBUG ESTï¿œ DESATIVADO.";
+        }
+    }
+    
+    public function gerarArquivoXLS($colunasarquivo = "") {
+    	if ($colunasarquivo == "") {
+    		$arcolunas = array();
+    		foreach ($this->colunas as $coluna) {
+    			if ($coluna->getVisibilidade()) {
+    			  $colunasarquivo .= $coluna->getIdColuna() . ",";
+    			} 
+    		}
+    		$colunasarquivo = substr($colunasarquivo,0,strlen($colunasarquivo)-1);
+    	}
+    	$arcolunas = explode(",",$colunasarquivo);
+    	$txtarquivo = "";
+    	$this->_colunasarquivo = $arcolunas;
+		$this->_temarquivocsv = true; 
+    }
+    
+    /*
+     * Funï¿œï¿œo utilizada pra somar intervalos de Horas */
+    public function somaIntervaloHoras($arrValores){
+    
+        // Somando separadamente os valores
+        foreach($arrValores as $valor){
+        
+            $arrTmp = explode(':',$valor);
+        
+            $seg += $arrTmp[2];
+            $min += $arrTmp[1];
+            $hor += $arrTmp[0]; 
+        }
+        
+        // Tratando os segundos
+        if( $seg >= 60){
+        
+            $min += floor($seg / 60) ;
+            
+            while($seg >= 60){
+                
+                $seg = $seg - 60;
+            }
+        
+        }
+        // Tratando os minutos
+        if( $min >= 60){
+        
+            $hor += floor($min / 60) ;
+            
+            while($min >= 60){
+                
+                $min = $min - 60;
+            }
+        
+        }
+        
+        return str_pad($hor,2,'0',STR_PAD_LEFT).':'.str_pad($min,2,'0',STR_PAD_LEFT).':'.str_pad($seg,2,'0',STR_PAD_LEFT);
+    }
+    
+    /**
+     * Funï¿œï¿œo que Retorna se a listagem Possui um checkBox adicionado.
+     */
+    public function getTemCheckBox() {
+        return $this->temcheck;
+    }
+    
+    /**
+     * Funï¿œï¿œo que retorna o array com os Totalizadores. 
+     */
+    public function getTotais() {
+    	return $this->arrtotais;
+    }
+    
+    /**
+     * Funï¿œï¿œo que Retorna o array com os Sub-Totalizadores.
+     */
+    public function getSubTotais() {
+    	return $this->arrsubtotais;
+    }
+    
+    /**
+     * Funï¿œï¿œo que Retorna o array com os Sub-Totalizadores.
+     */
+    public function getAgrupamentos() {
+        return $this->arragrupamentos;
+    }
+    
+    /**
+     * Funï¿œï¿œo Interna Utilizada quando a Listagem possui uma sublistagem para guardar quantos registros a listagem principal tem.
+     */
+    protected function setQuantidadeRegistrosListagemPrincipal($value) {
+    	$this->_qtdregistroslistagemprincipal = $value; 
+    }
+    
+    /**
+     * Funï¿œï¿œo Interna Utilizada quando a Listagem possui uma sublistagem para retornar quantos registros a listagem principal tem.
+     */
+    protected function getQuantidadeRegistrosListagemPrincipal() {
+    	return $this->_qtdregistroslistagemprincipal;
+    }
+    
+    protected function getTextoArquivoCSV() {
+    	return $this->_txtarquivo;
+    }
+    
+    public function autoAdicionarColunas() {
+    	$i = pg_num_fields($this->dados);
+        for ($j = 0; $j < $i; $j++) {
+            $fieldname = pg_field_name($this->dados, $j);
+            $tipo = pg_field_type($this->dados, $j);
+            $this->adicionarColuna("coluna_" .$j,"$fieldname","{" . $fieldname . "}","text","left");  
+        }
+    }
+}
+?>
Index: trunk/workflow/inc/report/includes/classes/Download.class.php
===================================================================
--- trunk/workflow/inc/report/includes/classes/Download.class.php	(revision 5307)
+++ trunk/workflow/inc/report/includes/classes/Download.class.php	(revision 5307)
@@ -0,0 +1,335 @@
+<?php
+/** 
+* Download.class.php 
+*/
+/** 
+* Download de Arquivos
+*  
+* Formulï¿œrios
+* <code>
+* include '../lib/config.php';
+* include '../includes/classes/Download.class.php';
+* 
+* $down = new Download('my_files/', 'true'); 
+* $down-> doDownload('tazmania2.jpg',true);
+*
+* if($down->getSysError() != ''){
+*    echo $down->getSysDebug();
+*    echo    $down->getSysError(); 
+* }
+*
+* </code>
+* 
+* 
+* 
+* 
+*/
+class Download {
+    
+    public  $sysError = '';
+    public  $sysDebug = '';
+    
+    private $_pathFolder = '';
+    private $_pathBase = "";
+    private $_file = "";
+    private $_fileExtension = '';
+    private $_fileMime = '';
+    
+    private $_fileSize = 0;
+    private $_forceDownload = true;
+    
+    /** 
+    * ï¿œ Construtor do metodo: 
+    * <code> 
+    * $down = $down = new Download('my_files/', 'true'); 
+    * </code> 
+    *ï¿œ
+    * @param string $path Pasta de onde serï¿œ feito Donwload  
+    * @param string $base 'true'/'false' caminho true (/var/www/) caminho false
+    * (/var/www/html/site.../)
+    */
+    
+    function Download($path, $base) {
+        
+        $this->sysDebug .= '<b>Download</b><br>';
+        
+        try{
+            //pastas que sï¿œo permitidas fazer download
+            $arrFolders = array();
+            $arrFolders[] = '/';
+            
+            
+            if(trim($path) != '' && in_array(trim($path), $arrFolders)){
+                $this->_pathFolder = trim($path);
+                $this->sysDebug .= '<b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Pasta: </b> ' . $this->_pathFolder . '<br>';
+            }/* else {
+                $this->sysDebug .= '<b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Pasta Invalida: </b> [' . $path . ']<br>';
+                throw new exception(' caminho [' . $path . '] ï¿œ invalido.');
+            }
+            */
+            if(trim($base) != '' && (trim($base) == 'true' || trim($base) == 'false') ){
+                if(trim($base) == 'true'){
+                    $this->_pathBase = '';
+                } else {
+                    $this->_pathBase = _SITEDIR_;
+                }
+                $this->sysDebug .= '<b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Base: </b> ' . $this->_pathBase . '<br>';
+            } else {
+                $this->sysDebug .= '<b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Base Invalida: </b> [' . $base . ']<br>';
+                throw new exception('Base [' . $base . '] ï¿œ invalido.');
+            }
+            
+            /*if(!is_dir($this->_pathBase . $this->_pathFolder)){
+                $this->sysDebug .= '<b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Caminho nï¿œo corresponde a uma pasta valida: </b> [' . $this->_pathBase . $this->_pathFolder . ']<br>';
+                throw new exception(' Caminho nï¿œo corresponde a uma pasta valida: </b> [' . $this->_pathBase . $this->_pathFolder . '].');
+            } */
+            
+        } catch (exception $e) {
+            
+            $this->sysError = '<b>Erro: </b>' . $e->getMessage() . '<br>';
+            $this->sysDebug .= '<b>Thows Construtor Exit</b> <br>';
+
+            $fp = fopen ("/tmp/logDownloadsIndevidos","a+");
+            $writeDebug = "Data : " . date('d/m/Y H:m:s') . 
+                          " \nPagina : " . $_SERVER['PHP_SELF'] . 
+                          " \nIP : " . $_SERVER['REMOTE_ADDR'] . 
+                          " \nUsuoid : " . $_SESSION['usuario']['oid'] .
+                          "\n" . $this->sysDebug . " \n\n";
+            $writeDebug = strip_tags(html_entity_decode(str_ireplace('<br>', "\n", $writeDebug), ENT_NOQUOTES, 'ISO8859-1'));
+            fwrite($fp, $writeDebug );
+            fclose($fp);
+
+        }
+        
+    }
+
+    /** 
+    * ï¿œ Meodo de download de arquivos
+    *  <code> 
+    * $down-> doDownload('file.ext');
+    * </code> 
+    *ï¿œ
+    * @param string $file Arquivo que serï¿œ feito download
+    */
+    function doDownload($file, $forceDownload = true){
+        try{
+            
+            $this->_forceDownload = $forceDownload;
+            
+            if(trim($file) != ''){
+                $this->_file = trim($file);
+                $this->sysDebug .= '<b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;File Name: </b> [' . $this->_file . ']<br>';
+            } else {
+                $this->sysDebug .= '<b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Base Invalida: </b> [' . $file . ']<br>';
+                throw new exception(' Arquivo [' . $file . '] ï¿œ invalido.');
+            }
+            
+            
+            
+            preg_match('/\.([^\.]*$)/', $this->_file, $extension);
+            $this->_fileExtension = strtolower(substr($extension[0], 1, strlen($extension[0])));
+            $this->sysDebug .= '<b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Formato do Arquivo: </b> [' . $this->_fileExtension . ']<br>';
+            
+            if($this->_fileExtension == 'php'){
+                $this->sysDebug .= '<b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Formato de Arquivo invalido: </b> [' . $this->_fileExtension . ']<br>';
+                throw new exception('Arquivo invalido.');
+            }
+            
+            if(strstr( $this->_pathBase . $this->_pathFolder . $this->_file, '../' )){
+                $this->sysDebug .= '<b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Pasta contem caracteres invalidos: </b> [' . $this->_pathBase . $this->_pathFolder . $this->_file . ']<br>';
+                throw new exception(' caminho [' . $this->_pathBase . $this->_pathFolder . $this->_file . '] ï¿œ invalido.');
+            }
+            
+            if(!file_exists($this->_pathBase . $this->_pathFolder . $this->_file)){
+                $this->sysDebug .= '<b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Arquivo nï¿œo encontrado: </b> [' . $this->_pathBase . $this->_pathFolder . $this->_file . ']<br>';
+                throw new exception('Arquivo nï¿œo encontrado.');
+            }
+            
+            $sizeFile = filesize($this->_pathBase . $this->_pathFolder . $this->_file);
+            if($sizeFile > 0 ){
+                $this->_fileSize = $sizeFile;   
+                $this->sysDebug .= '<b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Arquivo com tamanho </b> [' . $this->_fileSize . '] bytes<br>';
+            } else {
+                $this->sysDebug .= '<b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Arquivo com tamanho 0 bytes: </b><br>';
+                throw new exception('Arquivo truncado.');
+            }
+            
+            $arrExtensions = array();
+            $arrExtensions[] = 'jpg';
+            $arrExtensions[] = 'jpeg';
+            $arrExtensions[] = 'jpe';
+            $arrExtensions[] = 'gif';
+            $arrExtensions[] = 'png';
+            $arrExtensions[] = 'bmp';
+            $arrExtensions[] = 'tiff';
+            $arrExtensions[] = 'tif';
+            $arrExtensions[] = 'doc';
+            $arrExtensions[] = 'docx';
+            $arrExtensions[] = 'xls';
+            $arrExtensions[] = 'xlt';
+            $arrExtensions[] = 'xlm';
+            $arrExtensions[] = 'xld';
+            $arrExtensions[] = 'xla';
+            $arrExtensions[] = 'xlc';
+            $arrExtensions[] = 'xlw';
+            $arrExtensions[] = 'xll';
+            $arrExtensions[] = 'ppt';
+            $arrExtensions[] = 'pps';
+            $arrExtensions[] = 'txt';
+            $arrExtensions[] = 'zip';
+            $arrExtensions[] = 'rar';
+            $arrExtensions[] = 'rtf';
+            $arrExtensions[] = 'pdf';
+            $arrExtensions[] = 'odt';
+            $arrExtensions[] = 'xml';
+            $arrExtensions[] = 'html';
+            $arrExtensions[] = 'htm';
+            $arrExtensions[] = 'csv';
+            $arrExtensions[] = 'eml';
+            
+            if(! in_array($this->_fileExtension, $arrExtensions) ){
+                $this->sysDebug .= '<b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Extensï¿œo de arquivo nï¿œo permitida</b><br>';
+                throw new exception('Extensï¿œo invalida [' . $this->_fileExtension . '].');
+            }
+           
+            switch($this->_fileExtension) {
+                case 'jpg': case 'jpeg': case 'jpe':
+                    $this->_fileMime = 'image/jpeg';                         break;
+                case 'gif':
+                    $this->_fileMime = 'image/gif';                          break;
+                case 'png':
+                    $this->_fileMime = 'image/png';                          break;
+                case 'bmp':
+                    $this->_fileMime = 'image/bmp';                          break;
+                case 'js' :
+                    $this->_fileMime = 'application/x-javascript';           break;
+                case 'json' :
+                    $this->_fileMime = 'application/json';                   break;
+                case 'tiff' :case 'tif' :
+                    $this->_fileMime = 'image/tiff';                         break;
+                case 'css' :
+                    $this->_fileMime = 'text/css';                           break;
+                case 'xml' :
+                    $this->_fileMime = 'application/xml';                    break;
+                case 'doc' :  case 'docx' :
+                    $this->_fileMime = 'application/msword';                 break;
+                case 'xls': case 'xlt': case 'xlm': case 'xld': case 'xla': case 'xlc': case 'xlw' : case 'xll' :
+                    $this->_fileMime = 'application/vnd.ms-excel';           break;
+                case 'ppt': case 'pps' :
+                    $this->_fileMime = 'application/vnd.ms-powerpoint';      break;
+                case 'rtf' :
+                    $this->_fileMime = 'application/rtf';                    break;
+                case 'pdf' :
+                    $this->_fileMime = 'application/pdf';                    break;
+                case 'html': case 'htm': case 'php' :
+                    $this->_fileMime = 'text/html';                          break;
+                case 'txt' :
+                    $this->_fileMime = 'text/plain';                         break;
+                case 'mpeg': case 'mpg': case 'mpe' :
+                    $this->_fileMime = 'video/mpeg';                         break;
+                case 'mp3' :
+                    $this->_fileMime = 'audio/mpeg3';                        break;
+                case 'wav' :
+                    $this->_fileMime = 'audio/wav';                          break;
+                case 'aiff':  case 'aif' :
+                    $this->_fileMime = 'audio/aiff';                         break;
+                case 'avi' :
+                    $this->_fileMime = 'video/msvideo';                      break;
+                case 'wmv' :
+                    $this->_fileMime = 'video/x-ms-wmv';                     break;
+                case 'mov' :
+                    $this->_fileMime = 'video/quicktime';                    break;
+                case 'zip' :
+                    $this->_fileMime = 'application/zip';                    break;
+                case 'tar' :
+                    $this->_fileMime = 'application/x-tar';                  break;
+                case 'swf' :
+                    $this->_fileMime = 'application/x-shockwave-flash';      break;
+                default : 
+                    $this->_fileMime = 'application/octet-stream'; 
+            }
+            if ($this->_fileMime == 'application/octet-stream') {
+               $this->sysDebug .= '<b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Mime Type Default: </b> [' . $this->_fileMime . ']<br>';
+            } else {
+                $this->sysDebug .= '<b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Mime Type Identificado: </b> [' . $this->_fileMime . ']<br>';;
+            }
+            
+            if($forceDownload === true){
+                $this->_forceDownload = "Content-Disposition: attachment; filename=" . $this->_file;
+                $this->sysDebug .= '<b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Download: </b> [' . $this->_forceDownload . ']<br>';
+            } else {
+                 $this->_forceDownload = "Content-Disposition: inline; filename=" . $this->_file;
+                 $this->sysDebug .= '<b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Download: </b> [' . $this->_forceDownload . ']<br>';
+            }
+
+            header("Expires: " . gmdate("D, d M Y H:i:s") . " GMT;");
+            header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT;");
+            header("cache-control: post-check=0, pre-check=0, false;"); 
+            header("Pragma: public;");
+            header("Cache-Control: must-revalidate, post-check=0, pre-check=0;");
+            header("Cache-Control: private, false;");
+            header("Content-Transfer-Encoding: binary;");
+            header("Content-Length: ". $this->_fileSize  . ';');
+            header($this->_forceDownload . ';');
+            header('Content-type: ' . $this->_fileMime . ';');
+            
+            
+            readfile($this->_pathBase . $this->_pathFolder . $this->_file);
+                
+            /*
+            //header("Expires: " . gmdate("D, d M Y H:i:s") . " GMT");
+            //header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
+            //header("cache-control: post-check=0, pre-check=0", false); 
+            header("Pragma: public");
+            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
+            header("Cache-Control: private",false);
+            header("Content-Transfer-Encoding: binary");
+            header("Content-Length: ". $this->_fileSize );
+            header($this->_forceDownload);
+            header('Content-type: ' . $this->_fileMime . ';');
+            //header('Content-Description: ' . $this->_file . ';');
+            */
+        } catch (exception $e) {
+            $this->sysError = '<b>Erro: </b>' . $e->getMessage() . '<br>';
+            $this->sysDebug .= '<b>Thows UPLOAD Exit</b> <br>';
+ 
+            $fp = fopen ("/tmp/logDownloadsIndevidos","a+");
+            $writeDebug = "Data : " . date('d/m/Y H:m:s') . 
+                          " \nPagina : " . $_SERVER['PHP_SELF'] . 
+                          " \nIP : " . $_SERVER['REMOTE_ADDR'] . 
+                          " \nUsuoid : " . $_SESSION['usuario']['oid'] .
+                          "\n" . $this->sysDebug . " \n\n";
+            $writeDebug = strip_tags(html_entity_decode(str_ireplace('<br>', "\n", $writeDebug), ENT_NOQUOTES, 'ISO8859-1'));
+            fwrite($fp, $writeDebug );
+            fclose($fp);
+            
+        }
+        
+        
+    }
+    /*
+    * ï¿œGet susError (Mensagem de erro)
+    * <code> 
+    *   $down-> getSysError();
+    * </code> 
+    *ï¿œ
+    */
+    function getSysError(){
+        $ret = '';
+        if(isset($this->sysError{0})){
+            $ret = '<font color="#FF0000">' . $this->sysError . '</font>';
+        }
+        return $ret;
+    }
+    /**
+    *  ï¿œGet sysDebug (Mensagem do Debug) 
+    * <code>   
+    *    $down- > getSysDebug();
+    * </code> 
+    *ï¿œ
+    */
+    function getSysDebug(){
+        return '<pre>' . $this->sysDebug . '</pre>'; 
+    }
+}
+?>
Index: trunk/workflow/inc/report/includes/classes/ListagemColuna.class.php
===================================================================
--- trunk/workflow/inc/report/includes/classes/ListagemColuna.class.php	(revision 5307)
+++ trunk/workflow/inc/report/includes/classes/ListagemColuna.class.php	(revision 5307)
@@ -0,0 +1,363 @@
+<?php
+/**
+ * ListagemColuna
+ *
+ * Implementação de Colunas das Listagems Padrões do Sistema.
+ */
+/**
+ * ListagemColuna
+ *
+ * Implementação de Colunas das Listagems Padrões do Sistema.
+ *
+ *
+ * @author Jair Pereira <pereira.jair@gmail.com>
+ * @since 01/06/2009
+ *
+ */
+
+class ListagemColuna {
+    private $idcoluna;
+    private $idlistagem;
+    private $nome;
+    private $align;
+    private $html;
+    private $width;
+    private $tipo;
+    private $nowrap;
+    private $valign;
+    private $link;
+    private $popup = false;
+    private $target;
+    private $condicao;
+    private $linkcondicao;
+    private $cor;
+    private $corcondicao;
+    private $visivel = true;
+
+    
+    public function getValorHTML($linha) {
+        $newhtml = "";
+        $newhtml .= $this->html;
+        $newhtml = $this->replaceValorLinha($newhtml,$linha);
+        
+        if ($this->tipo == "php") {
+        	ob_start();
+        	echo eval($newhtml);
+        	$novohtml = ob_get_contents();
+        	ob_end_clean();
+            $newhtml = $novohtml;
+        }
+        
+        if ($this->tipo == "php-moeda") {
+        	ob_start();
+        	echo eval($newhtml);
+        	$novohtml = ob_get_contents();
+        	ob_end_clean();
+            $newhtml = $novohtml;
+        }
+        
+        return $newhtml;
+    }
+    
+    public function getTextoArquivo($linha,$todososindicadores) {
+    	$newhtml = $this->html;
+    	foreach ($todososindicadores as $idindicador => $indicadores) {
+            foreach ($indicadores as $indicador) {
+                $nomeindicador = $indicador->getIdIndicador();
+                $condicao = $indicador->getCondicao();
+                $ret = $this->validaCondicao($condicao,$linha);
+                if ($ret) {
+                    $newhtml = str_replace("{" . $nomeindicador . "}",$indicador->getLegendaArquivo() ,$newhtml);
+                }
+            }
+        }
+        foreach ($todososindicadores as $idindicador => $indicadores) {
+            foreach ($indicadores as $indicador) {
+                $nomeindicador = $indicador->getIdIndicador();
+                $newhtml = str_replace("{" . $nomeindicador . "}","" ,$newhtml);
+            }
+        }
+        
+        $newhtml = $this->replaceValorLinha($newhtml,$linha);
+        if ($this->tipo == "data") {
+            if ($newhtml != "") {
+              $newhtml = date("d/m/Y",strtotime($newhtml));
+            }
+        }
+
+        if ($this->tipo == "moeda") {
+            if ($newhtml == "") { $newhtml = 0; }
+            $newhtml = number_format($newhtml,2,",",".");
+        }
+        
+        if ($this->tipo == "php") {
+        	ob_start();
+        	echo eval($newhtml);
+        	$novohtml = ob_get_contents();
+        	ob_end_clean();
+            $newhtml = $novohtml;
+        }
+        
+        if ($this->tipo == "php-moeda") {
+        	ob_start();
+        	echo eval($newhtml);
+        	$novohtml = ob_get_contents();
+        	ob_end_clean();
+            $newhtml = $novohtml;
+            $newhtml = number_format($newhtml,2,",",".");
+        }
+        
+        return $newhtml;
+    }
+    
+    public function validaCondicao($condicao,$linha,$debug = false) {
+        foreach (array_keys($linha) as $col) {
+            $condicao = str_replace("{" .  $col . "}","'" . $linha[$col] . "'",$condicao);
+        }
+        $condicao = html_entity_decode($condicao, ENT_QUOTES);
+        $fcondicao = ' if (' . $condicao . ') { $ret = true; } else { $ret = false; }';
+        if ($condicao != "") {
+          if ($debug) { echo "<br>" . $fcondicao ; } 
+          eval($fcondicao);
+        } else {
+            $ret = false;
+        }
+        return $ret;
+    }
+  
+    public function getHtml($linha,$todososindicadores,$classe,$i) {
+        $newhtml = "";
+        $newhtml .= $this->html;
+        if ($classe == "tdc") {
+            $fundo = false;
+        } else {
+            $fundo = true;
+        }
+        
+        foreach ($todososindicadores as $idindicador => $indicadores) {
+            foreach ($indicadores as $indicador) {
+                $nomeindicador = $indicador->getIdIndicador();
+                $condicao = $indicador->getCondicao();
+                
+                $ret = $this->validaCondicao($condicao,$linha);
+                if ($ret) {
+                    $newhtml = str_replace("{" . $nomeindicador . "}",$indicador->getHtml($fundo) . "{" . $nomeindicador . "}",$newhtml);
+                }
+            }
+
+        }
+        
+        $newhtml = str_replace("{this_num_linha}",$i,$newhtml);
+
+        foreach ($todososindicadores as $idindicador => $indicadores) {
+            foreach ($indicadores as $indicador) {
+                $nomeindicador = $indicador->getIdIndicador();
+                $newhtml = str_replace("{" . $nomeindicador . "}","",$newhtml);
+            }
+        }
+         
+        $newhtml = $this->replaceValorLinha($newhtml,$linha);
+
+        if ($this->tipo == "check") {
+            $condicao = $this->getCondicao();
+            $ret = $this->validaCondicao($condicao,$linha);
+            if ($ret) {
+                $checked = "";
+                if (isset($_POST[$this->idcoluna])) {
+                    if (is_array($newhtml)) {
+                        if (in_array($newhtml,$_POST[$this->idcoluna])) {
+                            $checked = " checked";
+                        }
+                    }
+                }
+                $newhtml = "<input id='" . $this->idcoluna ."_" . $this->idlistagem . "_" .$i . "' type='checkbox' name='" . $this->idcoluna . "[]' value='" . $newhtml . "' class='obrigatorio'" . $checked .">";
+            } else {
+                $newhtml = "";
+            }
+             
+        }
+
+        if ($this->tipo == "data") {
+            if ($newhtml != "") {
+                $newhtml = date("d/m/Y",strtotime($newhtml));
+            }
+        }
+        
+        if ($this->tipo == "moeda") {
+            if ($newhtml == "") { $newhtml = 0; }
+            $newhtml = number_format($newhtml,2,",",".");
+        }
+        
+        if ($this->tipo == "php") {
+        	ob_start();
+        	echo eval($newhtml);
+        	$novohtml = ob_get_contents();
+        	ob_end_clean();
+            $newhtml = $novohtml;
+        }
+
+        if ($this->tipo == "php-moeda") {
+        	ob_start();
+        	echo eval($newhtml);
+        	$novohtml = ob_get_contents();
+        	ob_end_clean();
+            $newhtml = $novohtml;
+            $newhtml = number_format($newhtml,2,",",".");
+        }
+
+
+        if ($this->link != "") {
+            $condicao = $this->linkcondicao;
+            //echo $this->linkcondicao;
+            $ret = $this->validaCondicao($condicao,$linha);
+            if ($ret) {
+                $novolink = $this->replaceValorLinha($this->link,$linha);
+                $novolink = str_replace("{this_num_linha}",$i,$novolink);
+                $addtarget = "";
+                if ($this->target) {
+                    $addtarget = " target='_blank'";
+                }
+                if ($this->popup) {
+                    $addonclick = "  onClick=\"window.open('$novolink','Popup','width=600,top=50,left=50, scrollbars=yes');\" ";
+                    $novolink = "#";
+                }
+                $newhtml = "<a href=\"" . $novolink . "\"" . $addtarget . $addonclick . ">" . $newhtml . "</a>";
+            }
+        }
+        
+        if ($this->cor != "") {
+            $condicao = $this->corcondicao;
+            $ret = $this->validaCondicao($condicao,$linha);
+            if ($ret) {
+                $newhtml = "<span style='color: #" . $this->cor . ";'>" . $newhtml . "</span>"; 
+            }
+        }
+
+        return $newhtml;
+    }
+
+    public function replaceValorLinha($html,$linha) {
+        $newhtml = $html;
+        foreach (array_keys($linha) as $col) {
+            $newhtml = str_replace("{" .  $col . "}",$linha[$col],$newhtml);
+        }
+        return $newhtml;
+    }
+
+    function setCondicao($condicao) {
+        $this->condicao = $condicao;
+    }
+    
+    function setIdListagem($idlistagem) {
+        $this->idlistagem = $idlistagem;
+    }
+    
+    function setLinkCondicao($condicao) {
+        $this->linkcondicao = $condicao;
+    }
+    
+    function getCondicao() {
+        return $this->condicao;
+    }
+    
+    function getLinkCondicao() {
+        return $this->condicao;
+    }
+
+    function getVAlign($formatado = false) {
+        if ($formatado) {
+            if ($this->valign != "") {
+                $addvalign = " valign='" . $this->valign . "' ";
+            } else {
+                $addvalign = "";
+            }
+            return $addvalign;
+        } else {
+            return $this->valign;
+        }
+    }
+
+    public function __construct($idcoluna,$tipo,$nome,$html,$width = "",$nowrap = false,$align = "") {
+        $this->idcoluna = $idcoluna;
+        $this->nome = $nome;
+        $this->html = $html;
+        $this->width = $width;
+        $this->setTipo($tipo);
+        if ($align != "") { 
+        	$this->align = $align;
+        }
+        $this->nowrap = $nowrap;
+        $this->valign= "center";
+    }
+
+    public function setTipo($tipo) {
+        $align = "";
+        if ($tipo == "imagem") { $align = "center"; }
+        if ($tipo == "int") { $align = "right"; }
+        if ($tipo == "check") { $align = "center"; }
+        if ($tipo == "moeda") { $align = "right"; }
+        if ($tipo == "php-moeda") { $align = "right"; }
+        if ($tipo == "text") { $align = "left"; }
+        if ($tipo == "data") { $align = "center"; }
+        if ($tipo == "hora") { $align = "center"; }
+  /*      if ($tipo == "center") { $align = "center"; }
+        if ($tipo == "left") { $align = "left"; }
+        if ($tipo == "right") { $align = "right"; } */ 
+        $this->align = $align;
+        $this->tipo = $tipo;
+    }
+
+    public function setLink($link,$condicao,$target = "",$popup = false) {
+        $this->link = $link;
+        $this->target = $target;
+        $this->linkcondicao = $condicao;
+        $this->popup = $popup;
+    }
+    
+    public function setCor($cor,$condicao) {
+        $this->cor = $cor;
+        $this->corcondicao = $condicao;
+    }
+
+    public function getWidth($formatado = false) {
+        if ($formatado) {
+            if ($this->width != "") {
+                $addwidth = " width='" . $this->width . "' ";
+            } else {
+                $addwidth = "";
+            }
+            return $addwidth;
+        } else {
+            return $this->width;
+        }
+    }
+
+    public function getIdColuna() {
+        return $this->idcoluna;
+    }
+
+    public function getNome() {
+        return $this->nome;
+    }
+
+    public function getTipo() {
+        return $this->tipo;
+    }
+
+    public function getNowrap() {
+        return $this->nowrap;
+    }
+
+    public function getAlign() {
+        return $this->align;
+    }
+    
+    public function setVisibilidade($value) {
+    	$this->visivel = $value;
+    }
+    public function getVisibilidade() {
+    	return $this->visivel;
+    }
+    
+}
+?>
Index: trunk/workflow/inc/report/includes/classes/SqlParser.class.php
===================================================================
--- trunk/workflow/inc/report/includes/classes/SqlParser.class.php	(revision 5307)
+++ trunk/workflow/inc/report/includes/classes/SqlParser.class.php	(revision 5307)
@@ -0,0 +1,229 @@
+<?php
+
+class SqlParser {
+    
+    var $_sql;
+    var $_bloqueios = array(
+        "insert",
+        "update",
+        "delete",
+        //" into [temp]", //DESSA FORMA A EXPRESSÃO INTO É BLOQUEADA MAS SE FOR ACOMPANHADA DA PALAVRA TEMP ENTÃO SERÁ LIBERADA.
+        "drop ",
+        "alter ",
+        "database",
+        "create ",
+        "disable ",
+        "begin",
+        "rollback",
+        "commit",
+        "declare",
+        " abort",
+        "copy",
+        "close",
+        "execute",
+        "grant",
+        "revoke",
+        "reset",
+        "vacuum",
+        "truncate",
+        "cascade",
+		" overlay",
+		"prepare",
+		"dblink",
+		"dblink_exec");
+    
+    var $_erro = "";
+	
+    function SqlParser($sql) {
+    	$this->setSql($sql); 
+    }
+    
+    protected function procuraPalavra($texto,$palavra,$msgerro) {
+        $achou = "";
+        $palavratemchaves = stristr(strtolower($palavra),"[");
+        if ($palavratemchaves) {
+        	$liberado = str_replace(" ","",str_replace("]","",str_replace("[","",$palavra)));
+        	$arr = explode("[",$palavra);
+        	$bloqueado = $arr[0];
+        	$txtsemespacos = strtolower(str_replace(" ","",$texto));
+
+        	$achouliberado = stristr($txtsemespacos,$liberado);
+        	$achoubloqueio = stristr($texto,$bloqueado);
+        	
+        	if ($achoubloqueio != "" && $achouliberado != "") {
+        		$achou = "";
+        	} else {
+        		if ($achoubloqueio) {
+        			$achou = $achoubloqueio;
+        		}
+        	}
+        } else {
+        	$achou = stristr(strtolower($texto),$palavra);	
+        }
+        $palavratemparenteses = stristr(strtolower($palavra),"(");
+        
+        if ($palavratemparenteses) {
+        	$achou = stristr(strtolower(str_replace(" ","",$texto)),$palavra);
+        }
+        if ($achou!="") {
+            throw new Exception($msgerro);
+        }
+    }
+    
+    public function bloquearPalavra($palavra,$bloquear = true) {
+        if ($bloquear) {
+    	   array_push($this->_bloqueios,$palavra);
+        } else {
+            $arr = array();
+        	foreach($this->_bloqueios as $a) {
+        		if ($a != $palavra) {
+                    array_push($arr,$palavra);
+                }
+        	}
+            $this->_bloqueios = $arr;
+        }
+    }
+    
+    function verificaSql() {
+        $ret = false;
+        try {
+            $select = $this->_sql;
+            foreach ($this->_bloqueios as $palavra) {
+            	$arr = explode("[",$palavra);
+            	$palavrabloqueada = $arr[0];
+            	$this->procuraPalavra($select,$palavra,"Por questões de segurança, a palavra: '" . trim(strtoupper($palavrabloqueada)) . "' não é permitida.");
+            }
+           
+            $ret = true;
+            
+        } catch (Exception $e) {
+            $this->_erro = $e->getMessage();
+            $ret = false;
+        }
+        return $ret;
+    }
+    
+    function getErro() {
+    	return $this->_erro;
+    }
+    
+    public function setSql($value) {
+        $this->_sql = $value;
+    }
+    
+    public function getSql() {
+    	return $this->_sql;
+    }
+    
+    protected function getQuantidadeIfs($texto) {
+        $qtd = 0;
+        for ($i = 0;  $i <= strlen($texto); $i++) {
+            if (strtolower(substr($texto,$i,3)) == "#if") {
+                $qtd = $qtd + 1;
+            }
+        }
+        return $qtd;
+    }
+    
+    protected function numerarCondicao($texto,$num) {
+        $qtd = 0;
+        for ($i = 0;  $i <= strlen($texto); $i++) {
+            if (strtolower(substr($texto,$i,3)) == "#if") {
+                $qtd = $qtd + 1;
+                $condicoesabertas = 1;
+                $condicoesfechadas = 0;
+                if ($qtd == $num) {
+                    for ($j = $i+1;  $j <= strlen($texto); $j++) {
+                        
+                        if ((strtolower(substr($texto,$j,5)) == "#/if#")) {
+                            $condicoesfechadas = $condicoesfechadas + 1;
+                        }
+                        
+                        if ((strtolower(substr($texto,$j,3)) == "#if")) {
+                            $condicoesabertas = $condicoesabertas + 1;
+                        }
+    
+                        if ($condicoesfechadas == $condicoesabertas) {
+                            $condicao = substr($texto,$i,$j-$i+5);
+                            $condicao = "#co$num " . substr($condicao,4,strlen($condicao)-9) . "#/co$num#";
+                            $prefixo = substr($texto,0,$i);
+                            $sufixo = substr($texto,$j+5,strlen($texto));
+                            return $prefixo . $condicao . $sufixo;
+                        }
+                    }
+                }
+                
+            } 
+        }
+    }
+    
+    protected function validarCondicao($texto,$num) {
+        
+        try {
+        
+            $inicond = stripos($texto,"#co$num");
+            $endcond = stripos($texto,"#/co$num#");
+            $condicao = substr($texto,$inicond,$endcond-$inicond+6);
+            $conteudo = "";
+            
+            $fincond = stripos(substr($condicao,1,strlen($condicao)),"#");
+            $condeval = substr($condicao,strlen("#co$num"),$fincond-strlen("#co$num")+1);  
+            $condconcat = substr($condicao,$fincond+2,strlen($condicao)-$fincond-strlen("#/co$num#")-2);
+            if ($condeval != "") {
+                $fcondicao = ' if (' . trim($condeval) . ') { $ret = true; } else { $ret = false; }';
+                
+              //  echo $fcondicao . "<br>";
+            
+                if ($this->verificaSintaxe($fcondicao) === false) {
+                    throw new Exception("Impossível validar condição: ( $condeval )");
+                }
+                
+                
+                eval($fcondicao);
+                
+                $prefixo = substr($texto,0,$inicond);
+                $sufixo = substr($texto,$endcond+strlen("#/co$num#"),strlen($texto));
+                
+                if ($ret) {
+                    $conteudo = $condconcat;
+                }
+                
+                $novotexto = $prefixo . $conteudo . $sufixo;
+                $ret = $novotexto;
+            }
+        
+        } catch (Exception $e) {
+            $this->_erro = $e->getMessage();
+            $ret = false;
+        }
+
+        return $ret; 
+    }
+    
+    function verificaCondicoes() {
+        $ret = true;
+        $texto = $this->getSql();
+        $novotexto = $this->getSql();
+        $qtdifs = $this->getQuantidadeIfs($texto);
+        for ($i = $qtdifs;  $i >= 1; $i--) {
+           $ftexto = $this->numerarCondicao($novotexto,$i);
+           $novotexto = $ftexto;
+        }
+        for ($i = $qtdifs;  $i >= 1; $i--) {
+           $novotexto = $this->validarCondicao($novotexto,$i);
+           if ($novotexto == false) {
+           	  $ret = false;
+           }
+        }
+        $this->setSql($novotexto);
+
+        return $ret;
+    }
+    
+    protected function verificaSintaxe($code) {
+        return @eval('return true;' . $code);
+    }
+    
+}
+
+?>
Index: trunk/workflow/inc/report/includes/classes/FormularioUtil.class.php
===================================================================
--- trunk/workflow/inc/report/includes/classes/FormularioUtil.class.php	(revision 5307)
+++ trunk/workflow/inc/report/includes/classes/FormularioUtil.class.php	(revision 5307)
@@ -0,0 +1,161 @@
+<?  
+/**
+ * FormularioUtil
+ * 
+ * Funções uteis que podem ser usadas para facilitar e padronizar o desenvolvimento.
+ * @author Jair Pereira <pereira.jair@gmail.com>
+ */
+class FormularioUtil {
+	
+
+   /**
+     * Inclui os arquivos de CSS e de Javascript na Página.
+     * 
+     * @return void
+     */
+   function incluiCssJavascript($addpath = "") {
+    	echo "\n\n<script language=\"Javascript\" type=\"text/javascript\" src=\"$addpath./includes/js/mascaras.js\"></script>\n
+<script language=\"Javascript\" type=\"text/javascript\" src=\"$addpath./includes/js/jquery-1.3.2.js\"></script>\n
+<script language=\"Javascript\" type=\"text/javascript\" src=\"$addpath./includes/js/validacoes.js\"></script>\n
+<script language=\"Javascript\" type=\"text/javascript\" src=\"$addpath./includes/js/auxiliares.js\"></script>\n
+<script language=\"Javascript\" type=\"text/javascript\" src=\"$addpath./includes/js/calendar.js\"></script>\n
+<script language=\"Javascript\" type=\"text/javascript\" src=\"$addpath./includes/js/FormularioUtil.js\"></script>\n
+<link rel=\"stylesheet\" href=\"$addpath./includes/css/base_form.css\" media=\"screen\"></link>\n
+<link rel=\"stylesheet\" href=\"$addpath./includes/css/calendar.css\" media=\"screen\"></link>\n\n";
+    	
+    }
+   
+    /**
+     * Função para escrever uma Mensagem de Erro ou Sucesso na Listagem.
+     * @param $msg
+     * @return unknown_type
+     */
+    function escreveMensagem($msg) {
+        if ($msg) {
+          echo "<div class='msg'>$msg<br><br></div>";
+        } else {
+            echo "<br>";
+        }
+    }
+   
+   /**
+     * Abre o Quadro Principal
+     * 
+     * Função para abrir o quadro Principal do Sistema.
+     *
+     * @param  string $titulo
+     * @return void
+     */
+   function abreQuadro($titulo) {
+   	 $html = '<br><div align=center><table width="98%" class="tableMoldura">
+<tr class="tableTitulo">
+    <td><h1>' . $titulo . '</h1></td>
+</tr>
+<tr>
+    <td align="center"><br>
+    
+    <table width="98%">';
+    
+    echo $html;
+   }
+   
+   /**
+     * Fecha o Quadro Principal
+     * 
+     * Função para fechar o quadro Principal do Sistema.
+     * 
+     * @return void
+     */
+   function fechaQuadro() {
+   	  	$html = "\n</td></tr>\n</table>\n</div>";
+    	echo $html;
+   }
+   
+   /**
+     * MontaArraySelect
+     * 
+     * Função para Retornar o array necessário para montar um campo do tipo SELECT. 
+     * Parâmetros: Conexão, SQL, Id (nome do campo que será usado para o value das options), Valor (nome do campo que será mostrado nas options) 
+     *
+     * @param  string $conn
+     * @param  string $sql
+     * @param  string $id
+     * @param  string $value
+     * @return array $arrSelectValues
+     */
+   function MontaArraySelect($conn,$sql,$id,$value) {
+	    $arrSelectValues = array();
+		$resu = pg_query($conn,$sql);
+		if (pg_num_rows($resu)>0) {
+	        for ($x=0;$x<pg_num_rows($resu);$x++)  {
+	            $arrSelectValues[pg_fetch_result($resu,$x,$id)] = pg_fetch_result($resu,$x,$value);
+	        }
+		}
+		return $arrSelectValues;
+    }
+    
+    /**
+     * MontaArraySelect
+     * 
+     * Função para Retornar o array necessário para montar um campo do tipo SELECT. 
+     * Parâmetros: Conexão, SQL, Id (nome do campo que será usado para o value das options), Valor (nome do campo que será mostrado nas options) 
+     *
+     * @param  string $conn
+     * @param  string $sql
+     * @param  string $id
+     * @param  string $value
+     * @return array $arrSelectValues
+     */
+   function MontaArrayCheckBox($conn,$sql,$oid,$descricao) {
+	    $arrSelectChecks = array();
+		$resu = pg_query($conn,$sql);	
+		if (pg_num_rows($resu)>0) {
+	        for ($x=0;$x<pg_num_rows($resu);$x++)  {
+	            $arrSelectChecks[] = array(pg_fetch_result($resu,$x,$oid), pg_fetch_result($resu,$x,$descricao), false);
+	        }
+		}
+		return $arrSelectChecks;
+    }
+    
+    function MontaArrayRadio($conn,$sql,$oid,$descricao) {
+	    $arrSelectChecks = array();
+		$resu = pg_query($conn,$sql);	
+		if (pg_num_rows($resu)>0) {
+	        for ($x=0;$x<pg_num_rows($resu);$x++)  {
+	            $arrSelectChecks[] = array(pg_fetch_result($resu,$x,$oid), pg_fetch_result($resu,$x,$descricao), false);
+	        }
+		}
+		return $arrSelectChecks;
+    }
+    
+    function MontaArrayCondicao($conn,$sql,$key,$condicao) {
+    	$arr = array();
+		$resu = pg_query($conn,$sql);	
+		if (pg_num_rows($resu)>0) {
+			while ($linha = pg_fetch_array($resu,$i,PGSQL_ASSOC)) {
+				$ret = $this->validaCondicao($condicao,$linha);
+				if ($ret) {
+					array_push($arr,$linha[$key]);
+				}
+			}
+		}
+		return $arr;
+    }
+    
+    public function validaCondicao($condicao,$linha,$debug = false) {
+        foreach (array_keys($linha) as $col) {
+            $condicao = str_replace("{" .  $col . "}","'" . $linha[$col] . "'",$condicao);
+        }
+        $fcondicao = ' if (' . $condicao . ') { $ret = true; } else { $ret = false; }';
+        if ($condicao != "") {
+          if ($debug) { echo "<br>" . $fcondicao ; } 
+          eval($fcondicao);
+        } else {
+            $ret = false;
+        }
+        return $ret;
+    }
+	
+}
+
+?>
Index: trunk/workflow/inc/report/includes/classes/Formulario.class.php
===================================================================
--- trunk/workflow/inc/report/includes/classes/Formulario.class.php	(revision 5307)
+++ trunk/workflow/inc/report/includes/classes/Formulario.class.php	(revision 5307)
@@ -0,0 +1,1313 @@
+<?php
+/**
+ * Formulario
+ *
+ * Implementacao de Formularios Padroes do Sistema.
+ */
+/**
+ * Formulario
+ *
+ * Implementacao de Formularios Padroes do Sistema.
+ *
+ *
+ * @author Jair Pereira <pereira.jair@gmail.com>
+ * @since 25/05/2009
+ *
+ * @package Formulario
+ */
+
+include 'FormularioHtml.class.php';
+include 'FormularioUtil.class.php';
+if (file_exists("../../xajax/xajax.inc.php")) { include_once "../../xajax/xajax.inc.php"; }
+if (file_exists("../../../xajax/xajax.inc.php")) { include_once "../../../xajax/xajax.inc.php"; }
+
+class Formulario {
+
+    /**
+     * FormularioUtil - Instï¿œncia da Classe Formulï¿œrio Util.
+     */
+    public $util = FormularioUtil;
+
+    /**
+     * Array de FormularioHtml do Formulï¿œrio
+     */
+    private $_arrinputs = array();
+
+    /**
+     * Array de funï¿œï¿œes em Xajax.
+     */
+    private $_arrxajax = array();
+
+    /**
+     * Array de Querys em ajax.
+     */
+    private $_arrxajaxquery = array();
+
+    /**
+     * Array de arquivos que vieram por upload.
+     */
+    private $_arrfilesuploaded = array();
+
+    /**
+     * Array de Quadros pertencentes ao formulï¿œrio.
+     */
+    private $_arrquadros = array();
+    /**
+     * Array de Campos Agrupados.
+     */
+    private $_agruparcampos = array();
+    /**
+     * Array de Campos que Jï¿œ foram Desenhados na tela,
+     * Utilizado para evitar que o mesmo campo seja desenhado duas vezes.
+     */
+    private $_desenhou = array();
+    /**
+     * Nome do Formulï¿œrio.
+     */
+    private $_nomeform;
+    /**
+     * Action do Formulï¿œrio.
+     */
+    private $_action;
+    /**
+     * Mï¿œtodo do Formulï¿œrio.
+     */
+    private $_method;
+    /**
+     * Valor do Onsubmit do formulï¿œrio.
+     */
+    private $_onsubmit;
+    /**
+     * Armazena o Cï¿œdigo HTML A ser impresso na tela.
+     */
+    //private $_htmlForm;
+    
+    private $html;
+
+    /**
+     * A funï¿œï¿œo desenhar() jï¿œ foi chamada?.
+     */
+    private $_desenhado = false;
+
+    /**
+     * ï¿œ um formulï¿œrio de Upload de arquivos?.
+     */
+    private $_isupload = false;
+
+    /**
+     * Depuraï¿œï¿œo de Cï¿œdigo ativada?
+     */
+    private $_debug = true;
+    
+    private $_iscachedform = false;
+
+    /**
+     * Array com os erros do debug.
+     */
+    private $_errors = array();
+    
+    private $_microtime;
+
+    private $inputDisplayOptions = array("open_tr" => true,
+                                         "open_td" => true,
+                                         "open_td_colspan" => 1,
+                                         "makedivision" => true,
+                                         "close_td" => true,
+                                         "close_tr" => true);
+
+    private $FirstGroupColsDisplayOptions = array("open_tr" => true,
+                                         "open_td" => true,
+                                         "open_td_colspan" => 1,
+                                         "makedivision" => true,
+                                         "close_td" => false,
+                                         "close_tr" => false);
+     
+    private $FirstGroupDisplayOptions = array("open_tr" => true,
+                                         "open_td" => true,
+                                         "open_td_colspan" => 100,
+                                         "makedivision" => true,
+                                         "close_td" => false,
+                                         "close_tr" => false);
+
+    private $InputGroupDisplayOptions = array("open_tr" => false,
+                                         "open_td" => false,
+                                         "open_td_colspan" => 1,
+                                         "makedivision" => false,
+                                         "close_td" => false,
+                                         "close_tr" => false);
+
+    private $InputGroupColsDisplayOptions = array("open_tr" => false,
+                                         "open_td" => true,
+                                         "open_td_colspan" => 1,
+                                         "makedivision" => true,
+                                         "close_td" => false,
+                                         "close_tr" => false);
+     
+    private $ButtonDisplayOptions = array("open_tr" => false,
+                                         "open_td" => false,
+                                         "makedivision" => false,
+                                         "close_td" => false,
+                                         "close_tr" => false);
+
+    /**
+     * Instancia uma nova Interface de Formulï¿œrio
+     *
+     * @param string $name Nome
+     * @param string $action Action
+     * @param string $method Mï¿œtodo
+     * @param string $onsubmit Funï¿œï¿œo Javascript do OnSubmit
+     * @return void
+     */
+    function Formulario($name = "frmpadrao",$action = "",$method = "post",$onsubmit = "") {
+        $this->Interface = new FormularioHtml();
+        $this->setForm($name);
+        $this->setAction($action);
+        $this->setMethod($method);
+        $this->setOnSubmit($onsubmit);
+        $this->util = new FormularioUtil();
+       // $microtime = microtime(true);
+        $microtime = rand(0,900);
+        $this->microtime = $microtime;
+        $this->adicionarHidden($name . "_pkey",$microtime);
+     //   $this->adicionarHidden($name . "_lastpkey",$_POST[$name . "_pkey"]);
+    }
+
+    /**
+     * Verifica se o ID passado jï¿œ foi adicionado como sendo um campo do formulï¿œrio.
+     *
+     * @param string $idinput ID Input
+     * @return void
+     */
+    protected function isInput($idinput) {
+        if ($idinput != "") {
+            $achou = false;
+            foreach ($this->_arrinputs as $input) {
+                if ($input->getName() == $idinput)
+                $achou = true;
+            }
+        } else {
+            $achou = true;
+        }
+        return $achou;
+    }
+
+    /**
+     * Retorna o Input para o ID passado.
+     *
+     * @param string $idinput ID Input
+     * @param boolean $retornaposicao Retorna a posiï¿œï¿œo do input no _arrinputs.
+     * @return void
+     */
+    protected function getInput($idinput,$retornaposicao = false) {
+        if ($idinput != "") {
+            $achou = "-1";
+            $i = 0;
+            foreach ($this->_arrinputs as $input) {
+                 
+                if ($input->getName() == $idinput) {
+                    if ($retornaposicao) {
+                        $achou = $i;
+                    } else {
+                        $achou = $input;
+                    }
+                }
+                $i = i + 1;
+            }
+        } else {
+            $achou = "-1";
+       	}
+       	return $achou;
+    }
+
+    /**
+     * Agrupar Campos em um Formulï¿œrio
+     *
+     * Posiciona Campos um lado do outro em um formulï¿œrio, em uma mesma linha sem criar divisï¿œes nas tabelas.
+     *
+     * Exemplo:
+     * <code>
+     * $form->adicionarCampo("nome",(.....));
+     * $form->adicionarCampo("cpf",(.....));
+     * $form->adicionarCampo("rg",(.....));
+     * $form->agruparCampos("nome,cpf,rg");
+     * </code>
+     *
+     * @param string $campos Nome dos Campos a serem Agrupados, Separados por vï¿œrgula.
+     */
+    function agruparCampos($camposagrupados,$colunas = true) {
+        $arrcampos1 = explode(";",$camposagrupados);
+        foreach ($arrcampos1 as $campos) {
+            $arrcampos = explode(",",$campos);
+            $agcampos = array($arrcampos[0] => $arrcampos);
+
+            //VERIFICA SE O CAMPO Jï¿œ FOI ADICIONADO E A ORDEM QUE FOI ADICIONADO AO FORMULï¿œRIO.
+            if ($this->_debug) {
+                //$achouprimeiro = false;
+                foreach ($arrcampos as $idcampo) {
+                     
+                    /*	if ($achouprimeiro) {
+                     if (in_array($idcampo,$this->desenhou)) {
+                     $this->adicionarErro("agruparCampos()<br>ID: " . $idcampo . " achou.",false);
+                     }
+                     }
+                     if ($idcampo == $arrcampos[0]) {
+                     $achouprimeiro = true;
+                     } */
+                    if ((!$this->isInput($idcampo)) && ($idcampo != "")) {
+                        $this->adicionarErro("agruparCampos()<br>ID: " . $idcampo . " nï¿œo ï¿œ um campo no formulï¿œrio.",false);
+                    }
+                }
+            }
+
+            $agcampos["colunas"] = $colunas;
+            array_push($this->_agruparcampos,$agcampos);
+        }
+    }
+
+    /**
+     * Adiciona um Quadro ao Formulï¿œrio
+     *
+     * $campos ï¿œ opcional, SOMENTE quando sï¿œ existe um quadro para o Formulï¿œrio, a classe automaticamente entende que ï¿œ todos os campos que jï¿œ foram adicionados.
+     *
+     * @param string $idquadro Id do Quadro
+     * @param string $titulo Tï¿œtulo do Quadro
+     * @param string $campos Campos que Pertencerï¿œo ao Quadro (separados por vï¿œrgula)
+     */
+    function adicionarQuadro($idquadro,$titulo = "",$campos = "") {
+        $arrcampos = explode(",",$campos);
+        if ($this->_debug) {
+            if (is_array($this->_arrquadros[$idquadro])) {
+                $this->adicionarErro("adicionarQuadro()<br>ID: $idquadro jï¿œ foi adicionado no formulï¿œrio.");
+            }
+            foreach ($arrcampos as $campo) {
+                if ($this->isInputInQuadro($campo)) {
+                    $this->adicionarErro("adicionarQuadro()<br>ID: $campo jï¿œ foi adicionado a outro quadro neste formulï¿œrio.");
+                }
+                if (!$this->isInput($campo)) {
+                    $this->adicionarErro("adicionarQuadro()<br>ID: $campo Nï¿œO estï¿œ adicionado no formulï¿œrio.");
+                }
+            }
+        }
+
+        if ($campos == "") {
+            $arrcampos = $this->montaArrayQuadroCampos($idquadro);
+        }
+
+        $quadro = array("idquadro" => $idquadro,"titulo" => $titulo, "campos" => $arrcampos,"botoes" => array());
+        $this->_arrquadros[$idquadro] = $quadro;
+    }
+
+    /**
+     * Funï¿œï¿œo interna para verificar se um Input jï¿œ foi adicionado em algum quadro.
+     *
+     * @param string $idinput Id do Input
+     * @return boolean
+     */
+    protected function isInputInQuadro($idinput) {
+        $ret = false;
+        foreach ($this->_arrquadros as $quadro) {
+            if (in_array($idinput,$quadro['campos'])) {
+                $ret = true;
+            }
+        }
+        return $ret;
+    }
+    
+    public function setCachedForm($value) {
+    	$this->_iscachedform = $value;
+    }
+
+    /**
+     * Adiciona um Botï¿œo ao Rodapï¿œ de um Quadro do Formulï¿œrio
+     *
+     * @param string $idquadro Id do Quadro
+     * @param string $idbutton Id do Botï¿œo
+     */
+    function adicionarQuadroButton($idquadro,$idbutton) {
+        if (!is_array($this->_arrquadros[$idquadro])) {
+            $erro = true;
+            if ($this->_debug) {
+                $this->adicionarErro("adicionarQuadroButton()<br>ID: $idquadro Nï¿œO estï¿œ adicionado no formulï¿œrio.");
+            }
+        }
+        if (!$this->isInput($idbutton)) {
+            $erro = true;
+            if ($this->_debug) {
+                $this->adicionarErro("adicionarQuadroButton()<br>ID: $idbutton Nï¿œO ï¿œ um campo no formulï¿œrio.");
+            }
+        }
+        if (!$erro) {
+            foreach ($this->_arrinputs as $input) {
+                if ($input->getName() == $idbutton) {
+                    array_push($this->_arrquadros[$idquadro]["botoes"],$input);
+                }
+            }
+        }
+    }
+
+    /**
+     * Adiciona Campo
+     *
+     * Funï¿œï¿œo para adicionar campos no formulï¿œrio, permite vï¿œrios formatos de tipo.
+     *
+     * tipo: text,data,periodo,moeda,cpf,cnpj,hidden,button
+     *
+     * @param  string $name
+     * @param  string $tipo
+     * @param  string $label
+     * @param  string $title
+     * @param  string $value
+     * @param  string $obrigatorio
+     * @param  string $width
+     * @param  string $maxlenght
+     * @param  string $inforight
+     * @return void
+     */
+    function adicionarCampo($name,$tipo,$label,$title,$value = "",$obrigatorio = false,$width = "30",$maxlenght = "100",$inforight = "") {
+        $iface = new FormularioHtml();
+        $iface->setForm($this->_nomeform);
+        $iface->setTipo($tipo);
+        $iface->setName($name);
+        $valores = explode("|",$value);
+        $iface->setValue(str_replace("\'","'",$valores[0]));
+        $iface->setValueAux(str_replace("\'","'",$valores[1]));
+        $iface->setTitle($title);
+        $iface->setLabel($label);
+        $iface->setObrigatorio($obrigatorio);
+        $iface->setSize($width,$maxlenght);
+        $iface->setInfoRight($inforight);
+        if ($this->isInput($name)) {
+            if ($this->_debug) {
+                $this->adicionarErro("adicionarCampo()<br>ID: $name foi adicionado duas vezes ao formulï¿œrio. Remova um campo ou altere seu ID.");
+            }
+        } else {
+            array_push($this->_arrinputs,$iface);
+        }
+    }
+
+    /**
+     * Adiciona Campo Hidden
+     *
+     * Funï¿œï¿œo para adicionar campos hidden no formulï¿œrio.
+     *
+     * @param  string $name Nome do Campo
+     * @param  string $value Valor do Campo
+     * @return void
+     */
+    function adicionarHidden($name,$value) {
+        $this->adicionarCampo($name,"hidden",$name,"",$value);
+    }
+
+    /**
+     * Adiciona Arquivo
+     *
+     * Funï¿œï¿œo para adicionar campos file no formulï¿œrio.
+     *
+     * @param  string $name Nome do Campo
+     * @param  string $value Valor do Campo
+     * @return void
+     */
+    function adicionarUploadArquivo($name,$label,$pasta,$prefixo,$obrigatorio = false,$force = false) {
+        $this->_isupload = true;
+        $this->adicionarCampo($name,"file",$label,$pasta,$prefixo,$obrigatorio,$force);
+    }
+
+    /**
+     * Adiciona Campo Select
+     *
+     * Funï¿œï¿œo para adicionar campos select no formulï¿œrio.
+     *
+     * @param string $name Nome do Campo
+     * @param string $label Label do Campo
+     * @param string $title Tï¿œtulo do Campo
+     * @param string $value Valor Prï¿œ-Selecionado
+     * @param array $data Array com Conteï¿œdo do Select. Veja: $IUtils->MontaArraySelect();
+     * @param boolean $obrigatorio Campo Obrigatï¿œrio
+     * @param string $textoescolha Adiciona um Option com value = '' com o Texto passado na variï¿œvel.
+     * @param string $width Tamanho em pixels do Select
+     * @param string $height Altura em Linhas do Select (Usado para Mï¿œltiplos Campos)
+     * @param boolean $multiplo Indica se pode haver mais de um item selecionado.
+     * @return void
+     */
+    function adicionarSelect($name,$label,$title,$value,$data,$obrigatorio = false,$textoescolha = "",$width = "100",$height = "1",$multiplo = false,$selectCor = "",$arrCores = "") {
+        $iface = new FormularioHtml();
+        $iface->setForm($this->_nomeform);
+        $iface->setName($name);
+        $iface->setValue($value);
+        $iface->setTitle($title);
+        $iface->setValuesSelect($data);
+        $iface->setSize($width,$height);
+        $mostraescolha = true;
+        if ($textoescolha == "") {
+            $mostraescolha = false;
+        }
+        $iface->setMultiplo($multiplo);
+        $iface->setSelectEscolha($mostraescolha, $textoescolha);
+        $iface->setLabel($label);
+        $iface->setObrigatorio($obrigatorio);
+        $iface->setTipo("select");
+        
+        if ($selectCor != "") {
+        	$iface->setValuesSelectCor($selectCor,$arrCores);
+        }
+        
+        if ($this->isInput($name)) {
+            if ($this->_debug) {
+                $this->adicionarErro("adicionarSelect()<br>ID: $name foi adicionado duas vezes ao formulï¿œrio. Remova um campo ou altere seu ID.");
+            }
+        } else {
+            array_push($this->_arrinputs,$iface);
+        }
+    }
+
+    /**
+     * Adiciona Campo CheckBox
+     *
+     * Funï¿œï¿œo para adicionar campos chekcbox no formulï¿œrio.
+     *
+     * @param string $name Nome do Campo
+     * @param string $label Label do Campo
+     * @param string $value Valor Prï¿œ-Selecionado
+     * @param array $data Array com Conteï¿œdo do CheckBox.
+     * @param boolean $obrigatorio Campo Obrigatï¿œrio
+     * @return void
+     */
+    function adicionarCheckBox($name,$label,$data,$obrigatorio = false) {
+        $iface = new FormularioHtml();
+        $iface->setForm($this->_nomeform);
+        $iface->setName($name);
+        $iface->setValuesChecks($data);
+        $iface->setLabel($label);
+        $iface->setObrigatorio($obrigatorio);
+        $iface->setTipo("checkbox");
+        if ($this->isInput($name)) {
+            if ($this->_debug) {
+                $this->adicionarErro("adicionarCheckBox()<br>ID: $name foi adicionado duas vezes ao formulï¿œrio. Remova um campo ou altere seu ID.");
+            }
+        } else {
+            array_push($this->_arrinputs,$iface);
+        }
+    }
+
+    /**
+     * Adiciona Campo Radios
+     *
+     * Funï¿œï¿œo para adicionar campos radios no formulï¿œrio.
+     *
+     * @param string $name Nome do Campo
+     * @param string $label Label do Campo
+     * @param string $value Valor Prï¿œ-Selecionado
+     * @param array $data Array com Conteï¿œdo do CheckBox.
+     * @param boolean $obrigatorio Campo Obrigatï¿œrio
+     * @return void
+     */
+    function adicionarRadio($name,$label,$data,$obrigatorio = false) {
+        $iface = new FormularioHtml();
+        $iface->setForm($this->_nomeform);
+        $iface->setName($name);
+        $iface->setValuesRadio($data);
+        $iface->setLabel($label);
+        $iface->setObrigatorio($obrigatorio);
+        $iface->setTipo("radio");
+        if ($this->isInput($name)) {
+            if ($this->_debug) {
+                $this->adicionarErro("adicionarRadio()<br>ID: $name foi adicionado duas vezes ao formulï¿œrio. Remova um campo ou altere seu ID.");
+            }
+        } else {
+            array_push($this->_arrinputs,$iface);
+        }
+    }
+
+    /**
+     * Adiciona Campo TextArea
+     *
+     * Funï¿œï¿œo para adicionar campos TextArea no formulï¿œrio.
+     *
+     * @param string $name Nome do Campo
+     * @param string $label Label do Campo
+     * @param string $value Valor Prï¿œ-Selecionado
+     * @param boolean $obrigatorio Campo Obrigatï¿œrio
+     * @param string $cols Colunas
+     * @param string $rows Linhas
+     * @return void
+     */
+    function adicionarTextarea($name,$label,$value,$obrigatorio = false,$cols = "80",$rows = "6") {
+        $iface = new FormularioHtml();
+        $iface->setForm($this->_nomeform);
+        $iface->setName($name);
+        $iface->setLabel($label);
+        $iface->setObrigatorio($obrigatorio);
+        $iface->setValue(str_replace("\'","'",$value));
+        $iface->setSize($cols,$rows);
+        $iface->setTipo("textarea");
+        if ($this->isInput($name)) {
+            if ($this->_debug) {
+                $this->adicionarErro("adicionarTextarea()<br>ID: $name foi adicionado duas vezes ao formulï¿œrio. Remova um campo ou altere seu ID.");
+            }
+        } else {
+            array_push($this->_arrinputs,$iface);
+        }
+    }
+
+    /**
+     * Adiciona Botï¿œo
+     *
+     * Funï¿œï¿œo para adicionar campos Button no formulï¿œrio.
+     *
+     * @param string $name Nome do Campo
+     * @param string $value Valor
+     * @return void
+     */
+    function adicionarButton($name,$value) {
+        $iface = new FormularioHtml();
+        $iface->setForm($this->_nomeform);
+        $iface->setName($name);
+        //$iface->setLabel($label);
+        $iface->setValue(str_replace("\'","'",$value));
+        $iface->setTipo("button");
+        if ($this->isInput($name)) {
+            if ($this->_debug) {
+                $this->adicionarErro("adicionarButton()<br>ID: $name foi adicionado duas vezes ao formulï¿œrio. Remova um campo ou altere seu ID.");
+            }
+        } else {
+            array_push($this->_arrinputs,$iface);
+        }
+    }
+
+
+    /**
+     * Adiciona Botï¿œo SUBMIT
+     *
+     * Funï¿œï¿œo para adicionar SUBMIT no formulï¿œrio.
+     *
+     * @param string $idquadro ID do Quadro
+     * @param string $name Nome do Campo
+     * @param string $value Valor
+     * @param string $acao Aï¿œï¿œo de Submit
+     * @return void
+     */
+    function adicionarSubmit($idquadro,$name,$value,$acao) {
+        $erro = false;
+        if (!is_array($this->_arrquadros[$idquadro])) {
+            if ($this->_debug) {
+                $this->adicionarErro("adicionarSubmit()<br>Quadro: $idquadro nï¿œo estï¿œ adicionado no formulï¿œrio.");
+            }
+            $erro = true;
+        }
+        if (!$erro) {
+            $this->adicionarButton($name,$value);
+            $this->adicionarCampoAcao($name,"onclick","valida(document." . $this->_nomeform . ",'" . $acao . "',true);");
+            $this->adicionarQuadroButton($idquadro,$name);
+        }
+    }
+
+    /**
+     * Adiciona Subtitulo
+     *
+     * Funï¿œï¿œo para adicionar Subtitulos no Formulï¿œrio
+     *
+     * @param string $value Subtï¿œtulo
+     * @return void
+     */
+    function adicionarSubTitulo($value) {
+        $iface = new FormularioHtml();
+        $iface->setForm($this->_nomeform);
+        $id = count($this->_arrinputs);
+        $iface->setName("iFace_subtitulo_" . $id);
+        $iface->setValue($value);
+        $iface->setTipo("subtitulo");
+        array_push($this->_arrinputs,$iface);
+    }
+    
+    /**
+     * Adiciona um Div
+     *
+     * Funï¿œï¿œo para adicionar um Div no Formulï¿œrio
+     *
+     * @param string $value Subtï¿œtulo
+     * @return void
+     */
+    function adicionarDiv($value) {
+        $iface = new FormularioHtml();
+        $iface->setForm($this->_nomeform);
+        $id = count($this->_arrinputs);
+        $iface->setName("iFace_div_" . $id);
+        $iface->setValue($value);
+        $iface->setTipo("div");
+        array_push($this->_arrinputs,$iface);
+    }
+
+    /**
+     * Altera o Nome do Formulï¿œrio
+     *
+     * @param string $name Nome do Formulï¿œrio
+     * @return void
+     */
+    protected function setForm($nome) {
+        $this->_nomeform = $nome;
+    }
+
+    /**
+     * Altera o Action do Formulï¿œrio
+     *
+     * @param string $action Action do Formulï¿œrio
+     * @return void
+     */
+    public function setAction($action) {
+        if ($action == "") { $action = $_SERVER['PHP_SELF']; }
+        $this->_action = $action;
+    }
+
+    /**
+     * Altera o Mï¿œtodo do Formulï¿œrio
+     *
+     * @param string $method Mï¿œtodo do Formulï¿œrio
+     * @return void
+     */
+    protected function setMethod($method) {
+        $this->_method = $method;
+    }
+
+    /**
+     * Altera o OnSubmit do Formulï¿œrio
+     *
+     * @param string $onsubmit OnSubmit do Formulï¿œrio
+     * @return void
+     */
+    protected function setOnSubmit($onsubmit) {
+        $this->_onsubmit = $onsubmit;
+    }
+
+    /**
+     * Escreve o Cï¿œdigo de Abertura do Formulï¿œrio.
+     *
+     * @return void
+     */
+    public function abreForm() {
+       	echo "\n\n";
+       	if ($this->_isupload) { $adicionarenctype = ' enctype="multipart/form-data"'; }
+       	echo '<form name="' .  $this->_nomeform  . '" id="' .  $this->_nomeform  . '" method="'  . $this->_method .'" action="' .  $this->_action  . '"' . $adicionarenctype .'>';
+       	echo "\n<input type='hidden' name='" .  $this->_nomeform  . "_acao' id='" .  $this->_nomeform  . "_acao'>";
+       	//echo "\n<input type='hidden' name='" .  $this->_nomeform  . "_ordem' id='" .  $this->_nomeform  . "_ordem' value='" . $_POST[$this->_nomeform . "_ordem"] . "'>";
+        //echo "\n<input type='hidden' name='" .  $this->_nomeform  . "_ordemtipo' id='" .  $this->_nomeform  . "_ordemtipo' value='" . $_POST[$this->_nomeform . "_ordemtipo"] . "'>";
+    }
+
+    /**
+     * Escreve o Cï¿œdigo de Fechamento do Formulï¿œrio.
+     *
+     * @return void
+     */
+    public function fechaForm() {
+        //SALVA NA SESSï¿œO A VARIï¿œVEL QUE VERIFï¿œCA SE O FORMULï¿œRIO FOI SUBMETIDO OU SE FOI PRESSIONADO F5.
+//        session_start();
+        $_SESSION[$this->_nomeform . "_pkey"] = $this->microtime;
+        echo "\n</form>";
+    }
+
+    /**
+     * Escreve o Cï¿œdigo de Abertura de um Quadro
+     *
+     * @param string $idquadro ID do quadro a ser Aberto
+     * @return void
+     */
+    public function escreveAbreQuadro($idquadro) {
+        if ($this->_arrquadros[$idquadro]["titulo"] != "") {
+            echo "\n<div align='center'>\n<table class='tableMoldura' width='98%'  id='quadro_$idquadro'>";
+            echo "\n\t<tr class='tableSubTitulo'>\n\t\t<td colspan='4'><h2>" . $this->_arrquadros[$idquadro]["titulo"] . "</h2></td>\n\t</tr>\n\t<tr>\n\t<td>\n\t<table width='100%' border='0'><br>";
+        } else {
+            echo "\n<div align='center'>\n<table width='100%'  id='quadro_$idquadro' cellpadicionaring=0 cellspacing=0><tr><td>\n\t<table width='100%' border='0' cellpadicionaring=0 cellspacing=0>";
+        }
+    }
+
+    /**
+     * Escreve o Cï¿œdigo de Fechamento de um Quadro
+     *
+     * @param string $idquadro ID do quadro a ser Fechado
+     * @return void
+     */
+    public function escreveFechaQuadro($idquadro) {
+        echo "</table>\n\t" .
+    			"\n\t</td></tr>\n";
+
+        if (count($this->_arrquadros[$idquadro]["botoes"])) {
+            echo "\t<tr class='tableRodapeModelo1''>\n
+			\t\t<td colspan='2' align='center'>\n"; 
+            foreach ($this->_arrquadros[$idquadro]["botoes"] as $botao) {
+                echo $botao->desenhaHtmlForm($this->ButtonDisplayOptions) . "";
+                array_push($this->_desenhou,$botao->getName());
+            }
+
+            echo "</td>\n\t</tr>\n";
+        }
+
+
+        echo "</table>\n
+		</div>\n";
+    }
+
+
+    /**
+     * Adiciona uma Aï¿œï¿œo Javascript para qualquer campo do formulï¿œrio
+     *
+     * Exemplo:
+     * <code>
+     * $form->adicionarCampo("nome",(...));
+     * $form->adicionarCampoAcao("nome","onclick","alert('onclick');");
+     * $form->adicionarCampoAcao("nome","onblur","alert('onblur');");
+     * </code>
+     *
+     * Possï¿œveis valores para tipo:
+     * onclick, onchange, onblur, onmouseout, onmousemove, onkeydown, onkeypress, onkeyup
+     *
+     *
+     * @param string $name Nome do Campo
+     * @param string $tipo Tipo de Aï¿œï¿œo
+     * @param string $javascript Cï¿œdigo em JavaScript a ser Executado.
+     * @return void
+     */
+    public function adicionarCampoAcao($name,$tipo,$javascript) {
+        $i = 0;
+        if (!$this->isInput($name)) {
+            $this->adicionarErro("adicionarCampoAcao()<br>ID: " . $name . " nï¿œo ï¿œ um campo no formulï¿œrio.",false);
+        }
+        foreach ($this->_arrinputs as $input) {
+            $i = $i + 1;
+            if (is_object($this->_arrinputs[$i])) {
+                if ($this->_arrinputs[$i]->getName() == $name) {
+                    $campo = $this->_arrinputs[$i];
+                    $campo->adicionarEvento(strtolower($tipo),$javascript);
+                    $this->_arrinputs[$i] = $campo;
+                }
+            }
+        }
+    }
+
+
+    /**
+     * Funï¿œï¿œo utilizada internamente para verificar se um botï¿œo faz parte de um quadro.
+     *
+     * @param string $name Nome do Botï¿œo
+     * @return boolean
+     */
+    protected function isInRodapeQuadro($name) {
+        $ret = false;
+        foreach ($this->_arrquadros as $quadro) {
+            foreach ($quadro["botoes"] as $botoes) {
+                if ($botoes->getName() == $name) {
+                    $ret = true;
+                }
+            }
+        }
+        return $ret;
+    }
+
+    /**
+     * Funï¿œï¿œo utilizada para Desenhar um campo do Formulï¿œrio.
+     *
+     * @param string $name Nome do Botï¿œo
+     * @param boolean true $showtableRow Escreve a Divisï¿œo TR
+     * @param boolean treu $showtableDivision Escreve a Divisï¿œo TD
+     * @return boolean
+     */
+    public function desenhaCampo($name,$options = "") {
+        if ($options == "") { $options = $this->inputDisplayOptions; }
+        if (!is_object($name)) {
+            if (!in_array($name,$this->_desenhou)) {
+                foreach ($this->_arrinputs as $input) {
+                    if ($input->getName() == $name) {
+                        if (!$this->isInRodapeQuadro($input->getName())) {
+                            echo $input->desenhaHtmlForm($options);
+                            array_push($this->_desenhou,$input->getName());
+                        }
+                    }
+                }
+            } else {
+                $this->adicionarErro("desenhaCampo()<br>Nï¿œo ï¿œ possï¿œvel desenhar o ID: $name jï¿œ foi desenhado no formulï¿œrio.");
+            }
+        } else {
+            $input = $name;
+            if (!in_array($input->getName(),$this->_desenhou)) {
+                if (!$this->isInRodapeQuadro($input->getName())) {
+                    echo $input->desenhaHtmlForm($options);
+                    array_push($this->_desenhou,$input->getName());
+                }
+            } else {
+                //$this->adicionarErro("desenhaCampo()<br>Nï¿œo ï¿œ possï¿œvel desenhar o ID: " . $input->getName() . " jï¿œ foi desenhado no formulï¿œrio.");
+            }
+
+        }
+    }
+
+    /**
+     * Funï¿œï¿œo utilizada internamente para Desenhar campos Agrupados no Formulï¿œrio.
+     *
+     * @param string $name Nome do Botï¿œo
+     * @param boolean true $colunas Escreve a Divisï¿œo TR
+     * @return void
+     */
+    protected function desenhaAgrupados($campo) {
+        foreach ($this->_agruparcampos as $campoagru) {
+            $colunas = $campoagru["colunas"];
+            if ($colunas) {
+                $firstDisplayGroups = $this->FirstGroupColsDisplayOptions;
+                $displaygroups = 	$this->InputGroupColsDisplayOptions;
+            } else {
+                $firstDisplayGroups = $this->FirstGroupDisplayOptions;
+                $displaygroups = 	$this->InputGroupDisplayOptions;
+            }
+            if (count($campoagru[$campo])) {
+                foreach ($this->_arrinputs as $input) {
+                    if (in_array($input->getName(),$campoagru[$campo])) {
+                        if ($input->getName() == $campo) {
+                            echo $this->desenhaCampo($input,$firstDisplayGroups);
+
+                        } else {
+
+                            if ($this->_debug) {
+                                if (in_array($input->getName(),$this->_desenhou)) {
+                                    $this->adicionarErro("Funï¿œï¿œo Interna desenhaAgrupados()<br>Nï¿œo ï¿œ possï¿œvel desenhar o ID: " . $input->getName() . " na posiï¿œï¿œo correta.<br> O ID foi adicionado ao formulï¿œrio antes da chave do agrupamento. Verifique a ordem de criaï¿œï¿œo dos campos agrupados, ou se o ID nï¿œo foi adicionado a outro quadro.",true);
+                                }
+                            }
+                            echo $this->desenhaCampo($input,$displaygroups);
+                        }
+                    }
+                }
+            }
+       	}
+    }
+
+    /**
+     * Funï¿œï¿œo interna utilizada para montar o array de campos para um quadro quando nï¿œo ï¿œ informado nenhum campo no parï¿œmetro campos na funï¿œï¿œo adicionarQuadro, asumindo assim que todos os campos restantes serï¿œo adicionados nesse ï¿œltimo quadro.
+     *
+     * @param string $idquadro ID do quadro a ser Desenhado.
+     * @return void
+     */
+    protected function montaArrayQuadroCampos($idquadro) {
+        $arrcampos = array();
+        foreach ($this->_arrinputs as $input) {
+            if (!$this->isInputInQuadro($input->getName())) {
+                //echo $input->getName() . "<br>";
+                array_push($arrcampos,$input->getName());
+            }
+        }
+        return $arrcampos;
+        //print_r($this->_arrquadros);
+    }
+
+    /**
+     * Funï¿œï¿œo utilizada para desenhar um quadro especï¿œfico.
+     *
+     * @param string $idquadro ID do quadro a ser Desenhado.
+     * @return void
+     */
+    public function desenhaQuadro($idquadro) {
+
+
+
+        $quadro = $this->_arrquadros[$idquadro];
+        $this->escreveAbreQuadro($idquadro);
+         
+         
+        foreach ($this->_arrinputs as $input) {
+            	
+            //VERIFICA SE O CAMPO A SER DESENHADO PERTENCE AO QUADRO.
+            if (in_array($input->getName(),$quadro["campos"])) {
+                $desenhou = false;
+                //VERIFICA SE EXISTEM CAMPOS AGRUPADOS
+                if (count($this->_agruparcampos)) {
+                    foreach ($this->_agruparcampos as $campoagru) {
+                        if (count($campoagru[$input->getName()])) {
+                            //CHAMA A FUNï¿œï¿œO PARA DESENHAR OS CAMPOS AGRUPADOS.
+                            $this->desenhaAgrupados($input->getName());
+                            $desenhou = true;
+                        }
+                    }
+                }
+                 
+                if (!$desenhou) {
+                    //CASO Nï¿œO SEJAM CAMPOS AGRUPADOS DESENHA O CAMPO NORMAL.
+                    echo $this->desenhaCampo($input,$this->inputDisplayOptions);
+                }
+            }
+        }
+        $strcampos = "";
+        foreach ($quadro["campos"] as $campo) {
+            $strcampos .= $campo  . ",";
+        }
+        echo "<div id='" . $idquadro . "_campos' style='display:none;'>$strcampos</div>";
+        $this->escreveFechaQuadro($idquadro);
+    }
+
+    /**
+     * Desenha todos os quadros e todos os campos do formulï¿œrio.
+     *
+     * @return void
+     */
+    public function desenhaCampos() {
+        $this->_desenhado = true;
+        foreach ($this->_arrquadros as $quadro) {
+            $this->desenhaQuadro($quadro["idquadro"]);
+        }
+    }
+
+    /**
+     * Desenha o Formulï¿œrio.
+     *
+     * @return void
+     */
+    function desenhar() {
+        if (!$this->_desenhado) {
+            $this->_desenhado = true;
+            ob_start();
+            $this->abreForm();
+            $this->desenhaCampos();
+            $this->fechaForm();
+            $html = ob_get_contents();
+            ob_end_clean();
+            $this->displayErros();
+            $this->html = $html;
+            echo $html;
+        } else {
+            $this->adicionarErro("desenhar()<br>Formulï¿œrio jï¿œ foi Desenhado anteriormente.",true);
+        }
+    }
+
+    /**
+     * Altera o Valor do DEBUG para fazer Depuraï¿œï¿œo de Erros.
+     *
+     * @return void
+     */
+    function setDebug($value) {
+        $this->_debug = $value;
+    }
+
+
+    /**
+     * Verifica se o Formulï¿œrio foi Enviado para a aï¿œï¿œo passada como parï¿œmetro.
+     *
+     * Exemplo:
+     * <code>
+     * if ($form->isSubmit("enviar")) {
+     *   //executa a aï¿œï¿œo do botï¿œo enviar.
+     * }
+     * </code>
+     *
+     * @param string $acao Aï¿œï¿œo do Formulï¿œrio.
+     * @return void
+     */
+    public function isSubmit($acao,$permitirf5 = false) {
+        if (!$this->_iscachedform) { 
+	        if ($this->_method == "post") {
+	            $varacao = $_POST[$this->_nomeform . '_acao'];
+	        } else {
+	            $varacao = $_GET[$this->_nomeform . '_acao'];
+	        }
+	        
+	        $ret = true;
+	        
+	        if ($this->_desenhado) {
+	            $this->adicionarErro("isSubmit()<br>Ordem da funï¿œï¿œo isSubmit deve estar antes do formulï¿œrio ser desenhado.",true);
+	        }
+	        
+	        
+	        //VERIFICA SE O F5 FOI PRESSIONADO
+	        //session_start();
+	        if (!$permitirf5) {
+		        $sesspkey = $_SESSION[$this->_nomeform . '_pkey'];
+		        $postpkey = $_POST[$this->_nomeform . '_pkey'];
+		        if ($postpkey != "") {
+		            if ($postpkey != $sesspkey) {
+		                 //$this->adicionarErro("isSubmit()<br>Impossï¿œvel fazer aï¿œï¿œo, F5 pressionado.",false);
+		                 //$ret = false;
+		            }
+		        }
+	        }
+	        
+	        if ($ret) {
+	            if ($varacao == $acao) {
+	                if ($this->_isupload) {
+	                    include('UploadFile.class.php');
+	                    foreach ($this->_arrinputs as $input) {
+	                        if ($input->getTipo() == "file") {
+	                            $fname = $input->getName();
+	                            $pasta = $input->getTitle();
+	                            $prefixo = $input->getValue();
+	                            $force = $input->getWidth();
+	                            //echo $force;
+	                            $upload = new UploadFile($_FILES[$fname],$pasta, $prefixo, $force);
+	                            if($upload->doUpload() === true) {
+	                                $filename = $upload->getFileNomeFinal();
+	                                $this->_arrfilesuploaded[$fname] = array( "field" => $fname, "folder" => $pasta, "prefix" => $prefixo, "filename" => $filename, "completefilename" => $pasta . $filename);
+	                            } else {
+	                                echo $upload->getSysError();
+	                                echo $upload->getSysDebug();
+	                            }
+	                        }
+	                    }
+	                }
+	                $ret = true;
+	            } else {
+	                $ret = false;
+	            }
+	        }
+        }
+        return $ret;
+    }
+    /**
+     * Funï¿œï¿œo que retorna os arquivos que foram enviados e salvos por upload.
+     */
+    public function getFiles() {
+        return $this->_arrfilesuploaded;
+    }
+
+
+    /**
+     * Funï¿œï¿œo usada internamente para adicionar um erro ao formulï¿œrio.
+     *
+     * @param string $msgerro Mensagem de Erro
+     * @param boolean $fatal Se ï¿œ um erro Fatal = true ()
+     * */
+    protected function adicionarErro($msgerro,$fatal = false) {
+        if ($fatal) { $this->_errors = array(); }
+        $erro = array("msgerro" => $msgerro,"fatal" => $fatal);
+        array_push($this->_errors,$erro);
+         
+        if ($fatal) {
+            $this->displayErros();
+            exit;
+       	}
+       	 
+    }
+
+
+    /**
+     * Funï¿œï¿œo usada para exibir os erros.
+     *
+     * */
+    public function displayErros() {
+        if ($this->_debug) {
+            if (count($this->_errors)) {
+                echo "<style type='text/css'>#erros { background: #BAD0E5; color: #000000; font-size: 12px; Verdana,Arial,Helvetica,sans-serif; font-weight: bold; margin: 15px; padicionaring: 0px; padicionaring-top: 3px; padicionaring-bottom: 3px;  text-align: left; }" .
+		        		".erro { background: #E6EAEE; color: #000000; font-size: 12px; Verdana,Arial,Helvetica,sans-serif; font-weight: bold; margin: 2px; padicionaring: 5px; text-align: left; }" .
+		        		"</style>";
+                echo "<div id='erros'>";
+                foreach ($this->_errors as $erro) {
+                    echo "<div class=erro>";
+
+                    if ($erro["fatal"]) {
+                        $adicionarmsg = "<span style='color: #990000;'><b>ERRO FATAL:</b></span> ";
+                    } else {
+                        $adicionarmsg = "ERRO: ";
+                    }
+                    echo $adicionarmsg . $erro["msgerro"];
+                    echo "</div>";
+                }
+                echo "</div>";
+            }
+        }
+    }
+
+
+    /**
+     * Funï¿œï¿œo utilizada para Desenhar o XAJAX do formulï¿œrio e as funï¿œï¿œes registradas.
+     */
+    public function desenhaXAjax() {
+         
+         
+         
+        $ajax = new xajax("",$this->_nomeform . "_xajax_",'ISO-8859-1');
+        $ajax->decodeUTF8InputOn();
+         
+         
+         
+         
+        foreach ($this->_arrxajax as $xajax) {
+             
+            $findInput = $this->getInput($xajax['idorigem']);
+
+            $sql = $this->getSQLXajaxQuery($xajax['idquery']);
+            $fparametros = '$' . $this->_arrxajaxquery[$xajax['idquery']]["parametros"];
+            $fparametros = str_replace(",",',$',$fparametros);
+             
+            $camposquery = $this->_arrxajaxquery[$xajax['idquery']]["campos"];
+            $campos = explode(",",$camposquery);
+            //echo $camposquery;
+
+            if ($xajax['funcao'] == "redesenhar") {
+                 
+                $funcao = "";
+                 
+                if ($findInput->getTipo() == "select") {
+                    $funcao =
+	                'function ' . $xajax['idfuncao'] . '(' . $fparametros . '){
+					    $objResponse = new xajaxResponse("ISO-8859-1");
+					    global $conn;
+					    //$objResponse->AddAssign("img_' . $xajax['idcampo'] . '","style.display",""); 
+						$sql = "' . $sql . '"; 
+						$IUtils = new FormularioUtil();
+	                	$data = $IUtils->MontaArraySelect($conn,$sql,"' . $campos[0] .'","' . $campos[1] .'");
+						$iface = new FormularioHtml();
+			        	$iface->setForm("' . $this->_nomeform . '");
+						$iface->setName("' .  $xajax['idorigem'] . '") ;
+						$iface->setValue("' . $findInput->getValue() . '");
+						$iface->setTitle("' . $findInput->getTitle() . '");
+						$iface->setValuesSelect($data);
+						$iface->setSize(' . $findInput->getWidth() .  ',' . $findInput->getHeight()  . ');
+						$mostraescolha = true;
+				    	$textoescolha = "' . $findInput->getSelectEscolhaValue() . '";
+						if ($textoescolha == "") {
+							$mostraescolha = false;
+						}
+						$iface->setMultiplo("' . $findInput->getMultiplo() . '");
+						$iface->setSelectEscolha($mostraescolha, $textoescolha);
+						$iface->setLabel("' . $findInput->getLabel() . '");
+						$iface->setObrigatorio("' . $findInput->getObrigatorio() .'");
+						$iface->setTipo("select");
+						$iface->select();
+				   		$div = $iface->getHtml();
+						$objResponse->AddAssign(\'span_id_' . $xajax['idorigem'] . '\',\'innerHTML\',$div);
+					    //$objResponse->AddScript(\'sleep(5000);\');
+						//$objResponse->AddAssign("img_' . $xajax['idcampo'] . '","style.display","");
+					    return $objResponse->getXML();
+					}';
+                }
+                if ($findInput->getTipo() == "checkbox") {
+                    $funcao =
+	                'function ' . $xajax['idfuncao'] . '(' . $fparametros . '){
+					    $objResponse = new xajaxResponse("ISO-8859-1");
+					    global $conn;
+						$sql = "' . $sql . '"; 
+						$IUtils = new FormularioUtil();
+	                	$data = $IUtils->MontaArrayCheckBox($conn,$sql,"' . $campos[0] .'","' . $campos[1] .'");
+						$iface = new FormularioHtml();
+			        	$iface->setForm("' . $this->_nomeform . '");
+						$iface->setName("' .  $xajax['idorigem'] . '") ;
+						$iface->setValuesChecks($data);
+						$iface->setLabel("' . $findInput->getLabel() . '");
+						$iface->setObrigatorio("' . $findInput->getObrigatorio() .'");
+						$iface->setTipo("checkbox");
+						$iface->checkbox();
+				   		$div = $iface->getHtml();
+						$objResponse->AddAssign(\'span_id_' . $xajax['idorigem'] . '\',\'innerHTML\',$div);
+					    return $objResponse->getXML();
+					}';
+                }
+                 
+                if ($findInput->getTipo() == "radio") {
+                    $funcao =
+	                'function ' . $xajax['idfuncao'] . '(' . $fparametros . '){
+					    $objResponse = new xajaxResponse("ISO-8859-1");
+					    global $conn;
+						$sql = "' . $sql . '"; 
+						$IUtils = new FormularioUtil();
+	                	$data = $IUtils->MontaArrayCheckBox($conn,$sql,"' . $campos[0] .'","' . $campos[1] .'");
+						$iface = new FormularioHtml();
+			        	$iface->setForm("' . $this->_nomeform . '");
+						$iface->setName("' .  $xajax['idorigem'] . '") ;
+						$iface->setValuesRadio($data);
+						$iface->setLabel("' . $findInput->getLabel() . '");
+						$iface->setObrigatorio("' . $findInput->getObrigatorio() .'");
+						$iface->setTipo("radio");
+						$iface->radio();
+				   		$div = $iface->getHtml();
+						$objResponse->AddAssign(\'span_id_' . $xajax['idorigem'] . '\',\'innerHTML\',$div);
+					    return $objResponse->getXML();
+					}';
+                }
+
+                //echo $funcao;
+
+                if ($funcao != "") {
+                    eval($funcao);
+                }
+                 
+            }
+
+
+
+        }
+        foreach ($this->_arrxajax as $xajax) {
+            $ajax->registerFunction($xajax['idfuncao']);  //38
+
+            if ($xajax['idquery'] != "") {
+                $parametros = $this->_arrxajaxquery[$xajax['idquery']]["valores"];
+            } else {
+                $parametros = $xajax["valores"];
+            }
+
+            $this->adicionarCampoAcao($xajax['idcampo'],$xajax['acao']," formUtilExibeImgAjax('" . $xajax['idorigem'] . "'); " . $this->_nomeform . "_xajax_" . $xajax['idfuncao'] . "(" . $parametros .");  setTimeout('formUtilOcultaImgAjax(\'" . $xajax['idorigem'] . "\')',3000); ");
+        }
+        $ajax->processRequests();
+        $ajax->printJavascript();
+    }
+
+
+    /**
+     * Funï¿œï¿œo Utilizada para adicionar ï¿œ um campo especï¿œfico uma funï¿œï¿œo em XAJAX declarada fora do formulï¿œrio.
+     * Tambï¿œm faz o registro a funï¿œï¿œo em XAJAX no formulï¿œrio.
+     */
+    public function adicionarCampoXajax($idcampo,$acao,$idfuncao,$valores) {
+        $ajax = array( "idfuncao" => $idfuncao, "funcao" => "funcao", "idcampo" => $idcampo, "valores" => $valores, "acao" => $acao);
+        array_push($this->_arrxajax,$ajax);
+    }
+
+    /**
+     * Funï¿œï¿œo utilizada para Redesenhar um campo utilizando uma query em XAJAX.
+     */
+    public function adicionarXajaxRedesenhar($idorigem,$idquery,$idcampo,$acao) {
+        $rand = rand(0,999);
+        $nomefuncao = "redesenhar_" . $idorigem . "_" . $idcampo . "_" . $acao;
+        $ajax = array( "idfuncao" => $nomefuncao, "funcao" => "redesenhar", "idquery" => $idquery,"idorigem" => $idorigem,"idcampo" => $idcampo, "acao" => $acao);
+        array_push($this->_arrxajax,$ajax);
+    }
+
+    /**
+     * Funï¿œï¿œo utilizada Internamente para retornar o SQL formatado de uma query em XJAX.
+     */
+    protected function getSQLXajaxQuery($idquery) {
+        foreach ($this->_arrxajaxquery as $query) {
+            if ($query['idquery'] == $idquery) {
+                $fparametros = '$' . $query["parametros"];
+                $fparametros = str_replace(",",',$',$fparametros);
+                $arrparametros = explode(",",$query["parametros"]);
+                $sql = $query['sql'];
+                foreach ($arrparametros as $parametro) {
+                    $sql = str_replace('{' . $parametro. '}','$' . $parametro,$sql);
+                }
+            }
+        }
+        return $sql;
+    }
+
+    /**
+     * Funï¿œï¿œo utilizada para adicionar uma Query em XAJAX ao formulï¿œrio.
+     */
+    public function adicionarXajaxQuery($idquery,$sql,$campos,$parametros,$valores) {
+        $query = array( "idquery" => $idquery, "sql" => $sql, "campos" => $campos, "parametros" => $parametros,"valores" => $valores);
+        $this->_arrxajaxquery[$idquery] = $query;
+    }
+
+    public function getNome() {
+        return $this->_nomeform;
+    }
+
+    public function setInFormFieldsAsHidden($form) {
+        $form->adicionarHidden($this->_nomeform . "_acao",$_POST[$this->_nomeform . "_acao"]);
+       // $form->adicionarHidden($this->_nomeform . "_ordem",$_POST[$this->_nomeform . "_ordem"]);
+       // $form->adicionarHidden($this->_nomeform . "_ordemtipo",$_POST[$this->_nomeform . "_ordemtipo"]);
+        foreach ($this->_arrinputs as $input) {
+            $valor = "";
+            if ($_POST[$input->getName()]) {
+                $valor = $_POST[$input->getName()];
+            } else {
+                $valor = $_GET[$input->getName()];
+            }
+            $form->adicionarHidden($input->getName(),$valor);
+        }
+        return $form;
+    }
+
+}
+
+
+?>
Index: trunk/workflow/inc/report/includes/classes/FormularioInput.class.php
===================================================================
--- trunk/workflow/inc/report/includes/classes/FormularioInput.class.php	(revision 5307)
+++ trunk/workflow/inc/report/includes/classes/FormularioInput.class.php	(revision 5307)
@@ -0,0 +1,366 @@
+<?
+/**
+ * FormularioInput
+ * 
+ * Implementação de Formulários Padrões do Sistema.  
+ * @author Jair Pereira <pereira.jair@gmail.com>
+ */
+ 
+class FormularioInput {
+    
+    protected $html;
+    protected $tipo;
+    protected $name;
+    protected $value;
+    protected $valueAux;
+    protected $title;
+    protected $form;
+    protected $valuesSelect;
+    protected $selectEscolha;
+    protected $selectEscolhaValue;
+    protected $valuesChecks;
+    protected $valuesRadio;
+    protected $width;
+    protected $height;
+    protected $multiple;
+    protected $inforight;
+    protected $obrigatorio;
+    protected $selectCor;
+    protected $selectValuesCor = array();
+    public $arreventos = array();
+    
+    //$this->value
+    function input(){
+        $this->html = '';
+        $addeventos = $this->getHtmlEventos();
+        switch($this->tipo){
+            case 'periodo' : 
+                             $this->adicionarEvento("onkeyup","formatar(this,'@@/@@/@@@@'); validarPeriodo(document." . $this->form . "." . $this->name . "_inicio,document." .$this->form . "." . $this->name . "_fim);");
+                             $this->adicionarEvento("onblur","revalidar(this,'@@/@@/@@@@','data'); validarPeriodo(document." . $this->form . "." . $this->name . "_inicio,document." .$this->form . "." . $this->name . "_fim);");
+                             $addeventos = $this->getHtmlEventos();
+                             echo '<input type="text" id="'.$this->obrigatorio.'id_'. $this->name.'_inicio" name="' . $this->name . '_inicio" value="' . $this->value . '" size="10" maxlength="10" ' .  $addeventos .' title="' . $this->title . '">';
+                             echo '<img id="id_imgcal_' . $this->name . '_inicio" src="./images/calendar_cal.gif" align="absmiddle" border="0" alt="Calendário..." onClick="displayCalendar(document.' . $this->form . '.' . $this->name . '_inicio,\'dd/mm/yyyy\',this)">';
+                             echo '&nbsp;a&nbsp;' ;
+                             echo '<input type="text" id="'.$this->obrigatorio.'id_'. $this->name.'_fim" name="' . $this->name . '_fim" value="' . $this->valueAux . '" size="10" maxlength="10" ' .  $addeventos .' title="' . $this->title . '">' ;
+                             echo '<img id="id_imgcal_' . $this->name . '_fim" src="./images/calendar_cal.gif" align="absmiddle" border="0" alt="Calendário..."   onclick="displayCalendar(document.' . $this->form . '.' . $this->name . '_fim,\'dd/mm/yyyy\',this)"><span id="imgAjax_' . $this->name . '" style="display: none;"><img src="images/progress4.gif"></span>'; 
+                 break;
+            case 'data' : 
+                          $this->adicionarEvento("onkeyup","formatar(this,'@@/@@/@@@@'); validarPeriodo(document." . $this->form . "." . $this->name . "_inicio,document." .$this->form . "." . $this->name . "_fim);");
+                          $this->adicionarEvento("onblur","revalidar(this,'@@/@@/@@@@','data'); validarPeriodo(document." . $this->form . "." . $this->name . "_inicio,document." .$this->form . "." . $this->name . "_fim);");
+                          $addeventos = $this->getHtmlEventos();
+                          echo '<input type="text" id="'.$this->obrigatorio.'id_'. $this->name.'" name="' . $this->name . '_inicio" value="' . $this->value . '" size="10" maxlength="10" ' . $addeventos . ' title="' . $this->title . '">';
+                          echo '<img id="id_imgcal_' . $this->name . '_inicio" src="./images/calendar_cal.gif" align="absmiddle" border="0" alt="Calendário..." onClick="displayCalendar(document.' . $this->form . '.' . $this->name . '_inicio,\'dd/mm/yyyy\',this)"><span id="imgAjax_' . $this->name . '" style="display: none;"><img src="images/progress4.gif"></span>';
+                 break;
+                 
+            case 'moeda' : 
+            			  $this->adicionarEvento("onkeyup","milhar(this);");
+                          $this->adicionarEvento("onblur","revalidarMilhar(this);");
+                          $addeventos = $this->getHtmlEventos();
+            			  echo '<input type="text" name="' . $this->name . '" id="'.$this->obrigatorio.'id_' . $this->name . '" value="' . $this->value . '" size="20" maxlength="20" ' . $addeventos . ' title="' . $this->title . '"><span id="imgAjax_' . $this->name . '" style="display: none;"><img src="images/progress4.gif"></span>'; break;
+            case 'cpf'   : 
+            			  $this->adicionarEvento("onkeyup","formatar(this,'@@@.@@@.@@@-@@');");
+                          $this->adicionarEvento("onblur","revalidar(this,'@@@.@@@.@@@-@@','cpf');");
+                          $addeventos = $this->getHtmlEventos();
+            			  echo '<input type="text" name="' . $this->name . '" id="'.$this->obrigatorio.'id_' . $this->name . '" value="' . $this->value . '" size="20" maxlength="20" ' . $addeventos . ' title="' . $this->title . '"><span id="imgAjax_' . $this->name . '" style="display: none;"><img src="images/progress4.gif"></span>'; break;
+            case 'cnpj'  : 
+                          $this->adicionarEvento("onkeyup","formatar(this,'@@.@@@.@@@/@@@@-@@');");
+                          $this->adicionarEvento("onblur","revalidar(this,'@@.@@@.@@@/@@@@-@@','cnpj');");
+                          $addeventos = $this->getHtmlEventos();
+            			  echo '<input type="text" name="' . $this->name . '" id="'.$this->obrigatorio.'id_' . $this->name . '" value="' . $this->value . '" size="20" maxlength="20" ' . $addeventos . ' title="' . $this->title . '"><span id="imgAjax_' . $this->name . '" style="display: none;"><img src="images/progress4.gif"></span>'; break;
+            
+            case 'hidden':echo '<input type="hidden" name="' . $this->name . '" id="id_' . $this->name . '" value="' . $this->value . '">'; break;
+            
+            case 'int'   : 
+                          $this->adicionarEvento("onkeyup","formatar(this,'@@@@@@@@@@@@@@@@@@');");
+                          $this->adicionarEvento("onblur","revalidar(this,'@@@@@@@@@@@@@@@@@@');");
+                          $addeventos = $this->getHtmlEventos();
+                          echo '<input type="text" name="' . $this->name . '" id="'.$this->obrigatorio.'id_' . $this->name . '" value="' . $this->value . '"  title="' . $this->title . '" size="' . $this->width . '" maxlength="' . $this->height . '" ' . $addeventos . ' ><span id="id_info_' . $this->name . '" class=inforight style="color: rgb(100, 62, 65);">&nbsp;' . $this->inforight .'</span><span id="imgAjax_' . $this->name . '" style="display: none;"><img src="images/progress4.gif"></span>'; break;
+            
+            default      : 
+                          
+                          echo '<input type="text" name="' . $this->name . '" id="'.$this->obrigatorio.'id_' . $this->name . '" value="' . $this->value . '"  title="' . $this->title . '" size="' . $this->width . '" maxlength="' . $this->height . '" ' . $addeventos . ' ><span id="id_info_' . $this->name . '" class=inforight style="color: rgb(100, 62, 65);">&nbsp;' . $this->inforight .'</span><span id="imgAjax_' . $this->name . '" style="display: none;"><img src="images/progress4.gif"></span>';
+        }
+
+    }
+    
+    function subtitulo() {
+    	echo "<tr><td>" . $this->value . "</td></tr>";
+    }
+    
+    function button() {
+    	$addeventos = $this->getHtmlEventos();
+        echo "<input type='button' name='" . $this->name . "' id='" . $this->form. "_btn_". $this->name . "' value='" . $this->value . "' style='width: 90px;' class='botao' " . $addeventos ." >";
+    }
+    
+    function select(){
+        $selected = "";
+        $addeventos = $this->getHtmlEventos();
+        echo "\n\t\t\t";
+        if ($this->multiplo) { $addmultiplo = " MULTIPLE"; } 
+        echo '<table><tr><td><select id="'.$this->obrigatorio.'id_'. $this->name.'" name="' . $this->name . '"  title="' . $this->title . '" style="width: ' . $this->width . 'px;" size="' . $this->height . '" ' . $addeventos . ' ' . $addmultiplo . '>';
+        echo "\n";
+        if($this->selectEscolha == true){
+            echo "\t\t\t<option value=''>" . $this->selectEscolhaValue . "</option>";
+        }
+        if(count($this->valuesSelect) > 0 ){
+            foreach($this->valuesSelect as $chave => $valor){
+                $selected = ("$chave" == "$this->value") ? ' selected="selected" ' : '';
+                echo "\t\t\t\t";
+                if (in_array($chave,$this->selectValuesCor)) {
+                	$addstyle = ' style="color: '.$this->selectCor . ';"';
+                } else {
+                	$addstyle = '';
+                }
+                echo '<option value="' . $chave . '"' . $selected .  $addstyle . '>' . $valor . '</option>';
+                echo "\n";
+            }
+        }
+        echo "\t\t\t</select></td><td><span id='imgAjax_" . $this->name . "' style='display: none;'><img src='images/progress4.gif'></span></td></tr></table>\n";
+    }
+    
+    
+    function checkbox(){
+        $selected = "";
+        $addeventos = $this->getHtmlEventos();
+        echo '';
+        if(count($this->valuesChecks) > 0 ){
+        	
+            echo "\n\t\t<table border='0'>";
+            echo "\n\t\t<tr>\n\t\t\t<td>";
+            $i = 0;
+        	echo "\n\t\t\t<div id='".$this->obrigatorio .'div_ckbox_' .$this->name . "'>";
+            foreach($this->valuesChecks as  $valores){
+                //$class = ($class == 'tdc') ? 'tde' : 'tdc';
+                 $selected = ($valores[2] == true) ? ' checked ' : '';
+                 if (isset($_POST[$this->name])) {
+	                 if (in_array($valores[0],$_POST[$this->name])) {
+	                 	$selected = "checked";
+	                 }
+                 }
+                 $i = $i + 1;
+                 echo "\n\t\t\t\t";
+                 echo '<input type="checkbox" class="checkbox" id="' . $this->name . '[' . $i . ']" name="' . $this->name . '[' . $i . ']" value="' . $valores[0] . '" ' . $addeventos . ' ' . $selected . ' >' . $valores[1] ;
+                 echo "<br>";
+                
+            }
+            echo "\n\t\t\t</div>";
+		    echo "\n\t\t</td><td valign='top' id='imgAjax_" . $this->name . "' style='display: none;'><img src='images/progress4.gif'></td></tr>";
+		    echo "\n\t\t</table>\n"; 
+		    
+        }
+    }
+    
+    function radio(){
+        $selected = "";
+        $this->html = '';
+        $addeventos = $this->getHtmlEventos();
+        if(count($this->valuesRadio) > 0 ){
+        	echo "\n\t\t\t<div id='".$this->obrigatorio . $this->form. '_div_radio_' .$this->name . "'>";
+        	echo "\n\t\t<table border='0'>";
+            echo "\n\t\t<tr>\n\t\t\t<td>";
+            
+            foreach($this->valuesRadio as  $valores){		               
+                $selected = ($valores[2] == true) ? ' checked ' : '';
+                echo "\n\t\t\t\t";
+                echo '<input type="radio" id="'. $this->name .'" class="radio" name="' . $this->name . '" value="' . $valores[0] . '" ' . $addeventos . " " . $selected . " >" . $valores[1] ;
+                echo "<br>\n";
+            }
+            
+		    echo "\n\t\t</td><td valign='top' id='imgAjax_" . $this->name . "' style='display: none;'><img src='images/progress4.gif'></td></tr>";
+		    echo "\n\t\t</table>\n";
+            echo "\n\t\t\t</div>";
+        }
+        
+    }
+    
+    function arquivo() {
+    	$this->html = '';
+    	$this->html = '<input type="file" id="'. $this->name .'" name="'. $this->name .'">';
+    }
+    
+    function textArea(){
+        $this->html = '';
+        $addeventos = " " . $this->getHtmlEventos();
+        echo "<textarea name=\"" . $this->name . "\" id=\"" . $this->obrigatorio . "id_". $this->name . "\" cols=\"" . $this->width .  "\" rows=\"" . $this->height .  "\"$addeventos>" . $this->value . "</textarea>";
+       
+    }
+    
+    
+    
+    function desenhaForm(){
+       return $this->html;        
+    }
+    function setTipo($tipo){
+        $this->tipo = $tipo;
+    }
+    function setName($name){
+        $this->name = $name;
+    }
+    function setValue($value){
+        $this->value = "$value";
+        //echo $this->name . ": " . $this->value . "<br>";
+    }
+    function setValueAux($valueAux){
+        $this->valueAux = $valueAux;
+    }
+    function setTitle($title){
+        $this->title = $title;
+    }
+    function setInfoRight($info) {
+    	$this->inforight = $info;
+    }
+    function setObrigatorio($obrigatorio){
+    	
+    		if(strlen($obrigatorio)>1){
+    				$this->obrigatorio = $obrigatorio;
+    				return true;
+    		}
+    		
+    		switch($obrigatorio){
+    			case true :
+    				$this->obrigatorio = "";
+    				break;
+    			case false :
+    				$this->obrigatorio = "not_";
+    				break;
+    			default :
+    				$this->obrigatorio = "";
+    		}
+    }
+    
+    
+    function setValuesSelect($arrayValores){
+        $this->valuesSelect = $arrayValores;
+    }
+    function getName() {
+    	return $this->name;
+    }
+    function getValue() {
+    	return $this->value;
+    }
+    function getWidth() {
+    	return $this->width;
+    }
+    function getTipo() {
+    	return $this->tipo;
+    }
+    function getObrigatorio() {
+    	return $this->obrigatorio;
+    	/*if ($this->obrigatorio == "not_") {
+    		$ret = false;
+    	} else {
+    		$ret = true;
+    	}
+    	return $ret; */
+    }
+    function getHeight() {
+    	return $this->height;
+    }
+    function getMultiplo() {
+    	return $this->multiplo;
+    }
+    function getLabel() {
+    	return $this->label;
+    }
+    
+    function setValuesSelectCor($cor,$values) {
+    	$this->selectValuesCor = $values;
+    	$this->selectCor = $cor;
+    }
+    
+    function getTitle() {
+    	return $this->title;
+    }
+    function setForm($form){
+        $this->form = $form;
+    }
+    function getHtml() {
+        return $this->html;
+    }
+    function setSelectEscolha($escolha, $valor){
+        $this->selectEscolha = $escolha;
+        $this->selectEscolhaValue = $valor;
+    }
+    function getSelectEscolha() {
+      	return $this->selectEscolha;
+    }
+    function getSelectEscolhaValue() {
+      	return $this->selectEscolhaValue;
+    }
+    
+    function setValuesChecks($arrValores){
+       $this->valuesChecks = $arrValores;
+    }
+    function setValuesRadio($arrValores){
+       $this->valuesRadio = $arrValores;
+    }
+    
+    function setSize($tamanho1,$tamanho2 = "") {
+    	$this->width = $tamanho1;
+    	$this->height = $tamanho2;
+    }
+    function setMultiplo($multiplo) {
+    	$this->multiplo = $multiplo;
+    }
+    
+    function adicionarEvento($action,$javascript) {
+       $arrevt = array("action" => $action, "evento" =>$javascript);
+       array_push($this->arreventos,$arrevt);
+    }
+    function getHtmlEventos() {
+    	$streventos = "";
+    	foreach($this->arreventos as $evento) {
+    	    if ($evento["action"] == "onclick") { 
+    	    	$addonclick .= $evento["evento"];
+    	    }
+    	    if ($evento["action"] == "onchange") { 
+    	    	$addonchange .= $evento["evento"];
+    	    }
+    	    if ($evento["action"] == "onblur") { 
+    	    	$addonblur .= $evento["evento"];
+    	    }
+    	    if ($evento["action"] == "onmouseout") { 
+    	    	$addonmouseout .= $evento["evento"];
+    	    }
+    	    if ($evento["action"] == "onmousemove") { 
+    	    	$addonmousemove .= $evento["evento"];
+    	    }
+    	    if ($evento["action"] == "onkeydown") { 
+    	    	$addonkeydown .= $evento["evento"];
+    	    }
+    	    if ($evento["action"] == "onkeypress") { 
+    	    	$addonkeypress .= $evento["evento"];
+    	    }
+    	    if ($evento["action"] == "onkeyup") { 
+    	    	$addonkeyup .= $evento["evento"];
+    	    }
+    	}
+    	if ($addonclick != "") { 
+    		$streventos .= " OnClick=\" $addonclick \" ";
+    	}
+    	if ($addonchange != "") { 
+    		$streventos .= " OnChange=\" $addonchange \" ";
+    	}
+    	if ($addonmouseout != "") { 
+    		$streventos .= " OnMouseOut=\" $addonmouseout \" ";
+    	}
+    	if ($addonmousemove != "") { 
+    		$streventos .= " OnMouseMove=\" $addonmousemove \" ";
+    	}
+    	if ($addonkeypress != "") { 
+    		$streventos .= " OnKeyPress=\" $addonkeypress \" ";
+    	}
+    	if ($addonkeyup != "") { 
+    		$streventos .= " OnKeyUp=\" $addonkeyup \" ";
+    	}
+    	if ($addonkeydown != "") { 
+    		$streventos .= " OnKeyDown=\" $addonkeydown \" ";
+    	}
+    	if ($addonblur != "") { 
+    		$streventos .= " OnBlur=\" $addonblur \" ";
+    	}
+    	return $streventos;
+    }
+
+}
+?>
Index: trunk/workflow/inc/report/includes/classes/DatabaseInfo.class.php
===================================================================
--- trunk/workflow/inc/report/includes/classes/DatabaseInfo.class.php	(revision 5307)
+++ trunk/workflow/inc/report/includes/classes/DatabaseInfo.class.php	(revision 5307)
@@ -0,0 +1,326 @@
+<?php
+
+class DatabaseInfo {
+	private $_conn;
+    private $_dbhost;
+    private $_dbuser;
+    private $_dbpassword;
+    private $_dbname;
+    var $_sqlerror;
+    var $_parser;
+    
+    public function __construct($dbname,$dbhost,$dbuser,$dbpassword){
+        $this->_dbhost     = $dbhost;
+        $this->_dbuser     = $dbuser;
+        $this->_dbpassword = $dbpassword;
+        $this->_dbname     = $dbname;
+        $this->_parser     = new SqlParser("");
+        $this->_conn = $this->conectar();
+    }
+    
+    public function conectar() {
+        $connstring = "dbname=" . $this->_dbname . " host=" . $this->_dbhost . " user=" . $this->_dbuser . " password=" . $this->_dbpassword . "";
+        //echo $connstring;
+        $conn = pg_connect($connstring);
+        $this->_conn = $conn;
+        
+        $this->_parser->bloquearPalavra("controle_acesso_banco",true);
+        $this->_parser->bloquearPalavra("controle_acesso_banco_usuarios",true);
+        $this->_parser->bloquearPalavra("controle_acesso_banco_historico",true);
+        
+        //$this->bloquearFuncoes(true);
+        
+    	return $conn;
+    }
+    
+    public function bloquearFuncoes($bloqueio) {
+    	$res_funcoes = $this->getFuncoes();
+        while ($funcao = pg_fetch_object($res_funcoes)) {
+            $nome_funcao = $funcao->proname;
+            $this->_parser->bloquearPalavra($nome_funcao . "(",$bloqueio);
+        }
+    }
+    
+    public function getErro() {
+    	return $this->_sqlerror;
+    }
+    
+    public function executar($sql,$transaction = true) {
+    		$error = "";
+            $this->_sqlerror = ""; 
+
+            $this->_parser->setSql($sql);
+            
+            $ret_parser = $this->_parser->verificaSql();
+            
+            if ($ret_parser === false) {
+                $error = $this->_parser->getErro();
+            }
+
+            $sql = $this->_parser->getSql(); 
+            if ($error == "") {
+            	if ($transaction) {
+                	pg_query($this->_conn,"begin;");
+            	}
+                $res = pg_query($this->_conn,$sql);
+                $error = pg_last_error($this->_conn);
+                if ($transaction) {
+                	pg_query($this->_conn,"rollback;");
+                }
+                
+            }
+            if ($error == "") {
+                return $res;
+            } else {
+                $this->_sqlerror = $error;
+               	return false;
+            }
+    }
+    
+    public function fetch_array($recordset){
+        return pg_fetch_array($recordset);
+    }
+    
+    public function fetch_all($recordset) {
+    	$process = array();
+        while ($rsatt = $this->fetch_array($recordset)){
+            $process[] = $rsatt;
+        }
+        return $process;
+    }
+    
+    public function getDbIndices($schemaname,$tblname) {
+        $sqlstr = "select pg_get_indexdef(i.oid) as indice, x.indisprimary FROM pg_index x JOIN pg_class c ON c.oid = x.indrelid JOIN pg_class i ON i.oid = x.indexrelid WHERE c.relname=(select relname from pg_stat_user_tables where relname = '$tblname' and schemaname = '$schemaname') ";
+        $resu = $this->executar($sqlstr);
+        return $resu;
+    }
+    
+	public function getDbConstraints($schemaname,$tblname) {
+        $sqlstr = "select pg_get_constraintdef(ct.oid) AS constraint FROM pg_class c inner join pg_catalog.pg_constraint ct ON (c.oid = ct.conrelid)  WHERE c.relname=(select relname from pg_stat_user_tables where relname = '$tblname' and schemaname = '$schemaname')";
+        $resu = $this->executar($sqlstr);
+        return $resu;
+    }
+    
+    
+    
+    
+    public function getAttTable($schemaname,$tblname){
+
+        $sqlstr = "SELECT 
+                        pg_attribute.attnum AS index,
+                        attname AS field,
+                        typname AS type,
+                        atttypmod-4 as length,
+                        NOT attnotnull AS null,
+                        adsrc AS def,
+                        (select coalesce(d.description,'') as desc from pg_description d where d.objoid=attrelid and d.objsubid=attnum) as descricao_coluna
+                    FROM 
+                        pg_attribute,
+                        pg_class,
+                        pg_type,
+                        pg_attrdef
+                    WHERE 
+                        pg_class.oid=attrelid
+                    AND pg_type.oid=atttypid
+                    AND attnum>0
+                    AND pg_class.oid=adrelid
+                    AND adnum=attnum
+                    AND atthasdef='t'
+                    AND lower(relname)= (select relname from pg_stat_user_tables where relname = '$tblname' and schemaname = '$schemaname') 
+                UNION
+                    SELECT 
+                        pg_attribute.attnum AS index,
+                        attname AS field,
+                        typname AS type,
+                        atttypmod-4 as length,
+                        NOT attnotnull AS null,
+                        '' AS def,
+                        (select coalesce(d.description,'') as desc from pg_description d where d.objoid=attrelid and d.objsubid=attnum) as descricao_coluna
+                    FROM 
+                        pg_attribute,
+                        pg_class,
+                        pg_type
+                    WHERE 
+                        pg_class.oid=attrelid
+                    AND pg_type.oid=atttypid
+                    AND attnum>0
+                    AND atthasdef='f'
+                    AND lower(relname)=(select relname from pg_stat_user_tables where relname = '$tblname' and schemaname = '$schemaname')  
+                order by 
+                    index;";
+        
+        //echo $sqlstr;
+        $resu = $this->executar($sqlstr);
+        //print_r($resu);
+        return $resu;
+    }
+    
+    public function getDbViews($schemaname = "",$viewname = ""){
+    	$add = "";
+        if ($schemaname != "") {
+        	$add = " and schemaname ilike '%$schemaname%'";
+        }
+        if ($schemaname != "") {
+            $add .= " and viewname ilike '%$viewname%'";
+        }
+        $sqlstr = "select schemaname, viewname, definition from pg_views where schemaname not in ('information_schema','pg_catalog') $add ";
+        $resu = $this->executar($sqlstr);
+        //print_r($resu);
+        return $resu;
+    }
+    
+    public function getQueries() {
+    	
+    	$sql = "select datname, procpid, usename, query_start, 
+                    (   CASE WHEN client_addr is null then 
+                            'LOCAL' 
+                        ELSE 
+                            client_addr::text 
+                        END) AS client_addr, 
+                    current_query,
+                    
+(to_char(((timeofday()::TIMESTAMP)-query_start),'hh24:mi:ss')||' - 
+Inicio: '||to_char(query_start,'hh24:mi:ss') ) AS duracao,
+                    (   CASE WHEN timeofday()::TIMESTAMP-query_start > 
+INTERVAL '30 seconds' THEN 
+                            'LENTA' 
+                        ELSE 
+                            'NORMAL' 
+                        END) AS lentas,
+                    (   CASE WHEN waiting = 't' THEN 
+                            'SIM' 
+                        ELSE 
+                            'NAO' 
+                        END) AS waiting
+                    from pg_stat_activity 
+                    where current_query not ilike '<IDLE>' 
+                    order by query_start asc";
+    	
+    	//$sql = "SELECT pg_stat_activity.datid, pg_stat_activity.datname, pg_stat_activity.procpid, pg_stat_activity.usesysid, pg_stat_activity.usename, pg_stat_activity.current_query, pg_stat_activity.query_start, pg_stat_activity.backend_start, pg_stat_activity.client_addr, pg_stat_activity.client_port FROM pg_stat_activity WHERE (pg_stat_activity.current_query <> '<IDLE>'::text) ORDER BY pg_stat_activity.query_start DESC;";
+        $resu = $this->executar($sql);
+        return $resu;
+    }
+    
+    public function getDbTables() {
+        
+        $sqlstr = "SELECT c.relname as tablename,
+
+                    pg_catalog.pg_get_userbyid(c.relowner) AS dono,
+                    
+                    pg_catalog.obj_description(c.oid, 'pg_class') AS comentario, reltuples::integer as registros,
+                    
+                    (SELECT spcname FROM pg_catalog.pg_tablespace pt WHERE pt.oid=c.reltablespace) AS tablespace,
+                    'public' AS schemaname
+                    
+                    FROM pg_catalog.pg_class c 
+                    
+                    LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
+                    
+                    WHERE c.relkind = 'r'
+                    
+                    AND nspname='public'
+                    
+                    ORDER BY c.relname";
+        
+        $resu = $this->executar($sqlstr);
+        return $resu;
+    }
+    
+    public function getFuncoes($funnome = '') {
+        
+        if ($funnome != "") { $add .= " AND proname || '(' || pg_catalog.oidvectortypes(pg_proc.proargtypes) || ')' ilike '$funnome%' "; }
+        
+        
+    	$sql = "select pg_proc.oid as oid, proname, nspname, pg_catalog.pg_get_userbyid(proowner) AS proowner, pg_catalog.obj_description(pg_proc.oid, 'pg_proc') AS procomment, pg_catalog.oidvectortypes(pg_proc.proargtypes) AS proarguments from pg_namespace,pg_proc where pg_proc.pronamespace=pg_namespace.oid and nspname in ('public','representacoes') $add order by nspname, proname; ";
+        
+        $resu = $this->executar($sql);
+        return $resu;
+    }
+    
+    public function getDbFuncao($funcao,$funnome = '') {
+        
+        if ($funcao != "") { $add = " AND pc.oid = $funcao "; }
+        if ($funnome != "") { $add .= " AND proname || '(' || pg_catalog.oidvectortypes(pc.proargtypes) || ')' ilike '$funnome' "; }
+        
+    	$sqlstr = "SELECT
+						pc.oid AS prooid,
+						proname,
+						lanname as prolanguage,
+						pg_catalog.format_type(prorettype, NULL) as proresult,
+						prosrc,
+						probin,
+						proretset,
+						proisstrict,
+						provolatile,
+						prosecdef,
+						pg_catalog.oidvectortypes(pc.proargtypes) AS proarguments,
+						proargnames AS proargnames,
+						pg_catalog.pg_get_userbyid(proowner) AS proowner,
+						pg_catalog.obj_description(pc.oid, 'pg_proc') AS procomment,
+                        proname || '(' || pg_catalog.oidvectortypes(pc.proargtypes) || ')' as nomefuncao
+					FROM pg_catalog.pg_proc pc, pg_catalog.pg_language pl
+					WHERE
+					   pc.prolang = pl.oid
+                       $add 
+                    ";
+        $resu = $this->executar($sqlstr);
+        return $resu;
+    }
+    
+    public function getDbFuncaoSrc($funoid = "",$funnome = "") {
+        $this->bloquearFuncoes(false);
+        $res_funcoes = $this->getDbFuncao($funoid,$funnome);
+        
+        $textcontent = "";
+        
+        if (pg_num_rows($res_funcoes)) {
+        $dados = $this->fetch_array($res_funcoes);
+        
+        $textcontent = "
+-- Function: " . $dados["proname"]. "(" . $dados["proarguments"]. ")
+    
+-- DROP FUNCTION " . $dados["proname"]. "(" . $dados["proarguments"]. ");
+        
+CREATE OR REPLACE FUNCTION " . $dados["proname"]. "(" . $dados["proarguments"]. ") RETURNS " . $dados["proresult"]. " AS
+\$BODY\$";
+    $textcontent .= $dados["prosrc"];
+    $textcontent .= "\$BODY\$
+  LANGUAGE 'pltcl' VOLATILE
+  COST 100;
+ALTER FUNCTION " . $dados["proname"]. "(" . $dados["proarguments"]. ") OWNER TO " . $dados["proowner"].";";
+        
+        if ($dados["procomment"] != "") {
+            $textcontent .= "
+COMMENT ON FUNCTION " . $dados["proname"]. "(" . $dados["proarguments"]. ") IS '" .  $dados["procomment"] . "';";
+        }
+        }
+        
+        return $textcontent;
+        
+    }
+    
+    public function getPrefixo($prefixo) {
+    	 $sqlstr = "select 
+                        relname AS tabela, 
+                        attname AS valor 
+                    from 
+                        pg_attribute, 
+                        pg_class 
+                    where 
+                        not attname in ('cmax','xmax','xmin','cmin','ctid','tableoid') 
+                    and attrelid=relfilenode 
+                    and relhaspkey 
+                    and (attname ilike '%$prefixo%' or relname ilike '%$prefixo%') order by relname, attname";
+         $resu = $this->executar($sqlstr);
+         return $resu;
+    }
+    
+    function getDBTriggers() {
+    	$sql = "select tgname, tgfoid, tgrelid from pg_trigger where substring(trim(tgname),0,4) != 'RI_' and substring(trim(tgname),0,4) != 'pg_'  ";
+        $resu = $this->executar($sql);
+        return $resu;
+    }
+    
+}
+
+?>
Index: trunk/workflow/inc/report/includes/classes/ListagemIndicador.class.php
===================================================================
--- trunk/workflow/inc/report/includes/classes/ListagemIndicador.class.php	(revision 5307)
+++ trunk/workflow/inc/report/includes/classes/ListagemIndicador.class.php	(revision 5307)
@@ -0,0 +1,85 @@
+<?php
+/**
+ * ListagemIndicador
+ * 
+ * @author Jair Pereira <pereira.jair@gmail.com>
+ *
+ */
+class ListagemIndicador {
+	
+	private $idindicador;
+	private $tipo;
+	private $condicao;
+	private $codigoimagem;
+	private $legenda;
+	private $tamanho;
+	private $legendaarquivo;
+	private $_url_base_path;
+	
+	public function ListagemIndicador($idindicador,$condicao = "",$tipo = "R",$codigoimagem = "1",$legenda = "",$legendaarquivo = "",$tamanho = "1") {
+		$this->idindicador = $idindicador;
+		$this->condicao = $condicao;
+		$this->tipo = $tipo;
+		$this->codigoimagem = $codigoimagem;
+		$this->legenda = $legenda;
+		$this->legendaarquivo = $legendaarquivo;
+		$this->tamanho = $tamanho;
+		$this->_url_base_path = "";
+	}
+	
+	public function getLegenda() {
+		return $this->legenda;
+	}
+	
+	public function setUrlBasePath($base_path) {
+		$this->_url_base_path = $base_path;
+	}
+	
+	public function getIdIndicador() {
+		return $this->idindicador;
+	}
+	
+	public function getTipo() {
+		return $this->tipo;
+	}
+	
+	public function getCodigoImagem() {
+	    return $this->codigoimagem;
+	}
+	
+	protected function getFileName($fundo = false) {
+		if (strtoupper($this->tipo) == "R") { $pasta = $this->_url_base_path . "/images/indicadores/redondos/ap"; }
+		if (strtoupper($this->tipo) == "Q") { $pasta = $this->_url_base_path . "/images/indicadores/quadrados/ap"; }
+		if (strtoupper($this->tipo) == "T") { $pasta = $this->_url_base_path . "/images/indicadores/triangulares/ap"; }
+	    if (strtoupper($this->tipo) == "I") { $pasta = $this->_url_base_path . "/images/icones/t"; }
+		if ($fundo) { $pasta = $pasta . "f"; }
+		if (strtoupper($this->tipo) != "I") {
+    		if ($this->codigoimagem < 10) { 
+    			$nomeimagem = "ap0" . $this->codigoimagem . ".jpg"; 
+    		} else {
+    			$nomeimagem = "ap" . $this->codigoimagem . ".jpg";
+    		}
+    		$filename = $pasta ."/" .  $nomeimagem;
+		} else {
+		    $filename = $pasta . $this->tamanho . "/" . $this->codigoimagem . ".jpg";   
+		}
+		if (!file_exists($filename)) { 
+		    $filename = str_replace("../../../","",$filename);
+		}		
+		return $filename;
+	}
+	
+	public function getLegendaArquivo() {
+		return $this->legendaarquivo;
+	}
+	
+	public function getHtml($fundo = false) {
+	    $file = $this->getFileName($fundo);
+		$html = "<img src='" . $file . "' align='absmiddle' alt='" . $this->legenda . "' title='" . $this->legenda .  "'>";
+		return $html;
+	}
+	public function getCondicao() {
+		return $this->condicao;
+	}
+}
+?>
Index: trunk/workflow/inc/report/includes/classes/FormularioHtml.class.php
===================================================================
--- trunk/workflow/inc/report/includes/classes/FormularioHtml.class.php	(revision 5307)
+++ trunk/workflow/inc/report/includes/classes/FormularioHtml.class.php	(revision 5307)
@@ -0,0 +1,124 @@
+<?
+/**
+ * FormularioHtml
+ * 
+ * Implementação de Formulários Padrões do Sistema.  
+ * 
+ * @author Jair Pereira <pereira.jair@gmail.com>
+ */
+ 
+include 'FormularioInput.class.php';
+
+class FormularioHtml extends FormularioInput {
+    protected $htmlForm;
+    protected $label;
+    protected $widthlabel;
+    protected $widthinput;
+    
+    function desenhaHtmlForm($options,$showTableDivision = true, $showTableRow = true){
+    	switch($this->tipo){
+            case 'periodo' : $this->formInput($options);  break;
+            case 'data' : $this->formInput($options);  break;
+            case 'moeda' : $this->formInput($options);  break;
+            case 'cpf' : $this->formInput($options);  break;
+            case 'cnpj' : $this->formInput($options);  break;
+            case 'input' : $this->formInput($options);  break;
+            case 'select' : $this->formSelect($options);  break;
+            case 'checkbox' : $this->formCheckBox($options);  break;
+            case 'radio' : $this->formRadio($options);  break;
+            case 'textarea' : $this->formTextArea($options);  break;
+            case 'button' : $this->formButton($options);  break;
+            case 'hidden' : $this->formHidden(false,false);  break;
+            case 'subtitulo' : $this->formSubTitulo();  break;
+            case 'div' : $this->formDiv();  break;
+            case 'file' : $this->formArquivo($options); break;
+            default: $this->formInput($options);
+        }
+    	
+        return $this->htmlForm;
+    }
+    function makeDisplayHTML($options,$tipo = "input") {
+    	$opentr = $options["open_tr"];
+        $opentd = $options["open_td"];
+        $makedivision = $options["makedivision"];
+        $makedivision_colspan = $options["makedivision_colspan"];
+        $open_td_colspan = $options["open_td_colspan"];
+        $closetd = $options["close_td"];
+        $closetr = $options["close_tr"];
+
+        if ($opentr)       echo "\n\t<tr>";  
+	    if ($makedivision) { 
+	    	if ($makedivision_colspan) $addcolspan = " colspan=" . $makedivision_colspan;
+	      if ($this->widthlabel) { $addwidthlabel = " width='" . $this->widthlabel . "'"; }
+	      echo  "\n\t\t<td" . $addwidthlabel . $addcolspan ." nowrap>"; 
+	    }
+        echo "<label id='id_lbl_" . $this->name . "' for='" . $this->obrigatorio . "id_" . $this->name . "'>". $this->label . "</label>";
+        if ($makedivision) echo "</td>";
+        if ($opentd) { 
+          if ($open_td_colspan) $addcolspan2 = " colspan=" . $open_td_colspan;
+          if ($this->widthinput) { $addwidthinput = " width='" . $this->widthinput . "'"; }
+          echo "\n\t\t<td" . $addwidthinput . $addcolspan2 . ">";
+        }
+        
+        echo "\n\t\t\t<span id='span_id_" . $this->name . "'>";
+        if ($tipo == "input") { $this->input(); }
+        if ($tipo == "select") { $this->select(); }
+        if ($tipo == "checkbox") { $this->checkbox(); }
+        if ($tipo == "radio") { $this->radio(); }
+        if ($tipo == "textarea") { $this->textarea(); }
+        if ($tipo == "arquivo") { $this->arquivo(); }
+        if ($tipo == "button") { $this->button(); }
+        echo "</span>";
+        if ($closetd)      echo	"\n\t\t</td>";
+        if ($closetr)      echo	"\n\t</tr>\n";
+        
+        return $this->htmlForm;
+    }
+    
+    function formInput($options = array()){
+    	//$this->input();
+    	return $this->makeDisplayHTML($options);
+    }
+    
+    function formSelect($options){
+        //$this->select();
+    	return $this->makeDisplayHTML($options,"select");
+    } 
+    function formCheckbox($options){
+        //$this->checkbox();
+    	return $this->makeDisplayHTML($options,"checkbox");
+    }
+    function formRadio($options){
+    	//$this->radio();
+    	return $this->makeDisplayHTML($options,"radio");
+    }
+    function formHidden() {
+        echo "\n\t\t\t" . $this->input();
+    }
+    function formTextArea($options){
+       // $this->textArea();
+        return $this->makeDisplayHTML($options,"textarea");
+    }
+    function formButton($options){
+		//$this->button();
+    	return $this->makeDisplayHTML($options,"button");
+    }
+    function formSubTitulo() {
+    	echo "\n\t\t</td>\n\t</tr>\n\t</table>\n\t<table width='100%'>\n\t<tr>\n\t\t<td>\n\t\t\t&nbsp;<br><br>\n\t\t</td>\n\t</tr>\n\t<tr class='tableSubTitulo'>\n\t\t<td colspan='1000'><h2>" . $this->value . "</h2></td>\n\t</tr>\n\t<tr><td>&nbsp;</td></tr>";
+    }
+    function formDiv() {
+        echo "\n\t\t</td>\n\t</tr>\n\t</table>\n\t<table width='100%'>\n\t\n\t<div id='" . $this->value . "'></div>\n\t";
+    }
+    function formArquivo($options) {
+    	//$this->arquivo();
+    	return $this->makeDisplayHTML($options,"arquivo");
+    }
+    function setLabel($label){
+       $this->label = $label;
+    }
+
+}
+
+
+
+?>
Index: trunk/workflow/inc/report/xajax_js/xajax.js
===================================================================
--- trunk/workflow/inc/report/xajax_js/xajax.js	(revision 5307)
+++ trunk/workflow/inc/report/xajax_js/xajax.js	(revision 5307)
@@ -0,0 +1,172 @@
+/* xajax Javascript library :: version 0.2.4 */
+Array.prototype.containsValue=function(valueToCheck){for(var i=0;i<this.length;i++){if(this[i]==valueToCheck)return true;}
+return false;}
+function Xajax(){this.DebugMessage=function(text){if(text.length > 1000)text=text.substr(0,1000)+"...\n[long response]\n...";try{if(this.debugWindow==undefined||this.debugWindow.closed==true){this.debugWindow=window.open('about:blank','xajax-debug','width=800,height=600,scrollbars=1,resizable,status');this.debugWindow.document.write('<html><head><title>Xajax debug output</title></head><body><h2>Xajax debug output</h2><div id="debugTag"></div></body></html>');}
+text=text.replace(/&/g,"&amp;")
+text=text.replace(/</g,"&lt;")
+text=text.replace(/>/g,"&gt;")
+debugTag=this.debugWindow.document.getElementById('debugTag');debugTag.innerHTML=('<b>'+(new Date()).toString()+'</b>: '+text+'<hr/>')+debugTag.innerHTML;}catch(e){alert("Xajax Debug:\n "+text);}
+};this.workId='xajaxWork'+new Date().getTime();this.depth=0;this.responseErrorsForAlert=["400","401","402","403","404","500","501","502","503"];this.getRequestObject=function(){if(xajaxDebug)this.DebugMessage("Initializing Request Object..");var req=null;if(typeof XMLHttpRequest!="undefined")
+req=new XMLHttpRequest();if(!req&&typeof ActiveXObject!="undefined"){try{req=new ActiveXObject("Msxml2.XMLHTTP");}
+catch(e){try{req=new ActiveXObject("Microsoft.XMLHTTP");}
+catch(e2){try{req=new ActiveXObject("Msxml2.XMLHTTP.4.0");}
+catch(e3){req=null;}
+}
+}
+}
+if(!req&&window.createRequest)
+req=window.createRequest();if(!req)this.DebugMessage("Request Object Instantiation failed.");return req;}
+this.$=function(sId){if(!sId){return null;}
+var returnObj=document.getElementById(sId);if(!returnObj&&document.all){returnObj=document.all[sId];}
+if(xajaxDebug&&!returnObj&&sId!=this.workId){this.DebugMessage("Element with the id \""+sId+"\" not found.");}
+return returnObj;}
+this.include=function(sFileName){var objHead=document.getElementsByTagName('head');var objScript=document.createElement('script');objScript.type='text/javascript';objScript.src=sFileName;objHead[0].appendChild(objScript);}
+this.stripOnPrefix=function(sEventName){sEventName=sEventName.toLowerCase();if(sEventName.indexOf('on')==0){sEventName=sEventName.replace(/on/,'');}
+return sEventName;}
+this.addOnPrefix=function(sEventName){sEventName=sEventName.toLowerCase();if(sEventName.indexOf('on')!=0){sEventName='on'+sEventName;}
+return sEventName;}
+this.addHandler=function(sElementId,sEvent,sFunctionName){if(window.addEventListener){sEvent=this.stripOnPrefix(sEvent);eval("this.$('"+sElementId+"').addEventListener('"+sEvent+"',"+sFunctionName+",false);");}
+else{sAltEvent=this.addOnPrefix(sEvent);eval("this.$('"+sElementId+"').attachEvent('"+sAltEvent+"',"+sFunctionName+",false);");}
+}
+this.removeHandler=function(sElementId,sEvent,sFunctionName){if(window.addEventListener){sEvent=this.stripOnPrefix(sEvent);eval("this.$('"+sElementId+"').removeEventListener('"+sEvent+"',"+sFunctionName+",false);");}
+else{sAltEvent=this.addOnPrefix(sEvent);eval("this.$('"+sElementId+"').detachEvent('"+sAltEvent+"',"+sFunctionName+",false);");}
+}
+this.create=function(sParentId,sTag,sId){var objParent=this.$(sParentId);objElement=document.createElement(sTag);objElement.setAttribute('id',sId);if(objParent)
+objParent.appendChild(objElement);}
+this.insert=function(sBeforeId,sTag,sId){var objSibling=this.$(sBeforeId);objElement=document.createElement(sTag);objElement.setAttribute('id',sId);objSibling.parentNode.insertBefore(objElement,objSibling);}
+this.insertAfter=function(sAfterId,sTag,sId){var objSibling=this.$(sAfterId);objElement=document.createElement(sTag);objElement.setAttribute('id',sId);objSibling.parentNode.insertBefore(objElement,objSibling.nextSibling);}
+this.getInput=function(sType,sName,sId){var Obj;if(!window.addEventListener){Obj=document.createElement('<input type="'+sType+'" id="'+sId+'" name="'+sName+'">');}
+else{Obj=document.createElement('input');Obj.setAttribute('type',sType);Obj.setAttribute('name',sName);Obj.setAttribute('id',sId);}
+return Obj;}
+this.createInput=function(sParentId,sType,sName,sId){var objParent=this.$(sParentId);var objElement=this.getInput(sType,sName,sId);if(objParent&&objElement)
+objParent.appendChild(objElement);}
+this.insertInput=function(sBeforeId,sType,sName,sId){var objSibling=this.$(sBeforeId);var objElement=this.getInput(sType,sName,sId);if(objElement&&objSibling&&objSibling.parentNode)
+objSibling.parentNode.insertBefore(objElement,objSibling);}
+this.insertInputAfter=function(sAfterId,sType,sName,sId){var objSibling=this.$(sAfterId);var objElement=this.getInput(sType,sName,sId);if(objElement&&objSibling&&objSibling.parentNode){objSibling.parentNode.insertBefore(objElement,objSibling.nextSibling);}
+}
+this.remove=function(sId){objElement=this.$(sId);if(objElement&&objElement.parentNode&&objElement.parentNode.removeChild){objElement.parentNode.removeChild(objElement);}
+}
+this.replace=function(sId,sAttribute,sSearch,sReplace){var bFunction=false;if(sAttribute=="innerHTML")
+sSearch=this.getBrowserHTML(sSearch);eval("var txt=this.$('"+sId+"')."+sAttribute);if(typeof txt=="function"){txt=txt.toString();bFunction=true;}
+if(txt.indexOf(sSearch)>-1){var newTxt='';while(txt.indexOf(sSearch)>-1){x=txt.indexOf(sSearch)+sSearch.length+1;newTxt+=txt.substr(0,x).replace(sSearch,sReplace);txt=txt.substr(x,txt.length-x);}
+newTxt+=txt;if(bFunction){eval('this.$("'+sId+'").'+sAttribute+'=newTxt;');}
+else if(this.willChange(sId,sAttribute,newTxt)){eval('this.$("'+sId+'").'+sAttribute+'=newTxt;');}
+}
+}
+this.getFormValues=function(frm){var objForm;var submitDisabledElements=false;if(arguments.length > 1&&arguments[1]==true)
+submitDisabledElements=true;var prefix="";if(arguments.length > 2)
+prefix=arguments[2];if(typeof(frm)=="string")
+objForm=this.$(frm);else
+objForm=frm;var sXml="<xjxquery><q>";if(objForm&&objForm.tagName=='FORM'){var formElements=objForm.elements;for(var i=0;i < formElements.length;i++){if(!formElements[i].name)
+continue;if(formElements[i].name.substring(0,prefix.length)!=prefix)
+continue;if(formElements[i].type&&(formElements[i].type=='radio'||formElements[i].type=='checkbox')&&formElements[i].checked==false)
+continue;if(formElements[i].disabled&&formElements[i].disabled==true&&submitDisabledElements==false)
+continue;var name=formElements[i].name;if(name){if(sXml!='<xjxquery><q>')
+sXml+='&';if(formElements[i].type=='select-multiple'){for(var j=0;j < formElements[i].length;j++){if(formElements[i].options[j].selected==true)
+sXml+=name+"="+encodeURIComponent(formElements[i].options[j].value)+"&";}
+}
+else{sXml+=name+"="+encodeURIComponent(formElements[i].value);}
+}
+}
+}
+sXml+="</q></xjxquery>";return sXml;}
+this.objectToXML=function(obj){var sXml="<xjxobj>";for(i in obj){try{if(i=='constructor')
+continue;if(obj[i]&&typeof(obj[i])=='function')
+continue;var key=i;var value=obj[i];if(value&&typeof(value)=="object"&&this.depth <=50){this.depth++;value=this.objectToXML(value);this.depth--;}
+sXml+="<e><k>"+key+"</k><v>"+value+"</v></e>";}
+catch(e){if(xajaxDebug)this.DebugMessage(e.name+": "+e.message);}
+}
+sXml+="</xjxobj>";return sXml;}
+this._nodeToObject=function(node){if(node.nodeName=='#cdata-section'){var data="";for(var j=0;j<node.parentNode.childNodes.length;j++){data+=node.parentNode.childNodes[j].data;}
+return data;}
+else if(node.nodeName=='xjxobj'){var data=new Array();for(var j=0;j<node.childNodes.length;j++){var child=node.childNodes[j];var key;var value;if(child.nodeName=='e'){for(var k=0;k<child.childNodes.length;k++){if(child.childNodes[k].nodeName=='k'){key=child.childNodes[k].firstChild.data;}
+else if(child.childNodes[k].nodeName=='v'){value=this._nodeToObject(child.childNodes[k].firstChild);}
+}
+if(key!=null&&value!=null){data[key]=value;key=value=null;}
+}
+}
+return data;}
+}
+this.loadingFunction=function(){};this.doneLoadingFunction=function(){};var loadingTimeout;this.call=function(sFunction,aArgs,sRequestType){var i,r,postData;if(document.body&&xajaxWaitCursor)
+document.body.style.cursor='wait';if(xajaxStatusMessages==true)window.status='Sending Request...';clearTimeout(loadingTimeout);loadingTimeout=setTimeout("xajax.loadingFunction();",400);if(xajaxDebug)this.DebugMessage("Starting xajax...");if(sRequestType==null){var xajaxRequestType=xajaxDefinedPost;}
+else{var xajaxRequestType=sRequestType;}
+var uri=xajaxRequestUri;var value;switch(xajaxRequestType){case xajaxDefinedGet:{var uriGet=uri.indexOf("?")==-1?"?xajax="+encodeURIComponent(sFunction):"&xajax="+encodeURIComponent(sFunction);if(aArgs){for(i=0;i<aArgs.length;i++){value=aArgs[i];if(typeof(value)=="object")
+value=this.objectToXML(value);uriGet+="&xajaxargs[]="+encodeURIComponent(value);}
+}
+uriGet+="&xajaxr="+new Date().getTime();uri+=uriGet;postData=null;}break;case xajaxDefinedPost:{postData="xajax="+encodeURIComponent(sFunction);postData+="&xajaxr="+new Date().getTime();if(aArgs){for(i=0;i <aArgs.length;i++){value=aArgs[i];if(typeof(value)=="object")
+value=this.objectToXML(value);postData=postData+"&xajaxargs[]="+encodeURIComponent(value);}
+}
+}break;default:
+alert("Illegal request type: "+xajaxRequestType);return false;break;}
+r=this.getRequestObject();if(!r)return false;r.open(xajaxRequestType==xajaxDefinedGet?"GET":"POST",uri,true);if(xajaxRequestType==xajaxDefinedPost){try{r.setRequestHeader("Method","POST "+uri+" HTTP/1.1");r.setRequestHeader("Content-Type","application/x-www-form-urlencoded");}
+catch(e){alert("Your browser does not appear to  support asynchronous requests using POST.");return false;}
+}
+r.onreadystatechange=function(){if(r.readyState!=4)
+return;if(r.status==200){if(xajaxDebug)xajax.DebugMessage("Received:\n"+r.responseText);if(r.responseXML&&r.responseXML.documentElement)
+xajax.processResponse(r.responseXML);else{var errorString="Error: the XML response that was returned from the server is invalid.";errorString+="\nReceived:\n"+r.responseText;trimmedResponseText=r.responseText.replace(/^\s+/g,"");trimmedResponseText=trimmedResponseText.replace(/\s+$/g,"");if(trimmedResponseText!=r.responseText)
+errorString+="\nYou have whitespace in your response.";alert(errorString);document.body.style.cursor='default';if(xajaxStatusMessages==true)window.status='Invalid XML response error';}
+}
+else{if(xajax.responseErrorsForAlert.containsValue(r.status)){var errorString="Error: the server returned the following HTTP status: "+r.status;errorString+="\nReceived:\n"+r.responseText;alert(errorString);}
+document.body.style.cursor='default';if(xajaxStatusMessages==true)window.status='Invalid XML response error';}
+delete r;r=null;}
+if(xajaxDebug)this.DebugMessage("Calling "+sFunction+" uri="+uri+" (post:"+postData+")");r.send(postData);if(xajaxStatusMessages==true)window.status='Waiting for data...';delete r;return true;}
+this.getBrowserHTML=function(html){tmpXajax=this.$(this.workId);if(!tmpXajax){tmpXajax=document.createElement("div");tmpXajax.setAttribute('id',this.workId);tmpXajax.style.display="none";tmpXajax.style.visibility="hidden";document.body.appendChild(tmpXajax);}
+tmpXajax.innerHTML=html;var browserHTML=tmpXajax.innerHTML;tmpXajax.innerHTML='';return browserHTML;}
+this.willChange=function(element,attribute,newData){if(!document.body){return true;}
+if(attribute=="innerHTML"){newData=this.getBrowserHTML(newData);}
+elementObject=this.$(element);if(elementObject){var oldData;eval("oldData=this.$('"+element+"')."+attribute);if(newData!==oldData)
+return true;}
+return false;}
+this.viewSource=function(){return "<html>"+document.getElementsByTagName("HTML")[0].innerHTML+"</html>";}
+this.processResponse=function(xml){clearTimeout(loadingTimeout);this.doneLoadingFunction();if(xajaxStatusMessages==true)window.status='Processing...';var tmpXajax=null;xml=xml.documentElement;if(xml==null)
+return;var skipCommands=0;for(var i=0;i<xml.childNodes.length;i++){if(skipCommands > 0){skipCommands--;continue;}
+if(xml.childNodes[i].nodeName=="cmd"){var cmd;var id;var property;var data;var search;var type;var before;var objElement=null;for(var j=0;j<xml.childNodes[i].attributes.length;j++){if(xml.childNodes[i].attributes[j].name=="n"){cmd=xml.childNodes[i].attributes[j].value;}
+else if(xml.childNodes[i].attributes[j].name=="t"){id=xml.childNodes[i].attributes[j].value;}
+else if(xml.childNodes[i].attributes[j].name=="p"){property=xml.childNodes[i].attributes[j].value;}
+else if(xml.childNodes[i].attributes[j].name=="c"){type=xml.childNodes[i].attributes[j].value;}
+}
+if(xml.childNodes[i].childNodes.length > 1&&xml.childNodes[i].firstChild.nodeName=="#cdata-section"){data="";for(var j=0;j<xml.childNodes[i].childNodes.length;j++){data+=xml.childNodes[i].childNodes[j].data;}
+}
+else if(xml.childNodes[i].firstChild&&xml.childNodes[i].firstChild.nodeName=='xjxobj'){data=this._nodeToObject(xml.childNodes[i].firstChild);objElement="XJX_SKIP";}
+else if(xml.childNodes[i].childNodes.length > 1){for(var j=0;j<xml.childNodes[i].childNodes.length;j++){if(xml.childNodes[i].childNodes[j].childNodes.length > 1&&xml.childNodes[i].childNodes[j].firstChild.nodeName=="#cdata-section"){var internalData="";for(var k=0;k<xml.childNodes[i].childNodes[j].childNodes.length;k++){internalData+=xml.childNodes[i].childNodes[j].childNodes[k].nodeValue;}
+}else{var internalData=xml.childNodes[i].childNodes[j].firstChild.nodeValue;}
+if(xml.childNodes[i].childNodes[j].nodeName=="s"){search=internalData;}
+if(xml.childNodes[i].childNodes[j].nodeName=="r"){data=internalData;}
+}
+}
+else if(xml.childNodes[i].firstChild)
+data=xml.childNodes[i].firstChild.nodeValue;else
+data="";if(objElement!="XJX_SKIP")objElement=this.$(id);var cmdFullname;try{if(cmd=="cc"){cmdFullname="addConfirmCommands";var confirmResult=confirm(data);if(!confirmResult){skipCommands=id;}
+}
+if(cmd=="al"){cmdFullname="addAlert";alert(data);}
+else if(cmd=="js"){cmdFullname="addScript/addRedirect";eval(data);}
+else if(cmd=="jc"){cmdFullname="addScriptCall";var scr=id+'(';if(data[0]!=null){scr+='data[0]';for(var l=1;l<data.length;l++){scr+=',data['+l+']';}
+}
+scr+=');';eval(scr);}
+else if(cmd=="in"){cmdFullname="addIncludeScript";this.include(data);}
+else if(cmd=="as"){cmdFullname="addAssign/addClear";if(this.willChange(id,property,data)){eval("objElement."+property+"=data;");}
+}
+else if(cmd=="ap"){cmdFullname="addAppend";eval("objElement."+property+"+=data;");}
+else if(cmd=="pp"){cmdFullname="addPrepend";eval("objElement."+property+"=data+objElement."+property);}
+else if(cmd=="rp"){cmdFullname="addReplace";this.replace(id,property,search,data)
+}
+else if(cmd=="rm"){cmdFullname="addRemove";this.remove(id);}
+else if(cmd=="ce"){cmdFullname="addCreate";this.create(id,data,property);}
+else if(cmd=="ie"){cmdFullname="addInsert";this.insert(id,data,property);}
+else if(cmd=="ia"){cmdFullname="addInsertAfter";this.insertAfter(id,data,property);}
+else if(cmd=="ci"){cmdFullname="addCreateInput";this.createInput(id,type,data,property);}
+else if(cmd=="ii"){cmdFullname="addInsertInput";this.insertInput(id,type,data,property);}
+else if(cmd=="iia"){cmdFullname="addInsertInputAfter";this.insertInputAfter(id,type,data,property);}
+else if(cmd=="ev"){cmdFullname="addEvent";property=this.addOnPrefix(property);eval("this.$('"+id+"')."+property+"= function(){"+data+";}");}
+else if(cmd=="ah"){cmdFullname="addHandler";this.addHandler(id,property,data);}
+else if(cmd=="rh"){cmdFullname="addRemoveHandler";this.removeHandler(id,property,data);}
+}
+catch(e){if(xajaxDebug)
+alert("While trying to '"+cmdFullname+"' (command number "+i+"), the following error occured:\n"
++e.name+": "+e.message+"\n"
++(id&&!objElement?"Object with id='"+id+"' wasn't found.\n":""));}
+delete objElement;delete cmd;delete cmdFullname;delete id;delete property;delete search;delete data;delete type;delete before;delete internalData;delete j;delete k;}
+}
+delete xml;delete i;document.body.style.cursor='default';if(xajaxStatusMessages==true)window.status='Done';}
+}
+var xajax=new Xajax();xajaxLoaded=true;
Index: trunk/workflow/inc/report/xajax_js/xajax_uncompressed.js
===================================================================
--- trunk/workflow/inc/report/xajax_js/xajax_uncompressed.js	(revision 5307)
+++ trunk/workflow/inc/report/xajax_js/xajax_uncompressed.js	(revision 5307)
@@ -0,0 +1,795 @@
+/* xajax Javascript library :: version 0.2.4 */
+
+Array.prototype.containsValue = function(valueToCheck)
+{
+	for (var i=0;i<this.length;i++) {
+		if (this[i] == valueToCheck) return true;
+	}
+	return false;
+}
+
+function Xajax()
+{
+	this.DebugMessage = function(text)
+	{
+		if (text.length > 1000) text = text.substr(0,1000)+"...\n[long response]\n...";
+		try {
+			if (this.debugWindow == undefined || this.debugWindow.closed == true) {
+				this.debugWindow = window.open('about:blank', 'xajax-debug', 'width=800,height=600,scrollbars=1,resizable,status');
+				this.debugWindow.document.write('<html><head><title>Xajax debug output</title></head><body><h2>Xajax debug output</h2><div id="debugTag"></div></body></html>');
+			}
+			text = text.replace(/&/g, "&amp;")
+			text = text.replace(/</g, "&lt;")
+			text = text.replace(/>/g, "&gt;")
+			debugTag = this.debugWindow.document.getElementById('debugTag');
+			debugTag.innerHTML = ('<b>'+(new Date()).toString()+'</b>: ' + text + '<hr/>') + debugTag.innerHTML;
+		} catch (e) {
+			alert("Xajax Debug:\n " + text);
+		}
+	};
+	
+	this.workId = 'xajaxWork'+ new Date().getTime();
+	this.depth = 0;
+	this.responseErrorsForAlert = ["400","401","402","403","404","500","501","502","503"];
+	
+	//Get the XMLHttpRequest Object
+	this.getRequestObject = function()
+	{
+		if (xajaxDebug) this.DebugMessage("Initializing Request Object..");
+		var req = null;
+		if (typeof XMLHttpRequest != "undefined")
+			req = new XMLHttpRequest();
+		if (!req && typeof ActiveXObject != "undefined")
+		{
+			try
+			{
+				req=new ActiveXObject("Msxml2.XMLHTTP");
+			}
+			catch (e)
+			{
+				try
+				{
+					req=new ActiveXObject("Microsoft.XMLHTTP");
+				}
+				catch (e2)
+				{
+					try {
+						req=new ActiveXObject("Msxml2.XMLHTTP.4.0");
+					}
+					catch (e3)
+					{
+						req=null;
+					}
+				}
+			}
+		}
+		if(!req && window.createRequest)
+			req = window.createRequest();
+		
+		if (!req) this.DebugMessage("Request Object Instantiation failed.");
+			
+		return req;
+	}
+
+	// xajax.$() is shorthand for document.getElementById()
+	this.$ = function(sId)
+	{
+		if (!sId) {
+			return null;
+		}
+		var returnObj = document.getElementById(sId);
+		if (!returnObj && document.all) {
+			returnObj = document.all[sId];
+		}
+		if (xajaxDebug && !returnObj && sId != this.workId) {
+			this.DebugMessage("Element with the id \"" + sId + "\" not found.");
+		}
+		return returnObj;
+	}
+	
+	// xajax.include(sFileName) dynamically includes an external javascript file
+	this.include = function(sFileName)
+	{
+		var objHead = document.getElementsByTagName('head');
+		var objScript = document.createElement('script');
+		objScript.type = 'text/javascript';
+		objScript.src = sFileName;
+		objHead[0].appendChild(objScript);
+	}
+	
+	this.stripOnPrefix = function(sEventName)
+	{
+		sEventName = sEventName.toLowerCase();
+		if (sEventName.indexOf('on') == 0)
+		{
+			sEventName = sEventName.replace(/on/,'');
+		}
+		
+		return sEventName;
+	}
+	
+	this.addOnPrefix = function(sEventName)
+	{
+		sEventName = sEventName.toLowerCase();
+		if (sEventName.indexOf('on') != 0)
+		{
+			sEventName = 'on' + sEventName;
+		}
+		
+		return sEventName;
+	}
+	
+	// xajax.addHandler adds an event handler to an element
+	this.addHandler = function(sElementId, sEvent, sFunctionName)
+	{
+		if (window.addEventListener)
+		{
+			sEvent = this.stripOnPrefix(sEvent);
+			eval("this.$('"+sElementId+"').addEventListener('"+sEvent+"',"+sFunctionName+",false);");
+		}
+		else
+		{
+			sAltEvent = this.addOnPrefix(sEvent);
+			eval("this.$('"+sElementId+"').attachEvent('"+sAltEvent+"',"+sFunctionName+",false);");
+		}
+	}
+	
+	// xajax.removeHandler removes an event handler from an element
+	this.removeHandler = function(sElementId, sEvent, sFunctionName)
+	{
+		if (window.addEventListener)
+		{
+			sEvent = this.stripOnPrefix(sEvent);
+			eval("this.$('"+sElementId+"').removeEventListener('"+sEvent+"',"+sFunctionName+",false);");
+		}
+		else
+		{
+			sAltEvent = this.addOnPrefix(sEvent);
+			eval("this.$('"+sElementId+"').detachEvent('"+sAltEvent+"',"+sFunctionName+",false);");
+		}
+	}
+	
+	// xajax.create creates a new child node under a parent
+	this.create = function(sParentId, sTag, sId)
+	{
+		var objParent = this.$(sParentId);
+		objElement = document.createElement(sTag);
+		objElement.setAttribute('id',sId);
+		if (objParent)
+			objParent.appendChild(objElement);
+	}
+	
+	// xajax.insert inserts a new node before another node
+	this.insert = function(sBeforeId, sTag, sId)
+	{
+		var objSibling = this.$(sBeforeId);
+		objElement = document.createElement(sTag);
+		objElement.setAttribute('id',sId);
+		objSibling.parentNode.insertBefore(objElement, objSibling);
+	}
+
+	// xajax.insertAfter inserts a new node after another node
+	this.insertAfter = function(sAfterId, sTag, sId)
+	{
+		var objSibling = this.$(sAfterId);
+		objElement = document.createElement(sTag);
+		objElement.setAttribute('id',sId);
+		objSibling.parentNode.insertBefore(objElement, objSibling.nextSibling);
+	}
+	
+	this.getInput = function(sType, sName, sId)
+	{
+		var Obj;
+		if (!window.addEventListener)
+		{
+			Obj = document.createElement('<input type="'+sType+'" id="'+sId+'" name="'+sName+'">');
+		}
+		else
+		{
+			Obj = document.createElement('input');
+			Obj.setAttribute('type',sType);
+			Obj.setAttribute('name',sName);
+			Obj.setAttribute('id',sId);
+		}
+		return Obj;
+	}
+	
+	// xajax.createInput creates a new input node under a parent
+	this.createInput = function(sParentId, sType, sName, sId)
+	{
+		var objParent = this.$(sParentId);
+		var objElement = this.getInput(sType, sName, sId);
+		if (objParent && objElement)
+			objParent.appendChild(objElement);
+	}
+	
+	// xajax.insertInput creates a new input node before another node
+	this.insertInput = function(sBeforeId, sType, sName, sId)
+	{
+		var objSibling = this.$(sBeforeId);
+		var objElement = this.getInput(sType, sName, sId);
+		if (objElement && objSibling && objSibling.parentNode)
+			objSibling.parentNode.insertBefore(objElement, objSibling);
+	}
+
+	// xajax.insertInputAfter creates a new input node after another node
+	this.insertInputAfter = function(sAfterId, sType, sName, sId)
+	{
+		var objSibling = this.$(sAfterId);
+		var objElement = this.getInput(sType, sName, sId);
+		if (objElement && objSibling && objSibling.parentNode) {
+			objSibling.parentNode.insertBefore(objElement, objSibling.nextSibling);
+		}
+	}
+		
+	// xajax.remove deletes an element
+	this.remove = function(sId)
+	{
+		objElement = this.$(sId);
+		if (objElement && objElement.parentNode && objElement.parentNode.removeChild)
+		{
+			objElement.parentNode.removeChild(objElement);
+		}
+	}
+	
+	//xajax.replace searches for text in an attribute of an element and replaces it
+	//with a different text
+	this.replace = function(sId,sAttribute,sSearch,sReplace)
+	{
+		var bFunction = false;
+		
+		if (sAttribute == "innerHTML")
+			sSearch = this.getBrowserHTML(sSearch);
+		
+		eval("var txt=this.$('"+sId+"')."+sAttribute);
+		if (typeof txt == "function")
+        {
+            txt = txt.toString();
+            bFunction = true;
+        }
+		if (txt.indexOf(sSearch)>-1)
+		{
+			var newTxt = '';
+			while (txt.indexOf(sSearch) > -1)
+			{
+				x = txt.indexOf(sSearch)+sSearch.length+1;
+				newTxt += txt.substr(0,x).replace(sSearch,sReplace);
+				txt = txt.substr(x,txt.length-x);
+			}
+			newTxt += txt;
+			if (bFunction)
+			{
+				eval('this.$("'+sId+'").'+sAttribute+'=newTxt;');
+			}
+			else if (this.willChange(sId,sAttribute,newTxt))
+			{
+				eval('this.$("'+sId+'").'+sAttribute+'=newTxt;');
+			}
+		}
+	}
+	
+	// xajax.getFormValues() builds a query string XML message from the elements of a form object
+	// * The first argument is the id of the form
+	// * The second argument (optional) can be set to true if you want to submit disabled elements
+	// * The third argument (optional) allows you to specify a string prefix that a form element
+	//   name must contain if you want that element to be submitted
+	this.getFormValues = function(frm)
+	{
+		var objForm;
+		var submitDisabledElements = false;
+		if (arguments.length > 1 && arguments[1] == true)
+			submitDisabledElements = true;
+		var prefix="";
+		if(arguments.length > 2)
+			prefix = arguments[2];
+		
+		if (typeof(frm) == "string")
+			objForm = this.$(frm);
+		else
+			objForm = frm;
+		var sXml = "<xjxquery><q>";
+		if (objForm && objForm.tagName == 'FORM')
+		{
+			var formElements = objForm.elements;
+			for( var i=0; i < formElements.length; i++)
+			{
+				if (!formElements[i].name)
+					continue;
+				if (formElements[i].name.substring(0, prefix.length) != prefix)
+					continue;
+				if (formElements[i].type && (formElements[i].type == 'radio' || formElements[i].type == 'checkbox') && formElements[i].checked == false)
+					continue;
+				if (formElements[i].disabled && formElements[i].disabled == true && submitDisabledElements == false)
+					continue;
+				var name = formElements[i].name;
+				if (name)
+				{
+					if (sXml != '<xjxquery><q>')
+						sXml += '&';
+					if(formElements[i].type=='select-multiple')
+					{
+						for (var j = 0; j < formElements[i].length; j++)
+						{
+							if (formElements[i].options[j].selected == true)
+								sXml += name+"="+encodeURIComponent(formElements[i].options[j].value)+"&";
+						}
+					}
+					else
+					{
+						sXml += name+"="+encodeURIComponent(formElements[i].value);
+					}
+				} 
+			}
+		}
+		
+		sXml +="</q></xjxquery>";
+		
+		return sXml;
+	}
+	
+	// Generates an XML message that xajax can understand from a javascript object
+	this.objectToXML = function(obj)
+	{
+		var sXml = "<xjxobj>";
+		for (i in obj)
+		{
+			try
+			{
+				if (i == 'constructor')
+					continue;
+				if (obj[i] && typeof(obj[i]) == 'function')
+					continue;
+					
+				var key = i;
+				var value = obj[i];
+				if (value && typeof(value)=="object" && this.depth <= 50)
+				{
+					this.depth++;
+					value = this.objectToXML(value);
+					this.depth--;
+				}
+				
+				sXml += "<e><k>"+key+"</k><v>"+value+"</v></e>";
+				
+			}
+			catch(e)
+			{
+				if (xajaxDebug) this.DebugMessage(e.name+": "+e.message);
+			}
+		}
+		sXml += "</xjxobj>";
+	
+		return sXml;
+	}
+
+	// unserializes data structure from xajaxResponse::_buildObjXml()
+	this._nodeToObject = function(node) {
+		// parentNode here is weird, have to tune
+		if (node.nodeName == '#cdata-section') {
+			var data = "";
+			for (var j=0; j<node.parentNode.childNodes.length; j++) {
+				data += node.parentNode.childNodes[j].data;
+			}
+			return data;
+		}
+		else if (node.nodeName == 'xjxobj') {
+			var data = new Array();
+			for (var j=0; j<node.childNodes.length; j++) {
+				var child = node.childNodes[j];
+				var key;
+				var value;
+				if (child.nodeName == 'e') {
+					for (var k=0; k<child.childNodes.length; k++) {
+						if (child.childNodes[k].nodeName == 'k') {
+							key = child.childNodes[k].firstChild.data;
+						}
+						else if (child.childNodes[k].nodeName == 'v') {
+							value = this._nodeToObject(child.childNodes[k].firstChild);
+						}
+					}
+					if (key != null && value != null) {
+						data[key] = value;
+						key = value = null;
+					}
+				}
+			}
+			return data;
+		}		
+	}
+
+	this.loadingFunction = function(){};
+	this.doneLoadingFunction = function(){};
+	var loadingTimeout;
+
+	// Sends a XMLHttpRequest to call the specified PHP function on the server
+	// * sRequestType is optional -- defaults to POST
+	this.call = function(sFunction, aArgs, sRequestType)
+	{
+		var i,r,postData;
+		if (document.body && xajaxWaitCursor)
+			document.body.style.cursor = 'wait';
+		if (xajaxStatusMessages == true) window.status = 'Sending Request...';
+		clearTimeout(loadingTimeout);
+		loadingTimeout = setTimeout("xajax.loadingFunction();",400);
+		if (xajaxDebug) this.DebugMessage("Starting xajax...");
+		if (sRequestType == null) {
+		   var xajaxRequestType = xajaxDefinedPost;
+		}
+		else {
+			var xajaxRequestType = sRequestType;
+		}
+		var uri = xajaxRequestUri;
+		var value;
+		switch(xajaxRequestType)
+		{
+			case xajaxDefinedGet:{
+				var uriGet = uri.indexOf("?")==-1?"?xajax="+encodeURIComponent(sFunction):"&xajax="+encodeURIComponent(sFunction);
+				if (aArgs) {
+					for (i = 0; i<aArgs.length; i++)
+					{
+						value = aArgs[i];
+						if (typeof(value)=="object")
+							value = this.objectToXML(value);
+						uriGet += "&xajaxargs[]="+encodeURIComponent(value);
+					}
+				}
+				uriGet += "&xajaxr=" + new Date().getTime();
+				uri += uriGet;
+				postData = null;
+				} break;
+			case xajaxDefinedPost:{
+				postData = "xajax="+encodeURIComponent(sFunction);
+				postData += "&xajaxr="+new Date().getTime();
+				if (aArgs) {
+					for (i = 0; i <aArgs.length; i++)
+					{
+						value = aArgs[i];
+						if (typeof(value)=="object")
+							value = this.objectToXML(value);
+						postData = postData+"&xajaxargs[]="+encodeURIComponent(value);
+					}
+				}
+				} break;
+			default:
+				alert("Illegal request type: " + xajaxRequestType); return false; break;
+		}
+		r = this.getRequestObject();
+		if (!r) return false;
+		r.open(xajaxRequestType==xajaxDefinedGet?"GET":"POST", uri, true);
+		if (xajaxRequestType == xajaxDefinedPost)
+		{
+			try
+			{
+				r.setRequestHeader("Method", "POST " + uri + " HTTP/1.1");
+				r.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
+			}
+			catch(e)
+			{
+				alert("Your browser does not appear to  support asynchronous requests using POST.");
+				return false;
+			}
+		}
+		r.onreadystatechange = function()
+		{
+			if (r.readyState != 4)
+				return;
+			
+			if (r.status==200)
+			{
+				if (xajaxDebug) xajax.DebugMessage("Received:\n" + r.responseText);
+				if (r.responseXML && r.responseXML.documentElement)
+					xajax.processResponse(r.responseXML);
+				else {
+					var errorString = "Error: the XML response that was returned from the server is invalid.";
+					errorString += "\nReceived:\n" + r.responseText;
+					trimmedResponseText = r.responseText.replace( /^\s+/g, "" );// strip leading space
+					trimmedResponseText = trimmedResponseText.replace( /\s+$/g, "" );// strip trailing
+					if (trimmedResponseText != r.responseText)
+						errorString += "\nYou have whitespace in your response.";
+					alert(errorString);
+					document.body.style.cursor = 'default';
+					if (xajaxStatusMessages == true) window.status = 'Invalid XML response error';				
+				}
+			}
+			else {
+				if (xajax.responseErrorsForAlert.containsValue(r.status)) {
+					var errorString = "Error: the server returned the following HTTP status: " + r.status;
+					errorString += "\nReceived:\n" + r.responseText;
+					alert(errorString);
+				}
+				document.body.style.cursor = 'default';
+				if (xajaxStatusMessages == true) window.status = 'Invalid XML response error';								
+			}
+			
+			delete r;
+			r = null;
+		}
+		if (xajaxDebug) this.DebugMessage("Calling "+sFunction +" uri="+uri+" (post:"+ postData +")");
+		r.send(postData);
+		if (xajaxStatusMessages == true) window.status = 'Waiting for data...';
+		delete r;
+		return true;
+	}
+	
+	//Gets the text as it would be if it were being retrieved from
+	//the innerHTML property in the current browser
+	this.getBrowserHTML = function(html)
+	{
+		tmpXajax = this.$(this.workId);
+		if (!tmpXajax)
+		{
+			tmpXajax = document.createElement("div");
+			tmpXajax.setAttribute('id',this.workId);
+			tmpXajax.style.display = "none";
+			tmpXajax.style.visibility = "hidden";
+			document.body.appendChild(tmpXajax);
+		}
+		tmpXajax.innerHTML = html;
+		var browserHTML = tmpXajax.innerHTML;
+		tmpXajax.innerHTML = '';	
+		
+		return browserHTML;
+	}
+	
+	// Tests if the new Data is the same as the extant data
+	this.willChange = function(element, attribute, newData)
+	{
+		if (!document.body)
+		{
+			return true;
+		}
+		if (attribute == "innerHTML")
+		{
+			newData = this.getBrowserHTML(newData);
+		}
+		elementObject = this.$(element);
+		if (elementObject) {
+			var oldData;		
+			eval("oldData=this.$('"+element+"')."+attribute);
+			if (newData !== oldData)
+				return true;
+		}
+
+		return false;
+	}
+	
+	//Returns the source code of the page after it's been modified by xajax
+	this.viewSource = function()
+	{
+		return "<html>"+document.getElementsByTagName("HTML")[0].innerHTML+"</html>";
+	}
+	
+	//Process XML xajaxResponses returned from the request
+	this.processResponse = function(xml)
+	{
+		clearTimeout(loadingTimeout);
+		this.doneLoadingFunction();
+		if (xajaxStatusMessages == true) window.status = 'Processing...';
+		var tmpXajax = null;
+		xml = xml.documentElement;
+		if (xml == null)
+			return;
+		
+		var skipCommands = 0;
+		for (var i=0; i<xml.childNodes.length; i++)
+		{
+			if (skipCommands > 0) {
+				skipCommands--;
+				continue;
+			}
+			if (xml.childNodes[i].nodeName == "cmd")
+			{
+				var cmd;
+				var id;
+				var property;
+				var data;
+				var search;
+				var type;
+				var before;
+				var objElement = null;
+
+				for (var j=0; j<xml.childNodes[i].attributes.length; j++)
+				{
+					if (xml.childNodes[i].attributes[j].name == "n")
+					{
+						cmd = xml.childNodes[i].attributes[j].value;
+					}
+					else if (xml.childNodes[i].attributes[j].name == "t")
+					{
+						id = xml.childNodes[i].attributes[j].value;
+					}
+					else if (xml.childNodes[i].attributes[j].name == "p")
+					{
+						property = xml.childNodes[i].attributes[j].value;
+					}
+					else if (xml.childNodes[i].attributes[j].name == "c")
+					{
+						type = xml.childNodes[i].attributes[j].value;
+					}
+				}
+				if (xml.childNodes[i].childNodes.length > 1 && xml.childNodes[i].firstChild.nodeName == "#cdata-section")
+				{
+					data = "";
+					for (var j=0; j<xml.childNodes[i].childNodes.length; j++)
+					{
+						data += xml.childNodes[i].childNodes[j].data;
+					}
+				}
+				else if (xml.childNodes[i].firstChild && xml.childNodes[i].firstChild.nodeName == 'xjxobj') {
+					data = this._nodeToObject(xml.childNodes[i].firstChild);
+					objElement = "XJX_SKIP";
+				}
+				else if (xml.childNodes[i].childNodes.length > 1)
+				{
+					for (var j=0; j<xml.childNodes[i].childNodes.length; j++)
+					{
+						if (xml.childNodes[i].childNodes[j].childNodes.length > 1 && xml.childNodes[i].childNodes[j].firstChild.nodeName == "#cdata-section")
+						{
+							var internalData = "";
+							for (var k=0; k<xml.childNodes[i].childNodes[j].childNodes.length;k++)
+							{
+								internalData+=xml.childNodes[i].childNodes[j].childNodes[k].nodeValue;
+							}
+						} else {
+							var internalData = xml.childNodes[i].childNodes[j].firstChild.nodeValue;
+						}
+					
+						if (xml.childNodes[i].childNodes[j].nodeName == "s")
+						{
+							search = internalData;
+						}
+						if (xml.childNodes[i].childNodes[j].nodeName == "r")
+						{
+							data = internalData;
+						}
+					}
+				}
+				else if (xml.childNodes[i].firstChild)
+					data = xml.childNodes[i].firstChild.nodeValue;
+				else
+					data = "";
+				
+				if (objElement != "XJX_SKIP") objElement = this.$(id);
+				var cmdFullname;
+				try
+				{
+					if (cmd=="cc") {
+						cmdFullname = "addConfirmCommands";
+						var confirmResult = confirm(data);
+						if (!confirmResult) {
+							skipCommands = id;
+						}
+					}
+					if (cmd=="al")
+					{
+						cmdFullname = "addAlert";
+						alert(data);
+					}
+					else if (cmd=="js")
+					{
+						cmdFullname = "addScript/addRedirect";
+						eval(data);
+					}
+					else if (cmd=="jc")
+					{
+						cmdFullname = "addScriptCall";
+						var scr = id + '(';
+						if (data[0] != null) {
+							scr += 'data[0]';
+							for (var l=1; l<data.length; l++) {
+								scr += ',data['+l+']';
+							}
+						}
+						scr += ');';
+						eval(scr);
+					}
+					else if (cmd=="in")
+					{
+						cmdFullname = "addIncludeScript";
+						this.include(data);
+					}
+					else if (cmd=="as")
+					{
+						cmdFullname = "addAssign/addClear";
+						if (this.willChange(id,property,data))
+						{
+							eval("objElement."+property+"=data;");
+						}
+					}
+					else if (cmd=="ap")
+					{
+						cmdFullname = "addAppend";
+						eval("objElement."+property+"+=data;");
+					}
+					else if (cmd=="pp")
+					{
+						cmdFullname = "addPrepend";
+						eval("objElement."+property+"=data+objElement."+property);
+					}
+					else if (cmd=="rp")
+					{
+						cmdFullname = "addReplace";
+						this.replace(id,property,search,data)
+					}
+					else if (cmd=="rm")
+					{
+						cmdFullname = "addRemove";
+						this.remove(id);
+					}
+					else if (cmd=="ce")
+					{
+						cmdFullname = "addCreate";
+						this.create(id,data,property);
+					}
+					else if (cmd=="ie")
+					{
+						cmdFullname = "addInsert";
+						this.insert(id,data,property);
+					}
+					else if (cmd=="ia")
+					{
+						cmdFullname = "addInsertAfter";
+						this.insertAfter(id,data,property);
+					}
+					else if (cmd=="ci")
+					{
+						cmdFullname = "addCreateInput";
+						this.createInput(id,type,data,property);
+					}
+					else if (cmd=="ii")
+					{
+						cmdFullname = "addInsertInput";
+						this.insertInput(id,type,data,property);
+					}
+					else if (cmd=="iia")
+					{
+						cmdFullname = "addInsertInputAfter";
+						this.insertInputAfter(id,type,data,property);
+					}
+					else if (cmd=="ev")
+					{
+						cmdFullname = "addEvent";
+						property = this.addOnPrefix(property);
+						eval("this.$('"+id+"')."+property+"= function(){"+data+";}");
+					}
+					else if (cmd=="ah")
+					{
+						cmdFullname = "addHandler";
+						this.addHandler(id, property, data);
+					}
+					else if (cmd=="rh")
+					{
+						cmdFullname = "addRemoveHandler";
+						this.removeHandler(id, property, data);
+					}
+				}
+				catch(e)
+				{
+					if (xajaxDebug)
+						alert("While trying to '"+cmdFullname+"' (command number "+i+"), the following error occured:\n"
+							+ e.name+": "+e.message+"\n"
+							+ (id&&!objElement?"Object with id='"+id+"' wasn't found.\n":""));
+				}
+				delete objElement;
+				delete cmd;
+				delete cmdFullname;
+				delete id;
+				delete property;
+				delete search;
+				delete data;
+				delete type;
+				delete before;
+				delete internalData;
+				delete j;
+				delete k;
+			}	
+		}
+		delete xml;
+		delete i;
+		document.body.style.cursor = 'default';
+		if (xajaxStatusMessages == true) window.status = 'Done';
+	}
+}
+
+var xajax = new Xajax();
+xajaxLoaded = true;
Index: trunk/workflow/inc/report/xajax/LICENSE.txt
===================================================================
--- trunk/workflow/inc/report/xajax/LICENSE.txt	(revision 5307)
+++ trunk/workflow/inc/report/xajax/LICENSE.txt	(revision 5307)
@@ -0,0 +1,504 @@
+		  GNU LESSER GENERAL PUBLIC LICENSE
+		       Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+     51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL.  It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+			    Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+  This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it.  You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+  When we speak of free software, we are referring to freedom of use,
+not price.  Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+  To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights.  These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+  For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you.  You must make sure that they, too, receive or can get the source
+code.  If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it.  And you must show them these terms so they know their rights.
+
+  We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+  To protect each distributor, we want to make it very clear that
+there is no warranty for the free library.  Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+
+  Finally, software patents pose a constant threat to the existence of
+any free program.  We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder.  Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+  Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License.  This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License.  We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+  When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library.  The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom.  The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+  We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License.  It also provides other free software developers Less
+of an advantage over competing non-free programs.  These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries.  However, the Lesser license provides advantages in certain
+special circumstances.
+
+  For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard.  To achieve this, non-free programs must be
+allowed to use the library.  A more frequent case is that a free
+library does the same job as widely used non-free libraries.  In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+  In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software.  For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+  Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.  Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library".  The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+
+		  GNU LESSER GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+  A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+  The "Library", below, refers to any such software library or work
+which has been distributed under these terms.  A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language.  (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+  "Source code" for a work means the preferred form of the work for
+making modifications to it.  For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+  Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it).  Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+  
+  1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+  You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+  2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) The modified work must itself be a software library.
+
+    b) You must cause the files modified to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    c) You must cause the whole of the work to be licensed at no
+    charge to all third parties under the terms of this License.
+
+    d) If a facility in the modified Library refers to a function or a
+    table of data to be supplied by an application program that uses
+    the facility, other than as an argument passed when the facility
+    is invoked, then you must make a good faith effort to ensure that,
+    in the event an application does not supply such function or
+    table, the facility still operates, and performs whatever part of
+    its purpose remains meaningful.
+
+    (For example, a function in a library to compute square roots has
+    a purpose that is entirely well-defined independent of the
+    application.  Therefore, Subsection 2d requires that any
+    application-supplied function or table used by this function must
+    be optional: if the application does not supply it, the square
+    root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library.  To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License.  (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.)  Do not make any other change in
+these notices.
+
+  Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+  This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+  4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+  If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library".  Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+  However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library".  The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+  When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library.  The
+threshold for this to be true is not precisely defined by law.
+
+  If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work.  (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+  Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+  6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+  You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License.  You must supply a copy of this License.  If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License.  Also, you must do one
+of these things:
+
+    a) Accompany the work with the complete corresponding
+    machine-readable source code for the Library including whatever
+    changes were used in the work (which must be distributed under
+    Sections 1 and 2 above); and, if the work is an executable linked
+    with the Library, with the complete machine-readable "work that
+    uses the Library", as object code and/or source code, so that the
+    user can modify the Library and then relink to produce a modified
+    executable containing the modified Library.  (It is understood
+    that the user who changes the contents of definitions files in the
+    Library will not necessarily be able to recompile the application
+    to use the modified definitions.)
+
+    b) Use a suitable shared library mechanism for linking with the
+    Library.  A suitable mechanism is one that (1) uses at run time a
+    copy of the library already present on the user's computer system,
+    rather than copying library functions into the executable, and (2)
+    will operate properly with a modified version of the library, if
+    the user installs one, as long as the modified version is
+    interface-compatible with the version that the work was made with.
+
+    c) Accompany the work with a written offer, valid for at
+    least three years, to give the same user the materials
+    specified in Subsection 6a, above, for a charge no more
+    than the cost of performing this distribution.
+
+    d) If distribution of the work is made by offering access to copy
+    from a designated place, offer equivalent access to copy the above
+    specified materials from the same place.
+
+    e) Verify that the user has already received a copy of these
+    materials or that you have already sent this user a copy.
+
+  For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it.  However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+  It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system.  Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+  7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+    a) Accompany the combined library with a copy of the same work
+    based on the Library, uncombined with any other library
+    facilities.  This must be distributed under the terms of the
+    Sections above.
+
+    b) Give prominent notice with the combined library of the fact
+    that part of it is a work based on the Library, and explaining
+    where to find the accompanying uncombined form of the same work.
+
+  8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License.  Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License.  However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+  9. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Library or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+  10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+
+  11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded.  In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+  13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation.  If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+  14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission.  For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this.  Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+			    NO WARRANTY
+
+  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+		     END OF TERMS AND CONDITIONS
+
+           How to Apply These Terms to Your New Libraries
+
+  If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change.  You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+  To apply these terms, attach the following notices to the library.  It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the library's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the
+  library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+  <signature of Ty Coon>, 1 April 1990
+  Ty Coon, President of Vice
+
+That's all there is to it!
+
+
Index: trunk/workflow/inc/report/xajax/xajax_js/xajax.js
===================================================================
--- trunk/workflow/inc/report/xajax/xajax_js/xajax.js	(revision 5307)
+++ trunk/workflow/inc/report/xajax/xajax_js/xajax.js	(revision 5307)
@@ -0,0 +1,172 @@
+/* xajax Javascript library :: version 0.2.4 */
+Array.prototype.containsValue=function(valueToCheck){for(var i=0;i<this.length;i++){if(this[i]==valueToCheck)return true;}
+return false;}
+function Xajax(){this.DebugMessage=function(text){if(text.length > 1000)text=text.substr(0,1000)+"...\n[long response]\n...";try{if(this.debugWindow==undefined||this.debugWindow.closed==true){this.debugWindow=window.open('about:blank','xajax-debug','width=800,height=600,scrollbars=1,resizable,status');this.debugWindow.document.write('<html><head><title>Xajax debug output</title></head><body><h2>Xajax debug output</h2><div id="debugTag"></div></body></html>');}
+text=text.replace(/&/g,"&amp;")
+text=text.replace(/</g,"&lt;")
+text=text.replace(/>/g,"&gt;")
+debugTag=this.debugWindow.document.getElementById('debugTag');debugTag.innerHTML=('<b>'+(new Date()).toString()+'</b>: '+text+'<hr/>')+debugTag.innerHTML;}catch(e){alert("Xajax Debug:\n "+text);}
+};this.workId='xajaxWork'+new Date().getTime();this.depth=0;this.responseErrorsForAlert=["400","401","402","403","404","500","501","502","503"];this.getRequestObject=function(){if(xajaxDebug)this.DebugMessage("Initializing Request Object..");var req=null;if(typeof XMLHttpRequest!="undefined")
+req=new XMLHttpRequest();if(!req&&typeof ActiveXObject!="undefined"){try{req=new ActiveXObject("Msxml2.XMLHTTP");}
+catch(e){try{req=new ActiveXObject("Microsoft.XMLHTTP");}
+catch(e2){try{req=new ActiveXObject("Msxml2.XMLHTTP.4.0");}
+catch(e3){req=null;}
+}
+}
+}
+if(!req&&window.createRequest)
+req=window.createRequest();if(!req)this.DebugMessage("Request Object Instantiation failed.");return req;}
+this.$=function(sId){if(!sId){return null;}
+var returnObj=document.getElementById(sId);if(!returnObj&&document.all){returnObj=document.all[sId];}
+if(xajaxDebug&&!returnObj&&sId!=this.workId){this.DebugMessage("Element with the id \""+sId+"\" not found.");}
+return returnObj;}
+this.include=function(sFileName){var objHead=document.getElementsByTagName('head');var objScript=document.createElement('script');objScript.type='text/javascript';objScript.src=sFileName;objHead[0].appendChild(objScript);}
+this.stripOnPrefix=function(sEventName){sEventName=sEventName.toLowerCase();if(sEventName.indexOf('on')==0){sEventName=sEventName.replace(/on/,'');}
+return sEventName;}
+this.addOnPrefix=function(sEventName){sEventName=sEventName.toLowerCase();if(sEventName.indexOf('on')!=0){sEventName='on'+sEventName;}
+return sEventName;}
+this.addHandler=function(sElementId,sEvent,sFunctionName){if(window.addEventListener){sEvent=this.stripOnPrefix(sEvent);eval("this.$('"+sElementId+"').addEventListener('"+sEvent+"',"+sFunctionName+",false);");}
+else{sAltEvent=this.addOnPrefix(sEvent);eval("this.$('"+sElementId+"').attachEvent('"+sAltEvent+"',"+sFunctionName+",false);");}
+}
+this.removeHandler=function(sElementId,sEvent,sFunctionName){if(window.addEventListener){sEvent=this.stripOnPrefix(sEvent);eval("this.$('"+sElementId+"').removeEventListener('"+sEvent+"',"+sFunctionName+",false);");}
+else{sAltEvent=this.addOnPrefix(sEvent);eval("this.$('"+sElementId+"').detachEvent('"+sAltEvent+"',"+sFunctionName+",false);");}
+}
+this.create=function(sParentId,sTag,sId){var objParent=this.$(sParentId);objElement=document.createElement(sTag);objElement.setAttribute('id',sId);if(objParent)
+objParent.appendChild(objElement);}
+this.insert=function(sBeforeId,sTag,sId){var objSibling=this.$(sBeforeId);objElement=document.createElement(sTag);objElement.setAttribute('id',sId);objSibling.parentNode.insertBefore(objElement,objSibling);}
+this.insertAfter=function(sAfterId,sTag,sId){var objSibling=this.$(sAfterId);objElement=document.createElement(sTag);objElement.setAttribute('id',sId);objSibling.parentNode.insertBefore(objElement,objSibling.nextSibling);}
+this.getInput=function(sType,sName,sId){var Obj;if(!window.addEventListener){Obj=document.createElement('<input type="'+sType+'" id="'+sId+'" name="'+sName+'">');}
+else{Obj=document.createElement('input');Obj.setAttribute('type',sType);Obj.setAttribute('name',sName);Obj.setAttribute('id',sId);}
+return Obj;}
+this.createInput=function(sParentId,sType,sName,sId){var objParent=this.$(sParentId);var objElement=this.getInput(sType,sName,sId);if(objParent&&objElement)
+objParent.appendChild(objElement);}
+this.insertInput=function(sBeforeId,sType,sName,sId){var objSibling=this.$(sBeforeId);var objElement=this.getInput(sType,sName,sId);if(objElement&&objSibling&&objSibling.parentNode)
+objSibling.parentNode.insertBefore(objElement,objSibling);}
+this.insertInputAfter=function(sAfterId,sType,sName,sId){var objSibling=this.$(sAfterId);var objElement=this.getInput(sType,sName,sId);if(objElement&&objSibling&&objSibling.parentNode){objSibling.parentNode.insertBefore(objElement,objSibling.nextSibling);}
+}
+this.remove=function(sId){objElement=this.$(sId);if(objElement&&objElement.parentNode&&objElement.parentNode.removeChild){objElement.parentNode.removeChild(objElement);}
+}
+this.replace=function(sId,sAttribute,sSearch,sReplace){var bFunction=false;if(sAttribute=="innerHTML")
+sSearch=this.getBrowserHTML(sSearch);eval("var txt=this.$('"+sId+"')."+sAttribute);if(typeof txt=="function"){txt=txt.toString();bFunction=true;}
+if(txt.indexOf(sSearch)>-1){var newTxt='';while(txt.indexOf(sSearch)>-1){x=txt.indexOf(sSearch)+sSearch.length+1;newTxt+=txt.substr(0,x).replace(sSearch,sReplace);txt=txt.substr(x,txt.length-x);}
+newTxt+=txt;if(bFunction){eval('this.$("'+sId+'").'+sAttribute+'=newTxt;');}
+else if(this.willChange(sId,sAttribute,newTxt)){eval('this.$("'+sId+'").'+sAttribute+'=newTxt;');}
+}
+}
+this.getFormValues=function(frm){var objForm;var submitDisabledElements=false;if(arguments.length > 1&&arguments[1]==true)
+submitDisabledElements=true;var prefix="";if(arguments.length > 2)
+prefix=arguments[2];if(typeof(frm)=="string")
+objForm=this.$(frm);else
+objForm=frm;var sXml="<xjxquery><q>";if(objForm&&objForm.tagName=='FORM'){var formElements=objForm.elements;for(var i=0;i < formElements.length;i++){if(!formElements[i].name)
+continue;if(formElements[i].name.substring(0,prefix.length)!=prefix)
+continue;if(formElements[i].type&&(formElements[i].type=='radio'||formElements[i].type=='checkbox')&&formElements[i].checked==false)
+continue;if(formElements[i].disabled&&formElements[i].disabled==true&&submitDisabledElements==false)
+continue;var name=formElements[i].name;if(name){if(sXml!='<xjxquery><q>')
+sXml+='&';if(formElements[i].type=='select-multiple'){for(var j=0;j < formElements[i].length;j++){if(formElements[i].options[j].selected==true)
+sXml+=name+"="+encodeURIComponent(formElements[i].options[j].value)+"&";}
+}
+else{sXml+=name+"="+encodeURIComponent(formElements[i].value);}
+}
+}
+}
+sXml+="</q></xjxquery>";return sXml;}
+this.objectToXML=function(obj){var sXml="<xjxobj>";for(i in obj){try{if(i=='constructor')
+continue;if(obj[i]&&typeof(obj[i])=='function')
+continue;var key=i;var value=obj[i];if(value&&typeof(value)=="object"&&this.depth <=50){this.depth++;value=this.objectToXML(value);this.depth--;}
+sXml+="<e><k>"+key+"</k><v>"+value+"</v></e>";}
+catch(e){if(xajaxDebug)this.DebugMessage(e.name+": "+e.message);}
+}
+sXml+="</xjxobj>";return sXml;}
+this._nodeToObject=function(node){if(node.nodeName=='#cdata-section'){var data="";for(var j=0;j<node.parentNode.childNodes.length;j++){data+=node.parentNode.childNodes[j].data;}
+return data;}
+else if(node.nodeName=='xjxobj'){var data=new Array();for(var j=0;j<node.childNodes.length;j++){var child=node.childNodes[j];var key;var value;if(child.nodeName=='e'){for(var k=0;k<child.childNodes.length;k++){if(child.childNodes[k].nodeName=='k'){key=child.childNodes[k].firstChild.data;}
+else if(child.childNodes[k].nodeName=='v'){value=this._nodeToObject(child.childNodes[k].firstChild);}
+}
+if(key!=null&&value!=null){data[key]=value;key=value=null;}
+}
+}
+return data;}
+}
+this.loadingFunction=function(){};this.doneLoadingFunction=function(){};var loadingTimeout;this.call=function(sFunction,aArgs,sRequestType){var i,r,postData;if(document.body&&xajaxWaitCursor)
+document.body.style.cursor='wait';if(xajaxStatusMessages==true)window.status='Sending Request...';clearTimeout(loadingTimeout);loadingTimeout=setTimeout("xajax.loadingFunction();",400);if(xajaxDebug)this.DebugMessage("Starting xajax...");if(sRequestType==null){var xajaxRequestType=xajaxDefinedPost;}
+else{var xajaxRequestType=sRequestType;}
+var uri=xajaxRequestUri;var value;switch(xajaxRequestType){case xajaxDefinedGet:{var uriGet=uri.indexOf("?")==-1?"?xajax="+encodeURIComponent(sFunction):"&xajax="+encodeURIComponent(sFunction);if(aArgs){for(i=0;i<aArgs.length;i++){value=aArgs[i];if(typeof(value)=="object")
+value=this.objectToXML(value);uriGet+="&xajaxargs[]="+encodeURIComponent(value);}
+}
+uriGet+="&xajaxr="+new Date().getTime();uri+=uriGet;postData=null;}break;case xajaxDefinedPost:{postData="xajax="+encodeURIComponent(sFunction);postData+="&xajaxr="+new Date().getTime();if(aArgs){for(i=0;i <aArgs.length;i++){value=aArgs[i];if(typeof(value)=="object")
+value=this.objectToXML(value);postData=postData+"&xajaxargs[]="+encodeURIComponent(value);}
+}
+}break;default:
+alert("Illegal request type: "+xajaxRequestType);return false;break;}
+r=this.getRequestObject();if(!r)return false;r.open(xajaxRequestType==xajaxDefinedGet?"GET":"POST",uri,true);if(xajaxRequestType==xajaxDefinedPost){try{r.setRequestHeader("Method","POST "+uri+" HTTP/1.1");r.setRequestHeader("Content-Type","application/x-www-form-urlencoded");}
+catch(e){alert("Your browser does not appear to  support asynchronous requests using POST.");return false;}
+}
+r.onreadystatechange=function(){if(r.readyState!=4)
+return;if(r.status==200){if(xajaxDebug)xajax.DebugMessage("Received:\n"+r.responseText);if(r.responseXML&&r.responseXML.documentElement)
+xajax.processResponse(r.responseXML);else{var errorString="Error: the XML response that was returned from the server is invalid.";errorString+="\nReceived:\n"+r.responseText;trimmedResponseText=r.responseText.replace(/^\s+/g,"");trimmedResponseText=trimmedResponseText.replace(/\s+$/g,"");if(trimmedResponseText!=r.responseText)
+errorString+="\nYou have whitespace in your response.";alert(errorString);document.body.style.cursor='default';if(xajaxStatusMessages==true)window.status='Invalid XML response error';}
+}
+else{if(xajax.responseErrorsForAlert.containsValue(r.status)){var errorString="Error: the server returned the following HTTP status: "+r.status;errorString+="\nReceived:\n"+r.responseText;alert(errorString);}
+document.body.style.cursor='default';if(xajaxStatusMessages==true)window.status='Invalid XML response error';}
+delete r;r=null;}
+if(xajaxDebug)this.DebugMessage("Calling "+sFunction+" uri="+uri+" (post:"+postData+")");r.send(postData);if(xajaxStatusMessages==true)window.status='Waiting for data...';delete r;return true;}
+this.getBrowserHTML=function(html){tmpXajax=this.$(this.workId);if(!tmpXajax){tmpXajax=document.createElement("div");tmpXajax.setAttribute('id',this.workId);tmpXajax.style.display="none";tmpXajax.style.visibility="hidden";document.body.appendChild(tmpXajax);}
+tmpXajax.innerHTML=html;var browserHTML=tmpXajax.innerHTML;tmpXajax.innerHTML='';return browserHTML;}
+this.willChange=function(element,attribute,newData){if(!document.body){return true;}
+if(attribute=="innerHTML"){newData=this.getBrowserHTML(newData);}
+elementObject=this.$(element);if(elementObject){var oldData;eval("oldData=this.$('"+element+"')."+attribute);if(newData!==oldData)
+return true;}
+return false;}
+this.viewSource=function(){return "<html>"+document.getElementsByTagName("HTML")[0].innerHTML+"</html>";}
+this.processResponse=function(xml){clearTimeout(loadingTimeout);this.doneLoadingFunction();if(xajaxStatusMessages==true)window.status='Processing...';var tmpXajax=null;xml=xml.documentElement;if(xml==null)
+return;var skipCommands=0;for(var i=0;i<xml.childNodes.length;i++){if(skipCommands > 0){skipCommands--;continue;}
+if(xml.childNodes[i].nodeName=="cmd"){var cmd;var id;var property;var data;var search;var type;var before;var objElement=null;for(var j=0;j<xml.childNodes[i].attributes.length;j++){if(xml.childNodes[i].attributes[j].name=="n"){cmd=xml.childNodes[i].attributes[j].value;}
+else if(xml.childNodes[i].attributes[j].name=="t"){id=xml.childNodes[i].attributes[j].value;}
+else if(xml.childNodes[i].attributes[j].name=="p"){property=xml.childNodes[i].attributes[j].value;}
+else if(xml.childNodes[i].attributes[j].name=="c"){type=xml.childNodes[i].attributes[j].value;}
+}
+if(xml.childNodes[i].childNodes.length > 1&&xml.childNodes[i].firstChild.nodeName=="#cdata-section"){data="";for(var j=0;j<xml.childNodes[i].childNodes.length;j++){data+=xml.childNodes[i].childNodes[j].data;}
+}
+else if(xml.childNodes[i].firstChild&&xml.childNodes[i].firstChild.nodeName=='xjxobj'){data=this._nodeToObject(xml.childNodes[i].firstChild);objElement="XJX_SKIP";}
+else if(xml.childNodes[i].childNodes.length > 1){for(var j=0;j<xml.childNodes[i].childNodes.length;j++){if(xml.childNodes[i].childNodes[j].childNodes.length > 1&&xml.childNodes[i].childNodes[j].firstChild.nodeName=="#cdata-section"){var internalData="";for(var k=0;k<xml.childNodes[i].childNodes[j].childNodes.length;k++){internalData+=xml.childNodes[i].childNodes[j].childNodes[k].nodeValue;}
+}else{var internalData=xml.childNodes[i].childNodes[j].firstChild.nodeValue;}
+if(xml.childNodes[i].childNodes[j].nodeName=="s"){search=internalData;}
+if(xml.childNodes[i].childNodes[j].nodeName=="r"){data=internalData;}
+}
+}
+else if(xml.childNodes[i].firstChild)
+data=xml.childNodes[i].firstChild.nodeValue;else
+data="";if(objElement!="XJX_SKIP")objElement=this.$(id);var cmdFullname;try{if(cmd=="cc"){cmdFullname="addConfirmCommands";var confirmResult=confirm(data);if(!confirmResult){skipCommands=id;}
+}
+if(cmd=="al"){cmdFullname="addAlert";alert(data);}
+else if(cmd=="js"){cmdFullname="addScript/addRedirect";eval(data);}
+else if(cmd=="jc"){cmdFullname="addScriptCall";var scr=id+'(';if(data[0]!=null){scr+='data[0]';for(var l=1;l<data.length;l++){scr+=',data['+l+']';}
+}
+scr+=');';eval(scr);}
+else if(cmd=="in"){cmdFullname="addIncludeScript";this.include(data);}
+else if(cmd=="as"){cmdFullname="addAssign/addClear";if(this.willChange(id,property,data)){eval("objElement."+property+"=data;");}
+}
+else if(cmd=="ap"){cmdFullname="addAppend";eval("objElement."+property+"+=data;");}
+else if(cmd=="pp"){cmdFullname="addPrepend";eval("objElement."+property+"=data+objElement."+property);}
+else if(cmd=="rp"){cmdFullname="addReplace";this.replace(id,property,search,data)
+}
+else if(cmd=="rm"){cmdFullname="addRemove";this.remove(id);}
+else if(cmd=="ce"){cmdFullname="addCreate";this.create(id,data,property);}
+else if(cmd=="ie"){cmdFullname="addInsert";this.insert(id,data,property);}
+else if(cmd=="ia"){cmdFullname="addInsertAfter";this.insertAfter(id,data,property);}
+else if(cmd=="ci"){cmdFullname="addCreateInput";this.createInput(id,type,data,property);}
+else if(cmd=="ii"){cmdFullname="addInsertInput";this.insertInput(id,type,data,property);}
+else if(cmd=="iia"){cmdFullname="addInsertInputAfter";this.insertInputAfter(id,type,data,property);}
+else if(cmd=="ev"){cmdFullname="addEvent";property=this.addOnPrefix(property);eval("this.$('"+id+"')."+property+"= function(){"+data+";}");}
+else if(cmd=="ah"){cmdFullname="addHandler";this.addHandler(id,property,data);}
+else if(cmd=="rh"){cmdFullname="addRemoveHandler";this.removeHandler(id,property,data);}
+}
+catch(e){if(xajaxDebug)
+alert("While trying to '"+cmdFullname+"' (command number "+i+"), the following error occured:\n"
++e.name+": "+e.message+"\n"
++(id&&!objElement?"Object with id='"+id+"' wasn't found.\n":""));}
+delete objElement;delete cmd;delete cmdFullname;delete id;delete property;delete search;delete data;delete type;delete before;delete internalData;delete j;delete k;}
+}
+delete xml;delete i;document.body.style.cursor='default';if(xajaxStatusMessages==true)window.status='Done';}
+}
+var xajax=new Xajax();xajaxLoaded=true;
Index: trunk/workflow/inc/report/xajax/xajax_js/xajax_uncompressed.js
===================================================================
--- trunk/workflow/inc/report/xajax/xajax_js/xajax_uncompressed.js	(revision 5307)
+++ trunk/workflow/inc/report/xajax/xajax_js/xajax_uncompressed.js	(revision 5307)
@@ -0,0 +1,795 @@
+/* xajax Javascript library :: version 0.2.4 */
+
+Array.prototype.containsValue = function(valueToCheck)
+{
+	for (var i=0;i<this.length;i++) {
+		if (this[i] == valueToCheck) return true;
+	}
+	return false;
+}
+
+function Xajax()
+{
+	this.DebugMessage = function(text)
+	{
+		if (text.length > 1000) text = text.substr(0,1000)+"...\n[long response]\n...";
+		try {
+			if (this.debugWindow == undefined || this.debugWindow.closed == true) {
+				this.debugWindow = window.open('about:blank', 'xajax-debug', 'width=800,height=600,scrollbars=1,resizable,status');
+				this.debugWindow.document.write('<html><head><title>Xajax debug output</title></head><body><h2>Xajax debug output</h2><div id="debugTag"></div></body></html>');
+			}
+			text = text.replace(/&/g, "&amp;")
+			text = text.replace(/</g, "&lt;")
+			text = text.replace(/>/g, "&gt;")
+			debugTag = this.debugWindow.document.getElementById('debugTag');
+			debugTag.innerHTML = ('<b>'+(new Date()).toString()+'</b>: ' + text + '<hr/>') + debugTag.innerHTML;
+		} catch (e) {
+			alert("Xajax Debug:\n " + text);
+		}
+	};
+	
+	this.workId = 'xajaxWork'+ new Date().getTime();
+	this.depth = 0;
+	this.responseErrorsForAlert = ["400","401","402","403","404","500","501","502","503"];
+	
+	//Get the XMLHttpRequest Object
+	this.getRequestObject = function()
+	{
+		if (xajaxDebug) this.DebugMessage("Initializing Request Object..");
+		var req = null;
+		if (typeof XMLHttpRequest != "undefined")
+			req = new XMLHttpRequest();
+		if (!req && typeof ActiveXObject != "undefined")
+		{
+			try
+			{
+				req=new ActiveXObject("Msxml2.XMLHTTP");
+			}
+			catch (e)
+			{
+				try
+				{
+					req=new ActiveXObject("Microsoft.XMLHTTP");
+				}
+				catch (e2)
+				{
+					try {
+						req=new ActiveXObject("Msxml2.XMLHTTP.4.0");
+					}
+					catch (e3)
+					{
+						req=null;
+					}
+				}
+			}
+		}
+		if(!req && window.createRequest)
+			req = window.createRequest();
+		
+		if (!req) this.DebugMessage("Request Object Instantiation failed.");
+			
+		return req;
+	}
+
+	// xajax.$() is shorthand for document.getElementById()
+	this.$ = function(sId)
+	{
+		if (!sId) {
+			return null;
+		}
+		var returnObj = document.getElementById(sId);
+		if (!returnObj && document.all) {
+			returnObj = document.all[sId];
+		}
+		if (xajaxDebug && !returnObj && sId != this.workId) {
+			this.DebugMessage("Element with the id \"" + sId + "\" not found.");
+		}
+		return returnObj;
+	}
+	
+	// xajax.include(sFileName) dynamically includes an external javascript file
+	this.include = function(sFileName)
+	{
+		var objHead = document.getElementsByTagName('head');
+		var objScript = document.createElement('script');
+		objScript.type = 'text/javascript';
+		objScript.src = sFileName;
+		objHead[0].appendChild(objScript);
+	}
+	
+	this.stripOnPrefix = function(sEventName)
+	{
+		sEventName = sEventName.toLowerCase();
+		if (sEventName.indexOf('on') == 0)
+		{
+			sEventName = sEventName.replace(/on/,'');
+		}
+		
+		return sEventName;
+	}
+	
+	this.addOnPrefix = function(sEventName)
+	{
+		sEventName = sEventName.toLowerCase();
+		if (sEventName.indexOf('on') != 0)
+		{
+			sEventName = 'on' + sEventName;
+		}
+		
+		return sEventName;
+	}
+	
+	// xajax.addHandler adds an event handler to an element
+	this.addHandler = function(sElementId, sEvent, sFunctionName)
+	{
+		if (window.addEventListener)
+		{
+			sEvent = this.stripOnPrefix(sEvent);
+			eval("this.$('"+sElementId+"').addEventListener('"+sEvent+"',"+sFunctionName+",false);");
+		}
+		else
+		{
+			sAltEvent = this.addOnPrefix(sEvent);
+			eval("this.$('"+sElementId+"').attachEvent('"+sAltEvent+"',"+sFunctionName+",false);");
+		}
+	}
+	
+	// xajax.removeHandler removes an event handler from an element
+	this.removeHandler = function(sElementId, sEvent, sFunctionName)
+	{
+		if (window.addEventListener)
+		{
+			sEvent = this.stripOnPrefix(sEvent);
+			eval("this.$('"+sElementId+"').removeEventListener('"+sEvent+"',"+sFunctionName+",false);");
+		}
+		else
+		{
+			sAltEvent = this.addOnPrefix(sEvent);
+			eval("this.$('"+sElementId+"').detachEvent('"+sAltEvent+"',"+sFunctionName+",false);");
+		}
+	}
+	
+	// xajax.create creates a new child node under a parent
+	this.create = function(sParentId, sTag, sId)
+	{
+		var objParent = this.$(sParentId);
+		objElement = document.createElement(sTag);
+		objElement.setAttribute('id',sId);
+		if (objParent)
+			objParent.appendChild(objElement);
+	}
+	
+	// xajax.insert inserts a new node before another node
+	this.insert = function(sBeforeId, sTag, sId)
+	{
+		var objSibling = this.$(sBeforeId);
+		objElement = document.createElement(sTag);
+		objElement.setAttribute('id',sId);
+		objSibling.parentNode.insertBefore(objElement, objSibling);
+	}
+
+	// xajax.insertAfter inserts a new node after another node
+	this.insertAfter = function(sAfterId, sTag, sId)
+	{
+		var objSibling = this.$(sAfterId);
+		objElement = document.createElement(sTag);
+		objElement.setAttribute('id',sId);
+		objSibling.parentNode.insertBefore(objElement, objSibling.nextSibling);
+	}
+	
+	this.getInput = function(sType, sName, sId)
+	{
+		var Obj;
+		if (!window.addEventListener)
+		{
+			Obj = document.createElement('<input type="'+sType+'" id="'+sId+'" name="'+sName+'">');
+		}
+		else
+		{
+			Obj = document.createElement('input');
+			Obj.setAttribute('type',sType);
+			Obj.setAttribute('name',sName);
+			Obj.setAttribute('id',sId);
+		}
+		return Obj;
+	}
+	
+	// xajax.createInput creates a new input node under a parent
+	this.createInput = function(sParentId, sType, sName, sId)
+	{
+		var objParent = this.$(sParentId);
+		var objElement = this.getInput(sType, sName, sId);
+		if (objParent && objElement)
+			objParent.appendChild(objElement);
+	}
+	
+	// xajax.insertInput creates a new input node before another node
+	this.insertInput = function(sBeforeId, sType, sName, sId)
+	{
+		var objSibling = this.$(sBeforeId);
+		var objElement = this.getInput(sType, sName, sId);
+		if (objElement && objSibling && objSibling.parentNode)
+			objSibling.parentNode.insertBefore(objElement, objSibling);
+	}
+
+	// xajax.insertInputAfter creates a new input node after another node
+	this.insertInputAfter = function(sAfterId, sType, sName, sId)
+	{
+		var objSibling = this.$(sAfterId);
+		var objElement = this.getInput(sType, sName, sId);
+		if (objElement && objSibling && objSibling.parentNode) {
+			objSibling.parentNode.insertBefore(objElement, objSibling.nextSibling);
+		}
+	}
+		
+	// xajax.remove deletes an element
+	this.remove = function(sId)
+	{
+		objElement = this.$(sId);
+		if (objElement && objElement.parentNode && objElement.parentNode.removeChild)
+		{
+			objElement.parentNode.removeChild(objElement);
+		}
+	}
+	
+	//xajax.replace searches for text in an attribute of an element and replaces it
+	//with a different text
+	this.replace = function(sId,sAttribute,sSearch,sReplace)
+	{
+		var bFunction = false;
+		
+		if (sAttribute == "innerHTML")
+			sSearch = this.getBrowserHTML(sSearch);
+		
+		eval("var txt=this.$('"+sId+"')."+sAttribute);
+		if (typeof txt == "function")
+        {
+            txt = txt.toString();
+            bFunction = true;
+        }
+		if (txt.indexOf(sSearch)>-1)
+		{
+			var newTxt = '';
+			while (txt.indexOf(sSearch) > -1)
+			{
+				x = txt.indexOf(sSearch)+sSearch.length+1;
+				newTxt += txt.substr(0,x).replace(sSearch,sReplace);
+				txt = txt.substr(x,txt.length-x);
+			}
+			newTxt += txt;
+			if (bFunction)
+			{
+				eval('this.$("'+sId+'").'+sAttribute+'=newTxt;');
+			}
+			else if (this.willChange(sId,sAttribute,newTxt))
+			{
+				eval('this.$("'+sId+'").'+sAttribute+'=newTxt;');
+			}
+		}
+	}
+	
+	// xajax.getFormValues() builds a query string XML message from the elements of a form object
+	// * The first argument is the id of the form
+	// * The second argument (optional) can be set to true if you want to submit disabled elements
+	// * The third argument (optional) allows you to specify a string prefix that a form element
+	//   name must contain if you want that element to be submitted
+	this.getFormValues = function(frm)
+	{
+		var objForm;
+		var submitDisabledElements = false;
+		if (arguments.length > 1 && arguments[1] == true)
+			submitDisabledElements = true;
+		var prefix="";
+		if(arguments.length > 2)
+			prefix = arguments[2];
+		
+		if (typeof(frm) == "string")
+			objForm = this.$(frm);
+		else
+			objForm = frm;
+		var sXml = "<xjxquery><q>";
+		if (objForm && objForm.tagName == 'FORM')
+		{
+			var formElements = objForm.elements;
+			for( var i=0; i < formElements.length; i++)
+			{
+				if (!formElements[i].name)
+					continue;
+				if (formElements[i].name.substring(0, prefix.length) != prefix)
+					continue;
+				if (formElements[i].type && (formElements[i].type == 'radio' || formElements[i].type == 'checkbox') && formElements[i].checked == false)
+					continue;
+				if (formElements[i].disabled && formElements[i].disabled == true && submitDisabledElements == false)
+					continue;
+				var name = formElements[i].name;
+				if (name)
+				{
+					if (sXml != '<xjxquery><q>')
+						sXml += '&';
+					if(formElements[i].type=='select-multiple')
+					{
+						for (var j = 0; j < formElements[i].length; j++)
+						{
+							if (formElements[i].options[j].selected == true)
+								sXml += name+"="+encodeURIComponent(formElements[i].options[j].value)+"&";
+						}
+					}
+					else
+					{
+						sXml += name+"="+encodeURIComponent(formElements[i].value);
+					}
+				} 
+			}
+		}
+		
+		sXml +="</q></xjxquery>";
+		
+		return sXml;
+	}
+	
+	// Generates an XML message that xajax can understand from a javascript object
+	this.objectToXML = function(obj)
+	{
+		var sXml = "<xjxobj>";
+		for (i in obj)
+		{
+			try
+			{
+				if (i == 'constructor')
+					continue;
+				if (obj[i] && typeof(obj[i]) == 'function')
+					continue;
+					
+				var key = i;
+				var value = obj[i];
+				if (value && typeof(value)=="object" && this.depth <= 50)
+				{
+					this.depth++;
+					value = this.objectToXML(value);
+					this.depth--;
+				}
+				
+				sXml += "<e><k>"+key+"</k><v>"+value+"</v></e>";
+				
+			}
+			catch(e)
+			{
+				if (xajaxDebug) this.DebugMessage(e.name+": "+e.message);
+			}
+		}
+		sXml += "</xjxobj>";
+	
+		return sXml;
+	}
+
+	// unserializes data structure from xajaxResponse::_buildObjXml()
+	this._nodeToObject = function(node) {
+		// parentNode here is weird, have to tune
+		if (node.nodeName == '#cdata-section') {
+			var data = "";
+			for (var j=0; j<node.parentNode.childNodes.length; j++) {
+				data += node.parentNode.childNodes[j].data;
+			}
+			return data;
+		}
+		else if (node.nodeName == 'xjxobj') {
+			var data = new Array();
+			for (var j=0; j<node.childNodes.length; j++) {
+				var child = node.childNodes[j];
+				var key;
+				var value;
+				if (child.nodeName == 'e') {
+					for (var k=0; k<child.childNodes.length; k++) {
+						if (child.childNodes[k].nodeName == 'k') {
+							key = child.childNodes[k].firstChild.data;
+						}
+						else if (child.childNodes[k].nodeName == 'v') {
+							value = this._nodeToObject(child.childNodes[k].firstChild);
+						}
+					}
+					if (key != null && value != null) {
+						data[key] = value;
+						key = value = null;
+					}
+				}
+			}
+			return data;
+		}		
+	}
+
+	this.loadingFunction = function(){};
+	this.doneLoadingFunction = function(){};
+	var loadingTimeout;
+
+	// Sends a XMLHttpRequest to call the specified PHP function on the server
+	// * sRequestType is optional -- defaults to POST
+	this.call = function(sFunction, aArgs, sRequestType)
+	{
+		var i,r,postData;
+		if (document.body && xajaxWaitCursor)
+			document.body.style.cursor = 'wait';
+		if (xajaxStatusMessages == true) window.status = 'Sending Request...';
+		clearTimeout(loadingTimeout);
+		loadingTimeout = setTimeout("xajax.loadingFunction();",400);
+		if (xajaxDebug) this.DebugMessage("Starting xajax...");
+		if (sRequestType == null) {
+		   var xajaxRequestType = xajaxDefinedPost;
+		}
+		else {
+			var xajaxRequestType = sRequestType;
+		}
+		var uri = xajaxRequestUri;
+		var value;
+		switch(xajaxRequestType)
+		{
+			case xajaxDefinedGet:{
+				var uriGet = uri.indexOf("?")==-1?"?xajax="+encodeURIComponent(sFunction):"&xajax="+encodeURIComponent(sFunction);
+				if (aArgs) {
+					for (i = 0; i<aArgs.length; i++)
+					{
+						value = aArgs[i];
+						if (typeof(value)=="object")
+							value = this.objectToXML(value);
+						uriGet += "&xajaxargs[]="+encodeURIComponent(value);
+					}
+				}
+				uriGet += "&xajaxr=" + new Date().getTime();
+				uri += uriGet;
+				postData = null;
+				} break;
+			case xajaxDefinedPost:{
+				postData = "xajax="+encodeURIComponent(sFunction);
+				postData += "&xajaxr="+new Date().getTime();
+				if (aArgs) {
+					for (i = 0; i <aArgs.length; i++)
+					{
+						value = aArgs[i];
+						if (typeof(value)=="object")
+							value = this.objectToXML(value);
+						postData = postData+"&xajaxargs[]="+encodeURIComponent(value);
+					}
+				}
+				} break;
+			default:
+				alert("Illegal request type: " + xajaxRequestType); return false; break;
+		}
+		r = this.getRequestObject();
+		if (!r) return false;
+		r.open(xajaxRequestType==xajaxDefinedGet?"GET":"POST", uri, true);
+		if (xajaxRequestType == xajaxDefinedPost)
+		{
+			try
+			{
+				r.setRequestHeader("Method", "POST " + uri + " HTTP/1.1");
+				r.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
+			}
+			catch(e)
+			{
+				alert("Your browser does not appear to  support asynchronous requests using POST.");
+				return false;
+			}
+		}
+		r.onreadystatechange = function()
+		{
+			if (r.readyState != 4)
+				return;
+			
+			if (r.status==200)
+			{
+				if (xajaxDebug) xajax.DebugMessage("Received:\n" + r.responseText);
+				if (r.responseXML && r.responseXML.documentElement)
+					xajax.processResponse(r.responseXML);
+				else {
+					var errorString = "Error: the XML response that was returned from the server is invalid.";
+					errorString += "\nReceived:\n" + r.responseText;
+					trimmedResponseText = r.responseText.replace( /^\s+/g, "" );// strip leading space
+					trimmedResponseText = trimmedResponseText.replace( /\s+$/g, "" );// strip trailing
+					if (trimmedResponseText != r.responseText)
+						errorString += "\nYou have whitespace in your response.";
+					alert(errorString);
+					document.body.style.cursor = 'default';
+					if (xajaxStatusMessages == true) window.status = 'Invalid XML response error';				
+				}
+			}
+			else {
+				if (xajax.responseErrorsForAlert.containsValue(r.status)) {
+					var errorString = "Error: the server returned the following HTTP status: " + r.status;
+					errorString += "\nReceived:\n" + r.responseText;
+					alert(errorString);
+				}
+				document.body.style.cursor = 'default';
+				if (xajaxStatusMessages == true) window.status = 'Invalid XML response error';								
+			}
+			
+			delete r;
+			r = null;
+		}
+		if (xajaxDebug) this.DebugMessage("Calling "+sFunction +" uri="+uri+" (post:"+ postData +")");
+		r.send(postData);
+		if (xajaxStatusMessages == true) window.status = 'Waiting for data...';
+		delete r;
+		return true;
+	}
+	
+	//Gets the text as it would be if it were being retrieved from
+	//the innerHTML property in the current browser
+	this.getBrowserHTML = function(html)
+	{
+		tmpXajax = this.$(this.workId);
+		if (!tmpXajax)
+		{
+			tmpXajax = document.createElement("div");
+			tmpXajax.setAttribute('id',this.workId);
+			tmpXajax.style.display = "none";
+			tmpXajax.style.visibility = "hidden";
+			document.body.appendChild(tmpXajax);
+		}
+		tmpXajax.innerHTML = html;
+		var browserHTML = tmpXajax.innerHTML;
+		tmpXajax.innerHTML = '';	
+		
+		return browserHTML;
+	}
+	
+	// Tests if the new Data is the same as the extant data
+	this.willChange = function(element, attribute, newData)
+	{
+		if (!document.body)
+		{
+			return true;
+		}
+		if (attribute == "innerHTML")
+		{
+			newData = this.getBrowserHTML(newData);
+		}
+		elementObject = this.$(element);
+		if (elementObject) {
+			var oldData;		
+			eval("oldData=this.$('"+element+"')."+attribute);
+			if (newData !== oldData)
+				return true;
+		}
+
+		return false;
+	}
+	
+	//Returns the source code of the page after it's been modified by xajax
+	this.viewSource = function()
+	{
+		return "<html>"+document.getElementsByTagName("HTML")[0].innerHTML+"</html>";
+	}
+	
+	//Process XML xajaxResponses returned from the request
+	this.processResponse = function(xml)
+	{
+		clearTimeout(loadingTimeout);
+		this.doneLoadingFunction();
+		if (xajaxStatusMessages == true) window.status = 'Processing...';
+		var tmpXajax = null;
+		xml = xml.documentElement;
+		if (xml == null)
+			return;
+		
+		var skipCommands = 0;
+		for (var i=0; i<xml.childNodes.length; i++)
+		{
+			if (skipCommands > 0) {
+				skipCommands--;
+				continue;
+			}
+			if (xml.childNodes[i].nodeName == "cmd")
+			{
+				var cmd;
+				var id;
+				var property;
+				var data;
+				var search;
+				var type;
+				var before;
+				var objElement = null;
+
+				for (var j=0; j<xml.childNodes[i].attributes.length; j++)
+				{
+					if (xml.childNodes[i].attributes[j].name == "n")
+					{
+						cmd = xml.childNodes[i].attributes[j].value;
+					}
+					else if (xml.childNodes[i].attributes[j].name == "t")
+					{
+						id = xml.childNodes[i].attributes[j].value;
+					}
+					else if (xml.childNodes[i].attributes[j].name == "p")
+					{
+						property = xml.childNodes[i].attributes[j].value;
+					}
+					else if (xml.childNodes[i].attributes[j].name == "c")
+					{
+						type = xml.childNodes[i].attributes[j].value;
+					}
+				}
+				if (xml.childNodes[i].childNodes.length > 1 && xml.childNodes[i].firstChild.nodeName == "#cdata-section")
+				{
+					data = "";
+					for (var j=0; j<xml.childNodes[i].childNodes.length; j++)
+					{
+						data += xml.childNodes[i].childNodes[j].data;
+					}
+				}
+				else if (xml.childNodes[i].firstChild && xml.childNodes[i].firstChild.nodeName == 'xjxobj') {
+					data = this._nodeToObject(xml.childNodes[i].firstChild);
+					objElement = "XJX_SKIP";
+				}
+				else if (xml.childNodes[i].childNodes.length > 1)
+				{
+					for (var j=0; j<xml.childNodes[i].childNodes.length; j++)
+					{
+						if (xml.childNodes[i].childNodes[j].childNodes.length > 1 && xml.childNodes[i].childNodes[j].firstChild.nodeName == "#cdata-section")
+						{
+							var internalData = "";
+							for (var k=0; k<xml.childNodes[i].childNodes[j].childNodes.length;k++)
+							{
+								internalData+=xml.childNodes[i].childNodes[j].childNodes[k].nodeValue;
+							}
+						} else {
+							var internalData = xml.childNodes[i].childNodes[j].firstChild.nodeValue;
+						}
+					
+						if (xml.childNodes[i].childNodes[j].nodeName == "s")
+						{
+							search = internalData;
+						}
+						if (xml.childNodes[i].childNodes[j].nodeName == "r")
+						{
+							data = internalData;
+						}
+					}
+				}
+				else if (xml.childNodes[i].firstChild)
+					data = xml.childNodes[i].firstChild.nodeValue;
+				else
+					data = "";
+				
+				if (objElement != "XJX_SKIP") objElement = this.$(id);
+				var cmdFullname;
+				try
+				{
+					if (cmd=="cc") {
+						cmdFullname = "addConfirmCommands";
+						var confirmResult = confirm(data);
+						if (!confirmResult) {
+							skipCommands = id;
+						}
+					}
+					if (cmd=="al")
+					{
+						cmdFullname = "addAlert";
+						alert(data);
+					}
+					else if (cmd=="js")
+					{
+						cmdFullname = "addScript/addRedirect";
+						eval(data);
+					}
+					else if (cmd=="jc")
+					{
+						cmdFullname = "addScriptCall";
+						var scr = id + '(';
+						if (data[0] != null) {
+							scr += 'data[0]';
+							for (var l=1; l<data.length; l++) {
+								scr += ',data['+l+']';
+							}
+						}
+						scr += ');';
+						eval(scr);
+					}
+					else if (cmd=="in")
+					{
+						cmdFullname = "addIncludeScript";
+						this.include(data);
+					}
+					else if (cmd=="as")
+					{
+						cmdFullname = "addAssign/addClear";
+						if (this.willChange(id,property,data))
+						{
+							eval("objElement."+property+"=data;");
+						}
+					}
+					else if (cmd=="ap")
+					{
+						cmdFullname = "addAppend";
+						eval("objElement."+property+"+=data;");
+					}
+					else if (cmd=="pp")
+					{
+						cmdFullname = "addPrepend";
+						eval("objElement."+property+"=data+objElement."+property);
+					}
+					else if (cmd=="rp")
+					{
+						cmdFullname = "addReplace";
+						this.replace(id,property,search,data)
+					}
+					else if (cmd=="rm")
+					{
+						cmdFullname = "addRemove";
+						this.remove(id);
+					}
+					else if (cmd=="ce")
+					{
+						cmdFullname = "addCreate";
+						this.create(id,data,property);
+					}
+					else if (cmd=="ie")
+					{
+						cmdFullname = "addInsert";
+						this.insert(id,data,property);
+					}
+					else if (cmd=="ia")
+					{
+						cmdFullname = "addInsertAfter";
+						this.insertAfter(id,data,property);
+					}
+					else if (cmd=="ci")
+					{
+						cmdFullname = "addCreateInput";
+						this.createInput(id,type,data,property);
+					}
+					else if (cmd=="ii")
+					{
+						cmdFullname = "addInsertInput";
+						this.insertInput(id,type,data,property);
+					}
+					else if (cmd=="iia")
+					{
+						cmdFullname = "addInsertInputAfter";
+						this.insertInputAfter(id,type,data,property);
+					}
+					else if (cmd=="ev")
+					{
+						cmdFullname = "addEvent";
+						property = this.addOnPrefix(property);
+						eval("this.$('"+id+"')."+property+"= function(){"+data+";}");
+					}
+					else if (cmd=="ah")
+					{
+						cmdFullname = "addHandler";
+						this.addHandler(id, property, data);
+					}
+					else if (cmd=="rh")
+					{
+						cmdFullname = "addRemoveHandler";
+						this.removeHandler(id, property, data);
+					}
+				}
+				catch(e)
+				{
+					if (xajaxDebug)
+						alert("While trying to '"+cmdFullname+"' (command number "+i+"), the following error occured:\n"
+							+ e.name+": "+e.message+"\n"
+							+ (id&&!objElement?"Object with id='"+id+"' wasn't found.\n":""));
+				}
+				delete objElement;
+				delete cmd;
+				delete cmdFullname;
+				delete id;
+				delete property;
+				delete search;
+				delete data;
+				delete type;
+				delete before;
+				delete internalData;
+				delete j;
+				delete k;
+			}	
+		}
+		delete xml;
+		delete i;
+		document.body.style.cursor = 'default';
+		if (xajaxStatusMessages == true) window.status = 'Done';
+	}
+}
+
+var xajax = new Xajax();
+xajaxLoaded = true;
Index: trunk/workflow/inc/report/xajax/xajaxResponse.inc.php
===================================================================
--- trunk/workflow/inc/report/xajax/xajaxResponse.inc.php	(revision 5307)
+++ trunk/workflow/inc/report/xajax/xajaxResponse.inc.php	(revision 5307)
@@ -0,0 +1,580 @@
+<?php
+/**
+ * xajaxResponse.inc.php :: xajax XML response class
+ *
+ * xajax version 0.2.4
+ * copyright (c) 2005 by Jared White & J. Max Wilson
+ * http://www.xajaxproject.org
+ *
+ * xajax is an open source PHP class library for easily creating powerful
+ * PHP-driven, web-based Ajax Applications. Using xajax, you can asynchronously
+ * call PHP functions and update the content of your your webpage without
+ * reloading the page.
+ *
+ * xajax is released under the terms of the LGPL license
+ * http://www.gnu.org/copyleft/lesser.html#SEC3
+ *
+ * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ * 
+ * @package xajax
+ * @version $Id$
+ * @copyright Copyright (c) 2005-2006  by Jared White & J. Max Wilson
+ * @license http://www.gnu.org/copyleft/lesser.html#SEC3 LGPL License
+ */
+
+/*
+   ----------------------------------------------------------------------------
+   | Online documentation for this class is available on the xajax wiki at:   |
+   | http://wiki.xajaxproject.org/Documentation:xajaxResponse.inc.php         |
+   ----------------------------------------------------------------------------
+*/
+
+/**
+ * The xajaxResponse class is used to create responses to be sent back to your
+ * Web page.  A response contains one or more command messages for updating
+ * your page.
+ * Currently xajax supports 21 kinds of command messages, including some common
+ * ones such as:
+ * <ul>
+ * <li>Assign - sets the specified attribute of an element in your page</li>
+ * <li>Append - appends data to the end of the specified attribute of an
+ * element in your page</li>
+ * <li>Prepend - prepends data to the beginning of the specified attribute of
+ * an element in your page</li>
+ * <li>Replace - searches for and replaces data in the specified attribute of
+ * an element in your page</li>
+ * <li>Script - runs the supplied JavaScript code</li>
+ * <li>Alert - shows an alert box with the supplied message text</li>
+ * </ul>
+ *
+ * <i>Note:</i> elements are identified by their HTML id, so if you don't see
+ * your browser HTML display changing from the request, make sure you're using
+ * the right id names in your response.
+ * 
+ * @package xajax
+ */
+class xajaxResponse
+{
+	/**#@+
+	 * @access protected
+	 */
+	/**
+	 * @var string internal XML storage
+	 */	
+	var $xml;
+	/**
+	 * @var string the encoding type to use
+	 */
+	var $sEncoding;
+	/**
+	 * @var boolean if special characters in the XML should be converted to
+	 *              entities
+	 */
+	var $bOutputEntities;
+
+	/**#@-*/
+	
+	/**
+	 * The constructor's main job is to set the character encoding for the
+	 * response.
+	 * 
+	 * <i>Note:</i> to change the character encoding for all of the
+	 * responses, set the XAJAX_DEFAULT_ENCODING constant before you
+	 * instantiate xajax.
+	 * 
+	 * @param string  contains the character encoding string to use
+	 * @param boolean lets you set if you want special characters in the output
+	 *                converted to HTML entities
+	 * 
+	 */
+	function xajaxResponse($sEncoding=XAJAX_DEFAULT_CHAR_ENCODING, $bOutputEntities=false)
+	{
+		$this->setCharEncoding($sEncoding);
+		$this->bOutputEntities = $bOutputEntities;
+	}
+	
+	/**
+	 * Sets the character encoding for the response based on $sEncoding, which
+	 * is a string containing the character encoding to use. You don't need to
+	 * use this method normally, since the character encoding for the response
+	 * gets set automatically based on the XAJAX_DEFAULT_CHAR_ENCODING
+	 * constant.
+	 * 
+	 * @param string
+	 */
+	function setCharEncoding($sEncoding)
+	{
+		$this->sEncoding = $sEncoding;
+	}
+	
+	/**
+	 * Tells the response object to convert special characters to HTML entities
+	 * automatically (only works if the mb_string extension is available).
+	 */
+	function outputEntitiesOn()
+	{
+		$this->bOutputEntities = true;
+	}
+	
+	/**
+	 * Tells the response object to output special characters intact. (default
+	 * behavior)
+	 */
+	function outputEntitiesOff()
+	{
+		$this->bOutputEntities = false;
+	}
+
+	/**
+	 * Adds a confirm commands command message to the XML response.
+	 * 
+	 * <i>Usage:</i> <kbd>$objResponse->addConfirmCommands(1, "Do you want to preview the new data?");</kbd>
+	 *
+	 * @param integer the number of commands to skip if the user presses
+	 *                Cancel in the browsers's confirm dialog
+	 * @param string  the message to show in the browser's confirm dialog
+	 */
+	function addConfirmCommands($iCmdNumber, $sMessage)
+	{
+		$this->xml .= $this->_cmdXML(array("n"=>"cc","t"=>$iCmdNumber),$sMessage);
+	}
+	
+	/**
+	 * Adds an assign command message to the XML response.
+	 * 
+	 * <i>Usage:</i> <kbd>$objResponse->addAssign("contentDiv", "innerHTML", "Some Text");</kbd>
+	 * 
+	 * @param string contains the id of an HTML element
+	 * @param string the part of the element you wish to modify ("innerHTML",
+	 *               "value", etc.)
+	 * @param string the data you want to set the attribute to
+	 */
+	function addAssign($sTarget,$sAttribute,$sData)
+	{
+		$this->xml .= $this->_cmdXML(array("n"=>"as","t"=>$sTarget,"p"=>$sAttribute),$sData);
+	}
+
+	/**
+	 * Adds an append command message to the XML response.
+	 * 
+	 * <i>Usage:</i> <kbd>$objResponse->addAppend("contentDiv", "innerHTML", "Some New Text");</kbd>
+	 * 
+	 * @param string contains the id of an HTML element
+	 * @param string the part of the element you wish to modify ("innerHTML",
+	 *               "value", etc.)
+	 * @param string the data you want to append to the end of the attribute
+	 */
+	function addAppend($sTarget,$sAttribute,$sData)
+	{	
+		$this->xml .= $this->_cmdXML(array("n"=>"ap","t"=>$sTarget,"p"=>$sAttribute),$sData);
+	}
+
+	/**
+	 * Adds an prepend command message to the XML response.
+	 * 
+	 * <i>Usage:</i> <kbd>$objResponse->addPrepend("contentDiv", "innerHTML", "Some Starting Text");</kbd>
+	 * 
+	 * @param string contains the id of an HTML element
+	 * @param string the part of the element you wish to modify ("innerHTML",
+	 *               "value", etc.)
+	 * @param string the data you want to prepend to the beginning of the
+	 *               attribute
+	 */
+	function addPrepend($sTarget,$sAttribute,$sData)
+	{
+		$this->xml .= $this->_cmdXML(array("n"=>"pp","t"=>$sTarget,"p"=>$sAttribute),$sData);
+	}
+
+	/**
+	 * Adds a replace command message to the XML response.
+	 * 
+	 * <i>Usage:</i> <kbd>$objResponse->addReplace("contentDiv", "innerHTML", "text", "<b>text</b>");</kbd>
+	 * 
+	 * @param string contains the id of an HTML element
+	 * @param string the part of the element you wish to modify ("innerHTML",
+	 *               "value", etc.)
+	 * @param string the string to search for
+	 * @param string the string to replace the search string when found in the
+	 *               attribute
+	 */
+	function addReplace($sTarget,$sAttribute,$sSearch,$sData)
+	{
+		$sDta = "<s><![CDATA[$sSearch]]></s><r><![CDATA[$sData]]></r>";
+		$this->xml .= $this->_cmdXML(array("n"=>"rp","t"=>$sTarget,"p"=>$sAttribute),$sDta);
+	}
+
+	/**
+	 * Adds a clear command message to the XML response.
+	 * 
+	 * <i>Usage:</i> <kbd>$objResponse->addClear("contentDiv", "innerHTML");</kbd>
+	 * 
+	 * @param string contains the id of an HTML element
+	 * @param string the part of the element you wish to clear ("innerHTML",
+	 *               "value", etc.)
+	 */	
+	function addClear($sTarget,$sAttribute)
+	{
+		$this->addAssign($sTarget,$sAttribute,'');
+	}
+	
+	/**
+	 * Adds an alert command message to the XML response.
+	 * 
+	 * <i>Usage:</i> <kbd>$objResponse->addAlert("This is important information");</kbd>
+	 * 
+	 * @param string the text to be displayed in the Javascript alert box
+	 */
+	function addAlert($sMsg)
+	{
+		$this->xml .= $this->_cmdXML(array("n"=>"al"),$sMsg);
+	}
+
+	/**
+	 * Uses the addScript() method to add a Javascript redirect to another URL.
+	 * 
+	 * <i>Usage:</i> <kbd>$objResponse->addRedirect("http://www.xajaxproject.org");</kbd>
+	 * 
+	 * @param string the URL to redirect the client browser to
+	 */	
+	function addRedirect($sURL)
+	{
+		//we need to parse the query part so that the values are rawurlencode()'ed
+		//can't just use parse_url() cos we could be dealing with a relative URL which
+		//  parse_url() can't deal with.
+		$queryStart = strpos($sURL, '?', strrpos($sURL, '/'));
+		if ($queryStart !== FALSE)
+		{
+			$queryStart++;
+			$queryEnd = strpos($sURL, '#', $queryStart);
+			if ($queryEnd === FALSE)
+				$queryEnd = strlen($sURL);
+			$queryPart = substr($sURL, $queryStart, $queryEnd-$queryStart);
+			parse_str($queryPart, $queryParts);
+			$newQueryPart = "";
+			foreach($queryParts as $key => $value)
+			{
+				$newQueryPart .= rawurlencode($key).'='.rawurlencode($value).ini_get('arg_separator.output');
+			}
+			$sURL = str_replace($queryPart, $newQueryPart, $sURL);
+		}
+		$this->addScript('window.location = "'.$sURL.'";');
+	}
+
+	/**
+	 * Adds a Javascript command message to the XML response.
+	 * 
+	 * <i>Usage:</i> <kbd>$objResponse->addScript("var x = prompt('get some text');");</kbd>
+	 * 
+	 * @param string contains Javascript code to be executed
+	 */
+	function addScript($sJS)
+	{
+		$this->xml .= $this->_cmdXML(array("n"=>"js"),$sJS);
+	}
+
+	/**
+	 * Adds a Javascript function call command message to the XML response.
+	 * 
+	 * <i>Usage:</i> <kbd>$objResponse->addScriptCall("myJSFunction", "arg 1", "arg 2", 12345);</kbd>
+	 * 
+	 * @param string $sFunc the name of a Javascript function
+	 * @param mixed $args,... optional arguments to pass to the Javascript function
+	 */
+	function addScriptCall() {
+		$arguments = func_get_args();
+		$sFunc = array_shift($arguments);
+		$sData = $this->_buildObjXml($arguments);
+		$this->xml .= $this->_cmdXML(array("n"=>"jc","t"=>$sFunc),$sData);
+	}
+
+	/**
+	 * Adds a remove element command message to the XML response.
+	 * 
+	 * <i>Usage:</i> <kbd>$objResponse->addRemove("Div2");</kbd>
+	 * 
+	 * @param string contains the id of an HTML element to be removed
+	 */
+	function addRemove($sTarget)
+	{
+		$this->xml .= $this->_cmdXML(array("n"=>"rm","t"=>$sTarget),'');
+	}
+
+	/**
+	 * Adds a create element command message to the XML response.
+	 * 
+	 * <i>Usage:</i> <kbd>$objResponse->addCreate("parentDiv", "h3", "myid");</kbd>
+	 * 
+	 * @param string contains the id of an HTML element to to which the new
+	 *               element will be appended.
+	 * @param string the tag to be added
+	 * @param string the id to be assigned to the new element
+	 * @param string deprecated, use the addCreateInput() method instead
+	 */
+	function addCreate($sParent, $sTag, $sId, $sType="")
+	{
+		if ($sType)
+		{
+			trigger_error("The \$sType parameter of addCreate has been deprecated.  Use the addCreateInput() method instead.", E_USER_WARNING);
+			return;
+		}
+		$this->xml .= $this->_cmdXML(array("n"=>"ce","t"=>$sParent,"p"=>$sId),$sTag);
+	}
+
+	/**
+	 * Adds a insert element command message to the XML response.
+	 * 
+	 * <i>Usage:</i> <kbd>$objResponse->addInsert("childDiv", "h3", "myid");</kbd>
+	 * 
+	 * @param string contains the id of the child before which the new element
+	 *               will be inserted
+	 * @param string the tag to be added
+	 * @param string the id to be assigned to the new element
+	 */
+	function addInsert($sBefore, $sTag, $sId)
+	{
+		$this->xml .= $this->_cmdXML(array("n"=>"ie","t"=>$sBefore,"p"=>$sId),$sTag);
+	}
+
+	/**
+	 * Adds a insert element command message to the XML response.
+	 * 
+	 * <i>Usage:</i> <kbd>$objResponse->addInsertAfter("childDiv", "h3", "myid");</kbd>
+	 * 
+	 * @param string contains the id of the child after which the new element
+	 *               will be inserted
+	 * @param string the tag to be added
+	 * @param string the id to be assigned to the new element
+	 */
+	function addInsertAfter($sAfter, $sTag, $sId)
+	{
+		$this->xml .= $this->_cmdXML(array("n"=>"ia","t"=>$sAfter,"p"=>$sId),$sTag);
+	}
+	
+	/**
+	 * Adds a create input command message to the XML response.
+	 * 
+	 * <i>Usage:</i> <kbd>$objResponse->addCreateInput("form1", "text", "username", "input1");</kbd>
+	 * 
+	 * @param string contains the id of an HTML element to which the new input
+	 *               will be appended
+	 * @param string the type of input to be created (text, radio, checkbox,
+	 *               etc.)
+	 * @param string the name to be assigned to the new input and the variable
+	 *               name when it is submitted
+	 * @param string the id to be assigned to the new input
+	 */
+	function addCreateInput($sParent, $sType, $sName, $sId)
+	{
+		$this->xml .= $this->_cmdXML(array("n"=>"ci","t"=>$sParent,"p"=>$sId,"c"=>$sType),$sName);
+	}
+
+	/**
+	 * Adds an insert input command message to the XML response.
+	 * 
+	 * <i>Usage:</i> <kbd>$objResponse->addInsertInput("input5", "text", "username", "input1");</kbd>
+	 * 
+	 * @param string contains the id of the child before which the new element
+	 *               will be inserted
+	 * @param string the type of input to be created (text, radio, checkbox,
+	 *               etc.)
+	 * @param string the name to be assigned to the new input and the variable
+	 *               name when it is submitted
+	 * @param string the id to be assigned to the new input
+	 */
+	function addInsertInput($sBefore, $sType, $sName, $sId)
+	{
+		$this->xml .= $this->_cmdXML(array("n"=>"ii","t"=>$sBefore,"p"=>$sId,"c"=>$sType),$sName);
+	}
+
+	/**
+	 * Adds an insert input command message to the XML response.
+	 * 
+	 * <i>Usage:</i> <kbd>$objResponse->addInsertInputAfter("input7", "text", "email", "input2");</kbd>
+	 * 
+	 * @param string contains the id of the child after which the new element
+	 *               will be inserted
+	 * @param string the type of input to be created (text, radio, checkbox,
+	 *               etc.)
+	 * @param string the name to be assigned to the new input and the variable
+	 *               name when it is submitted
+	 * @param string the id to be assigned to the new input
+	 */
+	function addInsertInputAfter($sAfter, $sType, $sName, $sId)
+	{
+		$this->xml .= $this->_cmdXML(array("n"=>"iia","t"=>$sAfter,"p"=>$sId,"c"=>$sType),$sName);
+	}
+
+	/**
+	 * Adds an event command message to the XML response.
+	 * 
+	 * <i>Usage:</i> <kbd>$objResponse->addEvent("contentDiv", "onclick", "alert(\'Hello World\');");</kbd>
+	 * 
+	 * @param string contains the id of an HTML element
+	 * @param string the event you wish to set ("onclick", "onmouseover", etc.)
+	 * @param string the Javascript string you want the event to invoke
+	 */
+	function addEvent($sTarget,$sEvent,$sScript)
+	{
+		$this->xml .= $this->_cmdXML(array("n"=>"ev","t"=>$sTarget,"p"=>$sEvent),$sScript);
+	}
+
+	/**
+	 * Adds a handler command message to the XML response.
+	 * 
+	 * <i>Usage:</i> <kbd>$objResponse->addHandler("contentDiv", "onclick", "content_click");</kbd>
+	 * 
+	 * @param string contains the id of an HTML element
+	 * @param string the event you wish to set ("onclick", "onmouseover", etc.)
+	 * @param string the name of a Javascript function that will handle the
+	 *               event. Multiple handlers can be added for the same event
+	 */
+	function addHandler($sTarget,$sEvent,$sHandler)
+	{	
+		$this->xml .= $this->_cmdXML(array("n"=>"ah","t"=>$sTarget,"p"=>$sEvent),$sHandler);
+	}
+
+	/**
+	 * Adds a remove handler command message to the XML response.
+	 * 
+	 * <i>Usage:</i> <kbd>$objResponse->addRemoveHandler("contentDiv", "onclick", "content_click");</kbd>
+	 * 
+	 * @param string contains the id of an HTML element
+	 * @param string the event you wish to remove ("onclick", "onmouseover",
+	 *               etc.)
+	 * @param string the name of a Javascript handler function that you want to
+	 *               remove
+	 */
+	function addRemoveHandler($sTarget,$sEvent,$sHandler)
+	{	
+		$this->xml .= $this->_cmdXML(array("n"=>"rh","t"=>$sTarget,"p"=>$sEvent),$sHandler);
+	}
+
+	/**
+	 * Adds an include script command message to the XML response.
+	 * 
+	 * <i>Usage:</i> <kbd>$objResponse->addIncludeScript("functions.js");</kbd>
+	 * 
+	 * @param string URL of the Javascript file to include
+	 */
+	function addIncludeScript($sFileName)
+	{
+		$this->xml .= $this->_cmdXML(array("n"=>"in"),$sFileName);
+	}
+
+	/**	
+	 * Returns the XML to be returned from your function to the xajax processor
+	 * on your page. Since xajax 0.2, you can also return an xajaxResponse
+	 * object from your function directly, and xajax will automatically request
+	 * the XML using this method call.
+	 * 
+	 * <i>Usage:</i> <kbd>return $objResponse->getXML();</kbd>
+	 * 
+	 * @return string response XML data
+	 */
+	function getXML()
+	{
+		$sXML = "<?xml version=\"1.0\"";
+		if ($this->sEncoding && strlen(trim($this->sEncoding)) > 0)
+			$sXML .= " encoding=\"".$this->sEncoding."\"";
+		$sXML .= " ?"."><xjx>" . $this->xml . "</xjx>";
+		
+		return $sXML;
+	}
+	
+	/**
+	 * Adds the commands of the provided response XML output to this response
+	 * object
+	 * 
+	 * <i>Usage:</i>
+	 * <code>$r1 = $objResponse1->getXML();
+	 * $objResponse2->loadXML($r1);
+	 * return $objResponse2->getXML();</code>
+	 * 
+	 * @param string the response XML (returned from a getXML() method) to add
+	 *               to the end of this response object
+	 */
+	function loadXML($mXML)
+	{
+		if (is_a($mXML, "xajaxResponse")) {
+			$mXML = $mXML->getXML();
+		}
+		$sNewXML = "";
+		$iStartPos = strpos($mXML, "<xjx>") + 5;
+		$sNewXML = substr($mXML, $iStartPos);
+		$iEndPos = strpos($sNewXML, "</xjx>");
+		$sNewXML = substr($sNewXML, 0, $iEndPos);
+		$this->xml .= $sNewXML;
+	}
+
+	/**
+	 * Generates XML from command data
+	 * 
+	 * @access private
+	 * @param array associative array of attributes
+	 * @param string data
+	 * @return string XML command
+	 */
+	function _cmdXML($aAttributes, $sData)
+	{
+		if ($this->bOutputEntities) {
+			if (function_exists('mb_convert_encoding')) {
+				$sData = call_user_func_array('mb_convert_encoding', array(&$sData, 'HTML-ENTITIES', $this->sEncoding));
+			}
+			else {
+				trigger_error("The xajax XML response output could not be converted to HTML entities because the mb_convert_encoding function is not available", E_USER_NOTICE);
+			}
+		}
+		$xml = "<cmd";
+		foreach($aAttributes as $sAttribute => $sValue)
+			$xml .= " $sAttribute=\"$sValue\"";
+		if ($sData !== null && !stristr($sData,'<![CDATA['))
+			$xml .= "><![CDATA[$sData]]></cmd>";
+		else if ($sData !== null)
+			$xml .= ">$sData</cmd>";
+		else
+			$xml .= "></cmd>";
+		
+		return $xml;
+	}
+
+	/**
+	 * Recursively serializes a data structure in XML so it can be sent to
+	 * the client. It could be thought of as the opposite of
+	 * {@link xajax::_parseObjXml()}.
+	 * 
+	 * @access private
+	 * @param mixed data structure to serialize to XML
+	 * @return string serialized XML
+	 */
+	function _buildObjXml($var) {
+		if (gettype($var) == "object") $var = get_object_vars($var);
+		if (!is_array($var)) {
+			return "<![CDATA[$var]]>";
+		}
+		else {
+			$data = "<xjxobj>";
+			foreach ($var as $key => $value) {
+				$data .= "<e>";
+				$data .= "<k>" . htmlspecialchars($key) . "</k>";
+				$data .= "<v>" . $this->_buildObjXml($value) . "</v>";
+				$data .= "</e>";
+			}
+			$data .= "</xjxobj>";
+			return $data;
+		}
+	}
+	
+}// end class xajaxResponse
+?>
Index: trunk/workflow/inc/report/xajax/xajax.inc.php
===================================================================
--- trunk/workflow/inc/report/xajax/xajax.inc.php	(revision 5307)
+++ trunk/workflow/inc/report/xajax/xajax.inc.php	(revision 5307)
@@ -0,0 +1,1239 @@
+<?php
+/**
+ * xajax.inc.php :: Main xajax class and setup file
+ *
+ * xajax version 0.2.4
+ * copyright (c) 2005 by Jared White & J. Max Wilson
+ * http://www.xajaxproject.org
+ *
+ * xajax is an open source PHP class library for easily creating powerful
+ * PHP-driven, web-based Ajax Applications. Using xajax, you can asynchronously
+ * call PHP functions and update the content of your your webpage without
+ * reloading the page.
+ *
+ * xajax is released under the terms of the LGPL license
+ * http://www.gnu.org/copyleft/lesser.html#SEC3
+ *
+ * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ * 
+ * @package xajax
+ * @version $Id$
+ * @copyright Copyright (c) 2005-2006  by Jared White & J. Max Wilson
+ * @license http://www.gnu.org/copyleft/lesser.html#SEC3 LGPL License
+ */
+
+/*
+   ----------------------------------------------------------------------------
+   | Online documentation for this class is available on the xajax wiki at:   |
+   | http://wiki.xajaxproject.org/Documentation:xajax.inc.php                 |
+   ----------------------------------------------------------------------------
+*/
+
+/**
+ * Define XAJAX_DEFAULT_CHAR_ENCODING that is used by both
+ * the xajax and xajaxResponse classes
+ */
+if (!defined ('XAJAX_DEFAULT_CHAR_ENCODING'))
+{
+	define ('XAJAX_DEFAULT_CHAR_ENCODING', 'iso-8859-1' );
+}
+
+require_once(dirname(__FILE__)."/xajaxResponse.inc.php");
+
+/**
+ * Communication Method Defines
+ */
+if (!defined ('XAJAX_GET'))
+{
+	define ('XAJAX_GET', 0);
+}
+if (!defined ('XAJAX_POST'))
+{
+	define ('XAJAX_POST', 1);
+}
+
+/**
+ * The xajax class generates the xajax javascript for your page including the 
+ * Javascript wrappers for the PHP functions that you want to call from your page.
+ * It also handles processing and executing the command messages in the XML responses
+ * sent back to your page from your PHP functions.
+ * 
+ * @package xajax
+ */ 
+class xajax
+{
+	/**#@+
+	 * @access protected
+	 */
+	/**
+	 * @var array Array of PHP functions that will be callable through javascript wrappers
+	 */
+	var $aFunctions;
+	/**
+	 * @var array Array of object callbacks that will allow Javascript to call PHP methods (key=function name)
+	 */
+	var $aObjects;
+	/**
+	 * @var array Array of RequestTypes to be used with each function (key=function name)
+	 */
+	var $aFunctionRequestTypes;
+	/**
+	 * @var array Array of Include Files for any external functions (key=function name)
+	 */
+	var $aFunctionIncludeFiles;
+	/**
+	 * @var string Name of the PHP function to call if no callable function was found
+	 */
+	var $sCatchAllFunction;
+	/**
+	 * @var string Name of the PHP function to call before any other function
+	 */
+	var $sPreFunction;
+	/**
+	 * @var string The URI for making requests to the xajax object
+	 */
+	var $sRequestURI;
+	/**
+	 * @var string The prefix to prepend to the javascript wraper function name
+	 */
+	var $sWrapperPrefix;
+	/**
+	 * @var boolean Show debug messages (default false)
+	 */
+	var $bDebug;
+	/**
+	 * @var boolean Show messages in the client browser's status bar (default false)
+	 */
+	var $bStatusMessages;	
+	/**
+	 * @var boolean Allow xajax to exit after processing a request (default true)
+	 */
+	var $bExitAllowed;
+	/**
+	 * @var boolean Use wait cursor in browser (default true)
+	 */
+	var $bWaitCursor;
+	/**
+	 * @var boolean Use an special xajax error handler so the errors are sent to the browser properly (default false)
+	 */
+	var $bErrorHandler;
+	/**
+	 * @var string Specify what, if any, file xajax should log errors to (and more information in a future release)
+	 */
+	var $sLogFile;
+	/**
+	 * @var boolean Clean all output buffers before outputting response (default false)
+	 */
+	var $bCleanBuffer;
+	/**
+	 * @var string String containing the character encoding used
+	 */
+	var $sEncoding;
+	/**
+	 * @var boolean Decode input request args from UTF-8 (default false)
+	 */
+	var $bDecodeUTF8Input;
+	/**
+	 * @var boolean Convert special characters to HTML entities (default false)
+	 */
+	var $bOutputEntities;
+	/**
+	 * @var array Array for parsing complex objects
+	 */
+	var $aObjArray;
+	/**
+	 * @var integer Position in $aObjArray
+	 */
+	var $iPos;
+	
+	/**#@-*/
+	
+	/**
+	 * Constructor. You can set some extra xajax options right away or use
+	 * individual methods later to set options.
+	 * 
+	 * @param string  defaults to the current browser URI
+	 * @param string  defaults to "xajax_";
+	 * @param string  defaults to XAJAX_DEFAULT_CHAR_ENCODING defined above
+	 * @param boolean defaults to false
+	 */
+	function xajax($sRequestURI="",$sWrapperPrefix="xajax_",$sEncoding=XAJAX_DEFAULT_CHAR_ENCODING,$bDebug=false)
+	{
+		$this->aFunctions = array();
+		$this->aObjects = array();
+		$this->aFunctionIncludeFiles = array();
+		$this->sRequestURI = $sRequestURI;
+		if ($this->sRequestURI == "")
+			$this->sRequestURI = $this->_detectURI();
+		$this->sWrapperPrefix = $sWrapperPrefix;
+		$this->bDebug = $bDebug;
+		$this->bStatusMessages = false;
+		$this->bWaitCursor = true;
+		$this->bExitAllowed = true;
+		$this->bErrorHandler = false;
+		$this->sLogFile = "";
+		$this->bCleanBuffer = false;
+		$this->setCharEncoding($sEncoding);
+		$this->bDecodeUTF8Input = false;
+		$this->bOutputEntities = false;
+	}
+		
+	/**
+	 * Sets the URI to which requests will be made.
+	 * <i>Usage:</i> <kbd>$xajax->setRequestURI("http://www.xajaxproject.org");</kbd>
+	 * 
+	 * @param string the URI (can be absolute or relative) of the PHP script
+	 *               that will be accessed when an xajax request occurs
+	 */
+	function setRequestURI($sRequestURI)
+	{
+		$this->sRequestURI = $sRequestURI;
+	}
+
+	/**
+	 * Sets the prefix that will be appended to the Javascript wrapper
+	 * functions (default is "xajax_").
+	 * 
+	 * @param string
+	 */ 
+	// 
+	function setWrapperPrefix($sPrefix)
+	{
+		$this->sWrapperPrefix = $sPrefix;
+	}
+	
+	/**
+	 * Enables debug messages for xajax.
+	 * */
+	function debugOn()
+	{
+		$this->bDebug = true;
+	}
+	
+	/**
+	 * Disables debug messages for xajax (default behavior).
+	 */
+	function debugOff()
+	{
+		$this->bDebug = false;
+	}
+		
+	/**
+	 * Enables messages in the browser's status bar for xajax.
+	 */
+	function statusMessagesOn()
+	{
+		$this->bStatusMessages = true;
+	}
+	
+	/**
+	 * Disables messages in the browser's status bar for xajax (default behavior).
+	 */
+	function statusMessagesOff()
+	{
+		$this->bStatusMessages = false;
+	}
+	
+	/**
+	 * Enables the wait cursor to be displayed in the browser (default behavior).
+	 */
+	function waitCursorOn()
+	{
+		$this->bWaitCursor = true;
+	}
+	
+	/**
+	 * Disables the wait cursor to be displayed in the browser.
+	 */
+	function waitCursorOff()
+	{
+		$this->bWaitCursor = false;
+	}	
+	
+	/**
+	 * Enables xajax to exit immediately after processing a request and
+	 * sending the response back to the browser (default behavior).
+	 */
+	function exitAllowedOn()
+	{
+		$this->bExitAllowed = true;
+	}
+	
+	/**
+	 * Disables xajax's default behavior of exiting immediately after
+	 * processing a request and sending the response back to the browser.
+	 */
+	function exitAllowedOff()
+	{
+		$this->bExitAllowed = false;
+	}
+	
+	/**
+	 * Turns on xajax's error handling system so that PHP errors that occur
+	 * during a request are trapped and pushed to the browser in the form of
+	 * a Javascript alert.
+	 */
+	function errorHandlerOn()
+	{
+		$this->bErrorHandler = true;
+	}
+
+	/**
+	 * Turns off xajax's error handling system (default behavior).
+	 */
+	function errorHandlerOff()
+	{
+		$this->bErrorHandler = false;
+	}
+	
+	/**
+	 * Specifies a log file that will be written to by xajax during a request
+	 * (used only by the error handling system at present). If you don't invoke
+	 * this method, or you pass in "", then no log file will be written to.
+	 * <i>Usage:</i> <kbd>$xajax->setLogFile("/xajax_logs/errors.log");</kbd>
+	 */
+	function setLogFile($sFilename)
+	{
+		$this->sLogFile = $sFilename;
+	}
+
+	/**
+	 * Causes xajax to clean out all output buffers before outputting a
+	 * response (default behavior).
+	 */
+	function cleanBufferOn()
+	{
+		$this->bCleanBuffer = true;
+	}
+	/**
+	 * Turns off xajax's output buffer cleaning.
+	 */
+	function cleanBufferOff()
+	{
+		$this->bCleanBuffer = false;
+	}
+	
+	/**
+	 * Sets the character encoding for the HTTP output based on
+	 * <kbd>$sEncoding</kbd>, which is a string containing the character
+	 * encoding to use. You don't need to use this method normally, since the
+	 * character encoding for the response gets set automatically based on the
+	 * <kbd>XAJAX_DEFAULT_CHAR_ENCODING</kbd> constant.
+	 * <i>Usage:</i> <kbd>$xajax->setCharEncoding("utf-8");</kbd>
+	 *
+	 * @param string the encoding type to use (utf-8, iso-8859-1, etc.)
+	 */
+	function setCharEncoding($sEncoding)
+	{
+		$this->sEncoding = $sEncoding;
+	}
+
+	/**
+	 * Causes xajax to decode the input request args from UTF-8 to the current
+	 * encoding if possible. Either the iconv or mb_string extension must be
+	 * present for optimal functionality.
+	 */
+	function decodeUTF8InputOn()
+	{
+		$this->bDecodeUTF8Input = true;
+	}
+
+	/**
+	 * Turns off decoding the input request args from UTF-8 (default behavior).
+	 */
+	function decodeUTF8InputOff()
+	{
+		$this->bDecodeUTF8Input = false;
+	}
+	
+	/**
+	 * Tells the response object to convert special characters to HTML entities
+	 * automatically (only works if the mb_string extension is available).
+	 */
+	function outputEntitiesOn()
+	{
+		$this->bOutputEntities = true;
+	}
+	
+	/**
+	 * Tells the response object to output special characters intact. (default
+	 * behavior).
+	 */
+	function outputEntitiesOff()
+	{
+		$this->bOutputEntities = false;
+	}
+				
+	/**
+	 * Registers a PHP function or method to be callable through xajax in your
+	 * Javascript. If you want to register a function, pass in the name of that
+	 * function. If you want to register a static class method, pass in an
+	 * array like so:
+	 * <kbd>array("myFunctionName", "myClass", "myMethod")</kbd>
+	 * For an object instance method, use an object variable for the second
+	 * array element (and in PHP 4 make sure you put an & before the variable
+	 * to pass the object by reference). Note: the function name is what you
+	 * call via Javascript, so it can be anything as long as it doesn't
+	 * conflict with any other registered function name.
+	 * 
+	 * <i>Usage:</i> <kbd>$xajax->registerFunction("myFunction");</kbd>
+	 * or: <kbd>$xajax->registerFunction(array("myFunctionName", &$myObject, "myMethod"));</kbd>
+	 * 
+	 * @param mixed  contains the function name or an object callback array
+	 * @param mixed  request type (XAJAX_GET/XAJAX_POST) that should be used 
+	 *               for this function.  Defaults to XAJAX_POST.
+	 */
+	function registerFunction($mFunction,$sRequestType=XAJAX_POST)
+	{
+		if (is_array($mFunction)) {
+			$this->aFunctions[$mFunction[0]] = 1;
+			$this->aFunctionRequestTypes[$mFunction[0]] = $sRequestType;
+			$this->aObjects[$mFunction[0]] = array_slice($mFunction, 1);
+		}	
+		else {
+			$this->aFunctions[$mFunction] = 1;
+			$this->aFunctionRequestTypes[$mFunction] = $sRequestType;
+		}
+	}
+	
+	/**
+	 * Registers a PHP function to be callable through xajax which is located
+	 * in some other file.  If the function is requested the external file will
+	 * be included to define the function before the function is called.
+	 * 
+	 * <i>Usage:</i> <kbd>$xajax->registerExternalFunction("myFunction","myFunction.inc.php",XAJAX_POST);</kbd>
+	 * 
+	 * @param string contains the function name or an object callback array
+	 *               ({@link xajax::registerFunction() see registerFunction} for
+	 *               more info on object callback arrays)
+	 * @param string contains the path and filename of the include file
+	 * @param mixed  the RequestType (XAJAX_GET/XAJAX_POST) that should be used 
+	 *		          for this function. Defaults to XAJAX_POST.
+	 */
+	function registerExternalFunction($mFunction,$sIncludeFile,$sRequestType=XAJAX_POST)
+	{
+		$this->registerFunction($mFunction, $sRequestType);
+		
+		if (is_array($mFunction)) {
+			$this->aFunctionIncludeFiles[$mFunction[0]] = $sIncludeFile;
+		}
+		else {
+			$this->aFunctionIncludeFiles[$mFunction] = $sIncludeFile;
+		}
+	}
+	
+	/**
+	 * Registers a PHP function to be called when xajax cannot find the
+	 * function being called via Javascript. Because this is technically
+	 * impossible when using "wrapped" functions, the catch-all feature is
+	 * only useful when you're directly using the xajax.call() Javascript
+	 * method. Use the catch-all feature when you want more dynamic ability to
+	 * intercept unknown calls and handle them in a custom way.
+	 * 
+	 * <i>Usage:</i> <kbd>$xajax->registerCatchAllFunction("myCatchAllFunction");</kbd>
+	 * 
+	 * @param string contains the function name or an object callback array
+	 *               ({@link xajax::registerFunction() see registerFunction} for
+	 *               more info on object callback arrays)
+	 */
+	function registerCatchAllFunction($mFunction)
+	{
+		if (is_array($mFunction)) {
+			$this->sCatchAllFunction = $mFunction[0];
+			$this->aObjects[$mFunction[0]] = array_slice($mFunction, 1);
+		}
+		else {
+			$this->sCatchAllFunction = $mFunction;
+		}
+	}
+	
+	/**
+	 * Registers a PHP function to be called before xajax calls the requested
+	 * function. xajax will automatically add the request function's response
+	 * to the pre-function's response to create a single response. Another
+	 * feature is the ability to return not just a response, but an array with
+	 * the first element being false (a boolean) and the second being the
+	 * response. In this case, the pre-function's response will be returned to
+	 * the browser without xajax calling the requested function.
+	 * 
+	 * <i>Usage:</i> <kbd>$xajax->registerPreFunction("myPreFunction");</kbd>
+	 * 
+	 * @param string contains the function name or an object callback array
+	 *               ({@link xajax::registerFunction() see registerFunction} for
+	 *               more info on object callback arrays)
+	 */
+	function registerPreFunction($mFunction)
+	{
+		if (is_array($mFunction)) {
+			$this->sPreFunction = $mFunction[0];
+			$this->aObjects[$mFunction[0]] = array_slice($mFunction, 1);
+		}
+		else {
+			$this->sPreFunction = $mFunction;
+		}
+	}
+	
+	/**
+	 * Returns true if xajax can process the request, false if otherwise.
+	 * You can use this to determine if xajax needs to process the request or
+	 * not.
+	 * 
+	 * @return boolean
+	 */ 
+	function canProcessRequests()
+	{
+		if ($this->getRequestMode() != -1) return true;
+		return false;
+	}
+	
+	/**
+	 * Returns the current request mode (XAJAX_GET or XAJAX_POST), or -1 if
+	 * there is none.
+	 * 
+	 * @return mixed
+	 */
+	function getRequestMode()
+	{
+		if (!empty($_GET["xajax"]))
+			return XAJAX_GET;
+		
+		if (!empty($_POST["xajax"]))
+			return XAJAX_POST;
+			
+		return -1;
+	}
+	
+	/**
+	 * This is the main communications engine of xajax. The engine handles all
+	 * incoming xajax requests, calls the apporiate PHP functions (or
+	 * class/object methods) and passes the XML responses back to the
+	 * Javascript response handler. If your RequestURI is the same as your Web
+	 * page then this function should be called before any headers or HTML has
+	 * been sent.
+	 */
+	function processRequests()
+	{	
+		
+		$requestMode = -1;
+		$sFunctionName = "";
+		$bFoundFunction = true;
+		$bFunctionIsCatchAll = false;
+		$sFunctionNameForSpecial = "";
+		$aArgs = array();
+		$sPreResponse = "";
+		$bEndRequest = false;
+		$sResponse = "";
+		
+		$requestMode = $this->getRequestMode();
+		if ($requestMode == -1) return;
+	
+		if ($requestMode == XAJAX_POST)
+		{
+			$sFunctionName = $_POST["xajax"];
+			
+			if (!empty($_POST["xajaxargs"])) 
+				$aArgs = $_POST["xajaxargs"];
+		}
+		else
+		{	
+			header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
+			header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
+			header ("Cache-Control: no-cache, must-revalidate");
+			header ("Pragma: no-cache");
+			
+			$sFunctionName = $_GET["xajax"];
+			
+			if (!empty($_GET["xajaxargs"])) 
+				$aArgs = $_GET["xajaxargs"];
+		}
+		
+		// Use xajax error handler if necessary
+		if ($this->bErrorHandler) {
+			$GLOBALS['xajaxErrorHandlerText'] = "";
+			set_error_handler("xajaxErrorHandler");
+		}
+		
+		if ($this->sPreFunction) {
+			if (!$this->_isFunctionCallable($this->sPreFunction)) {
+				$bFoundFunction = false;
+				$objResponse = new xajaxResponse();
+				$objResponse->addAlert("Unknown Pre-Function ". $this->sPreFunction);
+				$sResponse = $objResponse->getXML();
+			}
+		}
+		//include any external dependencies associated with this function name
+		if (array_key_exists($sFunctionName,$this->aFunctionIncludeFiles))
+		{
+			ob_start();
+			include_once($this->aFunctionIncludeFiles[$sFunctionName]);
+			ob_end_clean();
+		}
+		
+		if ($bFoundFunction) {
+			$sFunctionNameForSpecial = $sFunctionName;
+			if (!array_key_exists($sFunctionName, $this->aFunctions))
+			{
+				if ($this->sCatchAllFunction) {
+					$sFunctionName = $this->sCatchAllFunction;
+					$bFunctionIsCatchAll = true;
+				}
+				else {
+					$bFoundFunction = false;
+					$objResponse = new xajaxResponse();
+					$objResponse->addAlert("Unknown Function $sFunctionName.");
+					$sResponse = $objResponse->getXML();
+				}
+			}
+			else if ($this->aFunctionRequestTypes[$sFunctionName] != $requestMode)
+			{
+				$bFoundFunction = false;
+				$objResponse = new xajaxResponse();
+				$objResponse->addAlert("Incorrect Request Type.");
+				$sResponse = $objResponse->getXML();
+			}
+		}
+		
+		if ($bFoundFunction)
+		{
+			for ($i = 0; $i < sizeof($aArgs); $i++)
+			{
+				// If magic quotes is on, then we need to strip the slashes from the args
+				if (get_magic_quotes_gpc() == 1 && is_string($aArgs[$i])) {
+				
+					$aArgs[$i] = stripslashes($aArgs[$i]);
+				}
+				if (stristr($aArgs[$i],"<xjxobj>") != false)
+				{
+					$aArgs[$i] = $this->_xmlToArray("xjxobj",$aArgs[$i]);	
+				}
+				else if (stristr($aArgs[$i],"<xjxquery>") != false)
+				{
+					$aArgs[$i] = $this->_xmlToArray("xjxquery",$aArgs[$i]);	
+				}
+				else if ($this->bDecodeUTF8Input)
+				{
+					$aArgs[$i] = $this->_decodeUTF8Data($aArgs[$i]);	
+				}
+			}
+
+			if ($this->sPreFunction) {
+				$mPreResponse = $this->_callFunction($this->sPreFunction, array($sFunctionNameForSpecial, $aArgs));
+				if (is_array($mPreResponse) && $mPreResponse[0] === false) {
+					$bEndRequest = true;
+					$sPreResponse = $mPreResponse[1];
+				}
+				else {
+					$sPreResponse = $mPreResponse;
+				}
+				if (is_a($sPreResponse, "xajaxResponse")) {
+					$sPreResponse = $sPreResponse->getXML();
+				}
+				if ($bEndRequest) $sResponse = $sPreResponse;
+			}
+			
+			if (!$bEndRequest) {
+				if (!$this->_isFunctionCallable($sFunctionName)) {
+					$objResponse = new xajaxResponse();
+					$objResponse->addAlert("The Registered Function $sFunctionName Could Not Be Found.");
+					$sResponse = $objResponse->getXML();
+				}
+				else {
+					if ($bFunctionIsCatchAll) {
+						$aArgs = array($sFunctionNameForSpecial, $aArgs);
+					}
+					$sResponse = $this->_callFunction($sFunctionName, $aArgs);
+				}
+				if (is_a($sResponse, "xajaxResponse")) {
+					$sResponse = $sResponse->getXML();
+				}
+				if (!is_string($sResponse) || strpos($sResponse, "<xjx>") === FALSE) {
+					$objResponse = new xajaxResponse();
+					$objResponse->addAlert("No XML Response Was Returned By Function $sFunctionName.");
+					$sResponse = $objResponse->getXML();
+				}
+				else if ($sPreResponse != "") {
+					$sNewResponse = new xajaxResponse($this->sEncoding, $this->bOutputEntities);
+					$sNewResponse->loadXML($sPreResponse);
+					$sNewResponse->loadXML($sResponse);
+					$sResponse = $sNewResponse->getXML();
+				}
+			}
+		}
+		
+		$sContentHeader = "Content-type: text/xml;";
+		if ($this->sEncoding && strlen(trim($this->sEncoding)) > 0)
+			$sContentHeader .= " charset=".$this->sEncoding;
+		header($sContentHeader);
+		if ($this->bErrorHandler && !empty( $GLOBALS['xajaxErrorHandlerText'] )) {
+			$sErrorResponse = new xajaxResponse();
+			$sErrorResponse->addAlert("** PHP Error Messages: **" . $GLOBALS['xajaxErrorHandlerText']);
+			if ($this->sLogFile) {
+				$fH = @fopen($this->sLogFile, "a");
+				if (!$fH) {
+					$sErrorResponse->addAlert("** Logging Error **\n\nxajax was unable to write to the error log file:\n" . $this->sLogFile);
+				}
+				else {
+					fwrite($fH, "** xajax Error Log - " . strftime("%b %e %Y %I:%M:%S %p") . " **" . $GLOBALS['xajaxErrorHandlerText'] . "\n\n\n");
+					fclose($fH);
+				}
+			}
+
+			$sErrorResponse->loadXML($sResponse);
+			$sResponse = $sErrorResponse->getXML();
+			
+		}
+		if ($this->bCleanBuffer) while (@ob_end_clean());
+		print $sResponse;
+		if ($this->bErrorHandler) restore_error_handler();
+		
+		if ($this->bExitAllowed)
+			exit();
+	}
+
+	/**			
+	 * Prints the xajax Javascript header and wrapper code into your page by
+	 * printing the output of the getJavascript() method. It should only be
+	 * called between the <pre><head> </head></pre> tags in your HTML page.
+	 * Remember, if you only want to obtain the result of this function, use
+	 * {@link xajax::getJavascript()} instead.
+	 * 
+	 * <i>Usage:</i>
+	 * <code>
+	 *  <head>
+	 *		...
+	 *		< ?php $xajax->printJavascript(); ? >
+	 * </code>
+	 * 
+	 * @param string the relative address of the folder where xajax has been
+	 *               installed. For instance, if your PHP file is
+	 *               "http://www.myserver.com/myfolder/mypage.php"
+	 *               and xajax was installed in
+	 *               "http://www.myserver.com/anotherfolder", then $sJsURI
+	 *               should be set to "../anotherfolder". Defaults to assuming
+	 *               xajax is in the same folder as your PHP file.
+	 * @param string the relative folder/file pair of the xajax Javascript
+	 *               engine located within the xajax installation folder.
+	 *               Defaults to xajax_js/xajax.js.
+	 */
+	function printJavascript($sJsURI="", $sJsFile=NULL)
+	{
+		print $this->getJavascript($sJsURI, $sJsFile);
+	}
+	
+	/**
+	 * Returns the xajax Javascript code that should be added to your HTML page
+	 * between the <kbd><head> </head></kbd> tags.
+	 * 
+	 * <i>Usage:</i>
+	 * <code>
+	 *  < ?php $xajaxJSHead = $xajax->getJavascript(); ? >
+	 *	<head>
+	 *		...
+	 *		< ?php echo $xajaxJSHead; ? >
+	 * </code>
+	 * 
+	 * @param string the relative address of the folder where xajax has been
+	 *               installed. For instance, if your PHP file is
+	 *               "http://www.myserver.com/myfolder/mypage.php"
+	 *               and xajax was installed in
+	 *               "http://www.myserver.com/anotherfolder", then $sJsURI
+	 *               should be set to "../anotherfolder". Defaults to assuming
+	 *               xajax is in the same folder as your PHP file.
+	 * @param string the relative folder/file pair of the xajax Javascript
+	 *               engine located within the xajax installation folder.
+	 *               Defaults to xajax_js/xajax.js.
+	 * @return string
+	 */
+	function getJavascript($sJsURI="", $sJsFile=NULL)
+	{	
+		$html = $this->getJavascriptConfig();
+		$html .= $this->getJavascriptInclude($sJsURI, $sJsFile);
+		
+		return $html;
+	}
+	
+	/**
+	 * Returns a string containing inline Javascript that sets up the xajax
+	 * runtime (typically called internally by xajax from get/printJavascript).
+	 * 
+	 * @return string
+	 */
+	function getJavascriptConfig()
+	{
+		$html  = "\t<script type=\"text/javascript\">\n";
+		$html .= "var xajaxRequestUri=\"".$this->sRequestURI."\";\n";
+		$html .= "var xajaxDebug=".($this->bDebug?"true":"false").";\n";
+		$html .= "var xajaxStatusMessages=".($this->bStatusMessages?"true":"false").";\n";
+		$html .= "var xajaxWaitCursor=".($this->bWaitCursor?"true":"false").";\n";
+		$html .= "var xajaxDefinedGet=".XAJAX_GET.";\n";
+		$html .= "var xajaxDefinedPost=".XAJAX_POST.";\n";
+		$html .= "var xajaxLoaded=false;\n";
+
+		foreach($this->aFunctions as $sFunction => $bExists) {
+			$html .= $this->_wrap($sFunction,$this->aFunctionRequestTypes[$sFunction]);
+		}
+
+		$html .= "\t</script>\n";
+		return $html;		
+	}
+	
+	/**
+	 * Returns a string containing a Javascript include of the xajax.js file
+	 * along with a check to see if the file loaded after six seconds
+	 * (typically called internally by xajax from get/printJavascript).
+	 * 
+	 * @param string the relative address of the folder where xajax has been
+	 *               installed. For instance, if your PHP file is
+	 *               "http://www.myserver.com/myfolder/mypage.php"
+	 *               and xajax was installed in
+	 *               "http://www.myserver.com/anotherfolder", then $sJsURI
+	 *               should be set to "../anotherfolder". Defaults to assuming
+	 *               xajax is in the same folder as your PHP file.
+	 * @param string the relative folder/file pair of the xajax Javascript
+	 *               engine located within the xajax installation folder.
+	 *               Defaults to xajax_js/xajax.js.
+	 * @return string
+	 */
+	function getJavascriptInclude($sJsURI="", $sJsFile=NULL)
+	{
+		if ($sJsFile == NULL) $sJsFile = "xajax_js/xajax.js";
+			
+		if ($sJsURI != "" && substr($sJsURI, -1) != "/") $sJsURI .= "/";
+		
+		$html = "\t<script type=\"text/javascript\" src=\"" . $sJsURI . $sJsFile . "\"></script>\n";	
+		$html .= "\t<script type=\"text/javascript\">\n";
+		$html .= "window.setTimeout(function () { if (!xajaxLoaded) { alert('Error: the xajax Javascript file could not be included. Perhaps the URL is incorrect?\\nURL: {$sJsURI}{$sJsFile}'); } }, 6000);\n";
+		$html .= "\t</script>\n";
+		return $html;
+	}
+
+	/**
+	 * This method can be used to create a new xajax.js file out of the
+	 * xajax_uncompressed.js file (which will only happen if xajax.js doesn't
+	 * already exist on the filesystem).
+	 * 
+	 * @param string an optional argument containing the full server file path
+	 *               of xajax.js.
+	 */
+	function autoCompressJavascript($sJsFullFilename=NULL)
+	{	
+		$sJsFile = "xajax_js/xajax.js";
+		
+		if ($sJsFullFilename) {
+			$realJsFile = $sJsFullFilename;
+		}
+		else {
+			$realPath = realpath(dirname(__FILE__));
+			$realJsFile = $realPath . "/". $sJsFile;
+		}
+
+		// Create a compressed file if necessary
+		if (!file_exists($realJsFile)) {
+			$srcFile = str_replace(".js", "_uncompressed.js", $realJsFile);
+			if (!file_exists($srcFile)) {
+				trigger_error("The xajax uncompressed Javascript file could not be found in the <b>" . dirname($realJsFile) . "</b> folder. Error ", E_USER_ERROR);	
+			}
+			require(dirname(__FILE__)."/xajaxCompress.php");
+			$javaScript = implode('', file($srcFile));
+			$compressedScript = xajaxCompressJavascript($javaScript);
+			$fH = @fopen($realJsFile, "w");
+			if (!$fH) {
+				trigger_error("The xajax compressed javascript file could not be written in the <b>" . dirname($realJsFile) . "</b> folder. Error ", E_USER_ERROR);
+			}
+			else {
+				fwrite($fH, $compressedScript);
+				fclose($fH);
+			}
+		}
+	}
+	
+	/**
+	 * Returns the current URL based upon the SERVER vars.
+	 * 
+	 * @access private
+	 * @return string
+	 */
+	function _detectURI() {
+		$aURL = array();
+
+		// Try to get the request URL
+		if (!empty($_SERVER['REQUEST_URI'])) {
+			$aURL = parse_url($_SERVER['REQUEST_URI']);
+		}
+
+		// Fill in the empty values
+		if (empty($aURL['scheme'])) {
+			if (!empty($_SERVER['HTTP_SCHEME'])) {
+				$aURL['scheme'] = $_SERVER['HTTP_SCHEME'];
+			} else {
+				$aURL['scheme'] = (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off') ? 'https' : 'http';
+			}
+		}
+
+		if (empty($aURL['host'])) {
+			if (!empty($_SERVER['HTTP_HOST'])) {
+				if (strpos($_SERVER['HTTP_HOST'], ':') > 0) {
+					list($aURL['host'], $aURL['port']) = explode(':', $_SERVER['HTTP_HOST']);
+				} else {
+					$aURL['host'] = $_SERVER['HTTP_HOST'];
+				}
+			} else if (!empty($_SERVER['SERVER_NAME'])) {
+				$aURL['host'] = $_SERVER['SERVER_NAME'];
+			} else {
+				print "xajax Error: xajax failed to automatically identify your Request URI.";
+				print "Please set the Request URI explicitly when you instantiate the xajax object.";
+				exit();
+			}
+		}
+
+		if (empty($aURL['port']) && !empty($_SERVER['SERVER_PORT'])) {
+			$aURL['port'] = $_SERVER['SERVER_PORT'];
+		}
+
+		if (empty($aURL['path'])) {
+			if (!empty($_SERVER['PATH_INFO'])) {
+				$sPath = parse_url($_SERVER['PATH_INFO']);
+			} else {
+				$sPath = parse_url($_SERVER['PHP_SELF']);
+			}
+			$aURL['path'] = $sPath['path'];
+			unset($sPath);
+		}
+
+		if (!empty($aURL['query'])) {
+			$aURL['query'] = '?'.$aURL['query'];
+		}
+
+		// Build the URL: Start with scheme, user and pass
+		$sURL = $aURL['scheme'].'://';
+		if (!empty($aURL['user'])) {
+			$sURL.= $aURL['user'];
+			if (!empty($aURL['pass'])) {
+				$sURL.= ':'.$aURL['pass'];
+			}
+			$sURL.= '@';
+		}
+
+		// Add the host
+		$sURL.= $aURL['host'];
+
+		// Add the port if needed
+		if (!empty($aURL['port']) && (($aURL['scheme'] == 'http' && $aURL['port'] != 80) || ($aURL['scheme'] == 'https' && $aURL['port'] != 443))) {
+			$sURL.= ':'.$aURL['port'];
+		}
+
+		// Add the path and the query string
+		$sURL.= $aURL['path'].@$aURL['query'];
+
+		// Clean up
+		unset($aURL);
+		return $sURL;
+	}
+	
+	/**
+	 * Returns true if the function name is associated with an object callback,
+	 * false if not.
+	 * 
+	 * @param string the name of the function
+	 * @access private
+	 * @return boolean
+	 */
+	function _isObjectCallback($sFunction)
+	{
+		if (array_key_exists($sFunction, $this->aObjects)) return true;
+		return false;
+	}
+	
+	/**
+	 * Returns true if the function or object callback can be called, false if
+	 * not.
+	 * 
+	 * @param string the name of the function
+	 * @access private
+	 * @return boolean
+	 */
+	function _isFunctionCallable($sFunction)
+	{
+		if ($this->_isObjectCallback($sFunction)) {
+			if (is_object($this->aObjects[$sFunction][0])) {
+				return method_exists($this->aObjects[$sFunction][0], $this->aObjects[$sFunction][1]);
+			}
+			else {
+				return is_callable($this->aObjects[$sFunction]);
+			}
+		}
+		else {
+			return function_exists($sFunction);
+		}	
+	}
+	
+	/**
+	 * Calls the function, class method, or object method with the supplied
+	 * arguments.
+	 * 
+	 * @param string the name of the function
+	 * @param array  arguments to pass to the function
+	 * @access private
+	 * @return mixed the output of the called function or method
+	 */
+	function _callFunction($sFunction, $aArgs)
+	{
+		if ($this->_isObjectCallback($sFunction)) {
+			$mReturn = call_user_func_array($this->aObjects[$sFunction], $aArgs);
+		}
+		else {
+			$mReturn = call_user_func_array($sFunction, $aArgs);
+		}
+		return $mReturn;
+	}
+	
+	/**
+	 * Generates the Javascript wrapper for the specified PHP function.
+	 * 
+	 * @param string the name of the function
+	 * @param mixed  the request type
+	 * @access private
+	 * @return string
+	 */
+	function _wrap($sFunction,$sRequestType=XAJAX_POST)
+	{
+		$js = "function ".$this->sWrapperPrefix."$sFunction(){return xajax.call(\"$sFunction\", arguments, ".$sRequestType.");}\n";		
+		return $js;
+	}
+
+	/**
+	 * Takes a string containing xajax xjxobj XML or xjxquery XML and builds an
+	 * array representation of it to pass as an argument to the PHP function
+	 * being called.
+	 * 
+	 * @param string the root tag of the XML
+	 * @param string XML to convert
+	 * @access private
+	 * @return array
+	 */
+	function _xmlToArray($rootTag, $sXml)
+	{
+		$aArray = array();
+		$sXml = str_replace("<$rootTag>","<$rootTag>|~|",$sXml);
+		$sXml = str_replace("</$rootTag>","</$rootTag>|~|",$sXml);
+		$sXml = str_replace("<e>","<e>|~|",$sXml);
+		$sXml = str_replace("</e>","</e>|~|",$sXml);
+		$sXml = str_replace("<k>","<k>|~|",$sXml);
+		$sXml = str_replace("</k>","|~|</k>|~|",$sXml);
+		$sXml = str_replace("<v>","<v>|~|",$sXml);
+		$sXml = str_replace("</v>","|~|</v>|~|",$sXml);
+		$sXml = str_replace("<q>","<q>|~|",$sXml);
+		$sXml = str_replace("</q>","|~|</q>|~|",$sXml);
+		
+		$this->aObjArray = explode("|~|",$sXml);
+		
+		$this->iPos = 0;
+		$aArray = $this->_parseObjXml($rootTag);
+        
+		return $aArray;
+	}
+	
+	/**
+	 * A recursive function that generates an array from the contents of
+	 * $this->aObjArray.
+	 * 
+	 * @param string the root tag of the XML
+	 * @access private
+	 * @return array
+	 */
+	function _parseObjXml($rootTag)
+	{
+		$aArray = array();
+		
+		if ($rootTag == "xjxobj")
+		{
+			while(!stristr($this->aObjArray[$this->iPos],"</xjxobj>"))
+			{
+				$this->iPos++;
+				if(stristr($this->aObjArray[$this->iPos],"<e>"))
+				{
+					$key = "";
+					$value = null;
+						
+					$this->iPos++;
+					while(!stristr($this->aObjArray[$this->iPos],"</e>"))
+					{
+						if(stristr($this->aObjArray[$this->iPos],"<k>"))
+						{
+							$this->iPos++;
+							while(!stristr($this->aObjArray[$this->iPos],"</k>"))
+							{
+								$key .= $this->aObjArray[$this->iPos];
+								$this->iPos++;
+							}
+						}
+						if(stristr($this->aObjArray[$this->iPos],"<v>"))
+						{
+							$this->iPos++;
+							while(!stristr($this->aObjArray[$this->iPos],"</v>"))
+							{
+								if(stristr($this->aObjArray[$this->iPos],"<xjxobj>"))
+								{
+									$value = $this->_parseObjXml("xjxobj");
+									$this->iPos++;
+								}
+								else
+								{
+									$value .= $this->aObjArray[$this->iPos];
+									if ($this->bDecodeUTF8Input)
+									{
+										$value = $this->_decodeUTF8Data($value);
+									}
+								}
+								$this->iPos++;
+							}
+						}
+						$this->iPos++;
+					}
+					
+					$aArray[$key]=$value;
+				}
+			}
+		}
+		
+		if ($rootTag == "xjxquery")
+		{
+			$sQuery = "";
+			$this->iPos++;
+			while(!stristr($this->aObjArray[$this->iPos],"</xjxquery>"))
+			{
+				if (stristr($this->aObjArray[$this->iPos],"<q>") || stristr($this->aObjArray[$this->iPos],"</q>"))
+				{
+					$this->iPos++;
+					continue;
+				}
+				$sQuery	.= $this->aObjArray[$this->iPos];
+				$this->iPos++;
+			}
+			
+			parse_str($sQuery, $aArray);
+			if ($this->bDecodeUTF8Input)
+			{
+				foreach($aArray as $key => $value)
+				{
+					$aArray[$key] = $this->_decodeUTF8Data($value);
+				}
+			}
+			// If magic quotes is on, then we need to strip the slashes from the
+			// array values because of the parse_str pass which adds slashes
+			if (get_magic_quotes_gpc() == 1) {
+				$newArray = array();
+				foreach ($aArray as $sKey => $sValue) {
+					if (is_string($sValue))
+						$newArray[$sKey] = stripslashes($sValue);
+					else
+						$newArray[$sKey] = $sValue;
+				}
+				$aArray = $newArray;
+			}
+		}
+		
+		return $aArray;
+	}
+	
+	/**
+	 * Decodes string data from UTF-8 to the current xajax encoding.
+	 * 
+	 * @param string data to convert
+	 * @access private
+	 * @return string converted data
+	 */
+	function _decodeUTF8Data($sData)
+	{
+		$sValue = $sData;
+		if ($this->bDecodeUTF8Input)
+		{
+			$sFuncToUse = NULL;
+			
+			if (function_exists('iconv'))
+			{
+				$sFuncToUse = "iconv";
+			}
+			else if (function_exists('mb_convert_encoding'))
+			{
+				$sFuncToUse = "mb_convert_encoding";
+			}
+			else if ($this->sEncoding == "ISO-8859-1")
+			{
+				$sFuncToUse = "utf8_decode";
+			}
+			else
+			{
+				trigger_error("The incoming xajax data could not be converted from UTF-8", E_USER_NOTICE);
+			}
+			
+			if ($sFuncToUse)
+			{
+				if (is_string($sValue))
+				{
+					if ($sFuncToUse == "iconv")
+					{
+						$sValue = iconv("UTF-8", $this->sEncoding.'//TRANSLIT', $sValue);
+					}
+					else if ($sFuncToUse == "mb_convert_encoding")
+					{
+						$sValue = mb_convert_encoding($sValue, $this->sEncoding, "UTF-8");
+					}
+					else
+					{
+						$sValue = utf8_decode($sValue);
+					}
+				}
+			}
+		}
+		return $sValue;	
+	}
+		
+}// end class xajax 
+
+/**
+ * This function is registered with PHP's set_error_handler() function if
+ * the xajax error handling system is turned on.
+ */
+function xajaxErrorHandler($errno, $errstr, $errfile, $errline)
+{
+	$errorReporting = error_reporting();
+	if (($errno & $errorReporting) == 0) return;
+	
+	if ($errno == E_NOTICE) {
+		$errTypeStr = "NOTICE";
+	}
+	else if ($errno == E_WARNING) {
+		$errTypeStr = "WARNING";
+	}
+	else if ($errno == E_USER_NOTICE) {
+		$errTypeStr = "USER NOTICE";
+	}
+	else if ($errno == E_USER_WARNING) {
+		$errTypeStr = "USER WARNING";
+	}
+	else if ($errno == E_USER_ERROR) {
+		$errTypeStr = "USER FATAL ERROR";
+	}
+	else if ($errno == E_STRICT) {
+		return;
+	}
+	else {
+		$errTypeStr = "UNKNOWN: $errno";
+	}
+	$GLOBALS['xajaxErrorHandlerText'] .= "\n----\n[$errTypeStr] $errstr\nerror in line $errline of file $errfile";
+}
+
+?>
Index: trunk/workflow/inc/report/xajax/xajaxCompress.php
===================================================================
--- trunk/workflow/inc/report/xajax/xajaxCompress.php	(revision 5307)
+++ trunk/workflow/inc/report/xajax/xajaxCompress.php	(revision 5307)
@@ -0,0 +1,182 @@
+<?php
+/**
+ * xajaxCompress.php :: function to compress Javascript
+ *
+ * xajax version 0.2.4
+ * copyright (c) 2005 by Jared White & J. Max Wilson
+ * http://www.xajaxproject.org
+ *
+ * xajax is an open source PHP class library for easily creating powerful
+ * PHP-driven, web-based Ajax Applications. Using xajax, you can asynchronously
+ * call PHP functions and update the content of your your webpage without
+ * reloading the page.
+ *
+ * xajax is released under the terms of the LGPL license
+ * http://www.gnu.org/copyleft/lesser.html#SEC3
+ *
+ * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ * 
+ * @package xajax
+ * @version $Id$
+ * @copyright Copyright (c) 2005-2006  by Jared White & J. Max Wilson
+ * @license http://www.gnu.org/copyleft/lesser.html#SEC3 LGPL License
+ */
+
+/**
+ * Compresses the Javascript code for more efficient delivery.
+ * (used internally)
+ * 
+ * @param string contains the Javascript code to compress
+ */
+function xajaxCompressJavascript($sJS)
+{
+	//remove windows cariage returns
+	$sJS = str_replace("\r","",$sJS);
+	
+	//array to store replaced literal strings
+	$literal_strings = array();
+	
+	//explode the string into lines
+	$lines = explode("\n",$sJS);
+	//loop through all the lines, building a new string at the same time as removing literal strings
+	$clean = "";
+	$inComment = false;
+	$literal = "";
+	$inQuote = false;
+	$escaped = false;
+	$quoteChar = "";
+	
+	for($i=0;$i<count($lines);$i++)
+	{
+		$line = $lines[$i];
+		$inNormalComment = false;
+	
+		//loop through line's characters and take out any literal strings, replace them with ___i___ where i is the index of this string
+		for($j=0;$j<strlen($line);$j++)
+		{
+			$c = substr($line,$j,1);
+			$d = substr($line,$j,2);
+	
+			//look for start of quote
+			if(!$inQuote && !$inComment)
+			{
+				//is this character a quote or a comment
+				if(($c=="\"" || $c=="'") && !$inComment && !$inNormalComment)
+				{
+					$inQuote = true;
+					$inComment = false;
+					$escaped = false;
+					$quoteChar = $c;
+					$literal = $c;
+				}
+				else if($d=="/*" && !$inNormalComment)
+				{
+					$inQuote = false;
+					$inComment = true;
+					$escaped = false;
+					$quoteChar = $d;
+					$literal = $d;	
+					$j++;	
+				}
+				else if($d=="//") //ignore string markers that are found inside comments
+				{
+					$inNormalComment = true;
+					$clean .= $c;
+				}
+				else
+				{
+					$clean .= $c;
+				}
+			}
+			else //allready in a string so find end quote
+			{
+				if($c == $quoteChar && !$escaped && !$inComment)
+				{
+					$inQuote = false;
+					$literal .= $c;
+	
+					//subsitute in a marker for the string
+					$clean .= "___" . count($literal_strings) . "___";
+	
+					//push the string onto our array
+					array_push($literal_strings,$literal);
+	
+				}
+				else if($inComment && $d=="*/")
+				{
+					$inComment = false;
+					$literal .= $d;
+	
+					//subsitute in a marker for the string
+					$clean .= "___" . count($literal_strings) . "___";
+	
+					//push the string onto our array
+					array_push($literal_strings,$literal);
+	
+					$j++;
+				}
+				else if($c == "\\" && !$escaped)
+					$escaped = true;
+				else
+					$escaped = false;
+	
+				$literal .= $c;
+			}
+		}
+		if($inComment) $literal .= "\n";
+		$clean .= "\n";
+	}
+	//explode the clean string into lines again
+	$lines = explode("\n",$clean);
+	
+	//now process each line at a time
+	for($i=0;$i<count($lines);$i++)
+	{
+		$line = $lines[$i];
+	
+		//remove comments
+		$line = preg_replace("/\/\/(.*)/","",$line);
+	
+		//strip leading and trailing whitespace
+		$line = trim($line);
+	
+		//remove all whitespace with a single space
+		$line = preg_replace("/\s+/"," ",$line);
+	
+		//remove any whitespace that occurs after/before an operator
+		$line = preg_replace("/\s*([!\}\{;,&=\|\-\+\*\/\)\(:])\s*/","\\1",$line);
+	
+		$lines[$i] = $line;
+	}
+	
+	//implode the lines
+	$sJS = implode("\n",$lines);
+	
+	//make sure there is a max of 1 \n after each line
+	$sJS = preg_replace("/[\n]+/","\n",$sJS);
+	
+	//strip out line breaks that immediately follow a semi-colon
+	$sJS = preg_replace("/;\n/",";",$sJS);
+	
+	//curly brackets aren't on their own
+	$sJS = preg_replace("/[\n]*\{[\n]*/","{",$sJS);
+	
+	//finally loop through and replace all the literal strings:
+	for($i=0;$i<count($literal_strings);$i++)
+		$sJS = str_replace("___".$i."___",$literal_strings[$i],$sJS);
+	
+	return $sJS;
+}
+?>
Index: trunk/workflow/inc/hook_sidebox_menu.inc.php
===================================================================
--- trunk/workflow/inc/hook_sidebox_menu.inc.php	(revision 3255)
+++ trunk/workflow/inc/hook_sidebox_menu.inc.php	(revision 5307)
@@ -51,6 +51,8 @@
 		));
 
-	if ($isWorkflowAdmin)
+	if ($isWorkflowAdmin) { 
 		$file['Access Control List']= $GLOBALS['phpgw']->link('/index.php','menuaction=workflow.ui_adminaccess.form');
+		$file['Reports']= $GLOBALS['phpgw']->link('/index.php','menuaction=workflow.reports.form');	
+	}
 
 	/* every user can access the preference area */
