Index: branches/2.5/phpgwapi/setup/tables_baseline.inc.php
===================================================================
--- branches/2.5/phpgwapi/setup/tables_baseline.inc.php	(revision 2)
+++ branches/2.5/phpgwapi/setup/tables_baseline.inc.php	(revision 8232)
@@ -108,5 +108,5 @@
 				'sessionid' => array('type' => 'varchar', 'precision' => 30),
 				'loginid' => array('type' => 'varchar', 'precision' => 30),
-				'ip' => array('type' => 'varchar', 'precision' => 30),
+				'ip' => array('type' => 'varchar', 'precision' => 255),
 				'li' => array('type' => 'int', 'precision' => 4),
 				'lo' => array('type' => 'int', 'precision' => 4)
Index: branches/2.5/phpgwapi/setup/tables_current.inc.php
===================================================================
--- branches/2.5/phpgwapi/setup/tables_current.inc.php	(revision 7917)
+++ branches/2.5/phpgwapi/setup/tables_current.inc.php	(revision 8232)
Index: branches/2.5/phpgwapi/setup/tables_update.inc.php
===================================================================
--- branches/2.5/phpgwapi/setup/tables_update.inc.php	(revision 7917)
+++ branches/2.5/phpgwapi/setup/tables_update.inc.php	(revision 8232)
@@ -20,5 +20,4 @@
 		$GLOBALS['setup_info']['phpgwapi']['currentver'] = '1.0.0.008';
 		return $GLOBALS['setup_info']['phpgwapi']['currentver'];
-
 	}
 	
@@ -28,5 +27,4 @@
 		$GLOBALS['setup_info']['phpgwapi']['currentver'] = '2.0.0.pre-alpha';
 		return $GLOBALS['setup_info']['phpgwapi']['currentver'];
-
 	}
 
@@ -176,21 +174,54 @@
 		return $GLOBALS['setup_info']['phpgwapi']['currentver'];
 	}
-    $test[] = '2.4.2'; 
-    function phpgwapi_upgrade2_4_2() 
-    { 
-            $GLOBALS['setup_info']['phpgwapi']['currentver'] = '2.5.0'; 
-            return $GLOBALS['setup_info']['phpgwapi']['currentver']; 
-    } 
- 
-    $test[] = '2.5.0'; 
-        function phpgwapi_upgrade2_5_0() 
-        { 
-                $GLOBALS['setup_info']['phpgwapi']['currentver'] = '2.5.1'; 
-                global $setup_info,$phpgw_setup; 
-                $phpgw_setup->oProc->query("ALTER TABLE phpgw_access_log ALTER COLUMN ip TYPE character varying(255) "); 
- 
-                return $GLOBALS['setup_info']['phpgwapi']['currentver']; 
-        } 
-     
-
+    $test[] = '2.4.2';
+    function phpgwapi_upgrade2_4_2()
+    {
+        $GLOBALS['setup_info']['phpgwapi']['currentver'] = '2.5.0';
+        return $GLOBALS['setup_info']['phpgwapi']['currentver'];
+    }
+
+    $test[] = '2.5.0';
+	function phpgwapi_upgrade2_5_0()
+	{
+        $GLOBALS['setup_info']['phpgwapi']['currentver'] = '2.5.1';
+        global $setup_info,$phpgw_setup;
+        $phpgw_setup->oProc->query("ALTER TABLE phpgw_access_log ALTER COLUMN ip TYPE character varying(255) ");
+
+        return $GLOBALS['setup_info']['phpgwapi']['currentver'];
+	}
+
+    $test[] = '2.5.1';
+    function phpgwapi_upgrade2_5_1()
+    {
+        global $phpgw_setup;
+
+        $phpgw_setup->oProc->query( 'select * from information_schema.tables where table_name= \'phpgw_vfs\'');
+        if( !$phpgw_setup->oProc->next_record() )
+        {
+            $phpgw_setup->oProc->CreateTable('phpgw_vfs', array(
+                'fd' => array(
+                    'file_id' => array('type' => 'auto','nullable' => False),
+                    'owner_id' => array('type' => 'int','precision' => '4','nullable' => False),
+                    'createdby_id' => array('type' => 'int','precision' => '4'),
+                    'modifiedby_id' => array('type' => 'int','precision' => '4'),
+                    'created' => array('type' => 'timestamp','nullable' => False,'default' => '1970-01-01'),
+                    'modified' => array('type' => 'timestamp'),
+                    'size' => array('type' => 'int','precision' => '4'),
+                    'mime_type' => array('type' => 'varchar','precision' => '64'),
+                    'deleteable' => array('type' => 'char','precision' => '1','default' => 'Y'),
+                    'comment' => array('type' => 'varchar','precision' => '255'),
+                    'app' => array('type' => 'varchar','precision' => '25'),
+                    'directory' => array('type' => 'varchar','precision' => '255'),
+                    'name' => array('type' => 'varchar','precision' => '128','nullable' => False),
+                    'link_directory' => array('type' => 'varchar','precision' => '255'),
+                    'link_name' => array('type' => 'varchar','precision' => '128'),
+                    'version' => array('type' => 'varchar','precision' => '30','nullable' => False,'default' => '0.0.0.0'),
+                    'content' => array('type' => 'longtext')
+                )
+            ));
+        }
+
+        $GLOBALS['setup_info']['phpgwapi']['currentver'] = '2.5.1.0';
+        return $GLOBALS['setup_info']['phpgwapi']['currentver'];
+    }
 ?>
Index: branches/2.5/phpgwapi/setup/setup.inc.php
===================================================================
--- branches/2.5/phpgwapi/setup/setup.inc.php	(revision 7917)
+++ branches/2.5/phpgwapi/setup/setup.inc.php	(revision 8232)
@@ -14,6 +14,6 @@
 	$setup_info['phpgwapi']['name']      = 'phpgwapi';
 	$setup_info['phpgwapi']['title']     = 'API';
-	$setup_info['phpgwapi']['version']   = '2.5.1';
-	$setup_info['phpgwapi']['versions']['current_header'] = '2.5.0';
+	$setup_info['phpgwapi']['version']   = '2.5.1.0';
+	$setup_info['phpgwapi']['versions']['current_header'] = '2.5.1';
 	$setup_info['phpgwapi']['enable']    = 3;
 	$setup_info['phpgwapi']['app_order'] = 1;
@@ -41,6 +41,2 @@
 	$setup_info['phpgwapi']['tables'][]  = 'phpgw_history_log';
 	$setup_info['phpgwapi']['tables'][]  = 'phpgw_async';
-
-
-
-
Index: branches/2.5/phpgwapi/inc/class.preferences.inc.php
===================================================================
--- branches/2.5/phpgwapi/inc/class.preferences.inc.php	(revision 7655)
+++ branches/2.5/phpgwapi/inc/class.preferences.inc.php	(revision 8232)
@@ -567,5 +567,7 @@
 					$value = $this->db->db_addslashes(serialize($value));	// this addslashes is for the database
 					$app = $this->db->db_addslashes($app);
-
+					if ($this->db->Type == "pgsql" && isset($value['signature'])){
+						$value['signature'] = pg_escape_string($value['signature']);							
+					}
 					$this->db->query($sql = "INSERT INTO phpgw_preferences"
 						. " (preference_owner,preference_app,preference_value)"
Index: branches/2.5/phpgwapi/templates/default/navbar.tpl
===================================================================
--- branches/2.5/phpgwapi/templates/default/navbar.tpl	(revision 4463)
+++ branches/2.5/phpgwapi/templates/default/navbar.tpl	(revision 8232)
@@ -87,5 +87,5 @@
 
 <div class="toolbar" id="toolbar" style="visibility:hidden">
-<table border="0" height="50px" width="100%" cellpadding=0 cellspacing=0><tr>
+<table border="0" height="50px" width="93%" cellpadding=0 cellspacing=0><tr>
 	<td class="logo_expresso">&nbsp;<br></td>
 	<td align="center">
Index: branches/2.5/phpgwapi/templates/default/css/base.css
===================================================================
--- branches/2.5/phpgwapi/templates/default/css/base.css	(revision 5754)
+++ branches/2.5/phpgwapi/templates/default/css/base.css	(revision 8232)
@@ -262,5 +262,6 @@
 .logo_expresso
 {
-	width: 191px;
+	/*width: 191px;*/
+	width: 273px;
 }
 
Index: branches/2.5/phpgwapi/templates/default/css/azul.css
===================================================================
--- branches/2.5/phpgwapi/templates/default/css/azul.css	(revision 7531)
+++ branches/2.5/phpgwapi/templates/default/css/azul.css	(revision 8232)
@@ -154,4 +154,5 @@
 {
 	background: url( ../../../../phpgwapi/templates/default/images/logo_expresso.jpg ) no-repeat 0 3px;
+	/*background: url( ../../../../phpgwapi/templates/default/images/logo_expresso.png ) no-repeat 0 3px;*/
 }
 
@@ -178,4 +179,5 @@
 {
 	background-image: url(../../../../phpgwapi/templates/default/images/back_app.png);
+	/*background-image: url(../../../../phpgwapi/templates/default/images/back_app_1.png);*/
 }
 
@@ -183,4 +185,5 @@
 {
 	background-image: url( ../../../../phpgwapi/templates/default/images/back_app_over.png );
+	/*background-image: url( ../../../../phpgwapi/templates/default/images/back_app_over_1.png );*/	
 }
 
@@ -188,4 +191,5 @@
 {
 	background-image: url( ../../../../phpgwapi/templates/default/images/back_app_out.png );
+	/*background-image: url( ../../../../phpgwapi/templates/default/images/back_app_out_1.png );*/
 }
 
@@ -203,4 +207,5 @@
 {
 	background-image: url( ../../../../phpgwapi/templates/default/images/fundo_topo.png );
+	/*background-image: url( ../../../../phpgwapi/templates/default/images/fundo_topo_2.png );*/	
 }
 
Index: branches/2.5/phpgwapi/templates/news_old/login.css
===================================================================
--- branches/2.5/phpgwapi/templates/news_old/login.css	(revision 8232)
+++ branches/2.5/phpgwapi/templates/news_old/login.css	(revision 8232)
@@ -0,0 +1,223 @@
+body{
+	margin-top: 0;
+	margin-bottom: 0;
+	margin-left: 0;
+	margin-right: 0; 
+	padding-top: 0;
+	padding-bottom: 0;
+	padding-left: 0;
+	padding-right: 0;
+}
+
+a:link,a:visited
+{
+	cursor:pointer;
+	color: #006699; 
+	text-decoration: none;
+}
+
+a:hover,a:active
+{
+	cursor:pointer;
+	color: #ff9933;
+	text-decoration: underline;
+}
+#conteudo {
+        background:url(../../../phpgwapi/templates/news/images/back_pagina.jpg) repeat-x #fff;
+}
+
+#conteudo_corpo{
+        margin:auto 0; width:770px;
+}
+
+#superior {
+        background: url(../../../phpgwapi/templates/news/images/fundo3.jpg) no-repeat top left;
+        height:340px;
+}
+
+#login {
+        text-align:left;
+        position: relative;
+        top: 49px;
+        left: -186px;
+}
+
+#login td {
+        text-align:left;
+}
+
+.login_label {
+        font-family:  Arial, Verdana,Helvetica, sans-serif;
+        font-size: 12px;
+        color: #003366;
+        font-weight: bold;
+}
+
+
+.button {
+        background:url(../../../phpgwapi/templates/news/images/back_botao.jpg) #1F4F7E no-repeat scroll left top;
+        color:#fff;
+        font-family: Arial,Verdana, Helvetica, sans-serif;
+        font-size:12px;
+        padding-top:2px 4px 2px 4px;
+        margin:2px 1px 0pt;
+        border: medium none;
+        font-weight: bold;
+        height:31px;
+        width:83px;
+}
+
+#caixa_login {
+	width: 262px; 
+	left: 30px;
+	position: relative;
+	float: left;
+	background: url("../../../phpgwapi/templates/news/images/corpo.jpg") repeat-y; 
+}
+
+#reflexo {
+	background:url(../../../phpgwapi/templates/news/images/topo_reflexo.jpg) no-repeat center top;	
+}
+
+.button:hover {
+        background:url(../../../phpgwapi/templates/news/images/back_botao_over.jpg) #FD9C0E no-repeat top left;
+        color:#1F4F7E;
+}
+
+#inferior {
+        background: url(../../../phpgwapi/templates/news/images/fundo4.jpg) no-repeat top left;
+        height:146px;
+}
+
+#rodape {
+        text-align:left;
+        width:100%;
+        position: relative;
+        margin:0;
+}
+
+#rodape_login {
+	background: #FFF url("../../../phpgwapi/templates/news/images/rodape.jpg") no-repeat; 
+	height: 41px;
+	clear: both; 
+}
+
+#rodape table {
+        width:250px;
+        font-family:  Arial, Verdana,Helvetica, sans-serif;
+        font-size:11px;
+        color: #666666;
+        text-align:right;
+        margin-left:108px;
+}
+
+#alterna_login {
+	clear: both;
+	text-align: left;
+	padding-left: 11px;
+	padding-top: 5px;
+}
+
+#alterna_login img {
+	margin-right: 5px;
+	vertical-align: middle;
+}
+
+#alterna_login a {
+	color: #fff;
+	font-family: Arial, Verdana, Helvetica, sans-serif;
+	font-size: 11px;
+	font-weight: bold;
+	text-decoration: none;
+	margin: 0px;
+	padding: 0px;
+}
+
+#alterna_login a:hover {
+	color: #fff !important;
+	text-decoration: underline !important;
+}
+
+.ajuda {
+	text-align: left;
+	padding-left: 11px;
+	padding-top: 9px;
+}
+
+.ajuda img {
+	vertical-align: middle;
+}
+
+.ajuda a {
+	font-family: Arial, Verdana, Helvetica, sans-serif;
+	font-size: 11px;
+	color: #FFF !important;
+	margin-top: 10px;
+	margin-left: 11px;
+	font-weight: bold;
+	text-decoration: none;
+}
+
+.ajuda a:hover {
+	text-decoration:underline;
+}
+
+.login_Label {
+	font-family: Verdana, Arial, Helvetica, sans-serif;
+	font-size: 11px;
+	color: #000066;
+	padding-top: 0px;
+	padding-bottom: 3px;
+}
+
+.msgInicial {
+	font-family: Verdana, Arial, Helvetica, sans-serif;
+	height: 15px;
+	font-size: 12px;
+	color: #000066;
+	font-weight: bold;
+	padding-bottom: 13px;
+	padding-left: 0px;
+}
+
+.titulo_login {
+	font-family:  Arial, Verdana,Helvetica, sans-serif;
+	font-size: 14px;
+	color: #85A9CF;
+	font-weight: bold;
+	width:250px;
+	text-transform:uppercase;
+	line-height:22px;
+	padding:2px;
+}
+#news {
+	position:relative;
+	float:left;	
+	left:400px;	
+	top:95px;		
+	width:250px;	
+}
+#news_block {
+	overflow: hidden;
+	width:250px;
+	height:115px;	
+	font-family:Arial, Helvetica, sans-serif;
+	font-size:12px; 
+	text-align:justify;	
+	background: #fff;
+	border:2px solid #71a8eb;		
+}
+#news_subject{
+	margin:7px 0px 0px 7px;	
+}
+#news_content{
+	margin:7px 7px 0px 7px;
+}
+.news_button_over{
+	cursor:pointer;
+	border:1px solid white;
+		
+}
+.news_button{		
+	border:1px solid transparent;
+}
Index: branches/2.5/phpgwapi/templates/news_old/login.tpl
===================================================================
--- branches/2.5/phpgwapi/templates/news_old/login.tpl	(revision 8232)
+++ branches/2.5/phpgwapi/templates/news_old/login.tpl	(revision 8232)
@@ -0,0 +1,220 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<HTML>
+<!-- BEGIN login_form -->
+<HEAD>
+<META http-equiv="Content-Type" content="text/html; charset={charset}">
+<META name="AUTHOR" content="dGroupWare http://www.eGroupWare.org">
+<META NAME="description" CONTENT="{website_title} login screen, working environment powered by eGroupWare">
+<META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
+<META NAME="keywords" CONTENT="{website_title} login screen, eGroupWare, groupware, groupware suite">
+{login_css}
+<TITLE>{website_title} - {lang_login}</TITLE>
+<script src="./phpgwapi/templates/{template}/js/hash.js" type="text/javascript"></script>
+<script src="./phpgwapi/templates/{template}/js/news.js" type="text/javascript"></script>
+<script language="Javascript">
+<!--
+
+	function setLogin(){
+		if( document.flogin.organization != null)
+			document.flogin.login.value = document.flogin.organization.value+'-'+document.flogin.user.value;
+		else
+			document.flogin.login.value = document.flogin.user.value;			
+	}
+	
+	function getLogin(){
+		var cookie = '{cookie}';
+		if( document.flogin.organization != null)
+			document.flogin.user.value= cookie.substring(cookie.indexOf('-')+1,cookie.length);
+		else	
+			document.flogin.user.value= cookie;
+
+		if(document.flogin.user.value == '') {
+			if(document.flogin.organization != null)
+				document.flogin.organization.focus();
+			else
+				document.flogin.user.focus();
+		}
+		else
+			document.flogin.passwd.focus();
+	}
+	
+ 	function openWindow(newWidth,newHeight,link) {					
+		newScreenX  = screen.width - newWidth;	
+		newScreenY  = 0;		
+		Window1=window.open('{dir_root}'+link,'',"width="+newWidth+",height="+newHeight+",screenX="+newScreenX+",left="+newScreenX+",screenY="+newScreenY+",top="+newScreenY+",toolbar=no,scrollbars=yes,resizable=no");
+	}
+        var opened = false, vkb = null, text = null; 
+        var userstr = navigator.userAgent.toLowerCase(); 
+        var safari = (userstr.indexOf('applewebkit') != -1); 
+        var gecko  = (userstr.indexOf('gecko') != -1) && !safari; 
+        function loadvkbd(){ 
+                if(typeof(VKeyboard) == 'function') 
+                        keyb_change(); 
+                else 
+                { 
+                        vkbdscript=document.createElement('SCRIPT'); 
+                        vkbdscript.src="phpgwapi/js/jscode/vkboards.js"; 
+                        vkbdscript.onload = keyb_change; 
+                        if(gecko || window.opera || safari) 
+                                vkbdscript.onload = keyb_change; 
+                        else 
+                                setTimeout('keyb_change()',3000);  
+                        document.body.appendChild(vkbdscript); 
+                } 
+        } 
+ 
+   var opened = false, vkb = null, text = null; 
+ 
+   function keyb_change() 
+   { 
+     opened = !opened; 
+ 
+     if(opened && !vkb) 
+     { 
+       vkb = new VKeyboard("keyboard",    // container's id 
+                           keyb_callback, // reference to the callback function 
+                           false,          // create the arrow keys or not? (this and the following params are optional) 
+                           false,          // create up and down arrow keys?  
+                           false,         // reserved 
+                           false,          // create the numpad or not? 
+                           "",            // font name ("" == system default) 
+                           "14px",        // font size in px 
+                           "#FFF",        // font color 
+                           "#F00",        // font color for the dead keys 
+                           "#83a6ce",        // keyboard base background color 
+                           "#28599e",        // keys' background color 
+                           "#DDD",        // background color of switched/selected item 
+                           "#777",        // border color 
+                           "#CCC",        // border/font color of "inactive" key (key with no value/disabled) 
+                           "#83a6ce",        // background color of "inactive" key (key with no value/disabled) 
+                           "#F77",        // border color of the language selector's cell 
+                           true,          // show key flash on click? (false by default) 
+                           "#CC3300",     // font color during flash 
+                           "#FF9966",     // key background color during flash 
+                           "#CC3300",     // key border color during flash 
+                           false,         // embed VKeyboard into the page? 
+                           true,          // use 1-pixel gap between the keys? 
+                           0);            // index(0-based) of the initial layout 
+     } 
+     else 
+       vkb.Show(opened); 
+ 
+     text = document.getElementById("passwd"); 
+     text.focus(); 
+     if (!(gecko || window.opera || safari)) 
+     { 
+        document.getElementById('keyboard').style.left = "0px"; 
+        document.getElementById('rodape').style.zIndex="-100"; 
+     } 
+ 
+   } 
+   // Callback function: 
+   function keyb_callback(ch) 
+   { 
+     var val = text.value; 
+ 
+     switch(ch) 
+     { 
+       case "BackSpace": 
+         var min = (val.charCodeAt(val.length - 1) == 10) ? 2 : 1; 
+         text.value = val.substr(0, val.length - min); 
+         break; 
+ 
+       case "Enter": 
+         document.getElementById('loginForm').submit(); 
+         break; 
+ 
+       default: 
+         text.value += ch; 
+     } 
+   } 
+ function setRange(ctrl, start, end){ 
+ } 	
+ var news = new News({public_news});
+	-->
+</script>
+</HEAD>
+<body scroll="no"  style="overflow:hidden" onLoad="javascript:getLogin();news.start(4000)" bgcolor="#ffffff">
+<form id="loginForm" name="flogin" method="post" action="{login_url}" {autocomplete}>
+<div id="conteudo">
+<div style="position: absolute; top:0px; right: 10px;"><span class="login_label">{lang_language}&nbsp;&nbsp;</span>{select_language}</div>
+<div align="center">
+	<div id="conteudo_corpo">
+		<div id="superior">
+			<div id="news">
+				<div id="news_block">				
+					<b><div id="news_subject"></div></b><div id="news_content"></div>
+				</div>
+				<img onmouseover="this.className='news_button_over'" onmouseout="this.className='news_button'" class="news_button" onclick="javascript:news.update('previous')" title="{lang_previous}" src="./phpgwapi/templates/{template}/images/player-previous.png"/>
+        	 	<img onmouseover="this.className='news_button_over'" onmouseout="this.className='news_button'" class="news_button" onclick="javascript:news.pause()" title="{lang_pause}" src="./phpgwapi/templates/{template}/images/player-pause.png" id="img_player_pause" />
+        	 	<img onmouseover="this.className='news_button_over'" onmouseout="this.className='news_button'" style="display:none" class="news_button" onclick="javascript:news.pause()" title="{lang_resume}" src="./phpgwapi/templates/{template}/images/player-resume.png" id="img_player_resume" />
+			 	<img onmouseover="this.className='news_button_over'" onmouseout="this.className='news_button'" class="news_button"  onclick="javascript:news.update('next')" title="{lang_next}" src="./phpgwapi/templates/{template}/images/player-next.png"/>			 			
+			</div>
+		<div id="login">
+      <div align="center">
+<input type="hidden" name="passwd_type" value="text">
+<input type="hidden" name="account type" value="u">
+<input type="hidden" name="login">
+<div id="caixa_login">
+          <div id="reflexo">
+           <div class="titulo_login">Expresso Livre</div>
+           <div id="mensagem" class="msgInicial" >{cd}<br>{lang_message}</div>
+	   {action}
+            <div id="conteudo_login" style="display:{show};">{select_organization}
+              <div class="login_label">
+                <label for="usuario">{lang_username}</label>
+                <br />
+                <input class="input" type="text" maxlength="70" size="20" name="user" id="user" value="">
+              </div>
+
+              <div class="login_label">
+                <label for="senha">{lang_password}</label>
+                <br />
+                <input class="input" type="password" maxlength="50" size="20" name="passwd" id="passwd" value="">
+		<div id="keyboard"></div>
+              </div>
+		{captcha}
+      
+              <input value="{lang_login}" name="submitit" class="button" onclick="javascript:setLogin()" type="submit" style="margin-top:10px"/>
+	      <img style="display:{show_kbd};" src="phpgwapi/templates/default/images/keyboard.png" alt="virtualkeyboard" title="virtualkeyboard" onclick="loadvkbd()" /> 
+            </div> 
+			<div id="alterna_login">
+			 {link_alterna_login}
+			</div>
+          </div>
+          <div id="rodape_login">
+	    	<div class="ajuda" style="display:{display_help}">
+				<img src="./phpgwapi/templates/{template}/images/help.png"/>
+				<a title="{lang_help}" target="help" href="./help.php?lang={lang}">{lang_help}</a>
+			</div>
+          </div>
+        </div>
+</form>
+</div>
+</div>
+</div>
+<div id="inferior"><br />
+<div id="rodape">
+<table align="center" cellspacing="0" cellpadding="0" border="0">
+	<tr>
+		<td>
+			<table border="0" cellpadding="0" cellspacing="0" width="300px">
+          		<tbody>
+          			<tr> 
+            			<td>{logo_config}
+				<br><a title="Projeto Expresso Livre" target="_blank" href="http://www.expressolivre.org/">Expresso Livre</a> {version}
+                                {ultima_rev}
+				<br><a title="eGroupWare" target="_blank" href="http://www.egroupware.org/"> Powered by eGroupWare </a></div></td>
+          			</tr>
+        		</tbody>
+        	</table>
+        </td>
+	</tr>
+</table>
+</div>
+</div>
+</div>
+</div>
+</div>
+<div>{applet}</div>
+</body></html>
Index: branches/2.5/phpgwapi/templates/news_old/login_news.php
===================================================================
--- branches/2.5/phpgwapi/templates/news_old/login_news.php	(revision 8232)
+++ branches/2.5/phpgwapi/templates/news_old/login_news.php	(revision 8232)
@@ -0,0 +1,606 @@
+<?php
+	/**************************************************************************\
+	* eGroupWare login                                                         *
+	* http://www.egroupware.org                                                *
+	* Originaly written by Dan Kuykendall <seek3r@phpgroupware.org>            *
+	*                      Joseph Engo    <jengo@phpgroupware.org>             *
+	* Updated by Nilton Emilio Buhrer Neto <niltonneto@celepar.pr.gov.br>      *
+	*  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.                                              *
+	\**************************************************************************/
+
+	function check_logoutcode($code)
+	{
+		switch($code)
+		{
+			case 1:
+				return lang('You have been successfully logged out');
+				
+			case 2:
+				return lang('Sorry, your login has expired');
+				
+			case 4:
+				return lang('Cookies are required to login to this site.');
+				
+			case 5:
+				return '<font color="FF0000">' . lang('Bad login or password') . '</font>';
+
+			case 6:
+				return '<font color="FF0000">' . lang('Your password has expired, and you do not have access to change it') . '</font>';
+				
+			case 98:
+				return '<font color="FF0000">' . lang('Account is expired') . '</font>';
+				
+			case 99:
+				return '<font color="FF0000">' . lang('Blocked, too many attempts(%1)! Retry in %2 minute(s)',$GLOBALS['phpgw_info']['server']['num_unsuccessful_id'],$GLOBALS['phpgw_info']['server']['block_time']) . '</font>';
+			case 200:
+                            //return '<font color="FF0000">' . lang('Invalid code') . '</font>';
+                return '<font color="FF0000">' . lang('Bad login or password') . '</font>';
+			    break;
+			case 10:
+				$GLOBALS['phpgw']->session->phpgw_setcookie('sessionid');
+				$GLOBALS['phpgw']->session->phpgw_setcookie('kp3');
+				$GLOBALS['phpgw']->session->phpgw_setcookie('domain');
+
+				//fix for bug php4 expired sessions bug
+				if($GLOBALS['phpgw_info']['server']['sessions_type'] == 'php4')
+				{
+					$GLOBALS['phpgw']->session->phpgw_setcookie(PHPGW_PHPSESSID);
+				}
+
+				return '<font color="#FF0000">' . lang('Your session could not be verified.') . '</font>';
+				
+			default:
+				return '';
+		}
+	}
+	
+	$ifMobile = false;
+	$browser = CreateObject('phpgwapi.browser');
+	switch ( $browser->get_platform() )
+	{
+		case browser::PLATFORM_IPHONE:
+		case browser::PLATFORM_IPOD:
+		case browser::PLATFORM_IPAD:
+		case browser::PLATFORM_BLACKBERRY:
+		case browser::PLATFORM_NOKIA:
+		case browser::PLATFORM_ANDROID:
+			$ifMobile = true;						
+			break;
+	}
+	
+	if( $ifMobile && $_GET['dont_redirect_if_moble'] != 1 ) 
+	{
+		$GLOBALS['phpgw']->redirect_link('/mobile/login.php');
+	}
+	else
+	{
+	/* Program starts here */
+	if($GLOBALS['phpgw_info']['server']['auth_type'] == 'http' && isset($_SERVER['PHP_AUTH_USER']))
+	{
+		$submit = True;
+		$login  = $_SERVER['PHP_AUTH_USER'];
+		$passwd = $_SERVER['PHP_AUTH_PW'];
+		$passwd_type = 'text';
+	}
+	else
+	{
+		$passwd = $_POST['passwd'];
+		$passwd_type = $_POST['passwd_type'];
+	}
+
+	# Apache + mod_ssl style SSL certificate authentication
+	# Certificate (chain) verification occurs inside mod_ssl
+	if($GLOBALS['phpgw_info']['server']['auth_type'] == 'sqlssl' && isset($_SERVER['SSL_CLIENT_S_DN']) && !isset($_GET['cd']))
+	{
+		# an X.509 subject looks like:
+		# /CN=john.doe/OU=Department/O=Company/C=xx/Email=john@comapy.tld/L=City/
+		# the username is deliberately lowercase, to ease LDAP integration
+		$sslattribs = explode('/',$_SERVER['SSL_CLIENT_S_DN']);
+		# skip the part in front of the first '/' (nothing)
+		while($sslattrib = next($sslattribs))
+		{
+			list($key,$val) = explode('=',$sslattrib);
+			$sslattributes[$key] = $val;
+		}
+
+		if(isset($sslattributes['Email']))
+		{
+			$submit = True;
+
+			# login will be set here if the user logged out and uses a different username with
+			# the same SSL-certificate.
+			if(!isset($_POST['login'])&&isset($sslattributes['Email']))
+			{
+				$login = $sslattributes['Email'];
+				# not checked against the database, but delivered to authentication module
+				$passwd = $_SERVER['SSL_CLIENT_S_DN'];
+			}
+		}
+		unset($key);
+		unset($val);
+		unset($sslattributes);
+	}
+
+    if( isset( $_GET[ 'cd' ] ) && ( $_GET['cd']=='1' || $_GET['cd'] == 10 ) )
+	{
+            $_SESSION['contador'] = 0;
+	}
+
+	if(isset($passwd_type) || $_POST['submitit_x'] || $_POST['submitit_y'] || $submit)
+	{
+        
+	    // Primeiro testa o captcha....se houver......
+            if($GLOBALS['phpgw_info']['server']['captcha']==1)
+              {
+                if($_SESSION['contador'] > $GLOBALS['phpgw_info']['server']['num_badlogin'])
+                    {
+                        if ($_SESSION['CAPTCHAString'] != trim(strtoupper($_POST['codigo'])))
+                                {
+                                        if(!$_GET['cd'])
+                                        {
+                                            $_GET['cd'] = '200';
+                                        }
+                                }
+                        unset($_SESSION['CAPTCHAString']);
+                    }
+              }
+		if($_POST['user']) {
+			if($GLOBALS['phpgw_info']['server']['use_prefix_organization']) {
+				$common = CreateObject('phpgwapi.common');
+				$ldap_conn = $common->ldapConnect();
+				$justthese = array("uid");
+				$filter="(&(phpgwAccountType=u)(uid=".$_POST['user']."))";
+				$ldap_search = ldap_search($ldap_conn, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+				$ldap_info 	 = ldap_get_entries($ldap_conn, $ldap_search);
+				ldap_close($ldap_conn);
+				if ($ldap_info['count'] != 0) {
+					$_POST['login'] = $_POST['user'];
+				}
+			}
+			else
+				$_POST['login'] = $_POST['user'];
+		}
+		if(getenv('REQUEST_METHOD') != 'POST' && $_SERVER['REQUEST_METHOD'] != 'POST' &&
+			!isset($_SERVER['PHP_AUTH_USER']) && !isset($_SERVER['SSL_CLIENT_S_DN']))
+		{
+                        if(!$_GET['cd'])
+                            {
+                                $_GET['cd'] = '5';
+                            }
+		}
+		
+		// don't get login data again when $submit is true
+		if($submit == false)
+		{
+			$login = $_POST['login'];
+		}
+		
+		if(strstr($login,'@') === False && isset($_POST['logindomain']))
+		{
+			$login .= '@' . $_POST['logindomain'];
+		}
+		elseif(!isset($GLOBALS['phpgw_domain'][$GLOBALS['phpgw_info']['user']['domain']]))
+		{
+			$login .= '@'.$GLOBALS['phpgw_info']['server']['default_domain'];
+		}
+		
+		If(!$_GET['cd'])
+			$GLOBALS['sessionid'] = $GLOBALS['phpgw']->session->create(strtolower($login),$passwd,$passwd_type,'u');
+
+		if(!isset($GLOBALS['sessionid']) || ! $GLOBALS['sessionid'])
+		{
+			If(!$_GET['cd']) $_GET['cd'] = $GLOBALS['phpgw']->session->cd_reason;
+		}
+		else
+		{
+			if ($_POST['lang'] && preg_match('/^[a-z]{2}(-[a-z]{2}){0,1}$/',$_POST['lang']) &&
+			    $_POST['lang'] != $GLOBALS['phpgw_info']['user']['preferences']['common']['lang'])
+			{
+				$GLOBALS['phpgw']->preferences->add('common','lang',$_POST['lang'],'session');
+			}
+
+			if(!$GLOBALS['phpgw_info']['server']['disable_autoload_langfiles'])
+			{
+				$GLOBALS['phpgw']->translation->autoload_changed_langfiles();
+			}
+			$forward = isset($_GET['phpgw_forward']) ? urldecode($_GET['phpgw_forward']) : @$_POST['phpgw_forward'];
+			if (!$forward)
+			{
+				$extra_vars['cd'] = 'yes';
+				$forward = '/home.php';
+			}
+			else
+			{
+				list($forward,$extra_vars) = explode('?',$forward,2);
+			}
+		if ($GLOBALS['phpgw_info']['server']['use_https'] != 2)
+			{
+			//Modificacao feita para que o Expresso redirecione para o primeiro proxy caso haja um encadeamento de mais de um proxy.
+			//$forward = 'http://'.$_SERVER['HTTP_HOST'].($GLOBALS['phpgw']->link($forward.'?cd=yes'));
+			$forward = 'http://' . nearest_to_me() . $GLOBALS['phpgw']->link($forward.'?cd=yes');
+			echo "<script language='Javascript1.3'>location.href='".$forward."'</script>";
+			}
+		else
+			{
+			$GLOBALS['phpgw']->redirect_link($forward,$extra_vars);
+			}
+		}
+	}
+	//else   // =================================================================================
+	//{
+            $valor_contador = $_SESSION['contador'];
+            $valor_contador = $valor_contador + 1;
+            $_SESSION['contador'] = $valor_contador;
+		// !!! DONT CHANGE THESE LINES !!!
+		// If there is something wrong with this code TELL ME!
+		// Commenting out the code will not fix it. (jengo)
+		if(isset($_COOKIE['last_loginid']))
+		{
+			$accounts = CreateObject('phpgwapi.accounts');
+			$prefs = CreateObject('phpgwapi.preferences', $accounts->name2id($_COOKIE['last_loginid']));
+
+			if($prefs->account_id)
+			{
+				$GLOBALS['phpgw_info']['user']['preferences'] = $prefs->read_repository();
+			}
+		}
+		
+		$_GET['lang'] = addslashes($_GET['lang']);
+		if ($_GET['lang'])
+		{
+			$GLOBALS['phpgw_info']['user']['preferences']['common']['lang'] = $_GET['lang'];
+		}
+		elseif(!isset($_COOKIE['last_loginid']) || !$prefs->account_id)
+		{
+			// If the lastloginid cookies isn't set, we will default to the first language,
+			// the users browser accepts.
+			list($lang) = explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);
+			/*
+			if(strlen($lang) > 2)
+			{
+				$lang = substr($lang,0,2);
+			}
+			*/
+			$GLOBALS['phpgw_info']['user']['preferences']['common']['lang'] = $lang;
+		}
+		#print 'LANG:' . $GLOBALS['phpgw_info']['user']['preferences']['common']['lang'] . '<br>';
+
+		$GLOBALS['phpgw']->translation->init();	// this will set the language according to the (new) set prefs
+		$GLOBALS['phpgw']->translation->add_app('login');
+		$GLOBALS['phpgw']->translation->add_app('loginscreen');
+		if(lang('loginscreen_message') == 'loginscreen_message*')
+		{
+			$GLOBALS['phpgw']->translation->add_app('loginscreen','en');	// trying the en one
+		}
+		if(lang('loginscreen_message') != 'loginscreen_message*')
+		{
+			$tmpl->set_var('lang_message',stripslashes(lang('loginscreen_message')));
+		}
+	//}
+
+	if($GLOBALS['phpgw_info']['server']['use_prefix_organization'])
+	{
+		$obj_organization = CreateObject('phpgwapi.sector_search_ldap');
+		$organizations = $obj_organization->organization_search($GLOBALS['phpgw_info']['server']['ldap_context']);
+
+        $organizations_count = count($organizations);
+		for ($i=0; $i<$organizations_count; ++$i)
+		{
+			$tmp_array[strtolower($organizations[$i])] = $organizations[$i];	
+		}
+		
+		$arrayOrganization = $tmp_array;		
+		ksort($arrayOrganization);
+		
+		foreach($arrayOrganization
+			 as $organization_name => $organization_vars)
+		{
+			$organization_select .= '<option value="' . $organization_name . '"';
+
+			if($organization_name == $_COOKIE['last_organization'])
+			{
+				$organization_select .= ' selected';
+			}
+			$organization_select .= '>' . $organization_vars . "</option>\n";
+		}
+		$organization_select =  '<div class="login_label"><label>'.lang("organization")
+							.'</label><br><select name="organization">'
+							.$organization_select.'</select></div>';
+		$tmpl->set_var('select_organization',$organization_select);
+	}
+		
+	$domain_select = '&nbsp;';
+	$last_loginid = $_COOKIE['last_loginid'];
+	if($GLOBALS['phpgw_info']['server']['show_domain_selectbox'])
+	{
+		$domain_select = "<select name=\"logindomain\">\n";
+		foreach($GLOBALS['phpgw_domain'] as $domain_name => $domain_vars)
+		{
+			$domain_select .= '<option value="' . $domain_name . '"';
+
+			if($domain_name == $_COOKIE['last_domain'])
+			{
+				$domain_select .= ' selected';
+			}
+			$domain_select .= '>' . $domain_name . "</option>\n";
+		}
+		$domain_select .= "</select>\n";
+	}
+	elseif($last_loginid !== '')
+	{
+		reset($GLOBALS['phpgw_domain']);
+		list($default_domain) = each($GLOBALS['phpgw_domain']);
+
+		if($_COOKIE['last_domain'] != $default_domain && !empty($_COOKIE['last_domain']))
+		{
+			$last_loginid .= '@' . $_COOKIE['last_domain'];
+		}
+	}
+	$tmpl->set_var('select_domain',$domain_select);
+
+	foreach($_GET as $name => $value)
+	{
+		if(preg_match('/phpgw_/',$name))
+		{
+			$extra_vars .= '&' . $name . '=' . urlencode($value);
+		}
+	}
+
+	if ( is_string( $extra_vars ) )
+	{
+		$extra_vars = '?' . substr($extra_vars,1);
+	}
+
+	/********************************************************\
+	* Check is the registration app is installed, activated  *
+	* And if the register link must be placed                *
+	\********************************************************/
+	
+	$cnf_reg = createobject('phpgwapi.config','registration');
+	$cnf_reg->read_repository();
+	$config_reg = $cnf_reg->config_data;
+
+	if($config_reg['enable_registration']=='True' && $config_reg['register_link']=='True')
+	{
+		$reg_link='&nbsp;<a href="registration/">'.lang('Not a user yet? Register now').'</a><br/>';
+	}
+
+	$template = $GLOBALS['phpgw_info']['login_template_set'];
+	$GLOBALS['phpgw_info']['server']['template_set'] = $template;
+
+	$tmpl->set_var('register_link',$reg_link);
+	$tmpl->set_var('charset',$GLOBALS['phpgw']->translation->charset());
+	$tmpl->set_var('login_url', $GLOBALS['phpgw_info']['server']['webserver_url'] . '/login.php' . $extra_vars);
+	$tmpl->set_var('registration_url',$GLOBALS['phpgw_info']['server']['webserver_url'] . '/registration/');
+	$tmpl->set_var('version',$GLOBALS['phpgw_info']['server']['versions']['phpgwapi']);
+	$tmpl->set_var('cd',check_logoutcode($_GET['cd']));
+	$tmpl->set_var('cookie',$last_loginid);
+
+	$tmpl->set_var('lang_username',lang('username'));
+	$tmpl->set_var('lang_password',lang('password'));
+	$tmpl->set_var('lang_login',lang('login'));
+
+	$tmpl->set_var('website_title', $GLOBALS['phpgw_info']['server']['site_title']);
+	$tmpl->set_var('template_set', $template);
+
+	// loads the template's login.css
+	// and then the theme's login.css (if any)
+	$template_dir = $GLOBALS['phpgw_info']['server']['webserver_url'] . '/phpgwapi/templates/' . $template;
+	$login_dir = $template_dir . '/login.css';
+	$login_css = "<link href='" . $login_dir . "' rel='stylesheet' type='text/css' />";
+	$login_dir = $template_dir . '/themes/' . $GLOBALS['phpgw_info']['user']['preferences']['common']['theme'] . '/login.css';
+	if(file_exists('./'.$login_dir))
+	{
+		$login_css .= "<link href='" . $login_dir . "' rel='stylesheet' type='text/css' />";
+	}
+	$tmpl->set_var('login_css',$login_css);
+
+	$GLOBALS['phpgw']->translation->add_app('loginhelp',$_GET['lang']);
+
+	if(lang('loginhelp_message') != 'loginhelp_message*' && trim(lang('loginhelp_message')) != ""){					
+		$tmpl->set_var('lang_help',lang("Help"));	
+	}
+	else 
+		$tmpl->set_var('display_help','none');
+
+	$tmpl->set_var('bg_color',($GLOBALS['phpgw_info']['server']['login_bg_color']?$GLOBALS['phpgw_info']['server']['login_bg_color']:'FFFFFF'));
+	$tmpl->set_var('bg_color_title',($GLOBALS['phpgw_info']['server']['login_bg_color_title']?$GLOBALS['phpgw_info']['server']['login_bg_color_title']:'486591'));
+
+	if($GLOBALS['phpgw_info']['server']['use_frontend_name'])
+		$tmpl->set_var('frontend_name', " - ".$GLOBALS['phpgw_info']['server']['use_frontend_name']);
+
+	if (substr($GLOBALS['phpgw_info']['server']['login_logo_file'],0,4) == 'http')
+	{
+		$var['logo_file'] = $GLOBALS['phpgw_info']['server']['login_logo_file'];
+	}
+	else
+	{
+		$var['logo_file'] = $GLOBALS['phpgw']->common->image('phpgwapi',$GLOBALS['phpgw_info']['server']['login_logo_file']?$GLOBALS['phpgw_info']['server']['login_logo_file']:'logo');
+	}
+	$var['logo_url'] = $GLOBALS['phpgw_info']['server']['login_logo_url']?$GLOBALS['phpgw_info']['server']['login_logo_url']:'http://www.eGroupWare.org';
+	if (substr($var['logo_url'],0,4) != 'http')
+	{
+		$var['logo_url'] = 'http://'.$var['logo_url'];
+	}
+	$var['logo_title'] = $GLOBALS['phpgw_info']['server']['login_logo_title']?$GLOBALS['phpgw_info']['server']['login_logo_title']:'www.eGroupWare.org';
+	$tmpl->set_var($var);
+
+	if (!@$GLOBALS['phpgw_info']['server']['login_virtual_keyboard']) 
+		$tmpl->set_var('show_kbd','none'); 
+
+	if (@$GLOBALS['phpgw_info']['server']['login_show_language_selection'])
+	{
+		$select_lang = '<select name="lang" onchange="'."location.href=location.href+(location.search?'&':'?')+'lang='+this.value".'">';
+		$langs = $GLOBALS['phpgw']->translation->get_installed_langs();
+		uasort($langs,'strcasecmp');
+		foreach ($langs as $key => $name)	// if we have a translation use it
+		{
+			$select_lang .= "\n\t".'<option value="'.$key.'"'.($key == $GLOBALS['phpgw_info']['user']['preferences']['common']['lang'] ? ' selected="1"' : '').'>'.$name.'</option>';
+		}
+		$select_lang .= "\n</select>\n";
+		$tmpl->set_var(array(
+			'lang_language' => lang('Language'),
+			'select_language' => $select_lang,
+		));
+	}
+	else
+	{
+		$tmpl->set_block('login_form','language_select');
+		$tmpl->set_var('language_select','');
+	}
+
+	$tmpl->set_var('autocomplete', ($GLOBALS['phpgw_info']['server']['autocomplete_login'] ? 'autocomplete="off"' : ''));
+
+	// soh mostra o captcha se for login sem certificado....
+	if($GLOBALS['phpgw_info']['server']['captcha'] && $_GET['cd']!='300' )
+	{
+		$aux_captcha = '<input type="hidden" name="' . session_name() . '"  value="' . session_id() . '" >';
+	//        setcookie(session_name(),base64_encode(session_convert($key_convert . session_id(),$key_convert)),0);
+		if($valor_contador > $GLOBALS['phpgw_info']['server']['num_badlogin'])
+		{
+			$aux_captcha = '<div class="login_label" >
+			   <img id="id_captcha" src="./security/captcha.php?' . session_name() . '=' . session_id() . '" title="'.lang('Security code').'" alt="'.lang('Security code').'" style="position:static;">
+			   <input class="input" type="text" maxlength="50" size="20" name="codigo" id="codigo" value="" >
+			   <input type="hidden" name="' . session_name() . '"  value="' . session_id() . '" >
+			   </div>';
+		}
+	}
+	$tmpl->set_var('captcha',$aux_captcha);
+
+	// Testa se deve incluir applet para login com certificado......
+	if ($_GET['cd']=='300' && $GLOBALS['phpgw_info']['server']['certificado']==1)
+	{
+		//Zera o Cookie contador, responsavel pelo captcha
+		$_SESSION['contador'] = 0;
+		$valor_contador = 0;
+		$link_alterna_login = '<img src="phpgwapi/templates/news/images/warning.gif"/><a href="login.php">' . lang('Access without Digital Certificate') . '</a>';
+		$tmpl->set_var('show','none');
+		$tmpl->set_var('action','<div id="action"><img style="border:0px;margin:31px 0px 58px 0px;" src="phpgwapi/templates/news/images/acao.gif" /></div>');
+		// gera parametro com tokens suportados ....
+		$var_tokens = '';
+		for($ii = 1; $ii < 11; ++$ii)
+		{
+			if($GLOBALS['phpgw_info']['server']['test_token' . $ii . '1'])
+				$var_tokens .= $GLOBALS['phpgw_info']['server']['test_token' . $ii . '1'] . ',';
+		}
+
+		if(!$var_tokens)
+		{
+			$var_tokens = 'ePass2000Lx;/usr/lib/libepsng_p11.so,ePass2000Win;c:/windows/system32/ngp11v211.dll';
+		}
+		$param1 = "
+											'<param name=\"token\" value=\"" . substr($var_tokens,0,strlen($var_tokens)) . "\"> ' +
+										   ";
+		$param2 = "
+											'token=\"" . substr($var_tokens,0,strlen($var_tokens)) . "\" ' +
+										   ";
+
+		$cod_applet =
+
+/*    // com debug ativado
+            '<script type="text/javascript">
+					if (navigator.userAgent.match(\'MSIE\')){
+						document.write(\'<object style="display:yes;width:0;height:0;vertical-align:bottom;" id="login_applet" \' +
+						\'classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"> \' +
+						\'<param name="type" value="application/x-java-applet;version=1.5"> \' +
+						\'<param name="code" value="LoginApplet.class"> \' +
+						\'<param name="locale" value="' . $lang . '"> \' +
+						\'<param name="mayscript" value="true"> \' + '
+						. $param1
+						. ' \'<param name="archive" value="ExpressoCertLogin.jar,ExpressoCert.jar,commons-httpclient-3.1.jar,commons-logging-1.1.1.jar,commons-codec-1.3.jar,bcmail-jdk15-142.jar,mail.jar,activation.jar,bcprov-jdk15-142.jar"> \' +
+                        \'<param name="debug" value="true"> \' +
+						\'</object>\');
+					}
+					else {
+						document.write(\'<embed style="display:yes;width:0;height:0;vertical-align:bottom;" id="login_applet" code="LoginApplet.class" locale="' . $lang . '"\' +
+						\'archive="ExpressoCertLogin.jar,ExpressoCert.jar,commons-httpclient-3.1.jar,commons-logging-1.1.1.jar,commons-codec-1.3.jar,bcmail-jdk15-142.jar,mail.jar,activation.jar,bcprov-jdk15-142.jar" \' + '
+						. $param2
+						. ' \'type="application/x-java-applet;version=1.5" debug= "true" mayscript > \' +
+						\'<noembed> \' +
+						\'No Java Support. \' +
+						\'</noembed> \' +
+						\'</embed> \');
+					}
+				</script>';
+*/
+            // sem debug ativado
+            '<script type="text/javascript">
+					if (navigator.userAgent.match(\'MSIE\')){
+						document.write(\'<object style="display:yes;width:0;height:0;vertical-align:bottom;" id="login_applet" \' +
+						\'classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"> \' +
+						\'<param name="type" value="application/x-java-applet;version=1.5"> \' + 
+                                                \'<param name="codebase" value="/security/">\' +
+						\'<param name="code" value="LoginApplet.class"> \' +
+						\'<param name="locale" value="' . $lang . '"> \' +
+						\'<param name="mayscript" value="true"> \' + ' 
+						. $param1 
+						. ' \'<param name="archive" value="ExpressoCertLogin.jar,ExpressoCert.jar,commons-httpclient-3.1.jar,commons-logging-1.1.1.jar,commons-codec-1.3.jar,bcmail-jdk15-142.jar,mail.jar,activation.jar,bcprov-jdk15-142.jar"> \' +
+						\'</object>\');
+					}
+					else {
+						document.write(\'<embed style="display:yes;width:0;height:0;vertical-align:bottom;" id="login_applet" codebase="/security/" code="LoginApplet.class" locale="' . $lang . '"\' +
+						\'archive="ExpressoCertLogin.jar,ExpressoCert.jar,commons-httpclient-3.1.jar,commons-logging-1.1.1.jar,commons-codec-1.3.jar,bcmail-jdk15-142.jar,mail.jar,activation.jar,bcprov-jdk15-142.jar" \' + '
+						. $param2  
+						. ' \'type="application/x-java-applet;version=1.5" mayscript > \' +
+						\'<noembed> \' +
+						\'No Java Support. \' +
+						\'</noembed> \' +
+						\'</embed> \');
+					}
+				</script>';
+
+
+	}
+
+	else
+	{
+		if($GLOBALS['phpgw_info']['server']['certificado']==1)
+		{
+			$tmpl->set_var('show','yes');
+			$link_alterna_login = '<img src="phpgwapi/templates/news/images/lock1_icon.gif"/><a title="' . lang('Link to use digital certificate') . '" href="login.php?cd=300">' . lang('Logon with my digital certificate') . '</a>';
+		}
+		$tmpl->set_var('lang_username',lang('username'));
+		$tmpl->set_var('action','');
+		$cod_applet = '';
+
+	}
+
+	$tmpl->set_var('applet',$cod_applet);
+	$tmpl->set_var('link_alterna_login',$link_alterna_login);
+		
+	// Load News from NewsAdmin module - BEGIN
+	define('PHPGW_TEMPLATE_DIR','./phpgwapi/templates/'.$GLOBALS['phpgw_info']['login_template_set']);
+	$news = CreateObject('news_admin.uinews');
+	$public_news = $news->bo->get_all_public_news();
+	rsort($public_news);	
+	$newslist = array();
+	foreach($public_news as $i => $news){
+		$newslist[] = array_map('utf8_encode', $news);
+	}
+	$tmpl->set_var('public_news',json_encode($newslist));
+	$tmpl->set_var('lang_previous',lang('Previous'));
+	$tmpl->set_var('lang_next',lang('Next'));
+	$tmpl->set_var('lang_pause',lang('Pause'));
+	$tmpl->set_var('lang_resume',lang('Resume'));
+	
+	// Load News from NewsAdmin module - END
+	
+	$tmpl->set_var('dir_root', 'http://' . nearest_to_me() . '/');
+	if(is_file(dirname( __FILE__ ) . '/../../../infodist/ultima-revisao-svn.php'))
+	include_once(dirname( __FILE__ ) . '/../../../infodist/ultima-revisao-svn.php');
+	if(isset($ultima_revisao)) $tmpl->set_var('ultima_rev','<br>' . $ultima_revisao);
+
+	// Adiciona código personalizado de outro template
+	// que esteja utilizando o login_default.php
+	if(is_file('.'.$template_dir.'/login.inc.php')) {
+		include_once('.'.$template_dir.'/login.inc.php');
+	}
+
+	$tmpl->pfp('loginout','login_form');
+	}
+
+?>
+
Index: branches/2.5/phpgwapi/templates/news_old/js/news.js
===================================================================
--- branches/2.5/phpgwapi/templates/news_old/js/news.js	(revision 8232)
+++ branches/2.5/phpgwapi/templates/news_old/js/news.js	(revision 8232)
@@ -0,0 +1,40 @@
+/****************************************************************************************\
+|************************ 	LOAD NEWS FROM NEWSADMIN MODULE		*************************|
+\****************************************************************************************/
+function News(data){	
+	this.data = new Hash(data);
+	this.delay = 5000;
+	this.timeout = 0;
+}
+
+News.prototype.update = function(direction) {	
+	if(this.data.size() == 0) {
+		document.getElementById("news").style.visibility ="hidden";
+		return true;
+	}	
+	var item = this.data.seek(direction);	
+	document.getElementById("news_subject").innerHTML = item.subject;
+	document.getElementById("news_content").innerHTML = item.content;
+}
+
+News.prototype.start = function(delay){
+	if(delay)
+		this.delay = delay;
+	
+	this.update('next');
+	this.timeout = setTimeout("news.start()",this.delay);
+}
+
+News.prototype.pause = function(){	
+	if(this.timeout){
+		document.getElementById("img_player_pause").style.display = 'none';
+		document.getElementById("img_player_resume").style.display = '';
+		clearTimeout(this.timeout);
+		this.timeout = 0;
+	}
+	else{
+		document.getElementById("img_player_pause").style.display = '';
+		document.getElementById("img_player_resume").style.display = 'none';
+		this.start();
+	}
+}
Index: branches/2.5/phpgwapi/templates/news_old/js/hash.js
===================================================================
--- branches/2.5/phpgwapi/templates/news_old/js/hash.js	(revision 8232)
+++ branches/2.5/phpgwapi/templates/news_old/js/hash.js	(revision 8232)
@@ -0,0 +1,20 @@
+/*********************** HASH PROTOTYPE **************************/
+function Hash(data)	{
+	this.last_item = 0;
+	this.data = data;
+}
+Hash.prototype.size = function(){
+	var _thisObject = this;		
+	var size = 0;
+	for (var i in _thisObject.data)
+       	if(_thisObject.data[i] != null)
+           	size++;    	
+   	return size;	
+}	
+Hash.prototype.seek = function(direction){
+	var _thisObject = this;	
+	_thisObject.last_item = (direction == "previous" ? 
+			(_thisObject.last_item == 0 ? _thisObject.size() - 1 : _thisObject.last_item - 1) : 
+			(_thisObject.last_item == _thisObject.size() -1 ? 0	 : _thisObject.last_item + 1));	
+	return _thisObject.data[_thisObject.last_item];		
+}
Index: branches/2.5/phpgwapi/templates/news/list_images.php
===================================================================
--- branches/2.5/phpgwapi/templates/news/list_images.php	(revision 8232)
+++ branches/2.5/phpgwapi/templates/news/list_images.php	(revision 8232)
@@ -0,0 +1,37 @@
+<?php
+
+$dir = "apresentacao/";
+
+$dh  = opendir($dir);
+
+while (false !== ($filename = readdir($dh)))
+{
+    if( is_file($dir . $filename) )
+    {
+    	$files[] = $filename;
+    }
+}
+
+sort($files);
+
+$conf_ini = parse_ini_file('config_images.ini', true);
+
+for( $i = 0 ; $i < count($files); $i++ )
+{
+	foreach($conf_ini as $ini)
+	{
+		if( $ini['nome'] === $files[$i] )
+		{
+			$filesNew[$i]['nome']	= "phpgwapi/templates/news/" . $dir . $ini['nome'];
+			$filesNew[$i]['texto']	= ( $ini['texto'] ) ? $ini['texto'] : "";
+			$filesNew[$i]['titulo']	= ( $ini['titulo'] ) ? $ini['titulo'] : "";
+			$filesNew[$i]['link']	= ( $ini['link'] ) ? $ini['link'] : "";
+		}
+		else
+			$filesNew[$i]['nome'] = "phpgwapi/templates/news/" . $dir . $files[$i];
+	}
+}
+
+echo json_encode($filesNew);
+
+?>
Index: branches/2.5/phpgwapi/templates/news/login.tpl
===================================================================
--- branches/2.5/phpgwapi/templates/news/login.tpl	(revision 5159)
+++ branches/2.5/phpgwapi/templates/news/login.tpl	(revision 8232)
@@ -1,220 +1,71 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
-<HTML>
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
+<html>
 <!-- BEGIN login_form -->
-<HEAD>
-<META http-equiv="Content-Type" content="text/html; charset={charset}">
-<META name="AUTHOR" content="dGroupWare http://www.eGroupWare.org">
-<META NAME="description" CONTENT="{website_title} login screen, working environment powered by eGroupWare">
-<META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
-<META NAME="keywords" CONTENT="{website_title} login screen, eGroupWare, groupware, groupware suite">
-{login_css}
-<TITLE>{website_title} - {lang_login}</TITLE>
-<script src="./phpgwapi/templates/{template}/js/hash.js" type="text/javascript"></script>
-<script src="./phpgwapi/templates/{template}/js/news.js" type="text/javascript"></script>
-<script language="Javascript">
-<!--
-
-	function setLogin(){
-		if( document.flogin.organization != null)
-			document.flogin.login.value = document.flogin.organization.value+'-'+document.flogin.user.value;
-		else
-			document.flogin.login.value = document.flogin.user.value;			
-	}
-	
-	function getLogin(){
-		var cookie = '{cookie}';
-		if( document.flogin.organization != null)
-			document.flogin.user.value= cookie.substring(cookie.indexOf('-')+1,cookie.length);
-		else	
-			document.flogin.user.value= cookie;
-
-		if(document.flogin.user.value == '') {
-			if(document.flogin.organization != null)
-				document.flogin.organization.focus();
-			else
-				document.flogin.user.focus();
-		}
-		else
-			document.flogin.passwd.focus();
-	}
-	
- 	function openWindow(newWidth,newHeight,link) {					
-		newScreenX  = screen.width - newWidth;	
-		newScreenY  = 0;		
-		Window1=window.open('{dir_root}'+link,'',"width="+newWidth+",height="+newHeight+",screenX="+newScreenX+",left="+newScreenX+",screenY="+newScreenY+",top="+newScreenY+",toolbar=no,scrollbars=yes,resizable=no");
-	}
-        var opened = false, vkb = null, text = null; 
-        var userstr = navigator.userAgent.toLowerCase(); 
-        var safari = (userstr.indexOf('applewebkit') != -1); 
-        var gecko  = (userstr.indexOf('gecko') != -1) && !safari; 
-        function loadvkbd(){ 
-                if(typeof(VKeyboard) == 'function') 
-                        keyb_change(); 
-                else 
-                { 
-                        vkbdscript=document.createElement('SCRIPT'); 
-                        vkbdscript.src="phpgwapi/js/jscode/vkboards.js"; 
-                        vkbdscript.onload = keyb_change; 
-                        if(gecko || window.opera || safari) 
-                                vkbdscript.onload = keyb_change; 
-                        else 
-                                setTimeout('keyb_change()',3000);  
-                        document.body.appendChild(vkbdscript); 
-                } 
-        } 
- 
-   var opened = false, vkb = null, text = null; 
- 
-   function keyb_change() 
-   { 
-     opened = !opened; 
- 
-     if(opened && !vkb) 
-     { 
-       vkb = new VKeyboard("keyboard",    // container's id 
-                           keyb_callback, // reference to the callback function 
-                           false,          // create the arrow keys or not? (this and the following params are optional) 
-                           false,          // create up and down arrow keys?  
-                           false,         // reserved 
-                           false,          // create the numpad or not? 
-                           "",            // font name ("" == system default) 
-                           "14px",        // font size in px 
-                           "#FFF",        // font color 
-                           "#F00",        // font color for the dead keys 
-                           "#83a6ce",        // keyboard base background color 
-                           "#28599e",        // keys' background color 
-                           "#DDD",        // background color of switched/selected item 
-                           "#777",        // border color 
-                           "#CCC",        // border/font color of "inactive" key (key with no value/disabled) 
-                           "#83a6ce",        // background color of "inactive" key (key with no value/disabled) 
-                           "#F77",        // border color of the language selector's cell 
-                           true,          // show key flash on click? (false by default) 
-                           "#CC3300",     // font color during flash 
-                           "#FF9966",     // key background color during flash 
-                           "#CC3300",     // key border color during flash 
-                           false,         // embed VKeyboard into the page? 
-                           true,          // use 1-pixel gap between the keys? 
-                           0);            // index(0-based) of the initial layout 
-     } 
-     else 
-       vkb.Show(opened); 
- 
-     text = document.getElementById("passwd"); 
-     text.focus(); 
-     if (!(gecko || window.opera || safari)) 
-     { 
-        document.getElementById('keyboard').style.left = "0px"; 
-        document.getElementById('rodape').style.zIndex="-100"; 
-     } 
- 
-   } 
-   // Callback function: 
-   function keyb_callback(ch) 
-   { 
-     var val = text.value; 
- 
-     switch(ch) 
-     { 
-       case "BackSpace": 
-         var min = (val.charCodeAt(val.length - 1) == 10) ? 2 : 1; 
-         text.value = val.substr(0, val.length - min); 
-         break; 
- 
-       case "Enter": 
-         document.getElementById('loginForm').submit(); 
-         break; 
- 
-       default: 
-         text.value += ch; 
-     } 
-   } 
- function setRange(ctrl, start, end){ 
- } 	
- var news = new News({public_news});
-	-->
-</script>
-</HEAD>
-<body scroll="no"  style="overflow:hidden" onLoad="javascript:getLogin();news.start(4000)" bgcolor="#ffffff">
-<form id="loginForm" name="flogin" method="post" action="{login_url}" {autocomplete}>
-<div id="conteudo">
-<div style="position: absolute; top:0px; right: 10px;"><span class="login_label">{lang_language}&nbsp;&nbsp;</span>{select_language}</div>
-<div align="center">
-	<div id="conteudo_corpo">
-		<div id="superior">
-			<div id="news">
-				<div id="news_block">				
-					<b><div id="news_subject"></div></b><div id="news_content"></div>
+	<head>
+		<title>{website_title} - {lang_login}</title>
+		<meta http-equiv="Content-Type" content="text/html; charset={charset}">
+		<meta name="AUTHOR" content="dGroupWare http://www.eGroupWare.org">
+		<meta NAME="description" CONTENT="{website_title} login screen, working environment powered by eGroupWare">
+		<meta NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
+		<meta NAME="keywords" CONTENT="{website_title} login screen, eGroupWare, groupware, groupware suite">			
+		<link rel="stylesheet" type="text/css" href="./phpgwapi/templates/news/css/login.css"/>
+		<link rel="stylesheet" type="text/css" href="./prototype/plugins/jquery/jquery-ui.css" />
+		<link rel="stylesheet" type="text/css" href="./prototype/plugins/jquery.keyboard/jquery.keypad.css">		
+		<!-- JavaScript -->
+		<script type="text/javascript" src="./prototype/plugins/jquery/jquery.min.js"></script>
+		<script type="text/javascript" src="./prototype/plugins/jquery/jquery-ui.min.js"></script>
+		<script type="text/javascript" src="./prototype/plugins/jquery/jquery-ui.custom.min.js"></script>
+		<script type="text/javascript" src="./prototype/plugins/ejs/ejs.js"></script>
+		<script type="text/javascript" src="./prototype/plugins/ejs/ejs_production.js"></script>
+		<script type="text/javascript" src="./prototype/plugins/ejs/view.js"></script>
+		<script type="text/javascript" src="./prototype/plugins/jquery.cycle/jquery.cycle.js"></script>
+		<script type="text/javascript" src="./prototype/plugins/jquery.keyboard/jquery.keypad.js"></script>
+		<script type="text/javascript" src="./prototype/plugins/jquery.keyboard/jquery.keypad-pt-BR.js"></script>		
+		<script type="text/javascript" src="./phpgwapi/templates/news/js/slider.js"></script>
+		<script type="text/javascript" src="./phpgwapi/templates/news/js/loginExpresso.js"></script>
+	</head>
+	<body>
+		<div id="container">
+			<div id="main">
+				<div id="login">
+					<h1 id="logo-expresso">Expresso Livre</h1>
+					<form id="loginForm" name="flogin" method="post" action="{login_url}" {autocomplete}>
+						<input type="hidden" name="passwd_type" value="text">
+				      	<input type="hidden" name="account type" value="u">
+				      	<input type="hidden" name="login">
+				      	<input type="hidden" name="show_kbd" value="{show_kbd}">
+				      	<div style="display:{show_organization}">	
+							<label for="organizacao">Organização</label>
+							<select name="organizacao" id="organizacao">{select_organization}</select>
+						</div>
+						<div id="captcha">
+							{captcha}
+						</div>
+						<label for="user">{lang_username}</label>
+						<input type="text" name="user" id="user"  value="{cookie}"/>
+						<label for="passwd">{lang_password}</label>
+						<input type="password" name="passwd" id="passwd" value=""/>
+						<br/>
+						<input type="submit" name="submitit" id="submitit" value="{lang_login}" onclick="loginExpresso.setLogin();" />
+					</form>
+					<div id="keyboard"></div>
+					<div id="msg-login" class="sucesso" style="display:none;">{cd}</div>
 				</div>
-				<img onmouseover="this.className='news_button_over'" onmouseout="this.className='news_button'" class="news_button" onclick="javascript:news.update('previous')" title="{lang_previous}" src="./phpgwapi/templates/{template}/images/player-previous.png"/>
-        	 	<img onmouseover="this.className='news_button_over'" onmouseout="this.className='news_button'" class="news_button" onclick="javascript:news.pause()" title="{lang_pause}" src="./phpgwapi/templates/{template}/images/player-pause.png" id="img_player_pause" />
-        	 	<img onmouseover="this.className='news_button_over'" onmouseout="this.className='news_button'" style="display:none" class="news_button" onclick="javascript:news.pause()" title="{lang_resume}" src="./phpgwapi/templates/{template}/images/player-resume.png" id="img_player_resume" />
-			 	<img onmouseover="this.className='news_button_over'" onmouseout="this.className='news_button'" class="news_button"  onclick="javascript:news.update('next')" title="{lang_next}" src="./phpgwapi/templates/{template}/images/player-next.png"/>			 			
+				<div id="informacao-login"></div>
 			</div>
-		<div id="login">
-      <div align="center">
-<input type="hidden" name="passwd_type" value="text">
-<input type="hidden" name="account type" value="u">
-<input type="hidden" name="login">
-<div id="caixa_login">
-          <div id="reflexo">
-           <div class="titulo_login">Expresso Livre</div>
-           <div id="mensagem" class="msgInicial" >{cd}<br>{lang_message}</div>
-	   {action}
-            <div id="conteudo_login" style="display:{show};">{select_organization}
-              <div class="login_label">
-                <label for="usuario">{lang_username}</label>
-                <br />
-                <input class="input" type="text" maxlength="70" size="20" name="user" id="user" value="">
-              </div>
-
-              <div class="login_label">
-                <label for="senha">{lang_password}</label>
-                <br />
-                <input class="input" type="password" maxlength="50" size="20" name="passwd" id="passwd" value="">
-		<div id="keyboard"></div>
-              </div>
-		{captcha}
-      
-              <input value="{lang_login}" name="submitit" class="button" onclick="javascript:setLogin()" type="submit" style="margin-top:10px"/>
-	      <img style="display:{show_kbd};" src="phpgwapi/templates/default/images/keyboard.png" alt="virtualkeyboard" title="virtualkeyboard" onclick="loadvkbd()" /> 
-            </div> 
-			<div id="alterna_login">
-			 {link_alterna_login}
-			</div>
-          </div>
-          <div id="rodape_login">
-	    	<div class="ajuda" style="display:{display_help}">
-				<img src="./phpgwapi/templates/{template}/images/help.png"/>
-				<a title="{lang_help}" target="help" href="./help.php?lang={lang}">{lang_help}</a>
-			</div>
-          </div>
-        </div>
-</form>
-</div>
-</div>
-</div>
-<div id="inferior"><br />
-<div id="rodape">
-<table align="center" cellspacing="0" cellpadding="0" border="0">
-	<tr>
-		<td>
-			<table border="0" cellpadding="0" cellspacing="0" width="300px">
-          		<tbody>
-          			<tr> 
-            			<td>{logo_config}
-				<br><a title="Projeto Expresso Livre" target="_blank" href="http://www.expressolivre.org/">Expresso Livre</a> {version}
-                                {ultima_rev}
-				<br><a title="eGroupWare" target="_blank" href="http://www.egroupware.org/"> Powered by eGroupWare </a></div></td>
-          			</tr>
-        		</tbody>
-        	</table>
-        </td>
-	</tr>
-</table>
-</div>
-</div>
-</div>
-</div>
-</div>
-<div>{applet}</div>
-</body></html>
+			<center>
+				<div id="footer">
+					<ul id="footer-logos">
+						<li><a href="http://www.pr.gov.br/" class="logo-governo">Governo do Paraná</a></li>
+						<li>
+							<a href="http://www.pr.gov.br/" class="logo-celepar">Celepar - Tecnologia da Informação e Comunicação do Paraná</a>
+							<span id="info-deploy"><a title="Projeto Expresso Livre" target="_blank" href="http://www.expressolivre.org/">Expresso Livre</a>&nbsp;{version} {ultima_rev}<br />Powered by <a title="eGroupWare" target="_blank" href="http://www.egroupware.org/">eGroupWare</a>
+							</span>
+						</li>
+					</ul>
+				</div>
+			</center>
+		</div>
+		<div>{applet}</div>
+	</body>
+</html>
Index: branches/2.5/phpgwapi/templates/news/config_images.ini
===================================================================
--- branches/2.5/phpgwapi/templates/news/config_images.ini	(revision 8232)
+++ branches/2.5/phpgwapi/templates/news/config_images.ini	(revision 8232)
@@ -0,0 +1,10 @@
+[figura1]
+nome=msg_login.png
+titulo=Titulo da Imagem 1
+texto=Texto para acessibilidade da imagem 1
+
+[figura2]
+nome=msg_login2.png
+titulo=Titulo da Imagem 2
+texto=Texto para acessibilidade da imagem 2
+link=http://expresso.pr.gov.br
Index: branches/2.5/phpgwapi/templates/news/css/login.css
===================================================================
--- branches/2.5/phpgwapi/templates/news/css/login.css	(revision 8232)
+++ branches/2.5/phpgwapi/templates/news/css/login.css	(revision 8232)
@@ -0,0 +1,152 @@
+/* Eric Meyer's Reset CSS v2.0 - http://cssreset.com */
+html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark,audio,video{border:0;font-size:100%;font:inherit;vertical-align:baseline;margin:0;padding:0}article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section{display:block}body{line-height:1}ol,ul{list-style:none}blockquote,q{quotes:none}blockquote:before,blockquote:after,q:before,q:after{content:none}table{border-collapse:collapse;border-spacing:0}
+
+body {
+	font:12px Arial, Helvetica, sans-serif;
+	color:#333;
+}
+
+
+
+#main {
+	display:block;
+	height:500px;
+	/*background:url(../images/bg_main_default.jpg) no-repeat center top;*/
+	background:url(../images/bg_main_azul.jpg) no-repeat center top;
+}
+#main #login {
+	display:block;
+	width:284px;
+	min-height:354px;
+	padding:25px;
+	background:#FFF url(../images/bg_box_login.jpg) no-repeat;
+	position:absolute;
+	top:37px;
+	left:50%;
+	margin-left:97px;
+	border:1px solid #CCC;
+	-moz-box-shadow: 0 0 12px #999;
+	-webkit-box-shadow: 0 0 12px #999;
+	box-shadow: 0 0 12px #999;
+	/* For IE 8 */
+	-ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=12, Direction=180, Color='#999999')";
+	/* For IE 5.5 - 7 */
+	filter: progid:DXImageTransform.Microsoft.Shadow(Strength=12, Direction=180, Color='#999999');
+}
+#main #login h1 {
+	display:block;
+	width:278px;
+	height:125px;
+	background:url(../images/logo_expresso_login.png) no-repeat center;
+	overflow:hidden;
+	text-indent:-1000px;
+}
+#main #login label, #main #login input, #main #login select {display:block;clear:both;}
+#main #login label {color:#203184;font-size:1.083em;text-align:left;}
+#main #login #user, #main #login #passwd, #main #login #organizacao {display:block;width:292px;height:35px;padding:5 10px;border:1px solid #BABABA;background:#FFF;color:#666;font-size:1.083em;}
+#main #login #organizacao, #main #login #user {margin-bottom:7px;}
+#main #login #organizacao { padding:5px;}
+#main #login #submitit{display:block;width:77px;height:32px;background:url(../images/bt_login.png) no-repeat;text-indent:-1000px;overflow:hidden;border:none;margin:14px 0;float:left;font-size:0;}
+#main #login .bt-keyboard {display:block;width:32px;height:28px;background:url(../images/icon_teclado.png);text-indent:-1000px;overflow:hidden;float:left;margin:14px 10px;}
+
+#main #login #msg-login {display:block;padding:10px;border:1px solid #333;clear:both;}
+#main #login #msg-login.alerta {color:#D9A300;border-color:#FFDC73;background:#FFFFBF;}
+#main #login #msg-login.erro {color:#9C3030;border-color:#E29494;background:#F5DEDE;}
+#main #login #msg-login.sucesso {color:#0072C5;border-color:#97D2FF;background:#D9EFFF;}
+
+#main #informacao-login {
+	display:block;
+	width:500px;
+	height:424px;
+	overflow:hidden;
+	position:absolute;
+	top:37px;
+	left:50%;
+	margin-left:-448px;
+	z-index:5000;
+}
+#main #informacao-login ul {
+	display:block;
+	width:500px;
+	height:424px;
+}
+#main #informacao-login span {display:block;clear:both;height:0;overflow:hidden;}
+#nav-informacao-login {
+	display: block;
+    height: 12px;
+    left: 50%;
+    margin-left: -448px;
+    position: absolute;
+    top: 472px;
+    z-index: 9999;
+}
+#nav-informacao-login a {
+    display: block;
+    float: left;
+    width: 12px;
+	height: 12px;
+    margin: 0 4px 0 0;
+    overflow: hidden;
+    text-decoration: none;
+	text-indent: -1000px;
+	background:#CCC;
+}
+#nav-informacao-login a.activeSlide {
+    background:#DDD;
+}
+#nav-informacao-login-control.play-pause {
+    background: url("../images/icon_play_pause.png") left top #DFDFDF;
+    float: right;
+    margin-right: 0;
+    text-indent: -1000px;
+	
+	display: block;
+    float: left;
+    width: 12px;
+	height: 12px;
+    margin: 0 4px 0 0;
+    overflow: hidden;
+    text-decoration: none;
+	text-indent: -1000px;
+	position:absolute;
+	top:472px;
+	left:50%;
+	margin-left:48px;
+}
+#nav-informacao-login-control.play {background-position:bottom;}
+#footer {
+	display:block;
+	text-align:center;
+	padding:20px 0;
+	color:#006699;
+	font-size:0.917em;
+}
+#footer ul {
+	display:block;
+	margin:0 auto;
+	width:290px;
+}
+#footer li {
+	float:left;
+	width:130px;
+	text-align:center;
+}
+#footer .logo-governo,
+#footer .logo-celepar {
+	display:block;
+	float:left;
+	overflow:hidden;
+	text-indent:-1000px;
+}
+#footer .logo-governo {
+	width:83px;
+	height:71px;
+	background:url(../images/logo_govparana_83x71.png) no-repeat;
+}
+#footer .logo-celepar {
+	width:104px;
+	height:49px;
+	background:url(../images/logo_celepar_104x49.png) no-repeat;
+	margin:0 10px;
+}
+#footer span {display:block;clear:both;}
Index: branches/2.5/phpgwapi/templates/news/sliderImages.ejs
===================================================================
--- branches/2.5/phpgwapi/templates/news/sliderImages.ejs	(revision 8232)
+++ branches/2.5/phpgwapi/templates/news/sliderImages.ejs	(revision 8232)
@@ -0,0 +1,14 @@
+<li>
+	<%
+	if( link_image )
+	{ %>
+		<a href="<%=link_image%>" target="_blank">
+			<img src="<%=name_image%>" alt="<%=title_image%>" title="<%=title_image%>"/>
+		</a>
+	<% }else{ %>
+		<a href="#" style="cursor: default">
+			<img src="<%=name_image%>" alt="<%=title_image%>" title="<%=title_image%>"/>
+		</a>			
+	<% } %>
+	<span><%=text_image%></span>
+</li>
Index: branches/2.5/phpgwapi/templates/news/logout_code.php
===================================================================
--- branches/2.5/phpgwapi/templates/news/logout_code.php	(revision 8232)
+++ branches/2.5/phpgwapi/templates/news/logout_code.php	(revision 8232)
@@ -0,0 +1,51 @@
+<?php	
+	
+	function check_logoutcode($code)
+	{
+		switch($code)
+		{
+			case 1:
+				return lang('You have been successfully logged out');
+				
+			case 2:
+				return lang('Sorry, your login has expired');
+				
+			case 4:
+				return lang('Cookies are required to login to this site.');
+				
+			case 5:
+				return '<font color="FF0000">' . lang('Bad login or password') . '</font>';
+
+			case 6:
+				return '<font color="FF0000">' . lang('Your password has expired, and you do not have access to change it') . '</font>';
+				
+			case 98:
+				return '<font color="FF0000">' . lang('Account is expired') . '</font>';
+				
+			case 99:
+				return '<font color="FF0000">' . lang('Blocked, too many attempts(%1)! Retry in %2 minute(s)',$GLOBALS['phpgw_info']['server']['num_unsuccessful_id'],$GLOBALS['phpgw_info']['server']['block_time']) . '</font>';
+
+			case 200:
+                            //return '<font color="FF0000">' . lang('Invalid code') . '</font>';
+                return '<font color="FF0000">' . lang('Bad login or password') . '</font>';
+			    break;
+
+			case 10:
+				$GLOBALS['phpgw']->session->phpgw_setcookie('sessionid');
+				$GLOBALS['phpgw']->session->phpgw_setcookie('kp3');
+				$GLOBALS['phpgw']->session->phpgw_setcookie('domain');
+
+				//fix for bug php4 expired sessions bug
+				if($GLOBALS['phpgw_info']['server']['sessions_type'] == 'php4')
+				{
+					$GLOBALS['phpgw']->session->phpgw_setcookie(PHPGW_PHPSESSID);
+				}
+
+				return '<font color="#FF0000">' . lang('Your session could not be verified.') . '</font>';
+				
+			default:
+				return '';
+		}
+	}
+
+?>
Index: branches/2.5/phpgwapi/templates/news/login_news.php
===================================================================
--- branches/2.5/phpgwapi/templates/news/login_news.php	(revision 7681)
+++ branches/2.5/phpgwapi/templates/news/login_news.php	(revision 8232)
@@ -12,70 +12,6 @@
 	\**************************************************************************/
 
-	function check_logoutcode($code)
-	{
-		switch($code)
-		{
-			case 1:
-				return lang('You have been successfully logged out');
-				
-			case 2:
-				return lang('Sorry, your login has expired');
-				
-			case 4:
-				return lang('Cookies are required to login to this site.');
-				
-			case 5:
-				return '<font color="FF0000">' . lang('Bad login or password') . '</font>';
-
-			case 6:
-				return '<font color="FF0000">' . lang('Your password has expired, and you do not have access to change it') . '</font>';
-				
-			case 98:
-				return '<font color="FF0000">' . lang('Account is expired') . '</font>';
-				
-			case 99:
-				return '<font color="FF0000">' . lang('Blocked, too many attempts(%1)! Retry in %2 minute(s)',$GLOBALS['phpgw_info']['server']['num_unsuccessful_id'],$GLOBALS['phpgw_info']['server']['block_time']) . '</font>';
-			case 200:
-                            //return '<font color="FF0000">' . lang('Invalid code') . '</font>';
-                return '<font color="FF0000">' . lang('Bad login or password') . '</font>';
-			    break;
-			case 10:
-				$GLOBALS['phpgw']->session->phpgw_setcookie('sessionid');
-				$GLOBALS['phpgw']->session->phpgw_setcookie('kp3');
-				$GLOBALS['phpgw']->session->phpgw_setcookie('domain');
-
-				//fix for bug php4 expired sessions bug
-				if($GLOBALS['phpgw_info']['server']['sessions_type'] == 'php4')
-				{
-					$GLOBALS['phpgw']->session->phpgw_setcookie(PHPGW_PHPSESSID);
-				}
-
-				return '<font color="#FF0000">' . lang('Your session could not be verified.') . '</font>';
-				
-			default:
-				return '';
-		}
-	}
-	
-	$ifMobile = false;
-	$browser = CreateObject('phpgwapi.browser');
-	switch ( $browser->get_platform() )
-	{
-		case browser::PLATFORM_IPHONE:
-		case browser::PLATFORM_IPOD:
-		case browser::PLATFORM_IPAD:
-		case browser::PLATFORM_BLACKBERRY:
-		case browser::PLATFORM_NOKIA:
-		case browser::PLATFORM_ANDROID:
-			$ifMobile = true;						
-			break;
-	}
-	
-	if( $ifMobile && $_GET['dont_redirect_if_moble'] != 1 ) 
-	{
-		$GLOBALS['phpgw']->redirect_link('/mobile/login.php');
-	}
-	else
-	{
+	require_once "logout_code.php";
+
 	/* Program starts here */
 	if($GLOBALS['phpgw_info']['server']['auth_type'] == 'http' && isset($_SERVER['PHP_AUTH_USER']))
@@ -94,5 +30,5 @@
 	# Apache + mod_ssl style SSL certificate authentication
 	# Certificate (chain) verification occurs inside mod_ssl
-	if($GLOBALS['phpgw_info']['server']['auth_type'] == 'sqlssl' && isset($_SERVER['SSL_CLIENT_S_DN']) && !isset($_GET['cd']))
+	if( $GLOBALS['phpgw_info']['server']['auth_type'] == 'sqlssl' && isset($_SERVER['SSL_CLIENT_S_DN']) && !isset($_GET['cd']) )
 	{
 		# an X.509 subject looks like:
@@ -113,5 +49,5 @@
 			# login will be set here if the user logged out and uses a different username with
 			# the same SSL-certificate.
-			if(!isset($_POST['login'])&&isset($sslattributes['Email']))
+			if( !isset($_POST['login']) && isset($sslattributes['Email']) )
 			{
 				$login = $sslattributes['Email'];
@@ -127,57 +63,66 @@
     if( isset( $_GET[ 'cd' ] ) && ( $_GET['cd']=='1' || $_GET['cd'] == 10 ) )
 	{
-            $_SESSION['contador'] = 0;
-	}
-
-	if(isset($passwd_type) || $_POST['submitit_x'] || $_POST['submitit_y'] || $submit)
-	{
-        
+		$_SESSION['contador_captcha'] = 0;
+	}
+
+	if( isset($passwd_type) || $_POST['submitit_x'] || $_POST['submitit_y'] || $submit )
+	{
 	    // Primeiro testa o captcha....se houver......
-            if($GLOBALS['phpgw_info']['server']['captcha']==1)
-              {
-                if($_SESSION['contador'] > $GLOBALS['phpgw_info']['server']['num_badlogin'])
-                    {
-                        if ($_SESSION['CAPTCHAString'] != trim(strtoupper($_POST['codigo'])))
-                                {
-                                        if(!$_GET['cd'])
-                                        {
-                                            $_GET['cd'] = '200';
-                                        }
-                                }
-                        unset($_SESSION['CAPTCHAString']);
-                    }
-              }
-		if($_POST['user']) {
-			if($GLOBALS['phpgw_info']['server']['use_prefix_organization']) {
-				$common = CreateObject('phpgwapi.common');
-				$ldap_conn = $common->ldapConnect();
-				$justthese = array("uid");
-				$filter="(&(phpgwAccountType=u)(uid=".$_POST['user']."))";
-				$ldap_search = ldap_search($ldap_conn, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
-				$ldap_info 	 = ldap_get_entries($ldap_conn, $ldap_search);
+        if( $GLOBALS['phpgw_info']['server']['captcha'] == 1 )
+		{
+			if( $_SESSION['contador_captcha'] > $GLOBALS['phpgw_info']['server']['num_badlogin'] )
+			{
+				if ($_SESSION['CAPTCHAString'] != trim(strtoupper($_POST['codigo'])))
+				{
+					if(!$_GET['cd'])
+					{
+						$_GET['cd'] = '200';
+					}
+				}
+				
+				unset($_SESSION['CAPTCHAString']);
+			}
+		}
+		
+		if( $_POST['user'] )
+		{
+			if($GLOBALS['phpgw_info']['server']['use_prefix_organization'])
+			{
+				$common		= CreateObject('phpgwapi.common');
+				$ldap_conn	= $common->ldapConnect();
+				$justthese	= array("uid");
+				$filter		= "(&(phpgwAccountType=u)(uid=".$_POST['user']."))";
+				$ldap_search	= ldap_search($ldap_conn, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+				$ldap_info 	 	= ldap_get_entries($ldap_conn, $ldap_search);
+				
 				ldap_close($ldap_conn);
-				if ($ldap_info['count'] != 0) {
+				
+				if( $ldap_info['count'] != 0 )
+				{
 					$_POST['login'] = $_POST['user'];
 				}
 			}
 			else
+			{
 				$_POST['login'] = $_POST['user'];
-		}
+			}
+		}
+		
 		if(getenv('REQUEST_METHOD') != 'POST' && $_SERVER['REQUEST_METHOD'] != 'POST' &&
 			!isset($_SERVER['PHP_AUTH_USER']) && !isset($_SERVER['SSL_CLIENT_S_DN']))
 		{
-                        if(!$_GET['cd'])
-                            {
-                                $_GET['cd'] = '5';
-                            }
+            if(!$_GET['cd'])
+            {
+                $_GET['cd'] = '5';
+            }
 		}
 		
 		// don't get login data again when $submit is true
-		if($submit == false)
+		if( $submit == false )
 		{
 			$login = $_POST['login'];
 		}
 		
-		if(strstr($login,'@') === False && isset($_POST['logindomain']))
+		if( strstr($login,'@') === False && isset($_POST['logindomain']) )
 		{
 			$login .= '@' . $_POST['logindomain'];
@@ -188,8 +133,10 @@
 		}
 		
-		If(!$_GET['cd'])
+		if( !$_GET['cd'] )
+		{
 			$GLOBALS['sessionid'] = $GLOBALS['phpgw']->session->create(strtolower($login),$passwd,$passwd_type,'u');
-
-		if(!isset($GLOBALS['sessionid']) || ! $GLOBALS['sessionid'])
+		}
+
+		if( !isset($GLOBALS['sessionid']) || ! $GLOBALS['sessionid'] )
 		{
 			If(!$_GET['cd']) $_GET['cd'] = $GLOBALS['phpgw']->session->cd_reason;
@@ -197,6 +144,6 @@
 		else
 		{
-			if ($_POST['lang'] && preg_match('/^[a-z]{2}(-[a-z]{2}){0,1}$/',$_POST['lang']) &&
-			    $_POST['lang'] != $GLOBALS['phpgw_info']['user']['preferences']['common']['lang'])
+			if( $_POST['lang'] && preg_match('/^[a-z]{2}(-[a-z]{2}){0,1}$/',$_POST['lang']) &&
+			    $_POST['lang'] != $GLOBALS['phpgw_info']['user']['preferences']['common']['lang'] )
 			{
 				$GLOBALS['phpgw']->preferences->add('common','lang',$_POST['lang'],'session');
@@ -207,6 +154,8 @@
 				$GLOBALS['phpgw']->translation->autoload_changed_langfiles();
 			}
+			
 			$forward = isset($_GET['phpgw_forward']) ? urldecode($_GET['phpgw_forward']) : @$_POST['phpgw_forward'];
-			if (!$forward)
+			
+			if ( !$forward )
 			{
 				$extra_vars['cd'] = 'yes';
@@ -217,76 +166,67 @@
 				list($forward,$extra_vars) = explode('?',$forward,2);
 			}
-		if ($GLOBALS['phpgw_info']['server']['use_https'] != 2)
-			{
-			//Modificacao feita para que o Expresso redirecione para o primeiro proxy caso haja um encadeamento de mais de um proxy.
-			//$forward = 'http://'.$_SERVER['HTTP_HOST'].($GLOBALS['phpgw']->link($forward.'?cd=yes'));
-			$forward = 'http://' . nearest_to_me() . $GLOBALS['phpgw']->link($forward.'?cd=yes');
-			echo "<script language='Javascript1.3'>location.href='".$forward."'</script>";
-			}
-		else
-			{
-			$GLOBALS['phpgw']->redirect_link($forward,$extra_vars);
-			}
-		}
-	}
-	//else   // =================================================================================
-	//{
-            $valor_contador = $_SESSION['contador'];
-            $valor_contador = $valor_contador + 1;
-            $_SESSION['contador'] = $valor_contador;
-		// !!! DONT CHANGE THESE LINES !!!
-		// If there is something wrong with this code TELL ME!
-		// Commenting out the code will not fix it. (jengo)
-		if(isset($_COOKIE['last_loginid']))
-		{
-			$accounts = CreateObject('phpgwapi.accounts');
-			$prefs = CreateObject('phpgwapi.preferences', $accounts->name2id($_COOKIE['last_loginid']));
-
-			if($prefs->account_id)
-			{
-				$GLOBALS['phpgw_info']['user']['preferences'] = $prefs->read_repository();
-			}
-		}
-		
-		$_GET['lang'] = addslashes($_GET['lang']);
-		if ($_GET['lang'])
-		{
-			$GLOBALS['phpgw_info']['user']['preferences']['common']['lang'] = $_GET['lang'];
-		}
-		elseif(!isset($_COOKIE['last_loginid']) || !$prefs->account_id)
-		{
-			// If the lastloginid cookies isn't set, we will default to the first language,
-			// the users browser accepts.
-			list($lang) = explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);
-			/*
-			if(strlen($lang) > 2)
-			{
-				$lang = substr($lang,0,2);
-			}
-			*/
-			$GLOBALS['phpgw_info']['user']['preferences']['common']['lang'] = $lang;
-		}
-		#print 'LANG:' . $GLOBALS['phpgw_info']['user']['preferences']['common']['lang'] . '<br>';
-
-		$GLOBALS['phpgw']->translation->init();	// this will set the language according to the (new) set prefs
-		$GLOBALS['phpgw']->translation->add_app('login');
-		$GLOBALS['phpgw']->translation->add_app('loginscreen');
-		if(lang('loginscreen_message') == 'loginscreen_message*')
-		{
-			$GLOBALS['phpgw']->translation->add_app('loginscreen','en');	// trying the en one
-		}
-		if(lang('loginscreen_message') != 'loginscreen_message*')
-		{
-			$tmpl->set_var('lang_message',stripslashes(lang('loginscreen_message')));
-		}
-	//}
-
-	if($GLOBALS['phpgw_info']['server']['use_prefix_organization'])
-	{
+			
+			if( $GLOBALS['phpgw_info']['server']['use_https'] != 2 )
+			{
+				//Modificacao feita para que o Expresso redirecione para o primeiro proxy caso haja um encadeamento de mais de um proxy.
+				//$forward = 'http://'.$_SERVER['HTTP_HOST'].($GLOBALS['phpgw']->link($forward.'?cd=yes'));
+				$forward = 'http://' . nearest_to_me() . $GLOBALS['phpgw']->link($forward.'?cd=yes');
+				echo "<script language='Javascript1.3'>location.href='".$forward."'</script>";
+			}
+			else
+			{
+				$GLOBALS['phpgw']->redirect_link($forward,$extra_vars);
+			}
+		}
+	}
+
+	// Incrementar Contador para o Uso do Captcha
+    $_SESSION['contador_captcha']++;
+
+	// !!! DONT CHANGE THESE LINES !!!
+	// If there is something wrong with this code TELL ME!
+	// Commenting out the code will not fix it. (jengo)
+	if( isset( $_COOKIE['last_loginid'] ) )
+	{
+		$accounts = CreateObject('phpgwapi.accounts');
+
+		$prefs = CreateObject('phpgwapi.preferences', $accounts->name2id($_COOKIE['last_loginid']));
+
+		if($prefs->account_id)
+		{
+			$GLOBALS['phpgw_info']['user']['preferences'] = $prefs->read_repository();
+		}
+	}
+	
+	$_GET['lang'] = addslashes($_GET['lang']);
+	
+	if ($_GET['lang'])
+	{
+		$GLOBALS['phpgw_info']['user']['preferences']['common']['lang'] = $_GET['lang'];
+	}
+	elseif(!isset($_COOKIE['last_loginid']) || !$prefs->account_id)
+	{
+		// If the lastloginid cookies isn't set, we will default to the first language,
+		// the users browser accepts.
+		list($lang) = explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);
+		$GLOBALS['phpgw_info']['user']['preferences']['common']['lang'] = $lang;
+	}
+
+	$GLOBALS['phpgw']->translation->init();	// this will set the language according to the (new) set prefs
+	$GLOBALS['phpgw']->translation->add_app('login');
+	$GLOBALS['phpgw']->translation->add_app('loginscreen');
+
+	// OUs LDAP
+	$show_Organization = "none";
+	
+	if( $GLOBALS['phpgw_info']['server']['use_prefix_organization'] )
+	{
+		$show_Organization = "block";
+
 		$obj_organization = CreateObject('phpgwapi.sector_search_ldap');
+		
 		$organizations = $obj_organization->organization_search($GLOBALS['phpgw_info']['server']['ldap_context']);
-
-        $organizations_count = count($organizations);
-		for ($i=0; $i<$organizations_count; ++$i)
+		
+		for ($i=0; $i<count($organizations); $i++)
 		{
 			$tmp_array[strtolower($organizations[$i])] = $organizations[$i];	
@@ -294,12 +234,12 @@
 		
 		$arrayOrganization = $tmp_array;		
+		
 		ksort($arrayOrganization);
 		
-		foreach($arrayOrganization
-			 as $organization_name => $organization_vars)
+		foreach($arrayOrganization as $organization_name => $organization_vars)
 		{
 			$organization_select .= '<option value="' . $organization_name . '"';
 
-			if($organization_name == $_COOKIE['last_organization'])
+			if( $organization_name == $_COOKIE['last_organization'] )
 			{
 				$organization_select .= ' selected';
@@ -307,15 +247,18 @@
 			$organization_select .= '>' . $organization_vars . "</option>\n";
 		}
-		$organization_select =  '<div class="login_label"><label>'.lang("organization")
-							.'</label><br><select name="organization">'
-							.$organization_select.'</select></div>';
+
 		$tmpl->set_var('select_organization',$organization_select);
 	}
+
+	$tmpl->set_var( 'show_organization', $show_Organization );
 		
 	$domain_select = '&nbsp;';
+
 	$last_loginid = $_COOKIE['last_loginid'];
-	if($GLOBALS['phpgw_info']['server']['show_domain_selectbox'])
+	
+	if( $GLOBALS['phpgw_info']['server']['show_domain_selectbox'] )
 	{
 		$domain_select = "<select name=\"logindomain\">\n";
+		
 		foreach($GLOBALS['phpgw_domain'] as $domain_name => $domain_vars)
 		{
@@ -333,4 +276,5 @@
 	{
 		reset($GLOBALS['phpgw_domain']);
+		
 		list($default_domain) = each($GLOBALS['phpgw_domain']);
 
@@ -340,9 +284,10 @@
 		}
 	}
+
 	$tmpl->set_var('select_domain',$domain_select);
 
-	foreach($_GET as $name => $value)
-	{
-		if(preg_match('/phpgw_/',$name))
+ 	foreach($_GET as $name => $value)
+	{
+		if(ereg('phpgw_',$name))
 		{
 			$extra_vars .= '&' . $name . '=' . urlencode($value);
@@ -350,5 +295,5 @@
 	}
 
-	if ( is_string( $extra_vars ) )
+	if( is_string( $extra_vars ) )
 	{
 		$extra_vars = '?' . substr($extra_vars,1);
@@ -364,5 +309,5 @@
 	$config_reg = $cnf_reg->config_data;
 
-	if($config_reg['enable_registration']=='True' && $config_reg['register_link']=='True')
+	if($config_reg[enable_registration]=='True' && $config_reg[register_link]=='True')
 	{
 		$reg_link='&nbsp;<a href="registration/">'.lang('Not a user yet? Register now').'</a><br/>';
@@ -370,4 +315,5 @@
 
 	$template = $GLOBALS['phpgw_info']['login_template_set'];
+
 	$GLOBALS['phpgw_info']['server']['template_set'] = $template;
 
@@ -387,69 +333,6 @@
 	$tmpl->set_var('template_set', $template);
 
-	// loads the template's login.css
-	// and then the theme's login.css (if any)
-	$template_dir = $GLOBALS['phpgw_info']['server']['webserver_url'] . '/phpgwapi/templates/' . $template;
-	$login_dir = $template_dir . '/login.css';
-	$login_css = "<link href='" . $login_dir . "' rel='stylesheet' type='text/css' />";
-	$login_dir = $template_dir . '/themes/' . $GLOBALS['phpgw_info']['user']['preferences']['common']['theme'] . '/login.css';
-	if(file_exists('./'.$login_dir))
-	{
-		$login_css .= "<link href='" . $login_dir . "' rel='stylesheet' type='text/css' />";
-	}
-	$tmpl->set_var('login_css',$login_css);
-
-	$GLOBALS['phpgw']->translation->add_app('loginhelp',$_GET['lang']);
-
-	if(lang('loginhelp_message') != 'loginhelp_message*' && trim(lang('loginhelp_message')) != ""){					
-		$tmpl->set_var('lang_help',lang("Help"));	
-	}
-	else 
-		$tmpl->set_var('display_help','none');
-
-	$tmpl->set_var('bg_color',($GLOBALS['phpgw_info']['server']['login_bg_color']?$GLOBALS['phpgw_info']['server']['login_bg_color']:'FFFFFF'));
-	$tmpl->set_var('bg_color_title',($GLOBALS['phpgw_info']['server']['login_bg_color_title']?$GLOBALS['phpgw_info']['server']['login_bg_color_title']:'486591'));
-
-	if($GLOBALS['phpgw_info']['server']['use_frontend_name'])
-		$tmpl->set_var('frontend_name', " - ".$GLOBALS['phpgw_info']['server']['use_frontend_name']);
-
-	if (substr($GLOBALS['phpgw_info']['server']['login_logo_file'],0,4) == 'http')
-	{
-		$var['logo_file'] = $GLOBALS['phpgw_info']['server']['login_logo_file'];
-	}
-	else
-	{
-		$var['logo_file'] = $GLOBALS['phpgw']->common->image('phpgwapi',$GLOBALS['phpgw_info']['server']['login_logo_file']?$GLOBALS['phpgw_info']['server']['login_logo_file']:'logo');
-	}
-	$var['logo_url'] = $GLOBALS['phpgw_info']['server']['login_logo_url']?$GLOBALS['phpgw_info']['server']['login_logo_url']:'http://www.eGroupWare.org';
-	if (substr($var['logo_url'],0,4) != 'http')
-	{
-		$var['logo_url'] = 'http://'.$var['logo_url'];
-	}
-	$var['logo_title'] = $GLOBALS['phpgw_info']['server']['login_logo_title']?$GLOBALS['phpgw_info']['server']['login_logo_title']:'www.eGroupWare.org';
-	$tmpl->set_var($var);
-
-	if (!@$GLOBALS['phpgw_info']['server']['login_virtual_keyboard']) 
-		$tmpl->set_var('show_kbd','none'); 
-
-	if (@$GLOBALS['phpgw_info']['server']['login_show_language_selection'])
-	{
-		$select_lang = '<select name="lang" onchange="'."location.href=location.href+(location.search?'&':'?')+'lang='+this.value".'">';
-		$langs = $GLOBALS['phpgw']->translation->get_installed_langs();
-		uasort($langs,'strcasecmp');
-		foreach ($langs as $key => $name)	// if we have a translation use it
-		{
-			$select_lang .= "\n\t".'<option value="'.$key.'"'.($key == $GLOBALS['phpgw_info']['user']['preferences']['common']['lang'] ? ' selected="1"' : '').'>'.$name.'</option>';
-		}
-		$select_lang .= "\n</select>\n";
-		$tmpl->set_var(array(
-			'lang_language' => lang('Language'),
-			'select_language' => $select_lang,
-		));
-	}
-	else
-	{
-		$tmpl->set_block('login_form','language_select');
-		$tmpl->set_var('language_select','');
-	}
+	// Keyboard Virtual
+	$tmpl->set_var('show_kbd',$GLOBALS['phpgw_info']['server']['login_virtual_keyboard']); 
 
 	$tmpl->set_var('autocomplete', ($GLOBALS['phpgw_info']['server']['autocomplete_login'] ? 'autocomplete="off"' : ''));
@@ -458,29 +341,30 @@
 	if($GLOBALS['phpgw_info']['server']['captcha'] && $_GET['cd']!='300' )
 	{
-		$aux_captcha = '<input type="hidden" name="' . session_name() . '"  value="' . session_id() . '" >';
-	//        setcookie(session_name(),base64_encode(session_convert($key_convert . session_id(),$key_convert)),0);
-		if($valor_contador > $GLOBALS['phpgw_info']['server']['num_badlogin'])
-		{
-			$aux_captcha = '<div class="login_label" >
-			   <img id="id_captcha" src="./security/captcha.php?' . session_name() . '=' . session_id() . '" title="'.lang('Security code').'" alt="'.lang('Security code').'" style="position:static;">
-			   <input class="input" type="text" maxlength="50" size="20" name="codigo" id="codigo" value="" >
-			   <input type="hidden" name="' . session_name() . '"  value="' . session_id() . '" >
-			   </div>';
-		}
-	}
-	$tmpl->set_var('captcha',$aux_captcha);
+		$aux_captcha = '<input type="hidden" name="'.session_name().'"  value="'.session_id().'">';
+
+		if( $_SESSION['contador_captcha'] > $GLOBALS['phpgw_info']['server']['num_badlogin'] )
+		{
+			$aux_captcha = '<div>'
+			   .'<img id="id_captcha" src="./security/captcha.php?' . session_name() . '=' . session_id() . '" title="'.lang('Security code').'" alt="'.lang('Security code').'" style="position:static;">'
+			   .'<input class="input" type="text" maxlength="50" size="15" name="codigo" id="codigo" value="" >'
+			   .'<input type="hidden" name="' . session_name() . '"  value="' . session_id() . '" >'
+			   .'</div>';
+		}
+
+		$tmpl->set_var('captcha',$aux_captcha);
+	}
 
 	// Testa se deve incluir applet para login com certificado......
-	if ($_GET['cd']=='300' && $GLOBALS['phpgw_info']['server']['certificado']==1)
+	if ( $_GET['cd']=='300' && $GLOBALS['phpgw_info']['server']['certificado'] == 1 )
 	{
 		//Zera o Cookie contador, responsavel pelo captcha
-		$_SESSION['contador'] = 0;
-		$valor_contador = 0;
-		$link_alterna_login = '<img src="phpgwapi/templates/news/images/warning.gif"/><a href="login.php">' . lang('Access without Digital Certificate') . '</a>';
+		$_SESSION['contador_captcha'] = 0;
+		$link_alterna_login = '<img src="phpgwapi/templates/default/images/warning.gif"/><a href="login.php">' . lang('Access without Digital Certificate') . '</a>';
 		$tmpl->set_var('show','none');
-		$tmpl->set_var('action','<div id="action"><img style="border:0px;margin:31px 0px 58px 0px;" src="phpgwapi/templates/news/images/acao.gif" /></div>');
+		$tmpl->set_var('action','<div id="action"><img style="border:0px;margin:31px 0px 58px 0px;" src="phpgwapi/templates/default/images/acao.gif" /></div>');
 		// gera parametro com tokens suportados ....
 		$var_tokens = '';
-		for($ii = 1; $ii < 11; ++$ii)
+		
+		for($ii = 1; $ii < 11; $ii++)
 		{
 			if($GLOBALS['phpgw_info']['server']['test_token' . $ii . '1'])
@@ -492,39 +376,9 @@
 			$var_tokens = 'ePass2000Lx;/usr/lib/libepsng_p11.so,ePass2000Win;c:/windows/system32/ngp11v211.dll';
 		}
-		$param1 = "
-											'<param name=\"token\" value=\"" . substr($var_tokens,0,strlen($var_tokens)) . "\"> ' +
-										   ";
-		$param2 = "
-											'token=\"" . substr($var_tokens,0,strlen($var_tokens)) . "\" ' +
-										   ";
+		
+		$param1 = "'<param name=\"token\" value=\"" . substr($var_tokens,0,strlen($var_tokens)) . "\">'+";
+		$param2 = "'token=\"" . substr($var_tokens,0,strlen($var_tokens)) . "\" ' +";
 
 		$cod_applet =
-
-/*    // com debug ativado
-            '<script type="text/javascript">
-					if (navigator.userAgent.match(\'MSIE\')){
-						document.write(\'<object style="display:yes;width:0;height:0;vertical-align:bottom;" id="login_applet" \' +
-						\'classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"> \' +
-						\'<param name="type" value="application/x-java-applet;version=1.5"> \' +
-						\'<param name="code" value="LoginApplet.class"> \' +
-						\'<param name="locale" value="' . $lang . '"> \' +
-						\'<param name="mayscript" value="true"> \' + '
-						. $param1
-						. ' \'<param name="archive" value="ExpressoCertLogin.jar,ExpressoCert.jar,commons-httpclient-3.1.jar,commons-logging-1.1.1.jar,commons-codec-1.3.jar,bcmail-jdk15-142.jar,mail.jar,activation.jar,bcprov-jdk15-142.jar"> \' +
-                        \'<param name="debug" value="true"> \' +
-						\'</object>\');
-					}
-					else {
-						document.write(\'<embed style="display:yes;width:0;height:0;vertical-align:bottom;" id="login_applet" code="LoginApplet.class" locale="' . $lang . '"\' +
-						\'archive="ExpressoCertLogin.jar,ExpressoCert.jar,commons-httpclient-3.1.jar,commons-logging-1.1.1.jar,commons-codec-1.3.jar,bcmail-jdk15-142.jar,mail.jar,activation.jar,bcprov-jdk15-142.jar" \' + '
-						. $param2
-						. ' \'type="application/x-java-applet;version=1.5" debug= "true" mayscript > \' +
-						\'<noembed> \' +
-						\'No Java Support. \' +
-						\'</noembed> \' +
-						\'</embed> \');
-					}
-				</script>';
-*/
             // sem debug ativado
             '<script type="text/javascript">
@@ -553,7 +407,5 @@
 				</script>';
 
-
-	}
-
+	}
 	else
 	{
@@ -561,32 +413,14 @@
 		{
 			$tmpl->set_var('show','yes');
-			$link_alterna_login = '<img src="phpgwapi/templates/news/images/lock1_icon.gif"/><a title="' . lang('Link to use digital certificate') . '" href="login.php?cd=300">' . lang('Logon with my digital certificate') . '</a>';
+			$link_alterna_login = '<img src="phpgwapi/templates/default/images/lock1_icon.gif"/><a title="' . lang('Link to use digital certificate') . '" href="login.php?cd=300">' . lang('Logon with my digital certificate') . '</a>';
 		}
 		$tmpl->set_var('lang_username',lang('username'));
 		$tmpl->set_var('action','');
 		$cod_applet = '';
-
 	}
 
 	$tmpl->set_var('applet',$cod_applet);
 	$tmpl->set_var('link_alterna_login',$link_alterna_login);
-		
-	// Load News from NewsAdmin module - BEGIN
-	define('PHPGW_TEMPLATE_DIR','./phpgwapi/templates/'.$GLOBALS['phpgw_info']['login_template_set']);
-	$news = CreateObject('news_admin.uinews');
-	$public_news = $news->bo->get_all_public_news();
-	rsort($public_news);	
-	$newslist = array();
-	foreach($public_news as $i => $news){
-		$newslist[] = array_map('utf8_encode', $news);
-	}
-	$tmpl->set_var('public_news',json_encode($newslist));
-	$tmpl->set_var('lang_previous',lang('Previous'));
-	$tmpl->set_var('lang_next',lang('Next'));
-	$tmpl->set_var('lang_pause',lang('Pause'));
-	$tmpl->set_var('lang_resume',lang('Resume'));
-	
-	// Load News from NewsAdmin module - END
-	
+
 	$tmpl->set_var('dir_root', 'http://' . nearest_to_me() . '/');
 	if(is_file(dirname( __FILE__ ) . '/../../../infodist/ultima-revisao-svn.php'))
@@ -594,13 +428,12 @@
 	if(isset($ultima_revisao)) $tmpl->set_var('ultima_rev','<br>' . $ultima_revisao);
 
-	// Adiciona código personalizado de outro template
+	// Adiciona cÃ³digo personalizado de outro template
 	// que esteja utilizando o login_default.php
-	if(is_file('.'.$template_dir.'/login.inc.php')) {
+	if(is_file('.'.$template_dir.'/login.inc.php'))
+	{
 		include_once('.'.$template_dir.'/login.inc.php');
 	}
 
 	$tmpl->pfp('loginout','login_form');
-	}
 
 ?>
-
Index: branches/2.5/phpgwapi/templates/news/js/cookieManager.js
===================================================================
--- branches/2.5/phpgwapi/templates/news/js/cookieManager.js	(revision 8232)
+++ branches/2.5/phpgwapi/templates/news/js/cookieManager.js	(revision 8232)
@@ -0,0 +1,50 @@
+/*  Script contendo funcoes de manipulacao de cookies.
+	// baseado em script de Bill Dortch, hIdaho Design <bdortch@hidaho.com> e
+	// adaptado por Jorge Kinoshita.
+*/
+	function getCookieVal (offset) {
+	  var endstr = document.cookie.indexOf (";", offset);
+	  if (endstr == -1)
+	    endstr = document.cookie.length;
+	  return unescape(document.cookie.substring(offset, endstr));
+	}
+	
+	function FixCookieDate (date) {
+	  var base = new Date(0);
+	  var skew = base.getTime(); // dawn of (Unix) time - should be 0
+	  if (skew > 0)  // Except on the Mac - ahead of its time
+	    date.setTime (date.getTime() - skew);
+	}
+	//
+	//  Function to return the value of the cookie specified by "name".
+	//    name - String object containing the cookie name.
+	//    returns - String object containing the cookie value, or null if
+	//      the cookie does not exist.
+	
+	function GetCookie (name) {
+	  var arg = name + "=";
+	  var alen = arg.length;
+	  var clen = document.cookie.length;
+	  var i = 0;
+	  while (i < clen) {
+	    var j = i + alen;
+	    if (document.cookie.substring(i, j) == arg)
+	      return getCookieVal (j);
+	    i = document.cookie.indexOf(" ", i) + 1;
+	    if (i == 0) break; 
+	  }
+
+	  return 'true';
+	}
+		
+	function SetCookie (name,value,expires,path,domain,secure) {
+	  document.cookie = name + "=" + escape (value) +
+    	((expires) ? "; expires=" + expdate.toGMTString() : "") +
+	    ((path) ? "; path=" + path : "") +
+    	((domain) ? "; domain=" + domain : "") +
+	    ((secure) ? "; secure" : "");
+	}	
+	
+	var expdate = new Date ();
+	FixCookieDate (expdate); // Correct for Mac date bug - call only once for given Date object!
+	expdate.setTime (expdate.getTime() + (30 * 24 * 60 * 60 * 1000)); // Valid for 30 days.
Index: branches/2.5/phpgwapi/templates/news/js/pngfix.js
===================================================================
--- branches/2.5/phpgwapi/templates/news/js/pngfix.js	(revision 8232)
+++ branches/2.5/phpgwapi/templates/news/js/pngfix.js	(revision 8232)
@@ -0,0 +1,33 @@
+function correctPNG() // correctly handle PNG transparency in Win IE 5.5 or higher.
+   {
+   for(var i=0; i<document.images.length; i++)
+      {
+	  var img = document.images[i]
+	  var imgName = img.src.toUpperCase()
+	  if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
+	     {
+		 var imgID = (img.id) ? "id='" + img.id + "' " : ""
+		 var imgClass = (img.className) ? "class='" + img.className + "' " : ""
+		 var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
+		 var imgStyle = "display:inline-block;" + img.style.cssText 
+		 var imgAttribs = img.attributes;
+		 for (var j=0; j<imgAttribs.length; j++)
+			{
+			var imgAttrib = imgAttribs[j];
+			if (imgAttrib.nodeName == "align")
+			   {		  
+			   if (imgAttrib.nodeValue == "left") imgStyle = "float:left;" + imgStyle
+			   if (imgAttrib.nodeValue == "right") imgStyle = "float:right;" + imgStyle
+			   break
+			   }
+            }
+		 var strNewHTML = "<span " + imgID + imgClass + imgTitle
+		 strNewHTML += " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
+	     strNewHTML += "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
+		 strNewHTML += "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
+		 img.outerHTML = strNewHTML
+		 i = i-1
+	     }
+      }
+   }
+window.attachEvent("onload", correctPNG);
Index: branches/2.5/phpgwapi/templates/news/js/listUsers.js
===================================================================
--- branches/2.5/phpgwapi/templates/news/js/listUsers.js	(revision 8232)
+++ branches/2.5/phpgwapi/templates/news/js/listUsers.js	(revision 8232)
@@ -0,0 +1,203 @@
+//Funcoes
+	
+	function remUser(){
+		primary_group  = self.document.getElementById('primary_group_list');
+		select = self.document.getElementById('user_list');							
+			
+		for(var i = 0;i < select.options.length; i++) {
+			if(select.options[i].selected) {	
+				if(primary_group != null) {		
+					for(var j = 0;j < primary_group.options.length; j++) {
+						if(primary_group.options[j].value == select.options[i].value) {
+							primary_group.options[j] = null;
+							if(primary_group.options.length > 0)
+								primary_group.options[0].selected = true;
+							
+							break;
+						}
+					}	
+				}	
+				select.options[i--] = null;							
+			}
+		}
+		
+		if(select.options.length)
+			select.options[0].selected = true;					
+	}
+	
+	function remUserAcl(){
+		select = self.document.getElementById('user_list');								
+		for(var i = 0;i < select.options.length; i++)				
+			if(select.options[i].selected){
+				ids = getIds(select.options[i].value);
+				for(j = 0; j < ids.length; j++)
+					document.getElementById(ids[j]).disabled = true;
+				
+				select.options[i--] = null;
+			}
+		
+		if(select.options.length)
+			select.options[0].selected = true;			
+		
+		execAction('LOAD');
+	}
+	
+	function openListUsers(newWidth,newHeight,currentApp,type){			
+		
+		newScreenX  = screen.width - newWidth;		
+		newScreenY  = 0;
+
+		window.open('phpgwapi/templates/default/listUsers.php?'+(type == 'g' ? 'type=g&' : '')+'currentApp='+currentApp,"","width="+newWidth+",height="+newHeight+",screenX="+newScreenX+",left="+newScreenX+",screenY="+newScreenY+",top="+newScreenY+",status=1,toolbar=no,scrollbars=yes,resizable=no");
+		
+	}
+											
+	function execAction(action){
+								
+		if(!window.opener)				
+			doc = window.document;
+		else
+			doc = window.opener.document;
+		
+		select = doc.getElementById('user_list');					
+		checkAttr = doc.formAcl.checkAttr;												
+		for(i = 0; i < select.length; i++) {					
+			if(select.options[i].selected){
+				ids = getIds(select.options[i].value);
+											
+				for(j = 0; j < ids.length; j++){										
+					
+					if(action == 'SAVE') {
+						doc.getElementById(ids[j]).disabled = !checkAttr[j].checked;
+					}					
+					if(action == 'LOAD') {
+						
+						checkAttr[j].checked = !doc.getElementById(ids[j]).disabled;
+					}
+				}													
+			}			
+		}
+		
+		if(!select.length)
+			for(j = 0; j < checkAttr.length; j++)
+				checkAttr[j].disabled = true;
+				
+		else		
+			for(j = 0; j < checkAttr.length; j++)
+				checkAttr[j].disabled = false;
+			
+	}
+		
+	function getIds(value){
+			
+		ids = new Array();
+		ids[0] = value + '_1]' ;
+		ids[1] = value + '_2]' ;
+		ids[2] = value + '_4]' ;
+		ids[3] = value + '_8]' ;
+		ids[4] = value + '_16]';
+		
+		return ids;
+	}
+
+	
+ 	function optionFinder(oText) {				 		 													
+
+		for(var i = 0;i < select.options.length; i++)				
+			select.options[i--] = null;
+																							
+		for(i = 0; i < users.length; i++)
+																							
+			if(users[i].text.substring(0 ,oText.value.length).toUpperCase() == oText.value.toUpperCase() ||
+				(users[i].text.substring(0 ,3) == '(G)' &&
+				users[i].text.substring(4 ,4+oText.value.length).toUpperCase() == oText.value.toUpperCase())) {																					
+				sel = select.options;						
+				option = new Option(users[i].text,users[i].value);
+				option.onclick = users[i].onclick;				
+				sel[sel.length] = option;
+			 
+			}										  		
+ 	}			 
+ 
+ 
+ 	function addUser() {
+		var select = window.document.getElementById('user_list_in');
+		var selectOpener = window.opener.document.getElementById('user_list');
+	
+		var primary_group  = window.opener.document.getElementById('primary_group_list');
+
+		if(document.all)
+			primary_group  = window.opener.document.all['primary_group_list'];
+		
+		for (i = 0 ; i < select.length ; i++) {				
+
+			if (select.options[i].selected) {
+				isSelected = false;
+
+				for(var j = 0;j < selectOpener.options.length; j++) {																			
+					if(selectOpener.options[j].value == select.options[i].value){
+						isSelected = true;						
+						break;	
+					}
+				}
+
+				if(!isSelected){
+
+					option = window.opener.document.createElement('option');
+					option.value =select.options[i].value;
+					option.text = select.options[i].text;
+					selectOpener.options[selectOpener.options.length] = option;	
+					if(primary_group != null) {
+						primary_group.options[primary_group.options.length] = window.opener.document.createElement('option');
+						primary_group.options[primary_group.options.length - 1].value =select.options[i].value;
+						primary_group.options[primary_group.options.length - 1].text = select.options[i].text;
+					}
+					
+				}
+				
+			}
+		}
+		
+		selectOpener.options[selectOpener.options.length-1].selected = true;
+ 	}				
+ 	
+ 	function addUserAcl() {
+		var select = window.document.getElementById('user_list_in');
+		var selectOpener = window.opener.document.getElementById('user_list');
+		for (i = 0 ; i < select.length ; i++) {				
+
+			if (select.options[i].selected) {
+				isSelected = false;
+
+				for(var j = 0;j < selectOpener.options.length; j++) {																			
+					if(selectOpener.options[j].value == select.options[i].value){
+						isSelected = true;						
+						break;	
+					}
+				}
+
+				if(!isSelected){
+
+					option = window.opener.document.createElement('option');
+					option.value =select.options[i].value;
+					option.text = select.options[i].text;
+					if( option.value.charAt(0) == 'g' )
+						option.text = "(G) "+option.text;
+					selectOpener.options[selectOpener.options.length] = option;	
+					
+					ids = getIds(select.options[i].value);
+					for(k = 0; k < ids.length; k++) {															
+						el = window.opener.document.createElement('input');
+						el.type='hidden';
+						el.value ='Y';
+						el.name = ids[k];
+						el.disabled = true;						
+						el.id = ids[k];
+						window.opener.document.getElementById("tdHiddens").appendChild(el);
+					}
+				}
+				
+			}
+		}
+		selectOpener.options[selectOpener.options.length-1].selected = true;
+		execAction('LOAD');
+ 	} 	
Index: branches/2.5/phpgwapi/templates/news/js/loginExpresso.js
===================================================================
--- branches/2.5/phpgwapi/templates/news/js/loginExpresso.js	(revision 8232)
+++ branches/2.5/phpgwapi/templates/news/js/loginExpresso.js	(revision 8232)
@@ -0,0 +1,96 @@
+(function()
+{
+
+  var formLogin = null;
+
+  function msgLogin()
+  {
+      var divMsgLogin = $("#msg-login");
+
+      var msgType = divMsgLogin.html();
+
+      if( $.trim(msgType) != "" )
+      {  
+        divMsgLogin.css("display","block");
+
+        if( msgType.indexOf("color=\"FF0000\"") > -1 )
+        {
+          divMsgLogin.attr("class","erro").delay(3000).fadeOut('slow');
+        }
+        else
+        {
+          divMsgLogin.attr("class","sucesso").delay(3000).fadeOut('slow');
+        }
+      }
+  }
+
+  function setLogin()
+  {
+
+    if( formLogin.find("select[name=organization]").length > 0 )
+    {
+      formLogin.find("input[name=login]").val( formLogin.find("select[name=organization]").val() + "-"  + formLogin.find("input[name=user]").val() );
+    }
+    else
+    {
+      formLogin.find("input[name=login]").val( formLogin.find("input[name=login]").val() );
+    }
+  }
+
+  function loginExpresso()
+  {
+    $(document).ready(function()
+    {   
+      // Element Form
+      formLogin = $("form[name=flogin]");
+
+      // Msg Expresso  
+      msgLogin();
+
+      // KeyBoard Virtual   
+      var keyBoardV = formLogin.find("input[name=show_kbd]").val();
+    
+      if( $.trim(keyBoardV) != "" && keyBoardV == "True" )
+      {
+        // Keyboard virtual
+        $('#passwd').keypad({
+             keypadOnly: false,
+             showOn: 'button', 
+             layout: $.keypad.qwertyLayout,
+             buttonImageOnly: true,
+             buttonImage: './prototype/plugins/jquery.keyboard/keypad.png'
+        });
+      }
+
+      // Captcha      
+      var captcha = $("#captcha");
+          captcha.css("position","absolute");
+          captcha.css("left","115px");
+
+      if( $.trim(keyBoardV) != "" && keyBoardV == "True" )
+      {  
+        captcha.css("top","272px");
+
+        if( $("#organizacao").parent().css('display') == "block" )
+        {
+          captcha.css("top","327px");
+        }
+      }
+      else
+      {
+        captcha.css("top","263px");
+
+        if( $("#organizacao").parent().css('display') == "block" )
+        {
+          captcha.css("top","318px");
+        }
+      }
+
+    });
+  }
+
+  loginExpresso.prototype.setLogin      = setLogin;
+
+  window.loginExpresso = new loginExpresso;
+
+})();
Index: branches/2.5/phpgwapi/templates/news/js/simple_show_hide.js
===================================================================
--- branches/2.5/phpgwapi/templates/news/js/simple_show_hide.js	(revision 8232)
+++ branches/2.5/phpgwapi/templates/news/js/simple_show_hide.js	(revision 8232)
@@ -0,0 +1,183 @@
+/*****************************************************
+ * ypSlideOutMenu
+ * 3/04/2001
+ * 
+ * a nice little script to create exclusive, slide-out
+ * menus for ns4, ns6, mozilla, opera, ie4, ie5 on 
+ * mac and win32. I've got no linux or unix to test on but 
+ * it should(?) work... 
+ *
+ * --youngpup--
+ *****************************************************/
+
+//var isIE = false;
+//var isOther = false;
+//var isNS4 = false;
+//var isNS6 = false;
+// constructor
+function ypSlideOutMenu(id, dir, left, top, width, height,pos)
+{
+
+	this.ie  = document.all ? 1 : 0
+		this.ns4 = document.layers ? 1 : 0
+		this.dom = document.getElementById ? 1 : 0
+
+		if (this.ie || this.ns4 || this.dom) {
+			this.id			 = id
+				this.dir		 = dir
+				this.orientation = dir == "left" || dir == "right" ? "h" : "v"
+				this.dirType	 = dir == "right" || dir == "down" ? "-" : "+"
+				this.dim		 = this.orientation == "h" ? width : height
+				//this.hideTimer	 = false
+				//this.aniTimer	 = false
+				this.open		 = false
+				this.over		 = false
+				//this.startTime	 = 0
+
+				// global reference to this object
+				//this.gRef = "ypSlideOutMenu_"+id
+				//eval(this.gRef+"=this")
+
+				// add this menu object to an internal list of all menus
+				//ypSlideOutMenu.Registry[id] = this
+
+				var d = document
+
+				var strCSS = '<style type="text/css">';
+			strCSS += '#' + this.id + 'Container { visibility:hidden; '
+				if(pos)
+				{
+					strCSS += pos+':' + left + 'px; '
+				}
+				else
+				{
+					strCSS += 'left:' + left + 'px; '
+				}
+				strCSS += 'top:' + top + 'px; '
+					strCSS += 'overflow:visible; z-index:10000; }'
+					strCSS += '#' + this.id + 'Container, #' + this.id + 'Content { position:absolute; '
+						strCSS += 'width:' + width + 'px; '
+							//		strCSS += 'height:' + height + 'px; '
+							//		strCSS += 'clip:rect(0 ' + width + ' ' + height + ' 0); '
+							strCSS += '}'
+							strCSS += '</style>';
+
+						d.write(strCSS);
+						//	alert(strCSS);
+//						this.load()
+
+					}
+		}
+
+	ypSlideOutMenu.aLs = function(layerID)
+	{
+
+		this.isIE = false;
+		this.isOther = false;
+		this.isNS4 = false;
+		this.isNS6 = false;
+		if(document.getElementById)
+		{
+			if(!document.all)
+			{
+				this.isNS6=true;
+			}
+			if(document.all)
+			{
+				this.isIE=true;
+			}
+		}
+		else
+		{
+			if(document.layers)
+			{
+				this.isNS4=true;
+			}
+			else
+			{
+				this.isOther=true;
+			}
+		}
+
+		var returnLayer;
+		if(this.isIE)
+		{
+			returnLayer = eval("document.all." + layerID + ".style");
+		}
+		if(this.isNS6)
+		{
+			returnLayer = eval("document.getElementById('" + layerID + "').style");
+		}
+		if(this.isNS4)
+		{
+			returnLayer = eval("document." + layerID);
+		}
+		if(this.isOther)
+		{
+			returnLayer = "null";
+			alert("Error:\nDue to your browser you will probably not\nbe able to view all of the following page\nas it was designed to be viewed. We regret\nthis error sincerely.");
+		}
+		return returnLayer;
+	}
+	// HideShow 1.0	Jim Cummins - http://www.conxiondesigns.com
+
+	ypSlideOutMenu.ShowL = function(ID)
+	{
+		ypSlideOutMenu.aLs(ID).visibility = "visible";
+	}
+
+	ypSlideOutMenu.HideL =function(ID)
+	{
+		ypSlideOutMenu.aLs(ID).visibility = "hidden";
+	}
+
+	ypSlideOutMenu.HideShow = function(ID)
+	{
+
+		if((ypSlideOutMenu.aLs(ID).visibility == "visible") || (ypSlideOutMenu.aLs(ID).visibility == ""))
+		{
+			ypSlideOutMenu.aLs(ID).visibility = "hidden";
+		}
+		else if(ypSlideOutMenu.aLs(ID).visibility == "hidden")
+		{
+			ypSlideOutMenu.aLs(ID).visibility = "visible";
+		}
+	}
+
+
+	ypSlideOutMenu.showMenu = function(id)
+	{
+		//temporarly hide all selectboxes to fix IE bug with z-index  
+		if(document.all)
+		{
+			for (var i=0; i<document.all.length; i++) {
+				o = document.all(i)
+					if (o.type == 'select-one' || o.type == 'select-multiple') {
+						// todo: add check for select in div?
+						if (o.style) o.style.display = 'none';
+					}
+			}
+		}
+		ypSlideOutMenu.ShowL(id+'Container');
+
+	}
+
+	ypSlideOutMenu.hide = function(id)
+	{
+		ypSlideOutMenu.HideL(id+'Container');
+		//show all selectboxes again to fix IE bug with z-index  
+		if(document.all)
+		{
+			for (var i=0; i<document.all.length; i++) {
+				o = document.all(i)
+					if (o.type == 'select-one' || o.type == 'select-multiple') {
+						// todo: add check for select in div?
+						if (o.style) o.style.display = 'inline';
+					}
+			}
+		}
+
+	}
+
+
+
Index: branches/2.5/phpgwapi/templates/news/js/slider.js
===================================================================
--- branches/2.5/phpgwapi/templates/news/js/slider.js	(revision 8232)
+++ branches/2.5/phpgwapi/templates/news/js/slider.js	(revision 8232)
@@ -0,0 +1,76 @@
+(function()
+{
+	var divSlider = null;
+
+	function loadImages()
+	{
+		$.ajax(
+		{
+			  url: "./phpgwapi/templates/news/list_images.php",
+			  type	: "POST",
+			  dataType: 'json',
+			  success: function(data)
+			  {
+			  		var _html = "";
+
+			  		for( var i in data )
+			  		{
+		  				// Template EJS
+						_html += new EJS({url: './phpgwapi/templates/news/sliderImages.ejs'}).render(
+						{
+							'name_image'	: data[i]['nome'],
+							'title_image'	: data[i]['titulo'],
+							'text_image'	: data[i]['texto'],
+							'link_image'	: ( data[i]['link'] ) ? data[i]['link'] : ""
+						});
+			  		}
+
+			  		var ulSlider = $("<ul>");
+
+			  		ulSlider.html( _html );
+
+			  		divSlider.append(ulSlider);
+
+			  		configSlider();
+			  }
+		});
+	}
+
+	function configSlider()
+	{
+		divSlider.after('<div id="nav-informacao-login"></div>');
+		divSlider.find('ul').show();
+		divSlider.find('ul').cycle({
+			fx:      'scrollLeft',
+			timeout: 6100,
+			speed:   1000,
+			random:  0,
+			pager:'#nav-informacao-login'
+		});
+		
+		$('#nav-informacao-login-control').toggle(function(e) {
+			e.preventDefault();
+			divSlider.find('ul').cycle('pause');
+			$(this).addClass('play');
+		},
+		
+		function() {
+			divSlider.find('ul').cycle('resume');
+			$(this).removeClass('play');
+		});
+
+	}
+
+	function sliderLoad()
+	{
+		$(document).ready(function()
+		{		
+			divSlider = $('#informacao-login');
+			
+			loadImages();
+		});
+	}
+
+	window.sliderLoad = new sliderLoad;
+
+})();
Index: branches/2.5/phpgwapi/templates/news/js/slidereffects.js
===================================================================
--- branches/2.5/phpgwapi/templates/news/js/slidereffects.js	(revision 8232)
+++ branches/2.5/phpgwapi/templates/news/js/slidereffects.js	(revision 8232)
@@ -0,0 +1,217 @@
+/*****************************************************
+ * ypSlideOutMenu
+ * 3/04/2001
+ * 
+ * a nice little script to create exclusive, slide-out
+ * menus for ns4, ns6, mozilla, opera, ie4, ie5 on 
+ * mac and win32. I've got no linux or unix to test on but 
+ * it should(?) work... 
+ *
+ * --youngpup--
+ *****************************************************/
+
+ypSlideOutMenu.Registry = []
+ypSlideOutMenu.aniLen = 250
+ypSlideOutMenu.hideDelay = 1000
+ypSlideOutMenu.minCPUResolution = 10
+
+// constructor
+function ypSlideOutMenu(id, dir, left, top, width, height,pos)
+{
+	this.ie  = document.all ? 1 : 0
+		this.ns4 = document.layers ? 1 : 0
+		this.dom = document.getElementById ? 1 : 0
+
+		if (this.ie || this.ns4 || this.dom) {
+			this.id			 = id
+				this.dir		 = dir
+				this.orientation = dir == "left" || dir == "right" ? "h" : "v"
+				this.dirType	 = dir == "right" || dir == "down" ? "-" : "+"
+				this.dim		 = this.orientation == "h" ? width : height
+				this.hideTimer	 = false
+				this.aniTimer	 = false
+				this.open		 = false
+				this.over		 = false
+				this.startTime	 = 0
+
+				// global reference to this object
+				this.gRef = "ypSlideOutMenu_"+id
+				eval(this.gRef+"=this")
+
+				// add this menu object to an internal list of all menus
+				ypSlideOutMenu.Registry[id] = this
+
+				var d = document
+
+				var strCSS = '<style type="text/css">';
+			strCSS += '#' + this.id + 'Container { visibility:hidden; '
+				if(pos)
+				{
+					strCSS += pos+':' + left + 'px; '
+				}
+				else
+				{
+					strCSS += 'left:' + left + 'px; '
+				}
+				strCSS += 'top:' + top + 'px; '
+					strCSS += 'overflow:visible; z-index:10000; }'
+					strCSS += '#' + this.id + 'Container, #' + this.id + 'Content { position:absolute; '
+						strCSS += 'width:' + width + 'px; '
+							//		strCSS += 'height:' + height + 'px; '
+							//		strCSS += 'clip:rect(0 ' + width + ' ' + height + ' 0); '
+							strCSS += '}'
+							strCSS += '</style>';
+
+						d.write(strCSS)
+
+							this.load()
+					}
+		}
+
+	ypSlideOutMenu.prototype.load = function() {
+		var d = document
+			var lyrId1 = this.id + "Container"
+			var lyrId2 = this.id + "Content"
+			var obj1 = this.dom ? d.getElementById(lyrId1) : this.ie ? d.all[lyrId1] : d.layers[lyrId1]
+			if (obj1) var obj2 = this.ns4 ? obj1.layers[lyrId2] : this.ie ? d.all[lyrId2] : d.getElementById(lyrId2)
+				var temp
+
+					if (!obj1 || !obj2) window.setTimeout(this.gRef + ".load()", 100)
+					else {
+						this.container	= obj1
+							this.menu		= obj2
+							this.style		= this.ns4 ? this.menu : this.menu.style
+							this.homePos	= eval("0" + this.dirType + this.dim)
+							this.outPos		= 0
+							this.accelConst	= (this.outPos - this.homePos) / ypSlideOutMenu.aniLen / ypSlideOutMenu.aniLen 
+
+							// set event handlers.
+							if (this.ns4) this.menu.captureEvents(Event.MOUSEOVER | Event.MOUSEOUT);
+						this.menu.onmouseover = new Function("ypSlideOutMenu.showMenu('" + this.id + "')")
+							this.menu.onmouseout = new Function("ypSlideOutMenu.hideMenu('" + this.id + "')")
+
+							//set initial state
+							this.endSlide()
+					}
+	}
+
+	ypSlideOutMenu.showMenu = function(id)
+	{
+		var reg = ypSlideOutMenu.Registry
+			var obj = ypSlideOutMenu.Registry[id]
+
+			//document.all.select.style="visibily:hidden";
+
+
+			//temporarly hide all selectboxes to fix IE bug with z-index  
+			if(document.all)
+			{
+				for (var i=0; i<document.all.length; i++) {
+					o = document.all(i)
+						if (o.type == 'select-one' || o.type == 'select-multiple') {
+							// todo: add check for select in div?
+							if (o.style) o.style.display = 'none';
+						}
+				}
+			}
+
+
+		if (obj.container) {
+			obj.over = true
+
+				// close other menus.
+				for (menu in reg) if (id != menu) ypSlideOutMenu.hide(menu)
+
+					// if this menu is scheduled to close, cancel it.
+					if (obj.hideTimer) { reg[id].hideTimer = window.clearTimeout(reg[id].hideTimer) }
+
+			// if this menu is closed, open it.
+			if (!obj.open && !obj.aniTimer) reg[id].startSlide(true)
+		}
+	}
+
+	ypSlideOutMenu.hideMenu = function(id)
+	{
+		// schedules the menu to close after <hideDelay> ms, which
+		// gives the user time to cancel the action if they accidentally moused out
+		var obj = ypSlideOutMenu.Registry[id]
+			if (obj.container) {
+				if (obj.hideTimer) window.clearTimeout(obj.hideTimer)
+					obj.hideTimer = window.setTimeout("ypSlideOutMenu.hide('" + id + "')", ypSlideOutMenu.hideDelay);
+			}
+	}
+
+	ypSlideOutMenu.hide = function(id)
+	{
+		var obj = ypSlideOutMenu.Registry[id]
+			obj.over = false
+
+			if (obj.hideTimer) window.clearTimeout(obj.hideTimer)
+
+				// flag that this scheduled event has occured.
+				obj.hideTimer = 0
+
+					// if this menu is open, close it.
+					if (obj.open && !obj.aniTimer) obj.startSlide(false)
+
+						//show all selectboxes again to fix IE bug with z-index  
+						if(document.all)
+						{
+							for (var i=0; i<document.all.length; i++) {
+								o = document.all(i)
+									if (o.type == 'select-one' || o.type == 'select-multiple') {
+										// todo: add check for select in div?
+										if (o.style) o.style.display = 'inline';
+									}
+							}
+						}
+
+
+
+	}
+
+ypSlideOutMenu.prototype.startSlide = function(open) {
+	this[open ? "onactivate" : "ondeactivate"]()
+	this.open = open
+	if (open) this.setVisibility(true)
+	this.startTime = (new Date()).getTime()	
+	this.aniTimer = window.setInterval(this.gRef + ".slide()", ypSlideOutMenu.minCPUResolution)
+}
+
+ypSlideOutMenu.prototype.slide = function() {
+	var elapsed = (new Date()).getTime() - this.startTime
+	if (elapsed > ypSlideOutMenu.aniLen) this.endSlide()
+	else {
+		var d = Math.round(Math.pow(ypSlideOutMenu.aniLen-elapsed, 2) * this.accelConst)
+		if (this.open && this.dirType == "-")		d = -d
+		else if (this.open && this.dirType == "+")	d = -d
+		else if (!this.open && this.dirType == "-")	d = -this.dim + d
+		else										d = this.dim + d
+
+		this.moveTo(d)
+	}
+}
+
+ypSlideOutMenu.prototype.endSlide = function() {
+	this.aniTimer = window.clearTimeout(this.aniTimer)
+	this.moveTo(this.open ? this.outPos : this.homePos)
+	if (!this.open) this.setVisibility(false)
+	if ((this.open && !this.over) || (!this.open && this.over)) {
+		this.startSlide(this.over)
+	}
+}
+
+ypSlideOutMenu.prototype.setVisibility = function(bShow) { 
+	var s = this.ns4 ? this.container : this.container.style
+	s.visibility = bShow ? "visible" : "hidden"
+}
+ypSlideOutMenu.prototype.moveTo = function(p) { 
+	this.style[this.orientation == "h" ? "left" : "top"] = this.ns4 ? p : p + "px"
+}
+ypSlideOutMenu.prototype.getPos = function(c) {
+	return parseInt(this.style[c])
+}
+
+// events
+ypSlideOutMenu.prototype.onactivate		= function() { }
+ypSlideOutMenu.prototype.ondeactivate	= function() { }
Index: branches/2.5/phpgwapi/templates/news/js/news.js
===================================================================
--- branches/2.5/phpgwapi/templates/news/js/news.js	(revision 5159)
+++ 	(revision )
@@ -1,40 +1,0 @@
-/****************************************************************************************\
-|************************ 	LOAD NEWS FROM NEWSADMIN MODULE		*************************|
-\****************************************************************************************/
-function News(data){	
-	this.data = new Hash(data);
-	this.delay = 5000;
-	this.timeout = 0;
-}
-
-News.prototype.update = function(direction) {	
-	if(this.data.size() == 0) {
-		document.getElementById("news").style.visibility ="hidden";
-		return true;
-	}	
-	var item = this.data.seek(direction);	
-	document.getElementById("news_subject").innerHTML = item.subject;
-	document.getElementById("news_content").innerHTML = item.content;
-}
-
-News.prototype.start = function(delay){
-	if(delay)
-		this.delay = delay;
-	
-	this.update('next');
-	this.timeout = setTimeout("news.start()",this.delay);
-}
-
-News.prototype.pause = function(){	
-	if(this.timeout){
-		document.getElementById("img_player_pause").style.display = 'none';
-		document.getElementById("img_player_resume").style.display = '';
-		clearTimeout(this.timeout);
-		this.timeout = 0;
-	}
-	else{
-		document.getElementById("img_player_pause").style.display = '';
-		document.getElementById("img_player_resume").style.display = 'none';
-		this.start();
-	}
-}
Index: branches/2.5/phpgwapi/templates/news/js/hash.js
===================================================================
--- branches/2.5/phpgwapi/templates/news/js/hash.js	(revision 5159)
+++ 	(revision )
@@ -1,20 +1,0 @@
-/*********************** HASH PROTOTYPE **************************/
-function Hash(data)	{
-	this.last_item = 0;
-	this.data = data;
-}
-Hash.prototype.size = function(){
-	var _thisObject = this;		
-	var size = 0;
-	for (var i in _thisObject.data)
-       	if(_thisObject.data[i] != null)
-           	size++;    	
-   	return size;	
-}	
-Hash.prototype.seek = function(direction){
-	var _thisObject = this;	
-	_thisObject.last_item = (direction == "previous" ? 
-			(_thisObject.last_item == 0 ? _thisObject.size() - 1 : _thisObject.last_item - 1) : 
-			(_thisObject.last_item == _thisObject.size() -1 ? 0	 : _thisObject.last_item + 1));	
-	return _thisObject.data[_thisObject.last_item];		
-}
Index: branches/2.5/phpgwapi/templates/news/login.css
===================================================================
--- branches/2.5/phpgwapi/templates/news/login.css	(revision 5159)
+++ 	(revision )
@@ -1,223 +1,0 @@
-body{
-	margin-top: 0;
-	margin-bottom: 0;
-	margin-left: 0;
-	margin-right: 0; 
-	padding-top: 0;
-	padding-bottom: 0;
-	padding-left: 0;
-	padding-right: 0;
-}
-
-a:link,a:visited
-{
-	cursor:pointer;
-	color: #006699; 
-	text-decoration: none;
-}
-
-a:hover,a:active
-{
-	cursor:pointer;
-	color: #ff9933;
-	text-decoration: underline;
-}
-#conteudo {
-        background:url(../../../phpgwapi/templates/news/images/back_pagina.jpg) repeat-x #fff;
-}
-
-#conteudo_corpo{
-        margin:auto 0; width:770px;
-}
-
-#superior {
-        background: url(../../../phpgwapi/templates/news/images/fundo3.jpg) no-repeat top left;
-        height:340px;
-}
-
-#login {
-        text-align:left;
-        position: relative;
-        top: 49px;
-        left: -186px;
-}
-
-#login td {
-        text-align:left;
-}
-
-.login_label {
-        font-family:  Arial, Verdana,Helvetica, sans-serif;
-        font-size: 12px;
-        color: #003366;
-        font-weight: bold;
-}
-
-
-.button {
-        background:url(../../../phpgwapi/templates/news/images/back_botao.jpg) #1F4F7E no-repeat scroll left top;
-        color:#fff;
-        font-family: Arial,Verdana, Helvetica, sans-serif;
-        font-size:12px;
-        padding-top:2px 4px 2px 4px;
-        margin:2px 1px 0pt;
-        border: medium none;
-        font-weight: bold;
-        height:31px;
-        width:83px;
-}
-
-#caixa_login {
-	width: 262px; 
-	left: 30px;
-	position: relative;
-	float: left;
-	background: url("../../../phpgwapi/templates/news/images/corpo.jpg") repeat-y; 
-}
-
-#reflexo {
-	background:url(../../../phpgwapi/templates/news/images/topo_reflexo.jpg) no-repeat center top;	
-}
-
-.button:hover {
-        background:url(../../../phpgwapi/templates/news/images/back_botao_over.jpg) #FD9C0E no-repeat top left;
-        color:#1F4F7E;
-}
-
-#inferior {
-        background: url(../../../phpgwapi/templates/news/images/fundo4.jpg) no-repeat top left;
-        height:146px;
-}
-
-#rodape {
-        text-align:left;
-        width:100%;
-        position: relative;
-        margin:0;
-}
-
-#rodape_login {
-	background: #FFF url("../../../phpgwapi/templates/news/images/rodape.jpg") no-repeat; 
-	height: 41px;
-	clear: both; 
-}
-
-#rodape table {
-        width:250px;
-        font-family:  Arial, Verdana,Helvetica, sans-serif;
-        font-size:11px;
-        color: #666666;
-        text-align:right;
-        margin-left:108px;
-}
-
-#alterna_login {
-	clear: both;
-	text-align: left;
-	padding-left: 11px;
-	padding-top: 5px;
-}
-
-#alterna_login img {
-	margin-right: 5px;
-	vertical-align: middle;
-}
-
-#alterna_login a {
-	color: #fff;
-	font-family: Arial, Verdana, Helvetica, sans-serif;
-	font-size: 11px;
-	font-weight: bold;
-	text-decoration: none;
-	margin: 0px;
-	padding: 0px;
-}
-
-#alterna_login a:hover {
-	color: #fff !important;
-	text-decoration: underline !important;
-}
-
-.ajuda {
-	text-align: left;
-	padding-left: 11px;
-	padding-top: 9px;
-}
-
-.ajuda img {
-	vertical-align: middle;
-}
-
-.ajuda a {
-	font-family: Arial, Verdana, Helvetica, sans-serif;
-	font-size: 11px;
-	color: #FFF !important;
-	margin-top: 10px;
-	margin-left: 11px;
-	font-weight: bold;
-	text-decoration: none;
-}
-
-.ajuda a:hover {
-	text-decoration:underline;
-}
-
-.login_Label {
-	font-family: Verdana, Arial, Helvetica, sans-serif;
-	font-size: 11px;
-	color: #000066;
-	padding-top: 0px;
-	padding-bottom: 3px;
-}
-
-.msgInicial {
-	font-family: Verdana, Arial, Helvetica, sans-serif;
-	height: 15px;
-	font-size: 12px;
-	color: #000066;
-	font-weight: bold;
-	padding-bottom: 13px;
-	padding-left: 0px;
-}
-
-.titulo_login {
-	font-family:  Arial, Verdana,Helvetica, sans-serif;
-	font-size: 14px;
-	color: #85A9CF;
-	font-weight: bold;
-	width:250px;
-	text-transform:uppercase;
-	line-height:22px;
-	padding:2px;
-}
-#news {
-	position:relative;
-	float:left;	
-	left:400px;	
-	top:95px;		
-	width:250px;	
-}
-#news_block {
-	overflow: hidden;
-	width:250px;
-	height:115px;	
-	font-family:Arial, Helvetica, sans-serif;
-	font-size:12px; 
-	text-align:justify;	
-	background: #fff;
-	border:2px solid #71a8eb;		
-}
-#news_subject{
-	margin:7px 0px 0px 7px;	
-}
-#news_content{
-	margin:7px 7px 0px 7px;
-}
-.news_button_over{
-	cursor:pointer;
-	border:1px solid white;
-		
-}
-.news_button{		
-	border:1px solid transparent;
-}
Index: branches/2.5/news_admin/setup/tables_update.inc.php
===================================================================
--- branches/2.5/news_admin/setup/tables_update.inc.php	(revision 7516)
+++ branches/2.5/news_admin/setup/tables_update.inc.php	(revision 8232)
@@ -80,16 +80,23 @@
 	}
 
-    	$test[] = '2.4.1';
-    	function news_admin_upgrade2_4_1()
-    	{
-        	$GLOBALS['setup_info']['news_admin']['currentver'] = '2.4.2';
-        	return $GLOBALS['setup_info']['news_admin']['currentver'];
-    	}
+    $test[] = '2.4.1';
+    function news_admin_upgrade2_4_1()
+    {
+        $GLOBALS['setup_info']['news_admin']['currentver'] = '2.4.2';
+        return $GLOBALS['setup_info']['news_admin']['currentver'];
+    }
+
 	$test[] = '2.4.2';
-    	function news_admin_upgrade2_4_2()
-    	{
-        	$GLOBALS['setup_info']['news_admin']['currentver'] = '2.5.0';
-        	return $GLOBALS['setup_info']['news_admin']['currentver'];
-    	}
+    function news_admin_upgrade2_4_2()
+    {
+        $GLOBALS['setup_info']['news_admin']['currentver'] = '2.5.0';
+        return $GLOBALS['setup_info']['news_admin']['currentver'];
+    }
 
+    $test[] = '2.5.0';
+    function news_admin_upgrade2_5_0()
+    {
+        $GLOBALS['setup_info']['news_admin']['currentver'] = '2.5.1';
+        return $GLOBALS['setup_info']['news_admin']['currentver'];
+    }
 ?>
Index: branches/2.5/news_admin/setup/setup.inc.php
===================================================================
--- branches/2.5/news_admin/setup/setup.inc.php	(revision 7516)
+++ branches/2.5/news_admin/setup/setup.inc.php	(revision 8232)
@@ -14,5 +14,5 @@
 	$setup_info['news_admin']['name']      = 'news_admin';
 	$setup_info['news_admin']['title']     = 'News Admin';
-	$setup_info['news_admin']['version']   = '2.5.0';
+	$setup_info['news_admin']['version']   = '2.5.1';
 	$setup_info['news_admin']['app_order'] = 16;
 	$setup_info['news_admin']['enable']    = 1;
@@ -31,5 +31,5 @@
 	$setup_info['news_admin']['depends'][] = array(
 		 'appname' => 'phpgwapi',
-		 'versions' => Array('2.5.0')
+		 'versions' => Array('2.5.1.1')
 	);
 
Index: branches/2.5/login.php
===================================================================
--- branches/2.5/login.php	(revision 6714)
+++ branches/2.5/login.php	(revision 8232)
@@ -58,7 +58,6 @@
 	{
 	    $accountInfo = $GLOBALS['phpgw']->accounts->read_repository();
-	    session_id( $_COOKIE[ 'sessionid' ] ); 
+	    isset($_COOKIE[ 'sessionid' ]) ? session_id($_COOKIE[ 'sessionid' ]) : session_id(); 
 	    session_start();
-	    
 	    //Carregando na sessão configurações do usuario usado na nova API.	
 	    $_SESSION['wallet']['user']['uid']	          =  $accountInfo['account_lid'];
Index: branches/2.5/reports/setup/setup.inc.php
===================================================================
--- branches/2.5/reports/setup/setup.inc.php	(revision 7516)
+++ branches/2.5/reports/setup/setup.inc.php	(revision 8232)
@@ -13,5 +13,5 @@
 	$setup_info['reports']['title']     	= 'Expresso Reports';
 	/* Ao incrementar versão, não esquecer de declarar função do tables_update.inc.php*/
-	$setup_info['reports']['version']   	= '2.5.0';
+	$setup_info['reports']['version']   	= '2.5.1';
 	$setup_info['reports']['app_order']	= 17;
 	$setup_info['reports']['tables']    = '';
@@ -41,5 +41,5 @@
 	$setup_info['reports']['depends'][] = array(
 		'appname' => 'phpgwapi',
-		'versions' => Array('2.5.0')
+		'versions' => Array('2.5.1.1')
 	);
 ?>
Index: branches/2.5/header.inc.php.template
===================================================================
--- branches/2.5/header.inc.php.template	(revision 7503)
+++ branches/2.5/header.inc.php.template	(revision 8232)
@@ -119,5 +119,5 @@
 	$GLOBALS['phpgw_info']['server']['versions']['current_header'] = $setup_info['phpgwapi']['versions']['current_header'];
 	unset($setup_info);
-	$GLOBALS['phpgw_info']['server']['versions']['header'] = '2.5.0';
+	$GLOBALS['phpgw_info']['server']['versions']['header'] = '2.5.1';
 	/* This is a fix for NT */
 	if(!isset($GLOBALS['phpgw_info']['flags']['noapi']) || !$GLOBALS['phpgw_info']['flags']['noapi'] == True)
Index: branches/2.5/INSTALL/debian/squeeze/etc/ldap/slapd.conf
===================================================================
--- branches/2.5/INSTALL/debian/squeeze/etc/ldap/slapd.conf	(revision 6710)
+++ branches/2.5/INSTALL/debian/squeeze/etc/ldap/slapd.conf	(revision 8232)
@@ -5,6 +5,6 @@
 # Global Directives:
 sizelimit -1
-timelimit -1
-threads 2
+#timelimit -1
+#threads 2
 
 # Schema and objectClass definitions
Index: branches/2.5/INSTALL/debian/squeeze/etc/postfix/main.cf
===================================================================
--- branches/2.5/INSTALL/debian/squeeze/etc/postfix/main.cf	(revision 7278)
+++ branches/2.5/INSTALL/debian/squeeze/etc/postfix/main.cf	(revision 8232)
@@ -1,5 +1,6 @@
 # Configuracoes para o Expresso
-myorigin = DOMAIN
-myhostname = DOMAIN
+mydomain = DOMAIN
+myorigin = $mydomain
+myhostname = $mydomain
 biff = no
 
@@ -8,5 +9,5 @@
 
 # A lista de dominios que esta maquina considera seu destino final.
-mydestination = $myhostname, localhost.$mydomain, DOMAIN
+mydestination = $mydomain, $myhostname, expresso.$mydomain
 
 recipient_delimiter = + 
Index: branches/2.5/INSTALL/expressoInstall.sh
===================================================================
--- branches/2.5/INSTALL/expressoInstall.sh	(revision 7619)
+++ branches/2.5/INSTALL/expressoInstall.sh	(revision 8232)
@@ -35,5 +35,5 @@
 # Variaveis globais
 ARQS="arquivos"
-VERSAO="2.5.0"
+VERSAO="2.5.1"
 # Inclusao dos scripts de apoio
 . $ARQS/scripts/aux.sh
Index: branches/2.5/INSTALL/arquivos/header.inc.php
===================================================================
--- branches/2.5/INSTALL/arquivos/header.inc.php	(revision 7503)
+++ branches/2.5/INSTALL/arquivos/header.inc.php	(revision 8232)
@@ -131,5 +131,5 @@
 	$GLOBALS['phpgw_info']['server']['versions']['current_header'] = $setup_info['phpgwapi']['versions']['current_header'];
 	unset($setup_info);
-	$GLOBALS['phpgw_info']['server']['versions']['header'] = '2.5.0';
+	$GLOBALS['phpgw_info']['server']['versions']['header'] = '2.5.1';
 	/* This is a fix for NT */
 	if(!isset($GLOBALS['phpgw_info']['flags']['noapi']) || !$GLOBALS['phpgw_info']['flags']['noapi'] == True)
Index: branches/2.5/INSTALL/arquivos/expresso-cron
===================================================================
--- branches/2.5/INSTALL/arquivos/expresso-cron	(revision 7700)
+++ branches/2.5/INSTALL/arquivos/expresso-cron	(revision 8232)
@@ -5,6 +5,6 @@
 
 # Utilizado para verificar se ha algum alarme, por e-mail, do modulo ExpressoCalendar
-#CENTOS*/1 * 	* * *	apache	 php	EXPRESSO_DIR/prototype/modules/calendar/alarms.php 
-#DEBIAN*/1 * 	* * *	www-data php5	EXPRESSO_DIR/prototype/modules/calendar/alarms.php 
+#CENTOS*/1 * 	* * *	apache	 php	EXPRESSO_DIR/prototype/modules/calendar/alarms.php 1>& /dev/null
+#DEBIAN*/1 * 	* * *	www-data php5	EXPRESSO_DIR/prototype/modules/calendar/alarms.php 1>& /dev/null
 
 # Utilizado para limpar a tabela, temporaria, que contem os e-mails (rascunhos) antes de
@@ -19,7 +19,9 @@
 # Utilizado para limpar os arquivos de sessao do PHP
 #*/31 *  * * *   root                    find /dev/shm -type f -name "sess_*" -cmin 240 -print0 | xargs -n 200 -r -0 rm
+*/31 *  * * *   root                    find /dev/shm -type f -name "sess_*" -cmin +240 -delete
 
 # Utilizado para limpar os arquivos, eml, criados ao exportar mensagens
-13 */4 * * * root			find /tmp/ -iname "*.eml" -amin +60 -exec rm -f '{}' \;
+#13 */4 * * * root			find /tmp/ -iname "*.eml" -amin +60 -exec rm -f '{}' \;
+13 */4 	* * * root			find /tmp/ -iname "*.eml" -cmin +60 -delete
 
 #
Index: branches/2.5/INSTALL/arquivos/scripts/http.sh
===================================================================
--- branches/2.5/INSTALL/arquivos/scripts/http.sh	(revision 7619)
+++ branches/2.5/INSTALL/arquivos/scripts/http.sh	(revision 8232)
@@ -111,7 +111,8 @@
 	yum -y install httpd mod_ssl \
 		php php-cli php-ldap php-pgsql php-imap php-mbstring php-gd php-xml \
-		php-pecl-memcache graphviz-php php-pspell \
+		php-pecl-memcache php-pspell \
 		unzip zip memcached libmemcached \
 		php-soap php-process # para o zpush
+		#graphviz-php \ # problema com o PHP-5.4
 
 	# para que o yuicompressor funcione
@@ -122,4 +123,5 @@
 
 	chkconfig httpd on
+	chkconfig memcached on
 
 	# Ativa o script do CRON para o RedHat e similares
Index: branches/2.5/INSTALL/rhel/6/var/lib/pgsql/data/postgresql.conf
===================================================================
--- branches/2.5/INSTALL/rhel/6/var/lib/pgsql/data/postgresql.conf	(revision 5797)
+++ branches/2.5/INSTALL/rhel/6/var/lib/pgsql/data/postgresql.conf	(revision 8232)
@@ -484,8 +484,4 @@
 #backslash_quote = safe_encoding	# on, off, or safe_encoding
 #default_with_oids = off
-# Necessario para o Expresso
-standard_conforming_strings = off
-#bytea_output = 'escape'
-# Necessario para o Expresso
 #escape_string_warning = on
 #regex_flavor = advanced		# advanced, extended, or basic
@@ -494,4 +490,8 @@
 #synchronize_seqscans = on
 
+# Necessario para o Expresso
+standard_conforming_strings = off
+bytea_output = 'escape'
+
 # - Other Platforms and Clients -
 
Index: branches/2.5/INSTALL/rhel/6/etc/openldap/slapd.conf
===================================================================
--- branches/2.5/INSTALL/rhel/6/etc/openldap/slapd.conf	(revision 6761)
+++ branches/2.5/INSTALL/rhel/6/etc/openldap/slapd.conf	(revision 8232)
@@ -7,6 +7,6 @@
 # Global Directives:
 sizelimit -1
-timelimit -1
-threads 2
+#timelimit -1
+#threads 2
 
 # Schema and objectClass definitions
Index: branches/2.5/INSTALL/rhel/6/etc/cyrus.conf
===================================================================
--- branches/2.5/INSTALL/rhel/6/etc/cyrus.conf	(revision 7699)
+++ branches/2.5/INSTALL/rhel/6/etc/cyrus.conf	(revision 8232)
@@ -7,7 +7,4 @@
   # this is only necessary if using idled for IMAP IDLE
   idled		cmd="idled"
-
-  # this is recommended if using duplicate delivery suppression
-  delprune        cmd="/usr/lib/cyrus-imapd/ctl_deliver -E 3"
 }
 
@@ -37,7 +34,4 @@
   checkpoint	cmd="ctl_cyrusdb -c" period=30
 
-  # this is only necessary if using duplicate delivery suppression
-  delprune        cmd="/usr/lib/cyrus-imapd/ctl_deliver -E 3" at=0401
-
   # this is only necessary if using duplicate delivery suppression,
   # Sieve or NNTP
@@ -52,4 +46,4 @@
 
   # SQUATTER indexa as caixas postais, a cada 120 min, para otimizar a pesquisa
-  squatter_i	  cmd="/bin/nice -n 19 /usr/lib/cyrus-imapd/squatter -s -i -r" period=120
+  squatter_i	  cmd="/bin/nice -n 19 /usr/lib/cyrus-imapd/squatter -s -i -r -v" period=240
 }
Index: branches/2.5/INSTALL/rhel/6/etc/postfix/main.cf
===================================================================
--- branches/2.5/INSTALL/rhel/6/etc/postfix/main.cf	(revision 7278)
+++ branches/2.5/INSTALL/rhel/6/etc/postfix/main.cf	(revision 8232)
@@ -1,5 +1,6 @@
 # Configuracoes para o Expresso
-myorigin = DOMAIN
-myhostname = DOMAIN
+mydomain = DOMAIN
+myorigin = $mydomain
+myhostname = $mydomain
 biff = no
 
@@ -8,5 +9,5 @@
 
 # A lista de dominios que esta maquina considera seu destino final.
-mydestination = $myhostname, localhost.$mydomain, DOMAIN
+mydestination = $mydomain, $myhostname, expresso.$mydomain
 
 recipient_delimiter = + 
Index: branches/2.5/INSTALL/rhel/6/etc/imapd.conf
===================================================================
--- branches/2.5/INSTALL/rhel/6/etc/imapd.conf	(revision 5802)
+++ branches/2.5/INSTALL/rhel/6/etc/imapd.conf	(revision 8232)
@@ -9,5 +9,4 @@
 sasl_mech_list: LOGIN PLAIN
 allowplaintext: yes
-auxprop_plugin: ldapdb
 
 tls_cert_file: /etc/pki/cyrus-imapd/cyrus-imapd.pem
Index: branches/2.5/mobile/setup/setup.inc.php
===================================================================
--- branches/2.5/mobile/setup/setup.inc.php	(revision 7516)
+++ branches/2.5/mobile/setup/setup.inc.php	(revision 8232)
@@ -14,5 +14,5 @@
 	$setup_info['mobile']['name']      = 'mobile';
 	$setup_info['mobile']['title']     = 'Expresso Mini';
-	$setup_info['mobile']['version']   = '2.5.0';
+	$setup_info['mobile']['version']   = '2.5.1';
 	$setup_info['mobile']['app_order'] = 4;
 	$setup_info['mobile']['enable']    = 2;
@@ -39,5 +39,5 @@
 	$setup_info['mobile']['depends'][] = array(
 		'appname' => 'phpgwapi',
-		'versions' => Array('2.5.0')
+		'versions' => Array('2.5.1.1')
 	);
 ?>
Index: branches/2.5/mobile/inc/class.ui_home.inc.php
===================================================================
--- branches/2.5/mobile/inc/class.ui_home.inc.php	(revision 4358)
+++ branches/2.5/mobile/inc/class.ui_home.inc.php	(revision 8232)
@@ -4,5 +4,5 @@
 	var $imap_functions;
 	var $db;
-	var $bocalendar;
+	//var $bocalendar;
 	var $bo_mobilemail;
 	var $common;
@@ -22,5 +22,5 @@
 		$this->imap_functions	= CreateObject('expressoMail1_2.imap_functions');
 		$this->db	= CreateObject('phpgwapi.db');
-		$this->bocalendar = CreateObject('calendar.bocalendar');
+		//$this->bocalendar = CreateObject('calendar.bocalendar');
 		$this->bo_mobilemail = CreateObject('mobile.bo_mobilemail');
 	}
@@ -84,5 +84,5 @@
 		$this->template->set_var('quota_used', $this->common->borkb($total_quota["quota_used"]*1024));
 		$this->template->set_var('quota_limit', $this->common->borkb($total_quota["quota_limit"]*1024));
-		
+		/*
 		//pegando os eventos do dia atual
 		$year	= $this->bocalendar->year;
@@ -116,5 +116,5 @@
 		}
 		
-		
+		*/
 		
 		if($GLOBALS['phpgw']->session->appsession('mobile.layout','mobile')=="mini_desktop") {
Index: branches/2.5/mobile/index.php
===================================================================
--- branches/2.5/mobile/index.php	(revision 7655)
+++ branches/2.5/mobile/index.php	(revision 8232)
@@ -69,6 +69,6 @@
 
 	if(	array_key_exists('expressoMail1_2',$GLOBALS['phpgw_info']['user']['apps']) === FALSE ||
-		array_key_exists('contactcenter',$GLOBALS['phpgw_info']['user']['apps']) === FALSE ||
-		array_key_exists('calendar',$GLOBALS['phpgw_info']['user']['apps']) === FALSE) {
+		array_key_exists('contactcenter',$GLOBALS['phpgw_info']['user']['apps']) === FALSE /*||
+		array_key_exists('calendar',$GLOBALS['phpgw_info']['user']['apps']) === FALSE*/) {
 			$GLOBALS['phpgw']->session->phpgw_setcookie('lem', null);
 			$GLOBALS['phpgw']->session->phpgw_setcookie('pem', null);			
Index: branches/2.5/mobile/mobile_header.inc.php
===================================================================
--- branches/2.5/mobile/mobile_header.inc.php	(revision 4277)
+++ branches/2.5/mobile/mobile_header.inc.php	(revision 8232)
@@ -43,5 +43,6 @@
 				break;
 			case mobilecalendar:
-				$link = "ui_mobilecalendar.index";
+			//	$link = "ui_mobilecalendar.index";
+				$link = "ui_home.index";
 				break;
 			case mobilecc:
Index: branches/2.5/mobile/templates/default/home_index.tpl
===================================================================
--- branches/2.5/mobile/templates/default/home_index.tpl	(revision 5043)
+++ branches/2.5/mobile/templates/default/home_index.tpl	(revision 8232)
@@ -54,5 +54,5 @@
 			{personal_folders_box}
 	   	</span>		
-		<dd>			
+		<!--<dd>			
 			<div class="limpar_div resultado-titulo">
 				<label>
@@ -64,5 +64,5 @@
 			</div>	
 		</dd>
-		{commitments_box}
+			{commitments_box}-->
 		<dd>			
     		<div class="limpar_div resultado-titulo">
Index: branches/2.5/zpush/setup/setup.inc.php
===================================================================
--- branches/2.5/zpush/setup/setup.inc.php	(revision 7589)
+++ branches/2.5/zpush/setup/setup.inc.php	(revision 8232)
@@ -13,5 +13,5 @@
 	$setup_info['zpush']['title']     	= 'Z-Push' ;
 	/* Ao incrementar versão, não esquecer de declarar função do tables_update.inc.php*/
-	$setup_info['zpush']['version']   	= '2.5.0';
+	$setup_info['zpush']['version']   	= '2.5.1';
 	$setup_info['zpush']['app_order']	= 10;
 
Index: branches/2.5/zpush/lib/utils/utils.php
===================================================================
--- branches/2.5/zpush/lib/utils/utils.php	(revision 7589)
+++ branches/2.5/zpush/lib/utils/utils.php	(revision 8232)
@@ -446,5 +446,5 @@
     static public function IsSystemFolder($foldertype) {
         return ($foldertype == SYNC_FOLDER_TYPE_INBOX || $foldertype == SYNC_FOLDER_TYPE_DRAFTS || $foldertype == SYNC_FOLDER_TYPE_WASTEBASKET || $foldertype == SYNC_FOLDER_TYPE_SENTMAIL ||
-                $foldertype == SYNC_FOLDER_TYPE_OUTBOX || $foldertype == SYNC_FOLDER_TYPE_TASK || $foldertype == SYNC_FOLDER_TYPE_APPOINTMENT || $foldertype == SYNC_FOLDER_TYPE_CONTACT ||
+                $foldertype == SYNC_FOLDER_TYPE_OUTBOX || $foldertype == SYNC_FOLDER_TYPE_TASK /*|| $foldertype == SYNC_FOLDER_TYPE_APPOINTMENT */|| $foldertype == SYNC_FOLDER_TYPE_CONTACT ||
                 $foldertype == SYNC_FOLDER_TYPE_NOTE || $foldertype == SYNC_FOLDER_TYPE_JOURNAL) ? true:false;
     }
Index: branches/2.5/zpush/backend/expresso/providers/imapProvider.php
===================================================================
--- branches/2.5/zpush/backend/expresso/providers/imapProvider.php	(revision 8169)
+++ branches/2.5/zpush/backend/expresso/providers/imapProvider.php	(revision 8232)
@@ -497,9 +497,9 @@
             if (!empty($bccaddr)) $headers .= "\nBcc: $bccaddr";
             // changed by mku ZP-330
- 
-            require_once(__DIR__."/../../../../library/Mail/Mail.php"); 
-            $mail_object =& Mail::factory("smtp", $GLOBALS['config']['SMTP']); 
-            $send = $mail_object->send($toaddr, $message->headers , $body); 
-          //  $send =  @mail ( $toaddr, $message->headers["subject"], $body, $headers, $envelopefrom ); 
+
+	    require_once(__DIR__."/../../../../library/Mail/Mail.php");
+            $mail_object =& Mail::factory("smtp", $GLOBALS['config']['SMTP']);
+            $send = $mail_object->send($toaddr, $message->headers , $body);
+          //  $send =  @mail ( $toaddr, $message->headers["subject"], $body, $headers, $envelopefrom );
         }
 
@@ -904,20 +904,13 @@
 
         // build name for new mailboxBackendMaildir
-        $displayname = Utils::Utf7_iconv_encode(Utils::Utf8_to_utf7($displayname));
-        $newname = $this->server . $folderid . $this->serverdelimiter . $displayname;
-
+        $displayname = Utils::Utf7_iconv_encode(Utils::Utf8_to_utf7($displayname));;
+        $new = $this->server . $this->getImapIdFromFolderId($folderid) . $this->serverdelimiter.  $displayname;
         $csts = false;
-        // if $id is set => rename mailbox, otherwise create
-        if ($oldid) {
-            // rename doesn't work properly with IMAP
-            // the activesync client doesn't support a 'changing ID'
-            // TODO this would be solved by implementing hex ids (Mantis #459)
-            //$csts = imap_renamemailbox($this->mbox, $this->server . imap_utf7_encode(str_replace(".", $this->serverdelimiter, $oldid)), $newname);
-        }
-        else {
-            $csts = @imap_createmailbox($this->mbox, $newname);
-        }
+
+        $csts = ($oldid) ? imap_renamemailbox($this->mbox,  $this->server .$this->getImapIdFromFolderId($oldid) , $new) : imap_createmailbox($this->mbox, $new);
+
         if ($csts) {
-            return $this->StatFolder($folderid . $this->serverdelimiter . $displayname);
+           $newId =  $this->convertImapId($new);
+           return $this->StatFolder($newId);
         }
         else
@@ -936,7 +929,9 @@
      *
      */
-    public function DeleteFolder($id, $parentid){
-        // TODO implement
-        return false;
+    public function DeleteFolder($id, $parentid)
+    {
+        $ret = imap_deletemailbox($this->mbox , $this->server .$this->getImapIdFromFolderId($id) );
+        imap_expunge( $this->mbox );
+        return $ret;
     }
 
Index: branches/2.5/zpush/backend/expresso/providers/calendarProvider.php
===================================================================
--- branches/2.5/zpush/backend/expresso/providers/calendarProvider.php	(revision 8032)
+++ branches/2.5/zpush/backend/expresso/providers/calendarProvider.php	(revision 8232)
@@ -30,49 +30,49 @@
     {
         $return = array();
-        $criteria = CALENDAR_SYNC_SIGNED_CALENDARS ? array( 'filter' => array( 'AND' , array( '=' , 'type' , '0' ) , array( '=' , 'user' , $this->_uidnumber ))) : array( 'filter' => array ( 'AND'  ,array( '=' , 'isOwner' , '1' ),array( '=' , 'type' , '0' ) , array( '=' , 'user' , $this->_uidnumber ))); 
-        $sigs = Controller::find(array('concept' => 'calendarSignature'), array( 'id','calendar' ), $criteria); 
- 
-        if(Request::GetDeviceType()  == 'iPhone' || Request::GetDeviceType()  == 'iPad') 
-        { 
-            foreach($sigs as $sig) 
-            { 
-                $calendar =  Controller::read( array( 'concept' => 'calendar' , 'id' => $sig['calendar'] )); 
-                $tmpSig = array(); 
-                $tmpSig["id"] = 'calendar'.$sig['id']; 
-                $tmpSig["parent"] = 0; 
-                $tmpSig["mod"] = $calendar['name']; 
-                $return[] = $tmpSig; 
-            } 
-        } 
-        else 
-        { 
-            $defaultCalendar = Controller::find(array('concept' => 'modulePreference'), array('value','id') , array('filter' => array( 'and' , array('=' , 'name' , 'defaultCalendar') , array('=' , 'module' , 'expressoCalendar') , array('=' , 'user' , $this->_uidnumber )  )) ); 
- 
-            if(isset($defaultCalendar[0])) //Prioriza agenda default de importaÃÂ§ÃÂ£o pois o android so sincroniza a primeira agenda. 
-            { 
-                foreach($sigs as $i => $sig) 
-                { 
-                    if($sig['calendar'] == $defaultCalendar[0]['value']) 
-                    { 
-                        $calendar =  Controller::read( array( 'concept' => 'calendar' , 'id' => $sig['calendar'] )); 
-                        $tmpSig = array(); 
-                        $tmpSig["id"] = 'calendar'.$sig['id']; 
-                        $tmpSig["parent"] = 0; 
-                        $tmpSig["mod"] = $calendar['name']; 
-                        $return[] = $tmpSig; 
-                    } 
-                } 
-            } 
-            else 
-            { 
-                $sig = $sigs[0]; 
-                $calendar =  Controller::read( array( 'concept' => 'calendar' , 'id' => $sig['calendar'] )); 
-                $tmpSig = array(); 
-                $tmpSig["id"] = 'calendar'.$sig['id']; 
-                $tmpSig["parent"] = 0; 
-                $tmpSig["mod"] = $calendar['name']; 
-                $return[] = $tmpSig; 
- 
-            } 
+        $criteria = CALENDAR_SYNC_SIGNED_CALENDARS ? array( 'filter' => array( 'AND' , array( '=' , 'type' , '0' ) , array( '=' , 'user' , $this->_uidnumber ))) : array( 'filter' => array ( 'AND'  ,array( '=' , 'isOwner' , '1' ),array( '=' , 'type' , '0' ) , array( '=' , 'user' , $this->_uidnumber )));
+        $sigs = Controller::find(array('concept' => 'calendarSignature'), array( 'id','calendar' ), $criteria);
+
+        if(Request::GetDeviceType()  == 'iPhone' || Request::GetDeviceType()  == 'iPad')
+        {
+            foreach($sigs as $sig)
+            {
+                $calendar =  Controller::read( array( 'concept' => 'calendar' , 'id' => $sig['calendar'] ));
+                $tmpSig = array();
+                $tmpSig["id"] = 'calendar'.$sig['id'];
+                $tmpSig["parent"] = 0;
+                $tmpSig["mod"] = $calendar['name'];
+                $return[] = $tmpSig;
+            }
+        }
+        else
+        {
+            $defaultCalendar = Controller::find(array('concept' => 'modulePreference'), array('value','id') , array('filter' => array( 'and' , array('=' , 'name' , 'defaultCalendar') , array('=' , 'module' , 'expressoCalendar') , array('=' , 'user' , $this->_uidnumber )  )) );
+
+            if(isset($defaultCalendar[0])) //Prioriza agenda default de importaÃ§Ã£o pois o android so sincroniza a primeira agenda.
+            {
+                foreach($sigs as $i => $sig)
+                {
+                    if($sig['calendar'] == $defaultCalendar[0]['value'])
+                    {
+                        $calendar =  Controller::read( array( 'concept' => 'calendar' , 'id' => $sig['calendar'] ));
+                        $tmpSig = array();
+                        $tmpSig["id"] = 'calendar'.$sig['id'];
+                        $tmpSig["parent"] = 0;
+                        $tmpSig["mod"] = $calendar['name'];
+                        $return[] = $tmpSig;
+                    }
+                }
+            }
+            else
+            {
+                $sig = $sigs[0];
+                $calendar =  Controller::read( array( 'concept' => 'calendar' , 'id' => $sig['calendar'] ));
+                $tmpSig = array();
+                $tmpSig["id"] = 'calendar'.$sig['id'];
+                $tmpSig["parent"] = 0;
+                $tmpSig["mod"] = $calendar['name'];
+                $return[] = $tmpSig;
+
+            }
         }
 
@@ -154,5 +154,51 @@
     public function ChangeFolder($folderid, $oldid, $displayname, $type)
     {
-       return false;
+        if($oldid)
+        {
+            $idNumber = (int)str_replace('calendar' , '' , $oldid);
+            $calendarSignature =  Controller::read( array( 'concept' => 'calendarSignature' , 'id' => $idNumber ));
+
+            Controller::update( array('concept' => 'calendar' , 'id' => $calendarSignature['calendar']), array( 'name' => $displayname) );
+
+            return $this->StatFolder($oldid);
+        }
+        else
+        {
+             $cal = array('name' => $displayname,
+                'timezone' => 'America/Sao_Paulo',
+                'type' => '0'
+            );
+
+            $calCreated = Controller::create(array('concept' => 'calendar'), $cal);
+
+            if(!$calCreated){
+                return false;
+            }
+
+            $sig = array('user' => $_SESSION['wallet']['user']['uidNumber'],
+                'calendar' => $calCreated['id'],
+                'isOwner' => '1',
+                'dtstamp' => time() . '000',
+                'fontColor' => 'FFFFFF',
+                'backgroundColor' => '3366CC',
+                'borderColor' => '3366CC',
+            );
+
+            $sigCreated = Controller::create(array('concept' => 'calendarSignature'), $sig);
+
+            if(!$sigCreated){
+                return false;
+            }
+            else
+            {
+                $return = array();
+                $return["id"] = 'calendar'.$calCreated;
+                $return["parent"] = 0;
+                $return["mod"] = $displayname;
+                return $return;
+            }
+        }
+
+        return false;
 
     }
@@ -168,7 +214,17 @@
      * @throws StatusException              could throw specific SYNC_FSSTATUS_* exceptions
      */
-    public function DeleteFolder($id, $parentid)
-    {
-        return false;
+    public function DeleteFolder($id, $parent)
+    {
+        $interation = array();
+        $idNumber = (int)str_replace('calendar' , '' , $id);
+        $calendarSignature =  Controller::read( array( 'concept' => 'calendarSignature' , 'id' => $idNumber ));
+
+        $interation['calendar://' . $calendarSignature['calendar']] = false;
+        ob_start();
+        $args = $interation;
+        include EXPRESSO_PATH.'/prototype/Sync.php';
+        ob_end_clean();
+
+        return true;
     }
 
@@ -302,5 +358,5 @@
                                 break;
                             case 'd':
-                                $mult = 3600;
+                                $mult = 1440;
                                 break;
                             default:
@@ -316,5 +372,5 @@
                         case STATUS_ACCEPTED:
                             $message->busystatus = 2;
-                           break;
+                            break;
                         case STATUS_TENTATIVE:
                             $message->busystatus = 1;
@@ -333,7 +389,7 @@
         //------------------------------------------------------------------------------------------------------------//
 
-       /*
-       * SincronizaÃ§Ã£o de RecorrÃªncia
-       */
+        /*
+        * SincronizaÃ§Ã£o de RecorrÃªncia
+        */
         $repeats = Controller::find(array('concept' => 'repeat'), null , array( 'filter' => array( 'and' , array( '=' , 'schedulable' , $schedulable['id'] ),array( '!=' , 'frequency' , 'none' )  ) ));
         if(is_array($repeats) && count($repeats) > 0)
@@ -359,5 +415,5 @@
 
             if($repeat['endTime'])
-               $recur->until =  (int) substr($repeat['endTime'], 0, -3);
+                $recur->until =  (int) substr($repeat['endTime'], 0, -3);
 
             $recur->interval = $repeat['interval'] ? $repeat['interval'] : 1;
@@ -558,15 +614,15 @@
         $schedulable['timezone'] = $calendar['timezone'];
 
- 
-        $sv  = new DateTime('@'.($message->starttime + $GMT_CEL), $calendarSignatureTimezone); 
- 
-        if($sv->format('I') == 0) 
-            $schedulable['startTime'] = $schedulable['startTime'] - 3600000; 
- 
-        $ev  = new DateTime('@'.($message->endtime + $GMT_CEL), $calendarSignatureTimezone); 
- 
-        if($ev->format('I') == 0) 
-            $schedulable['endTime'] = $schedulable['endTime'] - 3600000; 
- 
+
+        $sv  = new DateTime('@'.($message->starttime + $GMT_CEL), $calendarSignatureTimezone);
+
+        if($sv->format('I') == 0)
+            $schedulable['startTime'] = $schedulable['startTime'] - 3600000;
+
+        $ev  = new DateTime('@'.($message->endtime + $GMT_CEL), $calendarSignatureTimezone);
+
+        if($ev->format('I') == 0)
+            $schedulable['endTime'] = $schedulable['endTime'] - 3600000;
+
         $schedulable['allDay'] = $message->alldayevent;
         $schedulable['description'] = $message->body;
@@ -741,5 +797,5 @@
             if($v['user']['id'] == $this->_uidnumber )
             {
-               $schedulable['participants'][$i]['status'] = $this->formatBusy($message->busystatus);
+                $schedulable['participants'][$i]['status'] = $this->formatBusy($message->busystatus);
             }
         }
@@ -779,15 +835,15 @@
         $schedulable['startTime'] = (($message->starttime + $GMT_CEL) + ($calendarSignatureTimezone->getOffset(new DateTime('@'.($message->starttime + $GMT_CEL), new DateTimeZone('UTC'))) * -1) ) *1000; //$message->starttime  * 1000;
         $schedulable['endTime'] = (($message->endtime + $GMT_CEL) + ($calendarSignatureTimezone->getOffset(new DateTime('@'.($message->endtime + $GMT_CEL), new DateTimeZone('UTC')))* -1)) *1000;//$message->endtime  * 1000;
- 
-        $sv  = new DateTime('@'.($message->starttime + $GMT_CEL), $calendarSignatureTimezone); 
- 
-        if($sv->format('I') == 0) 
-            $schedulable['startTime'] = $schedulable['startTime'] - 3600000; 
- 
-        $ev  = new DateTime('@'.($message->endtime + $GMT_CEL), $calendarSignatureTimezone); 
- 
-        if($ev->format('I') == 0) 
-            $schedulable['endTime'] = $schedulable['endTime'] - 3600000; 
- 
+
+        $sv  = new DateTime('@'.($message->starttime + $GMT_CEL), $calendarSignatureTimezone);
+
+        if($sv->format('I') == 0)
+            $schedulable['startTime'] = $schedulable['startTime'] - 3600000;
+
+        $ev  = new DateTime('@'.($message->endtime + $GMT_CEL), $calendarSignatureTimezone);
+
+        if($ev->format('I') == 0)
+            $schedulable['endTime'] = $schedulable['endTime'] - 3600000;
+
         $schedulable['timezone'] = $calendar['timezone'];
 
@@ -803,5 +859,5 @@
         $participant['isOrganizer'] = '1';
         $participant['acl'] = 'rowi';
-        $participant['status'] = '1'; 
+        $participant['status'] = '1';
 
         if($message->organizeremail)
@@ -1021,5 +1077,5 @@
             if($v['user']['id'] == $this->_uidnumber && $v['user']['isOrganizer']  == '1')
             {
-              $delete = true;
+                $delete = true;
             }
         }
@@ -1262,5 +1318,5 @@
                 break;
             case 0:
-               return STATUS_UNANSWERED;
+                return STATUS_UNANSWERED;
                 break;
         }
Index: branches/2.5/zpush/backend/expresso/expresso.php
===================================================================
--- branches/2.5/zpush/backend/expresso/expresso.php	(revision 7671)
+++ branches/2.5/zpush/backend/expresso/expresso.php	(revision 8232)
@@ -24,4 +24,6 @@
     private function getProvider( $folderId )
     {
+
+
         foreach($this->providers as $provider)
         {
@@ -109,5 +111,5 @@
     public function ChangeFolder($folderid, $oldid, $displayname, $type)
     {
-        // TODO: Implement ChangeFolder() method.
+        return $this->getProvider($oldid ? $oldid: $folderid)->ChangeFolder($folderid, $oldid, $displayname, $type);
     }
 
@@ -124,5 +126,5 @@
     public function DeleteFolder($id, $parentid)
     {
-        // TODO: Implement DeleteFolder() method.
+        return $this->getProvider($id)->DeleteFolder($id, $parentid);
     }
 
Index: branches/2.5/zpush/config.php
===================================================================
--- branches/2.5/zpush/config.php	(revision 8169)
+++ branches/2.5/zpush/config.php	(revision 8232)
@@ -284,7 +284,7 @@
     $row = pg_fetch_assoc( $rs );
 
-    $smtpConfig = parse_ini_file(EXPRESSO_PATH . '/prototype/config/SMTP.srv' , true ); 
-    $GLOBALS['config']['SMTP'] = $smtpConfig['config']; 
- 
+    $smtpConfig = parse_ini_file(EXPRESSO_PATH . '/prototype/config/SMTP.srv' , true );
+    $GLOBALS['config']['SMTP'] = $smtpConfig['config'];
+
     // ************************
     //  BackendIMAP settings
@@ -314,5 +314,5 @@
     define('IMAP_USE_IMAPMAIL', false);
 
-    define('CALENDAR_SYNC_SIGNED_CALENDARS', false); 
+    define('CALENDAR_SYNC_SIGNED_CALENDARS', false);
 
     $rs = pg_query( $GLOBALS['connections']['db'], 'SELECT app_id FROM phpgw_applications WHERE app_name = \'zpush\'' );
Index: branches/2.5/filemanager/setup/setup.inc.php
===================================================================
--- branches/2.5/filemanager/setup/setup.inc.php	(revision 7516)
+++ branches/2.5/filemanager/setup/setup.inc.php	(revision 8232)
@@ -14,5 +14,5 @@
 	$setup_info['filemanager']['name']    = 'filemanager';
 	$setup_info['filemanager']['title']   = 'Filemanager';
-	$setup_info['filemanager']['version'] = '2.5.0';
+	$setup_info['filemanager']['version'] = '2.5.1';
 	$setup_info['filemanager']['app_order'] = 6;
 	$setup_info['filemanager']['enable']  = 1;
@@ -28,5 +28,4 @@
     $setup_info['filemanager']['maintainer'] .= 'Coordenador do Projeto : Nilton Emilio Buhrer Neto<br/><br/>';	
 
-	$setup_info['filemanager']['tables'][] = 'phpgw_vfs';
     $setup_info['filemanager']['tables'][] = 'phpgw_vfs_quota';
 	$setup_info['filemanager']['tables'][] = 'phpgw_filemanager_notification';
@@ -48,5 +47,5 @@
 	(
 		 'appname' => 'phpgwapi',
-		 'versions' => array('2.5.0')
+		 'versions' => array('2.5.1.1')
 	);
 ?>
Index: branches/2.5/expressoAdmin1_2/setup/tables_update.inc.php
===================================================================
--- branches/2.5/expressoAdmin1_2/setup/tables_update.inc.php	(revision 7655)
+++ branches/2.5/expressoAdmin1_2/setup/tables_update.inc.php	(revision 8232)
@@ -339,8 +339,15 @@
 	}
 	$test[] = '2.4.2';
-        function expressoAdmin1_2_upgrade2_4_2()
-        {
-                $GLOBALS['setup_info']['expressoAdmin1_2']['currentver'] = '2.5.0';
-                return $GLOBALS['setup_info']['expressoAdmin1_2']['currentver'];
-        }
+    function expressoAdmin1_2_upgrade2_4_2()
+    {
+            $GLOBALS['setup_info']['expressoAdmin1_2']['currentver'] = '2.5.0';
+            return $GLOBALS['setup_info']['expressoAdmin1_2']['currentver'];
+    }
+
+    $test[] = '2.5.0';
+    function expressoAdmin1_2_upgrade2_5_0()
+    {
+        $GLOBALS['setup_info']['expressoAdmin1_2']['currentver'] = '2.5.1';
+        return $GLOBALS['setup_info']['expressoAdmin1_2']['currentver'];
+    }
 ?>
Index: branches/2.5/expressoAdmin1_2/setup/setup.inc.php
===================================================================
--- branches/2.5/expressoAdmin1_2/setup/setup.inc.php	(revision 7516)
+++ branches/2.5/expressoAdmin1_2/setup/setup.inc.php	(revision 8232)
@@ -13,5 +13,5 @@
 	$setup_info['expressoAdmin1_2']['title']     	= 'Expresso Admin';
 	/* Ao incrementar versão, não esquecer de declarar função do tables_update.inc.php*/
-	$setup_info['expressoAdmin1_2']['version']   	= '2.5.0';
+	$setup_info['expressoAdmin1_2']['version']   	= '2.5.1';
 	$setup_info['expressoAdmin1_2']['app_order']	= 1;
 	$setup_info['expressoAdmin1_2']['tables'][]		= 'phpgw_expressoadmin';
@@ -37,5 +37,5 @@
 	$setup_info['expressoAdmin1_2']['depends'][] = array(
 		'appname' => 'phpgwapi',
-		'versions' => Array('2.5.0')
+		'versions' => Array('2.5.1.1')
 	);
 ?>
Index: branches/2.5/expressoAdmin1_2/inc/class.db_functions.inc.php
===================================================================
--- branches/2.5/expressoAdmin1_2/inc/class.db_functions.inc.php	(revision 7769)
+++ branches/2.5/expressoAdmin1_2/inc/class.db_functions.inc.php	(revision 8232)
@@ -539,18 +539,14 @@
 	{
 		// AGENDA
-		$this->db->query('SELECT cal_id FROM phpgw_cal WHERE owner ='.$user_info['uidnumber']);
+		$this->db->query('SELECT calendar_id FROM calendar_signature WHERE user_uidnumber ='.$user_info['uidnumber'] . ' AND is_owner = 1' );
 		while($this->db->next_record())
 		{
 			$ids[] = $this->db->row();
 		}
+
 		if (count($ids))
 		{
 			foreach($ids as $i => $id)
-			{
-				$this->db->query('DELETE FROM phpgw_cal WHERE cal_id='.$id['cal_id']);
-				$this->db->query('DELETE FROM phpgw_cal_user WHERE cal_id='.$id['cal_id']);
-				$this->db->query('DELETE FROM phpgw_cal_repeats WHERE cal_id='.$id['cal_id']);
-				$this->db->query('DELETE FROM phpgw_cal_extra WHERE cal_id='.$id['cal_id']);
-			}
+                $this->db->query('DELETE FROM calendar WHERE id = '.$id['calendar_id']);
 		}
 		
Index: branches/2.5/expressoAdmin1_2/inc/class.uishared_accounts.inc.php
===================================================================
--- branches/2.5/expressoAdmin1_2/inc/class.uishared_accounts.inc.php	(revision 5907)
+++ branches/2.5/expressoAdmin1_2/inc/class.uishared_accounts.inc.php	(revision 8232)
@@ -107,7 +107,7 @@
                             'disabled_empty_inbox' => $this->functions->check_acl($account_lid,'empty_shared_accounts_inbox') ? '' : 'disabled',
                             'display_quota_used' => 'none',
-                            'aclExpressoCalendar' => (isset($config['defaultCalendar']) && ($config['defaultCalendar'] == 'expressoCalendar')) ? '' : 'none',
-                            'aclCalendar' => (isset($config['defaultCalendar']) && ($config['defaultCalendar'] == 'calendar')) ? '' : 'none',
-			    'calendarName' => (isset($config['defaultCalendar']) && ($config['defaultCalendar'] == 'calendar')) ? 'Calendar' : 'ExpressoCalendar',
+                            'aclExpressoCalendar' =>  '' ,
+                            'aclCalendar' => 'none',
+			                'calendarName' => 'ExpressoCalendar',
                             'sharedAccountsLocation' => isset($davicalConf['sharedAccountsLocation']) ? $davicalConf['sharedAccountsLocation'] : ''
 			  );
Index: branches/2.5/expressoAdmin1_2/inc/class.imap_functions.inc.php
===================================================================
--- branches/2.5/expressoAdmin1_2/inc/class.imap_functions.inc.php	(revision 7769)
+++ branches/2.5/expressoAdmin1_2/inc/class.imap_functions.inc.php	(revision 8232)
@@ -278,7 +278,7 @@
 	function getaclfrombox($params)
 	{
-		$boxacl = $params['uid'];
-		
-		$return = array();	
+        $boxacl = imap_utf7_encode($params['uid']);
+
+		$return = array();
 		
 		$mbox_acl = imap_getacl($this->imap, "user" . $this->imapDelimiter . $boxacl);
Index: branches/2.5/expressoAdmin1_2/inc/class.ldap_functions.inc.php
===================================================================
--- branches/2.5/expressoAdmin1_2/inc/class.ldap_functions.inc.php	(revision 8179)
+++ branches/2.5/expressoAdmin1_2/inc/class.ldap_functions.inc.php	(revision 8232)
@@ -138,4 +138,11 @@
 		}
 
+		if (empty($params['desc']))
+		{
+			$result['status'] = false;
+			$result['msg']  = $this->functions->lang('DESCRIPTION field is empty') . '.';
+			return $result;
+		}
+		
 		$uid = 'institutional_account_' . $params['mail'];
 		$dn = "uid=$uid," . $params['context'];
Index: branches/2.5/expressoAdmin1_2/js/jscode/shared_accounts.js
===================================================================
--- branches/2.5/expressoAdmin1_2/js/jscode/shared_accounts.js	(revision 8179)
+++ branches/2.5/expressoAdmin1_2/js/jscode/shared_accounts.js	(revision 8232)
@@ -97,5 +97,5 @@
 {
     combo_org_available_users = Element('ea_combo_org_available_users');
-    context = context.toLowerCase(); 
+    context = context.toLowerCase();
     for (i=0; i<combo_org_available_users.length; i++)
     {
@@ -300,5 +300,5 @@
 
 	    var combo_org = Element('ea_combo_org');
-            var context_to_select = data.user_context.toLowerCase(); 
+	    var context_to_select = data.user_context.toLowerCase();
 	    for (i=0; i<combo_org.length; i++)
 	    {
@@ -374,9 +374,10 @@
 
 		    for (var i=0; i < calendarPermission.length; i++){
-			sharemailbox.ownersExpressoCalendarAcl[ calendarPermission[i].user.uid ] = calendarPermission[i].aclValues;                   
-			sharemailbox.currentPemissions[calendarPermission[i].user.uid] = calendarPermission[i].id;
-			// sharemailbox.ownersExpressoCalendarAcl.length = sharemailbox.currentPemissions.length = i;
-		    
-			if(!current[calendarPermission[i].user.uid ]){
+			if (calendarPermission[i].user.uid ){
+				sharemailbox.ownersExpressoCalendarAcl[ calendarPermission[i].user.uid ] = calendarPermission[i].aclValues;                   
+				sharemailbox.currentPemissions[calendarPermission[i].user.uid] = calendarPermission[i].id;
+				// sharemailbox.ownersExpressoCalendarAcl.length = sharemailbox.currentPemissions.length = i;
+		    }
+			if(calendarPermission[i].user.uid && !current[calendarPermission[i].user.uid ]){
 			    Element('ea_select_owners').innerHTML = Element('ea_select_owners').innerHTML+'<option value='+ calendarPermission[i].user.uid +'>'+ calendarPermission[i].user.name +'</option>';
 			    Element('ea_select_owners').outerHTML = Element('ea_select_owners').outerHTML;
@@ -507,34 +508,34 @@
 
 	$.each(sharemailbox.ownersExpressoCalendarAcl, function(user, acl) {
-
-	    var usuario = DataLayer.get('user', {
-		filter: ['=','uid',user], 
-		criteria: {
-		    notExternal: true
+		if (user != "undefined"){
+		    var usuario = DataLayer.get('user', {
+			filter: ['=','uid',user], 
+			criteria: {
+			    notExternal: true
+			}
+		    });
+
+		    if($.isArray(usuario))
+			usuario = usuario[0];
+
+		    DataLayer.put('calendarToPermission', DataLayer.merge({
+			user:  usuario.id,
+			type: '0',
+			acl: acl,
+			calendar: calendar
+		    }, !!sharemailbox.currentPemissions[usuario.uid] ? {
+			id: sharemailbox.currentPemissions[usuario.uid]
+		    } : {}));
+
+		    if(!!!sharemailbox.currentPemissions[usuario.uid])
+			DataLayer.put('calendarSignature', {
+			    user: usuario.id,
+			    calendar:  calendar,
+			    isOwner:  '0',
+			    fontColor:  '000000',
+			    backgroundColor: 'f1efac',
+			    borderColor: 'eddb21'
+			});
 		}
-	    });
-
-	    if($.isArray(usuario))
-		usuario = usuario[0];
-
-	    DataLayer.put('calendarToPermission', DataLayer.merge({
-		user:  usuario.id,
-		type: '0',
-		acl: acl,
-		calendar: calendar
-	    }, !!sharemailbox.currentPemissions[usuario.uid] ? {
-		id: sharemailbox.currentPemissions[usuario.uid]
-	    } : {}));
-
-	    if(!!!sharemailbox.currentPemissions[usuario.uid])
-		DataLayer.put('calendarSignature', {
-		    user: usuario.id,
-		    calendar:  calendar,
-		    isOwner:  '0',
-		    fontColor:  '000000',
-		    backgroundColor: 'f1efac',
-		    borderColor: 'eddb21'
-		});
-
 	})
 	DataLayer.commit();  
@@ -622,5 +623,4 @@
 cShareMailbox.prototype.getaclfromuser = function(user)
 {
-	
     Element('em_input_readAcl').checked = false;
     Element('em_input_deleteAcl').checked = false;
@@ -642,6 +642,34 @@
     Element('em_input_deleteCalendar').disabled = true;
     Element('em_input_restrictCalendar').disabled = true;
-                
-                
+    
+    if (!this.ownersExpressoCalendarAcl[user] && !this.ownersCalendarAcl[user]){           
+  		DataLayer.dispatchPath = "prototype/";
+		var sharedUser = DataLayer.get('user', {
+		    filter: ['=','mail',$('#mail').val()]
+		});
+		for(var j = 0; j < sharedUser.length; j++)
+		    if(sharedUser[j].phpgwAccountType == 's'){
+			sharedUser = sharedUser[j];
+			break;
+		    }
+
+		var signature = DataLayer.get('calendarSignature', {
+		    filter: ['=','user', sharedUser.id]
+		});
+
+		if(!signature)
+		    return;
+
+		var usuario = DataLayer.get('user', {
+		    filter: ['=','uid',user], 
+		    criteria: {
+			notExternal: true
+		    }
+		});
+		var calendarPermission = DataLayer.get('calendarToPermission', {
+		    filter: ['AND', ['=','calendar',signature[0].calendar], ['=','user',usuario[0].id] ]
+		});
+		this.ownersExpressoCalendarAcl[user] = calendarPermission[0] ? calendarPermission[0].acl : "";
+    }
     if(this.ownersExpressoCalendarAcl[user])
     {
Index: branches/2.5/expressoAdmin1_2/index.php
===================================================================
--- branches/2.5/expressoAdmin1_2/index.php	(revision 6444)
+++ branches/2.5/expressoAdmin1_2/index.php	(revision 8232)
@@ -9,5 +9,8 @@
 	*  option) any later version.														 *
 	\*************************************************************************************/
-	
+	$GLOBALS['phpgw_info'] = array();
+	$GLOBALS['phpgw_info']['flags']['currentapp'] = 'expressoAdmin1_2';
+	include('../header.inc.php');
+    
         echo '
             <link rel="Stylesheet" type="text/css" href="../prototype/plugins/jquery/jquery-ui.css" />					
@@ -44,11 +47,6 @@
         ';
 
-        $debug = false;	
+    $debug = false;	
 	$time_start = microtime(true);
-
-	$GLOBALS['phpgw_info'] = array();
-	$GLOBALS['phpgw_info']['flags']['currentapp'] = 'expressoAdmin1_2';
-	include('../header.inc.php');
-
 	$c = CreateObject('phpgwapi.config','expressoAdmin1_2');
 	$c->read_repository();
Index: branches/2.5/listAdmin/setup/setup.inc.php
===================================================================
--- branches/2.5/listAdmin/setup/setup.inc.php	(revision 7516)
+++ branches/2.5/listAdmin/setup/setup.inc.php	(revision 8232)
@@ -9,5 +9,5 @@
 	$setup_info['listAdmin']['name'] = 'listAdmin';
 	$setup_info['listAdmin']['title'] = 'Mailman Admin';
-	$setup_info['listAdmin']['version'] = '2.5.0';
+	$setup_info['listAdmin']['version'] = '2.5.1';
 	$setup_info['listAdmin']['app_order'] = 10;
 	$setup_info['listAdmin']['enable'] = 1;
@@ -30,5 +30,5 @@
 	$setup_info['listAdmin']['depends'][] = array(
 		'appname' => 'phpgwapi',
-		'versions' => Array('2.0','2.1','2.2','2.4', '2.5.0')
+		'versions' => Array('2.5.1.1')
 	);
 ?>
Index: branches/2.5/admin/setup/setup.inc.php
===================================================================
--- branches/2.5/admin/setup/setup.inc.php	(revision 7516)
+++ branches/2.5/admin/setup/setup.inc.php	(revision 8232)
@@ -13,5 +13,5 @@
 	$setup_info['admin']['name']      = 'admin';
 	$setup_info['admin']['title']      = 'Admin';
-	$setup_info['admin']['version']   = '2.5.0';
+	$setup_info['admin']['version']   = '2.5.1';
 	$setup_info['admin']['app_order'] = 1;
 	$setup_info['admin']['tables']    = '';
@@ -48,5 +48,5 @@
 	$setup_info['admin']['depends'][] = array(
 		'appname' => 'phpgwapi',
-		'versions' => Array('2.5.0')
+		'versions' => Array('2.5.1.1')
 	);
 ?>
Index: branches/2.5/admin/inc/hook_admin.inc.php
===================================================================
--- branches/2.5/admin/inc/hook_admin.inc.php	(revision 5804)
+++ branches/2.5/admin/inc/hook_admin.inc.php	(revision 8232)
@@ -85,9 +85,5 @@
 		$file['VoIP settings']         = $GLOBALS['phpgw']->link('/index.php','menuaction=admin.uivoip.edit_conf');
 	}
-	
-	if (! $GLOBALS['phpgw']->acl->check('site_config_access',1,'admin'))
-	{
-		$file['Calendar settings'] = $GLOBALS['phpgw']->link('/index.php','menuaction=admin.uicalendar.edit_conf');
-	}
+
 
 	/* Do not modify below this line */
Index: branches/2.5/admin/inc/class.uiconfig.inc.php
===================================================================
--- branches/2.5/admin/inc/class.uiconfig.inc.php	(revision 8176)
+++ branches/2.5/admin/inc/class.uiconfig.inc.php	(revision 8232)
@@ -59,6 +59,6 @@
 			$t = CreateObject('phpgwapi.Template',$GLOBALS['phpgw']->common->get_tpl_dir($appname));
 			$t->set_unknowns('keep');
-                        $template_file = $config_appname == "migra" ? 'migra.tpl' : 'config.tpl';        
-                        $t->set_file(array('config' => $template_file)); 
+			$template_file = $config_appname == "migra" ? 'migra.tpl' : 'config.tpl';	
+			$t->set_file(array('config' => $template_file));
 			$t->set_block('config','header','header');
 			$t->set_block('config','body','body');
@@ -73,28 +73,28 @@
 			}
 	
-                if($appname === "expressoCalendar"){ 
- 
-            if($config_appname == 'expressoCalendar' ) 
-            { 
-                $t->set_var('action_url',$GLOBALS['phpgw']->link('/index.php','menuaction=admin.uiconfig.index&appname=' . $appname)); 
- 
-            }; 
- 
-            if($_POST['newsettings']['expressoCalendar_autoImportCalendars'] == 'true') 
-            { 
-                $db = $GLOBALS['phpgw']->db; 
-                $calendars = array(); 
-                $db->query('SELECT calendar_signature.user_uidnumber as "user",calendar.id as "calendar" FROM calendar,calendar_signature WHERE calendar.id = calendar_signature.calendar_id AND calendar.type = 0 AND calendar_signature.is_owner = 1 AND (SELECT id from module_preference WHERE user_uidnumber = calendar_signature.user_uidnumber AND module_preference.module = \'expressoCalendar\' AND module_preference.name = \'dafaultImportCalendar\'  ) IS NULL'); 
-                while( $db->next_record() ) 
-                { 
-                    $calendars[] = $db->row(); 
-                } 
- 
-                foreach($calendars as $v) 
-                { 
-                    $db->query('INSERT INTO module_preference ("user_uidnumber","value","name","module") VALUES ( \''.$v['user'].'\' , \''.$v['calendar'].'\',\'dafaultImportCalendar\' , \'expressoCalendar\')'); 
-                } 
-            } 
- 
+		if($appname === "expressoCalendar"){
+
+            if($config_appname == 'expressoCalendar' )
+            {
+                $t->set_var('action_url',$GLOBALS['phpgw']->link('/index.php','menuaction=admin.uiconfig.index&appname=' . $appname));
+
+            };
+
+            if($_POST['newsettings']['expressoCalendar_autoImportCalendars'] == 'true')
+            {
+                $db = $GLOBALS['phpgw']->db;
+                $calendars = array();
+                $db->query('SELECT calendar_signature.user_uidnumber as "user",calendar.id as "calendar" FROM calendar,calendar_signature WHERE calendar.id = calendar_signature.calendar_id AND calendar.type = 0 AND calendar_signature.is_owner = 1 AND (SELECT id from module_preference WHERE user_uidnumber = calendar_signature.user_uidnumber AND module_preference.module = \'expressoCalendar\' AND module_preference.name = \'dafaultImportCalendar\'  ) IS NULL');
+                while( $db->next_record() )
+                {
+                    $calendars[] = $db->row();
+                }
+
+                foreach($calendars as $v)
+                {
+                    $db->query('INSERT INTO module_preference ("user_uidnumber","value","name","module") VALUES ( \''.$v['user'].'\' , \''.$v['calendar'].'\',\'dafaultImportCalendar\' , \'expressoCalendar\')');
+                }
+            }
+
 			if (isset($_POST['migration']) && ($_POST['migration']  == "true")){
 			
@@ -104,5 +104,5 @@
 				$migratrion->calendar();
 			}
- 
+
 		}
 
Index: branches/2.5/admin/inc/class.uicalendar.inc.php
===================================================================
--- branches/2.5/admin/inc/class.uicalendar.inc.php	(revision 5804)
+++ 	(revision )
@@ -1,86 +1,0 @@
-<?php
-
- /**************************************************************************\
-  * Expresso Livre - Voip - administration                                   *
-  *															                 *
-  * --------------------------------------------                             *
-  *  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.                                              *
-  \**************************************************************************/
-
-class uicalendar
-{
-	var $public_functions = array(
-		'edit_conf' => True
-	);
-
-	final function __construct(){}
-	
-	final function edit_conf()
-	{
-		if($GLOBALS['phpgw']->acl->check('applications_access',1,'admin'))
-		{
-			$GLOBALS['phpgw']->redirect_link('/index.php');
-		}		
-
-		$GLOBALS['phpgw_info']['flags']['app_header'] = lang('Admin') .' - ' . lang('Configuration Calendars');
-
-		if(!@is_object($GLOBALS['phpgw']->js))
-		{
-			$GLOBALS['phpgw']->js = CreateObject('phpgwapi.javascript');
-		}
-
-		$webserver_url = $GLOBALS['phpgw_info']['server']['webserver_url'];
-		$webserver_url = ( !empty($webserver_url) ) ? $webserver_url : '/';
-
-		if(strrpos($webserver_url,'/') === false || strrpos($webserver_url,'/') != (strlen($webserver_url)-1))
-			$webserver_url .= '/';
-
-		$js = array('connector','xtools','functions');
-	
-		foreach( $js as $tmp )
-			$GLOBALS['phpgw']->js->validate_file('calendar',$tmp,'admin');
-		
-		$GLOBALS['phpgw']->common->phpgw_header();
-		echo parse_navbar();
-		echo '<script type="text/javascript">var path_adm="'.$webserver_url .'"</script>';
-		
-	    $c = CreateObject('phpgwapi.config','phpgwapi');
-		$c->read_repository();
-		$current_config = $c->config_data;    
- 	
-		if(isset($current_config['defaultCalendar'])){
-			$selected =  $current_config['defaultCalendar'] == 'calendar' ?  'calendar' :  'expressoCalendar';
-			$option = $selected == 'calendar' ?  'expressoCalendar' :  'calendar';
-		}else{
-			$selected = 'calendar';
-			$option = 'expressoCalendar';
-		}	
-	
-		$t = CreateObject('phpgwapi.Template', $GLOBALS['phpgw']->common->get_tpl_dir('admin'));
-		$t->set_unknowns('keep');
-		$t->set_file(array('calendar' => 'calendar.tpl'));
-		$t->set_block('calendar','calendar_page','calendar_page');
-		$t->set_var(array(
-                        'action_url' => $GLOBALS['phpgw']->link('/index.php','menuaction=admin.uiconfig.index&appname=admin'),
-                        'lang_Calendar_default_for_current_installation' => lang('Calendar default for current installation'),
-                        'lang_Calendar_settings' => 'Configuração do Calendar',	
-                        'lang_save' => lang('Save'),
-                        'lang_cancel' => lang('Cancel'),
-                        'selected' => $selected,
-                        'option' => $option
-                ));
-		$t->pparse('out','calendar');
-	}
-	
-	function display_row($label, $value)
-	{
-		$GLOBALS['phpgw']->template->set_var('tr_color',$this->nextmatchs->alternate_row_color());
-		$GLOBALS['phpgw']->template->set_var('label',$label);
-		$GLOBALS['phpgw']->template->set_var('value',$value);
-		$GLOBALS['phpgw']->template->parse('rows','row',True);
-	}
-}
-?>
Index: branches/2.5/admin/templates/default/calendar.tpl
===================================================================
--- branches/2.5/admin/templates/default/calendar.tpl	(revision 5804)
+++ 	(revision )
@@ -1,26 +1,0 @@
-	<!-- BEGIN calendar_page -->
-	<form method="POST" action="{action_url}">
-	<table align="center" width="60%" cellspacing="2" style="border: 1px solid #000000;">
-		<tr class="th">
-			<td colspan="2">&nbsp;<b>{lang_Calendar_settings}</b></td>
-		</tr>
-		<tr class="row_off">
-			<td>{lang_Calendar_default_for_current_installation}:</td>
-			<td>
-				<select name="newsettings[defaultCalendar]"> 
-					<option value="{selected}">{selected}</option> 
-					<option value="{option}"  >{option}</option> 
-				</select> 
-			</td>
-		</tr>   
-
-		<tr>
-			<td colspan="2" align="center">
-			  <input type="submit" name="submit" value="{lang_save}">
-			  <input type="submit" name="submit" value="{lang_cancel}">
-			  <br>
-			</td>
-		</tr>
-	</table>
-	</form>
-	<!-- END calendar_page -->
Index: branches/2.5/help/setup/setup.inc.php
===================================================================
--- branches/2.5/help/setup/setup.inc.php	(revision 7517)
+++ branches/2.5/help/setup/setup.inc.php	(revision 8232)
@@ -13,5 +13,5 @@
 	$setup_info['help']['name']      = 'help';
 	$setup_info['help']['title']     = 'User Manual and Help Page';
-	$setup_info['help']['version']   = '2.5.0';
+	$setup_info['help']['version']   = '2.5.1';
 	$setup_info['help']['app_order'] = 5;
 	$setup_info['help']['enable']    = 2;	// Invisible on top (navigation bar)
@@ -26,5 +26,5 @@
 	$setup_info['help']['depends'][] = array(
 		 'appname' => 'phpgwapi',
-		 'versions' => Array('2.5.0')
+		 'versions' => Array('2.5.1.1')
 	);
 ?>
Index: branches/2.5/help/enviasugestao.php
===================================================================
--- branches/2.5/help/enviasugestao.php	(revision 3024)
+++ branches/2.5/help/enviasugestao.php	(revision 8232)
@@ -24,7 +24,7 @@
 	$params['input_to'] = $GLOBALS['phpgw_info']['server']['sugestoes_email_to'];
 	$params['input_cc'] = $GLOBALS['phpgw_info']['server']['sugestoes_email_cc'];
-	$params['input_cc'] = $GLOBALS['phpgw_info']['server']['sugestoes_email_bcc'];
+	$params['input_bcc'] = $GLOBALS['phpgw_info']['server']['sugestoes_email_bcc'];
 	$params['input_subject'] = 	lang("Suggestions");
-	$params['body']	= $_POST['body'];
+	$params['body']	= base64_encode($_POST['body']);
 	$params['type'] = 'textplain'; 
 	$GLOBALS['phpgw']->preferences->read_repository();
Index: branches/2.5/jabberit_messenger/setup/setup.inc.php
===================================================================
--- branches/2.5/jabberit_messenger/setup/setup.inc.php	(revision 7516)
+++ branches/2.5/jabberit_messenger/setup/setup.inc.php	(revision 8232)
@@ -8,5 +8,5 @@
 	$setup_info['jabberit_messenger']['name']      	= 'jabberit_messenger';
 	$setup_info['jabberit_messenger']['title']     	= 'Expresso Messenger';
-	$setup_info['jabberit_messenger']['version']   	= '2.5.0';
+	$setup_info['jabberit_messenger']['version']   	= '2.5.1';
 	$setup_info['jabberit_messenger']['app_order'] 	= 9;
 	$setup_info['jabberit_messenger']['enable']    	= 1;
@@ -27,5 +27,5 @@
 	$setup_info['jabberit_messenger']['depends'][] = array(
 		'appname' => 'phpgwapi',
-		'versions' => Array('2.5.0')
+		'versions' => Array('2.5.1.1')
 	);
 ?>
Index: branches/2.5/contactcenter/setup/default_records.inc.php
===================================================================
--- branches/2.5/contactcenter/setup/default_records.inc.php	(revision 2)
+++ branches/2.5/contactcenter/setup/default_records.inc.php	(revision 8232)
@@ -19,5 +19,5 @@
 	$oProc->query("insert into phpgw_cc_typeof_ct_addrs (id_typeof_contact_address,contact_address_type_name) values(1,'Comercial')");	
 	$oProc->query("insert into phpgw_cc_typeof_ct_addrs (id_typeof_contact_address,contact_address_type_name) values(2,'Residencial')");
-
+  $oProc->query("ALTER TABLE phpgw_cc_groups SET WITH OIDS;");
 	// Populate brazilian database.
 	include("states_pt-br.inc.php"); 
Index: branches/2.5/contactcenter/setup/tables_update.inc.php
===================================================================
--- branches/2.5/contactcenter/setup/tables_update.inc.php	(revision 7516)
+++ branches/2.5/contactcenter/setup/tables_update.inc.php	(revision 8232)
@@ -100,7 +100,13 @@
     	}
 	$test[] = '2.4.2';
-    	function contactcenter_upgrade2_4_2() {
-        	$GLOBALS['setup_info']['contactcenter']['currentver'] = '2.5.0';
-        	return $GLOBALS['setup_info']['contactcenter']['currentver'];
-    	}
+    function contactcenter_upgrade2_4_2() {
+        $GLOBALS['setup_info']['contactcenter']['currentver'] = '2.5.0';
+        return $GLOBALS['setup_info']['contactcenter']['currentver'];
+    }
+
+    $test[] = '2.5.0';
+    function contactcenter_upgrade2_5_0() {
+        $GLOBALS['setup_info']['contactcenter']['currentver'] = '2.5.1';
+        return $GLOBALS['setup_info']['contactcenter']['currentver'];
+    }
 ?>
Index: branches/2.5/contactcenter/setup/setup.inc.php
===================================================================
--- branches/2.5/contactcenter/setup/setup.inc.php	(revision 7516)
+++ branches/2.5/contactcenter/setup/setup.inc.php	(revision 8232)
@@ -17,5 +17,5 @@
 	$setup_info['contactcenter']['name']      = 'contactcenter';
 	$setup_info['contactcenter']['title']     = 'ContactCenter';
-	$setup_info['contactcenter']['version']   = '2.5.0';
+	$setup_info['contactcenter']['version']   = '2.5.1';
 	$setup_info['contactcenter']['app_order'] = 4;
 	$setup_info['contactcenter']['enable']    = 1;
@@ -77,5 +77,5 @@
 	$setup_info['contactcenter']['depends'][] = array(
 		'appname' => 'phpgwapi',
-		'versions' => Array('2.5.0')
+		'versions' => Array('2.5.1.1')
 	);
 ?>
Index: branches/2.5/contactcenter/js/cc.js
===================================================================
--- branches/2.5/contactcenter/js/cc.js	(revision 7497)
+++ branches/2.5/contactcenter/js/cc.js	(revision 8232)
@@ -1250,4 +1250,5 @@
 		states.disabled = false;
 		var i = 1;
+		/*
 		for (var j in data['data'])
 		{
@@ -1255,6 +1256,12 @@
 			if(i == 1) data['data'] = data['data'].sort();
 			i++;
-		}
-
+		}*/
+		jQuery.each(data['data'],function(index,value){
+			if (value != undefined){
+				states.options[i] = new Option(value, index);
+				if(i == 1) data['data'] = data['data'].sort();
+				i++;
+			}			
+		});
 		states.disabled = false;
 		states.selectedIndex = 0;
@@ -1366,10 +1373,16 @@
 		cities.disabled = false;
 		var i = 1;
+		/*
 		for (var j in data['data'])
 		{
 			cities.options[i] = new Option(data['data'][j], j);
 			i++;
-		}
-
+		}*/
+		jQuery.each(data['data'],function(index,value){
+			if (value != undefined){
+				cities.options[i] = new Option(value,index);
+				i++;
+			}
+		});
 		cities.disabled = false;
 		cities.selectedIndex = 0;
Index: branches/2.5/emailadmin/setup/tables_update.inc.php
===================================================================
--- branches/2.5/emailadmin/setup/tables_update.inc.php	(revision 7516)
+++ branches/2.5/emailadmin/setup/tables_update.inc.php	(revision 8232)
@@ -142,10 +142,17 @@
       return $GLOBALS['setup_info']['emailadmin']['currentver'];
    }
-	$test[] = '2.4.2';
-	function emailadmin_upgrade2_4_2()
-	{
-      		$GLOBALS['setup_info']['emailadmin']['currentver'] = '2.5.0';
-      		return $GLOBALS['setup_info']['emailadmin']['currentver'];
-	}
+    $test[] = '2.4.2';
+    function emailadmin_upgrade2_4_2()
+    {
+            $GLOBALS['setup_info']['emailadmin']['currentver'] = '2.5.0';
+            return $GLOBALS['setup_info']['emailadmin']['currentver'];
+    }
+
+    $test[] = '2.5.0';
+    function emailadmin_upgrade2_5_0()
+    {
+        $GLOBALS['setup_info']['emailadmin']['currentver'] = '2.5.1';
+        return $GLOBALS['setup_info']['emailadmin']['currentver'];
+    }
 
 ?>
Index: branches/2.5/emailadmin/setup/setup.inc.php
===================================================================
--- branches/2.5/emailadmin/setup/setup.inc.php	(revision 7516)
+++ branches/2.5/emailadmin/setup/setup.inc.php	(revision 8232)
@@ -14,5 +14,5 @@
 	$setup_info['emailadmin']['name']      = 'emailadmin';
 	$setup_info['emailadmin']['title']     = 'EMailAdmin';
-	$setup_info['emailadmin']['version']   = '2.5.0';
+	$setup_info['emailadmin']['version']   = '2.5.1';
 	$setup_info['emailadmin']['app_order'] = 10;
 	$setup_info['emailadmin']['enable']    = 2;
@@ -40,5 +40,5 @@
 	$setup_info['emailadmin']['depends'][] = array(
 		'appname'  => 'phpgwapi',
-		'versions' => Array('2.5.0')
+		'versions' => Array('2.5.1.1')
 	);
 
Index: branches/2.5/emailadmin/inc/class.ui.inc.php
===================================================================
--- branches/2.5/emailadmin/inc/class.ui.inc.php	(revision 7673)
+++ branches/2.5/emailadmin/inc/class.ui.inc.php	(revision 8232)
@@ -77,5 +77,60 @@
 			print $this->t->get('out','main');
 		}
-	
+
+       function countProfiles(){
+            $return =  $this->boemailadmin->getProfileList();
+            (is_array($return) && count($return) > 0) ? $return = count($return) : $return = 0;
+    		return $return;
+        }
+
+       function addDefaultProfile()
+       {
+            $emailServer = $_SESSION['phpgw_info']['expressomail']['email_server'];          
+            $globalSettings = array(
+    			"profileID" => "",
+    			"description" => "Expresso",
+    			"defaultDomain" => $emailServer['defaultDomain'],
+    			"organisationName" => $emailServer['organisationName'],
+    			"userDefinedAccounts" => "0"
+            );
+
+            $smtpSettings   = array(
+            	"smtpServer" => "127.0.0.1",
+            	"smtpPort" => "25",
+            	"smtpAuth" => "",
+	            "smtpType" => "2", 
+	            "smtpLDAPServer" => "127.0.0.1", 
+	            "smtpLDAPAdminDN" => $emailServer['smtpLDAPAdminDN'],
+	            "smtpLDAPAdminPW" => $emailServer['smtpLDAPAdminPW'],
+	            "smtpLDAPBaseDN" =>  $emailServer['smtpLDAPBaseDN]'],
+	            "smtpLDAPUseDefault" => "yes"
+            );
+
+            $imapSettings = array(
+	            'imapServer' => "127.0.0.1",
+	            'imapPort' => "143",
+	            'imapDelimiter' => "/",
+	            'imapType' => "3",
+	            'imapLoginType' => "standard",
+	            'imapTLSEncryption' => "1",
+	            'imapTLSAuthentication' => "",
+	            'imapoldcclient' => "",
+	            'imapEnableCyrusAdmin' => "yes",
+	            'imapAdminUsername' => "expresso-admin",
+	            'imapAdminPW' => $emailServer['imapAdminPW'],
+	            'imapEnableSieve' => "yes",
+	            'imapSieveServer' => "127.0.0.1",
+	            'imapSievePort' => "2000",
+	            'imapCreateSpamFolder' => "yes",
+	            'imapCyrusUserPostSpam' => "",
+	            'imapDefaultTrashFolder' => "Trash",
+	            'imapDefaultSentFolder' => "Sent",
+	            'imapDefaultDraftsFolder' => "Drafts",
+	            'imapDefaultSpamFolder' => "Spam"
+            );
+
+            $this->boemailadmin->saveProfile($globalSettings, $smtpSettings, $imapSettings);
+        }
+
 		function css()
 		{
Index: branches/2.5/setup/check_install.php
===================================================================
--- branches/2.5/setup/check_install.php	(revision 7681)
+++ branches/2.5/setup/check_install.php	(revision 8232)
@@ -98,11 +98,11 @@
 			'safe_mode' => 'max_execution_time = 30'
 		),
-		'include_path' => array(
-			'func' => 'php_ini_check',
-			'value' => '.',
-			'check' => 'contain',
-			'error' => lang('include_path need to contain "." - the current directory'),
-			'save_mode' => 'max_execution_time = 30'
-		),
+#		'include_path' => array(
+#			'func' => 'php_ini_check',
+#			'value' => '.',
+#			'check' => 'contain',
+#			'error' => lang('include_path need to contain "." - the current directory'),
+#			'save_mode' => 'max_execution_time = 30'
+#		),
 #		'mysql' => array(
 #			'func' => 'extension_check',
Index: branches/2.5/preferences/setup/setup.inc.php
===================================================================
--- branches/2.5/preferences/setup/setup.inc.php	(revision 7516)
+++ branches/2.5/preferences/setup/setup.inc.php	(revision 8232)
@@ -13,5 +13,5 @@
 	$setup_info['preferences']['name']      = 'preferences';
 	$setup_info['preferences']['title']     = 'Preferences';
-	$setup_info['preferences']['version']   = '2.5.0';
+	$setup_info['preferences']['version']   = '2.5.1';
 	$setup_info['preferences']['app_order'] = 1;
 	$setup_info['preferences']['tables']    = '';
@@ -28,5 +28,5 @@
 	$setup_info['preferences']['depends'][] = array(
 		'appname' => 'phpgwapi',
-		'versions' => Array('2.5.0')
+		'versions' => Array('2.5.1.1')
 	);
 ?>
Index: branches/2.5/preferences/changepassword.php
===================================================================
--- branches/2.5/preferences/changepassword.php	(revision 3296)
+++ branches/2.5/preferences/changepassword.php	(revision 8232)
@@ -108,4 +108,5 @@
 	$GLOBALS['phpgw']->template->set_var('lang_change',lang('Change'));
 	$GLOBALS['phpgw']->template->set_var('lang_cancel',lang('Cancel'));
+    	$GLOBALS['phpgw']->template->set_var('cancel_action' , $GLOBALS['phpgw']->link('/preferences/')); 
 	$GLOBALS['phpgw']->template->set_var('form_action',$GLOBALS['phpgw']->link('/preferences/changepassword.php'));
 
Index: branches/2.5/expressoCalendar/setup/tables_current.inc.php
===================================================================
--- branches/2.5/expressoCalendar/setup/tables_current.inc.php	(revision 7938)
+++ branches/2.5/expressoCalendar/setup/tables_current.inc.php	(revision 8232)
@@ -234,5 +234,5 @@
                 'uidnumber' => array(  'type' => 'int', 'precision' => '8', 'nullable' => False),
                 'object_id' => array(  'type' => 'int', 'precision' => '8', 'nullable' => False),
-                'owner' => array(  'type' => 'int', 'precision' => '8', 'nullable' => False), 
+                'owner' => array(  'type' => 'int', 'precision' => '8', 'nullable' => False),
                 'object_type' => array(  'type' => 'int', 'precision' => '8', 'nullable' => False),
                 'permission' => array(  'type' => 'varchar','precision' => '50', 'nullable' => False)
@@ -313,6 +313,6 @@
                 'background_color' => array(  'type' => 'varchar','precision' => '6', 'nullable' => True),
                 'border_color' => array(  'type' => 'varchar','precision' => '6', 'nullable' => True),
-                'type' => array('type' => 'int', 'precision' => '2' ,'nullable' => false, 'default' => 0), 
-                'hidden' => array('type' => 'int', 'precision' => '2' ,'nullable' => false, 'default' => 0) 
+                'type' => array('type' => 'int', 'precision' => '2' ,'nullable' => false, 'default' => 0),
+                'hidden' => array('type' => 'int', 'precision' => '2' ,'nullable' => false, 'default' => 0)
             ),
             'pk' => array('id'),
Index: branches/2.5/expressoCalendar/setup/tables_update.inc.php
===================================================================
--- branches/2.5/expressoCalendar/setup/tables_update.inc.php	(revision 7938)
+++ branches/2.5/expressoCalendar/setup/tables_update.inc.php	(revision 8232)
@@ -234,14 +234,14 @@
         return $GLOBALS['setup_info']['expressoCalendar']['currentver'];
     };
- 
-    $test[] = '1.011'; 
-    function expressoCalendar_upgrade1_011() { 
-        $oProc = $GLOBALS['phpgw_setup']->oProc; 
- 
-        $oProc->query("ALTER TABLE calendar_signature ADD COLUMN hidden integer"); 
- 
-        $GLOBALS['setup_info']['expressoCalendar']['currentver'] = '1.012'; 
-        return $GLOBALS['setup_info']['expressoCalendar']['currentver']; 
-    }; 
+
+    $test[] = '1.011';
+    function expressoCalendar_upgrade1_011() {
+        $oProc = $GLOBALS['phpgw_setup']->oProc;
+
+        $oProc->query("ALTER TABLE calendar_signature ADD COLUMN hidden integer");
+
+        $GLOBALS['setup_info']['expressoCalendar']['currentver'] = '1.012';
+        return $GLOBALS['setup_info']['expressoCalendar']['currentver'];
+    };
         
 ?>
Index: branches/2.5/expressoCalendar/inc/hook_admin.inc.php
===================================================================
--- branches/2.5/expressoCalendar/inc/hook_admin.inc.php	(revision 7982)
+++ branches/2.5/expressoCalendar/inc/hook_admin.inc.php	(revision 8232)
@@ -13,6 +13,6 @@
 	$title = $appname;
 	$file = Array(
-                'ExpressoCalendar migration' => $GLOBALS['phpgw']->link('/index.php','menuaction=admin.uiconfig.index&appname=' . $appname. '&config=migra'), 
-        'Global Settings' => $GLOBALS['phpgw']->link('/index.php','menuaction=admin.uiconfig.index&appname=' . $appname) 
+		'ExpressoCalendar migration' => $GLOBALS['phpgw']->link('/index.php','menuaction=admin.uiconfig.index&appname=' . $appname. '&config=migra'),
+        'Global Settings' => $GLOBALS['phpgw']->link('/index.php','menuaction=admin.uiconfig.index&appname=' . $appname)
 	);
 	//Do not modify below this line
Index: branches/2.5/expressoCalendar/templates/default/config.tpl
===================================================================
--- branches/2.5/expressoCalendar/templates/default/config.tpl	(revision 7982)
+++ branches/2.5/expressoCalendar/templates/default/config.tpl	(revision 8232)
@@ -1,34 +1,34 @@
 <!-- BEGIN header -->
-<form method="POST" action="{action_url}"> 
-    <table border="0" align="center"> 
-        <!-- END header --> 
-        <!-- BEGIN body --> 
-        <tr class="th"> 
-            <td colspan="2" align="center"><b>{lang_expressoCalendar_Setup}</b></td> 
-        </tr> 
- 
-        <tr><td></td></tr> 
- 
-        <tr class="row_off"> 
-            <td>{lang_Auto_import_calendars_to_receive_an_internal_event}:</td> 
-            <td> 
-                <select name="newsettings[expressoCalendar_autoImportCalendars]"> 
-                    <option value="false" {selected_expressoCalendar_autoImportCalendars_false}>{lang_no}</option> 
-                    <option value="true"  {selected_expressoCalendar_autoImportCalendars_true}>{lang_yes}</option> 
-                </select> 
-            </td> 
-        </tr> 
-        <!-- END body --> 
-        <!-- BEGIN footer --> 
-        <tr class="th"> 
-            <td colspan="2">&nbsp;</td> 
-        </tr> 
-        <tr> 
-            <td colspan="2" align="center"> 
-                <input type="submit" name="submit" value="{lang_submit}"> 
-                <input type="submit" name="cancel" value="{lang_cancel}"> 
-            </td> 
-        </tr> 
-    </table> 
+<form method="POST" action="{action_url}">
+    <table border="0" align="center">
+        <!-- END header -->
+        <!-- BEGIN body -->
+        <tr class="th">
+            <td colspan="2" align="center"><b>{lang_expressoCalendar_Setup}</b></td>
+        </tr>
+
+        <tr><td></td></tr>
+
+        <tr class="row_off">
+            <td>{lang_Auto_import_calendars_to_receive_an_internal_event}:</td>
+            <td>
+                <select name="newsettings[expressoCalendar_autoImportCalendars]">
+                    <option value="false" {selected_expressoCalendar_autoImportCalendars_false}>{lang_no}</option>
+                    <option value="true"  {selected_expressoCalendar_autoImportCalendars_true}>{lang_yes}</option>
+                </select>
+            </td>
+        </tr>
+        <!-- END body -->
+        <!-- BEGIN footer -->
+        <tr class="th">
+            <td colspan="2">&nbsp;</td>
+        </tr>
+        <tr>
+            <td colspan="2" align="center">
+                <input type="submit" name="submit" value="{lang_submit}">
+                <input type="submit" name="cancel" value="{lang_cancel}">
+            </td>
+        </tr>
+    </table>
 </form>
 <!-- END footer -->
Index: branches/2.5/prototype/plugins/jquery.cycle/jquery.cycle.js
===================================================================
--- branches/2.5/prototype/plugins/jquery.cycle/jquery.cycle.js	(revision 8232)
+++ branches/2.5/prototype/plugins/jquery.cycle/jquery.cycle.js	(revision 8232)
@@ -0,0 +1,10 @@
+/*
+ * jQuery Cycle Plugin (with Transition Definitions)
+ * Examples and documentation at: http://malsup.com/jquery/cycle/
+ * Copyright (c) 2007-2008 M. Alsup
+ * Version: 2.30 (02-NOV-2008)
+ * Dual licensed under the MIT and GPL licenses:
+ * http://www.opensource.org/licenses/mit-license.php
+ * http://www.gnu.org/licenses/gpl.html
+ */
+;eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}(';(4($){8 q=\'2.30\';8 r=$.25.26&&/37 6.0/.1u(38.39);4 1n(){7(27.28&&27.28.1n)27.28.1n(\'[B] \'+3a.3b.3c.3d(2x,\'\'))};$.E.B=4(n){8 o=2x[1];O x.1s(4(){7(n===3e||n===P)n={};7(n.29==2y){3f(n){2a\'3g\':7(x.S)1v(x.S);x.S=0;$(x).1F(\'B.1M\',\'\');O;2a\'2b\':x.1g=1;O;2a\'2z\':x.1g=0;7(o===2c){n=$(x).1F(\'B.1M\');7(!n){1n(\'2A 1o 2B, 2C 1o 2z\');O}7(x.S){1v(x.S);x.S=0}1j(n.1N,n,1,1)}O;3h:n={1p:n}}}Q 7(n.29==3i){8 d=n;n=$(x).1F(\'B.1M\');7(!n){1n(\'2A 1o 2B, 2C 1o 1O 2D\');O}7(d<0||d>=n.1N.L){1n(\'3j 2D 1G: \'+d);O}n.N=d;7(x.S){1v(x.S);x.S=0}1j(n.1N,n,1,d>=n.1b);O}7(x.S)1v(x.S);x.S=0;x.1g=0;8 e=$(x);8 f=n.2d?$(n.2d,x):e.3k();8 g=f.3l();7(g.L<2){1n(\'3m; 3n 3o 3p: \'+g.L);O}8 h=$.3q({},$.E.B.2E,n||{},$.2F?e.2F():$.3r?e.1F():{});7(h.2e)h.2f=h.2g||g.L;e.1F(\'B.1M\',h);h.1w=x;h.1N=g;h.H=h.H?[h.H]:[];h.1k=h.1k?[h.1k]:[];h.1k.1P(4(){h.2h=0});7(h.1x)h.1k.J(4(){1j(g,h,0,!h.1y)});7(r&&h.1Q&&!h.2G)2i(f);8 j=x.3s;h.D=T((j.1H(/w:(\\d+)/)||[])[1])||h.D;h.C=T((j.1H(/h:(\\d+)/)||[])[1])||h.C;h.W=T((j.1H(/t:(\\d+)/)||[])[1])||h.W;7(e.u(\'1R\')==\'3t\')e.u(\'1R\',\'3u\');7(h.D)e.D(h.D);7(h.C&&h.C!=\'1S\')e.C(h.C);7(h.18)h.18=T(h.18);7(h.1l){h.1q=[];1I(8 i=0;i<g.L;i++)h.1q.J(i);h.1q.3v(4(a,b){O 3w.1l()-0.5});h.Z=0;h.18=h.1q[0]}Q 7(h.18>=g.L)h.18=0;8 k=h.18||0;f.u({1R:\'2H\',y:0,9:0}).U().1s(4(i){8 z=k?i>=k?g.L-(i-k):k-i:g.L-i;$(x).u(\'z-1G\',z)});$(g[k]).u(\'1h\',1).V();7($.25.26)g[k].2I.2J(\'2j\');7(h.1m&&h.D)f.D(h.D);7(h.1m&&h.C&&h.C!=\'1S\')f.C(h.C);7(h.2b)e.2K(4(){x.1g=1},4(){x.1g=0});8 l=$.E.B.M[h.1p];7($.2L(l))l(e,f,h);Q 7(h.1p!=\'2k\')1n(\'3x 3y: \'+h.1p);f.1s(4(){8 a=$(x);x.11=(h.1m&&h.C)?h.C:a.C();x.12=(h.1m&&h.D)?h.D:a.D()});h.A=h.A||{};h.I=h.I||{};h.G=h.G||{};f.1o(\':2l(\'+k+\')\').u(h.A);7(h.1f)$(f[k]).u(h.1f);7(h.W){h.W=T(h.W);7(h.19.29==2y)h.19=$.1p.3z[h.19]||T(h.19);7(!h.1T)h.19=h.19/2;3A((h.W-h.19)<3B)h.W+=h.19}7(h.2m)h.1U=h.1V=h.2m;7(!h.1z)h.1z=h.19;7(!h.1J)h.1J=h.19;h.2M=g.L;h.1b=k;7(h.1l){h.N=h.1b;7(++h.Z==g.L)h.Z=0;h.N=h.1q[h.Z]}Q h.N=h.18>=(g.L-1)?0:h.18+1;8 m=f[k];7(h.H.L)h.H[0].1W(m,[m,m,h,2c]);7(h.1k.L>1)h.1k[1].1W(m,[m,m,h,2c]);7(h.1K&&!h.1a)h.1a=h.1K;7(h.1a)$(h.1a).2n(\'1K\',4(){O 1O(g,h,h.1y?-1:1)});7(h.2o)$(h.2o).2n(\'1K\',4(){O 1O(g,h,h.1y?1:-1)});7(h.1r)2N(g,h);h.3C=4(a,b){8 c=$(a),s=c[0];7(!h.2g)h.2f++;g[b?\'1P\':\'J\'](s);7(h.1c)h.1c[b?\'1P\':\'J\'](s);h.2M=g.L;c.u(\'1R\',\'2H\');c[b?\'3D\':\'2O\'](e);7(b){h.1b++;h.N++}7(r&&h.1Q&&!h.2G)2i(c);7(h.1m&&h.D)c.D(h.D);7(h.1m&&h.C&&h.C!=\'1S\')f.C(h.C);s.11=(h.1m&&h.C)?h.C:c.C();s.12=(h.1m&&h.D)?h.D:c.D();c.u(h.A);7(h.1r)$.E.B.2p(g.L-1,s,$(h.1r),g,h);7(1X h.X==\'4\')h.X(c)};7(h.W||h.1x)x.S=1Y(4(){1j(g,h,0,!h.1y)},h.1x?10:h.W+(h.2P||0))})};4 1j(a,b,c,d){7(b.2h)O;8 p=b.1w,1A=a[b.1b],1a=a[b.N];7(p.S===0&&!c)O;7(!c&&!p.1g&&((b.2e&&(--b.2f<=0))||(b.1Z&&!b.1l&&b.N<b.1b))){7(b.2q)b.2q(b);O}7(c||!p.1g){7(b.H.L)$.1s(b.H,4(i,o){o.1W(1a,[1A,1a,b,d])});8 e=4(){7($.25.26&&b.1Q)x.2I.2J(\'2j\');$.1s(b.1k,4(i,o){o.1W(1a,[1A,1a,b,d])})};7(b.N!=b.1b){b.2h=1;7(b.20)b.20(1A,1a,b,e,d);Q 7($.2L($.E.B[b.1p]))$.E.B[b.1p](1A,1a,b,e);Q $.E.B.2k(1A,1a,b,e,c&&b.2Q)}7(b.1l){b.1b=b.N;7(++b.Z==a.L)b.Z=0;b.N=b.1q[b.Z]}Q{8 f=(b.N+1)==a.L;b.N=f?0:b.N+1;b.1b=f?a.L-1:b.N-1}7(b.1r)$.E.B.2r(b.1r,b.1b)}7(b.W&&!b.1x)p.S=1Y(4(){1j(a,b,0,!b.1y)},b.W);Q 7(b.1x&&p.1g)p.S=1Y(4(){1j(a,b,0,!b.1y)},10)};$.E.B.2r=4(a,b){$(a).3E(\'a\').3F(\'2R\').2j(\'a:2l(\'+b+\')\').3G(\'2R\')};4 1O(a,b,c){8 p=b.1w,W=p.S;7(W){1v(W);p.S=0}7(b.1l&&c<0){b.Z--;7(--b.Z==-2)b.Z=a.L-2;Q 7(b.Z==-1)b.Z=a.L-1;b.N=b.1q[b.Z]}Q 7(b.1l){7(++b.Z==a.L)b.Z=0;b.N=b.1q[b.Z]}Q{b.N=b.1b+c;7(b.N<0){7(b.1Z)O 21;b.N=a.L-1}Q 7(b.N>=a.L){7(b.1Z)O 21;b.N=0}}7(b.22&&1X b.22==\'4\')b.22(c>0,b.N,a[b.N]);1j(a,b,1,c>=0);O 21};4 2N(a,b){8 c=$(b.1r);$.1s(a,4(i,o){$.E.B.2p(i,o,c,a,b)});$.E.B.2r(b.1r,b.18)};$.E.B.2p=4(i,a,b,c,d){8 e=(1X d.2s==\'4\')?$(d.2s(i,a)):$(\'<a 3H="#">\'+(i+1)+\'</a>\');7(e.3I(\'3J\').L==0)e.2O(b);e.2n(d.2S,4(){d.N=i;8 p=d.1w,W=p.S;7(W){1v(W);p.S=0}7(1X d.2t==\'4\')d.2t(d.N,c[d.N]);1j(c,d,1,d.1b<i);O 21});7(d.2T)e.2K(4(){d.1w.1g=1},4(){d.1w.1g=0})};4 2i(b){4 23(s){8 s=T(s).3K(16);O s.L<2?\'0\'+s:s};4 2U(e){1I(;e&&e.3L.3M()!=\'3N\';e=e.3O){8 v=$.u(e,\'2V-2W\');7(v.3P(\'3Q\')>=0){8 a=v.1H(/\\d+/g);O\'#\'+23(a[0])+23(a[1])+23(a[2])}7(v&&v!=\'3R\')O v}O\'#3S\'};b.1s(4(){$(x).u(\'2V-2W\',2U(x))})};$.E.B.2k=4(a,b,c,d,e){8 f=$(a),$n=$(b);$n.u(c.A);8 g=e?1:c.1z;8 h=e?1:c.1J;8 i=e?P:c.1U;8 j=e?P:c.1V;8 k=4(){$n.24(c.I,g,i,d)};f.24(c.G,h,j,4(){7(c.K)f.u(c.K);7(!c.1T)k()});7(c.1T)k()};$.E.B.M={2X:4(b,c,d){c.1o(\':2l(\'+d.18+\')\').u(\'1h\',0);d.H.J(4(){$(x).V()});d.I={1h:1};d.G={1h:0};d.A={1h:0};d.K={R:\'Y\'};d.X=4(a){a.U()}}};$.E.B.3T=4(){O q};$.E.B.2E={1p:\'2X\',W:3U,1x:0,19:3V,1z:P,1J:P,1a:P,2o:P,22:P,1r:P,2t:P,2S:\'1K\',2s:P,H:P,1k:P,2q:P,2m:P,1U:P,1V:P,1L:P,I:P,G:P,A:P,K:P,20:P,C:\'1S\',18:0,1T:1,1l:0,1m:0,2b:0,2T:0,2e:0,2g:0,2P:0,2d:P,1Q:0,1Z:0,2Q:0}})(2Y);(4($){$.E.B.M.3W=4(d,e,f){d.u(\'17\',\'1d\');f.H.J(4(a,b,c){$(x).V();c.A.y=b.1B;c.G.y=0-a.1B});f.1f={y:0};f.I={y:0};f.K={R:\'Y\'}};$.E.B.M.3X=4(d,e,f){d.u(\'17\',\'1d\');f.H.J(4(a,b,c){$(x).V();c.A.y=0-b.1B;c.G.y=a.1B});f.1f={y:0};f.I={y:0};f.K={R:\'Y\'}};$.E.B.M.3Y=4(d,e,f){d.u(\'17\',\'1d\');f.H.J(4(a,b,c){$(x).V();c.A.9=b.1C;c.G.9=0-a.1C});f.1f={9:0};f.I={9:0}};$.E.B.M.3Z=4(d,e,f){d.u(\'17\',\'1d\');f.H.J(4(a,b,c){$(x).V();c.A.9=0-b.1C;c.G.9=a.1C});f.1f={9:0};f.I={9:0}};$.E.B.M.40=4(f,g,h){f.u(\'17\',\'1d\').D();h.H.J(4(a,b,c,d){$(x).V();8 e=a.1C,2u=b.1C;c.A=d?{9:2u}:{9:-2u};c.I.9=0;c.G.9=d?-e:e;g.1o(a).u(c.A)});h.1f={9:0};h.K={R:\'Y\'}};$.E.B.M.41=4(f,g,h){f.u(\'17\',\'1d\');h.H.J(4(a,b,c,d){$(x).V();8 e=a.1B,2v=b.1B;c.A=d?{y:-2v}:{y:2v};c.I.y=0;c.G.y=d?e:-e;g.1o(a).u(c.A)});h.1f={y:0};h.K={R:\'Y\'}};$.E.B.M.42=4(d,e,f){f.H.J(4(a,b,c){$(a).u(\'F\',1)});f.X=4(a){a.U()};f.A={F:2};f.I={D:\'V\'};f.G={D:\'U\'}};$.E.B.M.43=4(d,e,f){f.H.J(4(a,b,c){$(a).u(\'F\',1)});f.X=4(a){a.U()};f.A={F:2};f.I={C:\'V\'};f.G={C:\'U\'}};$.E.B.M.1L=4(g,h,j){8 w=g.u(\'17\',\'2Z\').D();h.u({9:0,y:0});j.H.J(4(){$(x).V()});j.19=j.19/2;j.1l=0;j.1L=j.1L||{9:-w,y:15};j.1c=[];1I(8 i=0;i<h.L;i++)j.1c.J(h[i]);1I(8 i=0;i<j.18;i++)j.1c.J(j.1c.31());j.20=4(a,b,c,d,e){8 f=e?$(a):$(b);f.24(c.1L,c.1z,c.1U,4(){e?c.1c.J(c.1c.31()):c.1c.1P(c.1c.44());7(e)1I(8 i=0,2w=c.1c.L;i<2w;i++)$(c.1c[i]).u(\'z-1G\',2w-i);Q{8 z=$(a).u(\'z-1G\');f.u(\'z-1G\',T(z)+1)}f.24({9:0,y:0},c.1J,c.1V,4(){$(e?x:a).U();7(d)d()})})};j.X=4(a){a.U()}};$.E.B.M.45=4(d,e,f){f.H.J(4(a,b,c){$(x).V();c.A.y=b.11;c.I.C=b.11});f.X=4(a){a.U()};f.1f={y:0};f.A={C:0};f.I={y:0};f.G={C:0};f.K={R:\'Y\'}};$.E.B.M.46=4(d,e,f){f.H.J(4(a,b,c){$(x).V();c.I.C=b.11;c.G.y=a.11});f.X=4(a){a.U()};f.1f={y:0};f.A={y:0,C:0};f.G={C:0};f.K={R:\'Y\'}};$.E.B.M.47=4(d,e,f){f.H.J(4(a,b,c){$(x).V();c.A.9=b.12;c.I.D=b.12});f.X=4(a){a.U()};f.A={D:0};f.I={9:0};f.G={D:0};f.K={R:\'Y\'}};$.E.B.M.48=4(d,e,f){f.H.J(4(a,b,c){$(x).V();c.I.D=b.12;c.G.9=a.12});f.X=4(a){a.U()};f.A={9:0,D:0};f.I={9:0};f.G={D:0};f.K={R:\'Y\'}};$.E.B.M.32=4(d,e,f){f.1f={y:0,9:0};f.K={R:\'Y\'};f.H.J(4(a,b,c){$(x).V();c.A={D:0,C:0,y:b.11/2,9:b.12/2};c.K={R:\'Y\'};c.I={y:0,9:0,D:b.12,C:b.11};c.G={D:0,C:0,y:a.11/2,9:a.12/2};$(a).u(\'F\',2);$(b).u(\'F\',1)});f.X=4(a){a.U()}};$.E.B.M.49=4(d,e,f){f.H.J(4(a,b,c){c.A={D:0,C:0,1h:1,9:b.12/2,y:b.11/2,F:1};c.I={y:0,9:0,D:b.12,C:b.11}});f.G={1h:0};f.K={F:0}};$.E.B.M.4a=4(d,e,f){8 w=d.u(\'17\',\'1d\').D();e.V();f.H.J(4(a,b,c){$(a).u(\'F\',1)});f.A={9:w,F:2};f.K={F:1};f.I={9:0};f.G={9:w}};$.E.B.M.4b=4(d,e,f){8 h=d.u(\'17\',\'1d\').C();e.V();f.H.J(4(a,b,c){$(a).u(\'F\',1)});f.A={y:h,F:2};f.K={F:1};f.I={y:0};f.G={y:h}};$.E.B.M.4c=4(d,e,f){8 h=d.u(\'17\',\'1d\').C();8 w=d.D();e.V();f.H.J(4(a,b,c){$(a).u(\'F\',1)});f.A={y:h,9:w,F:2};f.K={F:1};f.I={y:0,9:0};f.G={y:h,9:w}};$.E.B.M.4d=4(d,e,f){f.H.J(4(a,b,c){c.A={9:x.12/2,D:0,F:2};c.I={9:0,D:x.12};c.G={9:0};$(a).u(\'F\',1)});f.X=4(a){a.U().u(\'F\',1)}};$.E.B.M.4e=4(d,e,f){f.H.J(4(a,b,c){c.A={y:x.11/2,C:0,F:2};c.I={y:0,C:x.11};c.G={y:0};$(a).u(\'F\',1)});f.X=4(a){a.U().u(\'F\',1)}};$.E.B.M.4f=4(d,e,f){f.H.J(4(a,b,c){c.A={9:b.12/2,D:0,F:1,R:\'1D\'};c.I={9:0,D:x.12};c.G={9:a.12/2,D:0};$(a).u(\'F\',2)});f.X=4(a){a.U()};f.K={F:1,R:\'Y\'}};$.E.B.M.4g=4(d,e,f){f.H.J(4(a,b,c){c.A={y:b.11/2,C:0,F:1,R:\'1D\'};c.I={y:0,C:x.11};c.G={y:a.11/2,C:0};$(a).u(\'F\',2)});f.X=4(a){a.U()};f.K={F:1,R:\'Y\'}};$.E.B.M.4h=4(e,f,g){8 d=g.33||\'9\';8 w=e.u(\'17\',\'1d\').D();8 h=e.C();g.H.J(4(a,b,c){c.A=c.A||{};c.A.F=2;c.A.R=\'1D\';7(d==\'34\')c.A.9=-w;Q 7(d==\'35\')c.A.y=h;Q 7(d==\'36\')c.A.y=-h;Q c.A.9=w;$(a).u(\'F\',1)});7(!g.I)g.I={9:0,y:0};7(!g.G)g.G={9:0,y:0};g.K=g.K||{};g.K.F=2;g.K.R=\'Y\'};$.E.B.M.4i=4(e,f,g){8 d=g.33||\'9\';8 w=e.u(\'17\',\'1d\').D();8 h=e.C();g.H.J(4(a,b,c){c.A.R=\'1D\';7(d==\'34\')c.G.9=w;Q 7(d==\'35\')c.G.y=-h;Q 7(d==\'36\')c.G.y=h;Q c.G.9=-w;$(a).u(\'F\',2);$(b).u(\'F\',1)});g.X=4(a){a.U()};7(!g.I)g.I={9:0,y:0};g.A=g.A||{};g.A.y=0;g.A.9=0;g.K=g.K||{};g.K.F=1;g.K.R=\'Y\'};$.E.B.M.4j=4(d,e,f){8 w=d.u(\'17\',\'2Z\').D();8 h=d.C();f.H.J(4(a,b,c){$(a).u(\'F\',2);c.A.R=\'1D\';7(!c.G.9&&!c.G.y)c.G={9:w*2,y:-h/2,1h:0};Q c.G.1h=0});f.X=4(a){a.U()};f.A={9:0,y:0,F:1,1h:1};f.I={9:0};f.K={F:2,R:\'Y\'}};$.E.B.M.4k=4(o,p,q){8 w=o.u(\'17\',\'1d\').D();8 h=o.C();q.A=q.A||{};8 s;7(q.1i){7(/4l/.1u(q.1i))s=\'1t(1e 1e \'+h+\'14 1e)\';Q 7(/4m/.1u(q.1i))s=\'1t(1e \'+w+\'14 \'+h+\'14 \'+w+\'14)\';Q 7(/4n/.1u(q.1i))s=\'1t(1e \'+w+\'14 1e 1e)\';Q 7(/4o/.1u(q.1i))s=\'1t(\'+h+\'14 \'+w+\'14 \'+h+\'14 1e)\';Q 7(/32/.1u(q.1i)){8 t=T(h/2);8 l=T(w/2);s=\'1t(\'+t+\'14 \'+l+\'14 \'+t+\'14 \'+l+\'14)\'}}q.A.1i=q.A.1i||s||\'1t(1e 1e 1e 1e)\';8 d=q.A.1i.1H(/(\\d+)/g);8 t=T(d[0]),r=T(d[1]),b=T(d[2]),l=T(d[3]);q.H.J(4(g,i,j){7(g==i)O;8 k=$(g).u(\'F\',2);8 m=$(i).u({F:3,R:\'1D\'});8 n=1,1E=T((j.1z/13))-1;4 f(){8 a=t?t-T(n*(t/1E)):0;8 c=l?l-T(n*(l/1E)):0;8 d=b<h?b+T(n*((h-b)/1E||1)):h;8 e=r<w?r+T(n*((w-r)/1E||1)):w;m.u({1i:\'1t(\'+a+\'14 \'+e+\'14 \'+d+\'14 \'+c+\'14)\'});(n++<=1E)?1Y(f,13):k.u(\'R\',\'Y\')}f()});q.K={};q.I={9:0};q.G={9:0}}})(2Y);',62,273,'||||function|||if|var|left|||||||||||||||||||||css|||this|top||cssBefore|cycle|height|width|fn|zIndex|animOut|before|animIn|push|cssAfter|length|transitions|nextSlide|return|null|else|display|cycleTimeout|parseInt|hide|show|timeout|onAddSlide|none|randomIndex||cycleH|cycleW||px|||overflow|startingSlide|speed|next|currSlide|els|hidden|0px|cssFirst|cyclePause|opacity|clip|go|after|random|fit|log|not|fx|randomMap|pager|each|rect|test|clearTimeout|container|continuous|rev|speedIn|curr|offsetHeight|offsetWidth|block|count|data|index|match|for|speedOut|click|shuffle|opts|elements|advance|unshift|cleartype|position|auto|sync|easeIn|easeOut|apply|typeof|setTimeout|nowrap|fxFn|false|prevNextClick|hex|animate|browser|msie|window|console|constructor|case|pause|true|slideExpr|autostop|countdown|autostopCount|busy|clearTypeFix|filter|custom|eq|easing|bind|prev|createPagerAnchor|end|updateActivePagerLink|pagerAnchorBuilder|pagerClick|nextW|nextH|len|arguments|String|resume|options|found|can|slide|defaults|metadata|cleartypeNoBg|absolute|style|removeAttribute|hover|isFunction|slideCount|buildPager|appendTo|delay|fastOnEvent|activeSlide|pagerEvent|pauseOnPagerHover|getBg|background|color|fade|jQuery|visible||shift|zoom|direction|right|up|down|MSIE|navigator|userAgent|Array|prototype|join|call|undefined|switch|stop|default|Number|invalid|children|get|terminating|too|few|slides|extend|meta|className|static|relative|sort|Math|unknown|transition|speeds|while|250|addSlide|prependTo|find|removeClass|addClass|href|parents|body|toString|nodeName|toLowerCase|html|parentNode|indexOf|rgb|transparent|ffffff|ver|4000|1000|scrollUp|scrollDown|scrollLeft|scrollRight|scrollHorz|scrollVert|slideX|slideY|pop|turnUp|turnDown|turnLeft|turnRight|fadeZoom|blindX|blindY|blindZ|growX|growY|curtainX|curtainY|cover|uncover|toss|wipe|l2r|r2l|t2b|b2t'.split('|'),0,{}));
Index: branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad-it.js
===================================================================
--- branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad-it.js	(revision 8232)
+++ branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad-it.js	(revision 8232)
@@ -0,0 +1,21 @@
+﻿/* http://keith-wood.name/keypad.html
+   Italian initialisation for the jQuery keypad extension
+   Written by Francesco Strappini (www.strx.it). */
+(function($) { // hide the namespace
+	$.keypad.regional['it'] = {
+		buttonText: '...', buttonStatus: 'Visualizza Tastiera',
+		closeText: 'Chiudi', closeStatus: 'Nascondi Tastiera',
+		clearText: 'Pulisci', clearStatus: 'Elimina il Testo',
+		backText: 'Del', backStatus: 'Elimina l\'ultimo carattere',
+		shiftText: 'Shift', shiftStatus: 'Maiuscole/Minuscole',
+		spacebarText: '&nbsp;', spacebarStatus: '',
+		enterText: 'Enter', enterStatus: 'Ritorno a Capo',
+		tabText: '→', tabStatus: '',
+		alphabeticLayout: $.keypad.qwertyAlphabetic,
+		fullLayout: $.keypad.qwertyLayout,
+		isAlphabetic: $.keypad.isAlphabetic,
+		isNumeric: $.keypad.isNumeric,
+		toUpper: $.keypad.toUpper,
+		isRTL: false};
+	$.keypad.setDefaults($.keypad.regional['it']);
+})(jQuery);
Index: branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad.alt.css
===================================================================
--- branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad.alt.css	(revision 8232)
+++ branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad.alt.css	(revision 8232)
@@ -0,0 +1,106 @@
+/* Alternate style sheet for jQuery Keypad v1.5.0. */
+button.keypad-trigger {
+	width: 25px;
+	padding: 0px;
+}
+img.keypad-trigger {
+	margin: 2px;
+	vertical-align: middle;
+}
+.keypad-popup, .keypad-inline, .keypad-key, .keypad-special {
+	font-family: Arial,Helvetica,sans-serif;
+	font-size: 14px;
+}
+.keypad-popup {
+	display: none;
+	z-index: 10;
+	margin: 0;
+	padding: 0;
+	background-color: #fff;
+	color: #000;
+	border: 1px solid #888;
+	border-radius: 0.25em;
+	-moz-border-radius: 0.25em;
+	-webkit-border-radius: 0.25em;
+}
+.keypad-keyentry {
+	display: none;
+}
+.keypad-inline {
+	background-color: #fff;
+	border: 1px solid #888;
+	border-radius: 0.25em;
+	-moz-border-radius: 0.25em;
+	-webkit-border-radius: 0.25em;
+}
+.keypad-disabled {
+	position: absolute;
+	z-index: 100;
+	background-color: white;
+	opacity: 0.25;
+	filter: alpha(opacity=25);
+}
+.keypad-rtl {
+	direction: rtl;
+}
+.keypad-prompt {
+	clear: both;
+	text-align: center;
+}
+.keypad-prompt.ui-widget-header {
+	margin: 0.125em;
+}
+.keypad-row {
+	clear: both;
+	float: left;
+	width: 100%;
+}
+.keypad-space {
+	float: left;
+	margin: 0.125em;
+	width: 2em;
+}
+* html .keypad-space { /* IE6 */
+	margin: 0em;
+	width: 2.25em;
+}
+.keypad-half-space {
+	float: left;
+	margin: 0.125em 0.0625em;
+	width: 1em;
+}
+* html .keypad-half-space { /* IE6 */
+	margin: 0em;
+	width: 1.125em;
+}
+.keypad-key, .keypad-special {
+	float: left;
+	margin: 0.125em;
+	padding: 0em;
+	width: 2em;
+	text-align: center;
+	cursor: pointer;
+}
+.keypad-special {
+	width: 4.25em;
+}
+.keypad-spacebar {
+	width: 13.25em;
+}
+.keypad-tab {
+	width: 2em;
+}
+.keypad-clear, .keypad-back, .keypad-close, .keypad-shift {
+	font-weight: bold;
+}
+.keypad-cover {
+	display: none;
+	display/**/: block;
+	position: absolute;
+	z-index: -1;
+	filter: mask();
+	top: -4px;
+	left: -4px;
+	width: 125px;
+	height: 200px;
+}
Index: branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad.css
===================================================================
--- branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad.css	(revision 8232)
+++ branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad.css	(revision 8232)
@@ -0,0 +1,128 @@
+/* Main style sheet for jQuery Keypad v1.5.0. */
+button.keypad-trigger {
+	width: 25px;
+	padding: 0px;
+}
+img.keypad-trigger {
+	margin: 2px;
+	vertical-align: middle;
+}
+.keypad-popup, .keypad-inline, .keypad-key, .keypad-special {
+	font-family: Arial,Helvetica,sans-serif;
+	font-size: 14px;
+}
+.keypad-popup {
+	display: none;
+	z-index: 10;
+	margin: 0;
+	padding: 0;
+	background-color: #fff;
+	color: #000;
+	border: 1px solid #888;
+	border-radius: 0.25em;
+	-moz-border-radius: 0.25em;
+	-webkit-border-radius: 0.25em;
+}
+.keypad-keyentry {
+	display: none;
+}
+.keypad-inline {
+	background-color: #fff;
+	border: 1px solid #888;
+	border-radius: 0.25em;
+	-moz-border-radius: 0.25em;
+	-webkit-border-radius: 0.25em;
+}
+.keypad-disabled {
+	position: absolute;
+	z-index: 100;
+	background-color: white;
+	opacity: 0.5;
+	filter: alpha(opacity=50);
+}
+.keypad-rtl {
+	direction: rtl;
+}
+.keypad-prompt {
+	clear: both;
+	text-align: center;
+}
+.keypad-prompt.ui-widget-header {
+	margin: 0.125em;
+}
+.keypad-row {
+	clear: both;
+	float: left;
+	width: 100%;
+}
+.keypad-space {
+	float: left;
+	margin: 0.125em;
+	width: 2em;
+}
+* html .keypad-space { /* IE6 */
+	margin: 0em;
+	width: 2.25em;
+}
+.keypad-half-space {
+	float: left;
+	margin: 0.125em 0.0625em;
+	width: 1em;
+}
+* html .keypad-half-space { /* IE6 */
+	margin: 0em;
+	width: 1.125em;
+}
+.keypad-key, .keypad-special {
+	float: left;
+	margin: 0.125em;
+	padding: 0em;
+	width: 2em;
+	background-color: #f4f4f4;
+	border-radius: 0.25em;
+	-moz-border-radius: 0.25em;
+	-webkit-border-radius: 0.25em;
+	text-align: center;
+	cursor: pointer;
+}
+.keypad-key[disabled] {
+	border: 0.125em outset;
+}
+.keypad-key-down {
+}
+.keypad-special {
+	width: 4.25em;
+}
+.keypad-spacebar {
+	width: 13.25em;
+}
+.keypad-tab {
+	width: 2em;
+}
+.keypad-clear, .keypad-back, .keypad-close, .keypad-shift {
+	color: #000;
+	font-weight: bold;
+}
+/*.keypad-clear {
+	background-color: #a00;
+}
+.keypad-back {
+	background-color: #00a;
+}
+.keypad-close {
+	background-color: #0a0;
+}
+.keypad-shift {
+	background-color: #0aa;
+}*/
+.keypad-cover {
+	display: none;
+	display/**/: block;
+	position: absolute;
+	z-index: -1;
+	filter: mask();
+	top: -4px;
+	left: -4px;
+	width: 125px;
+	height: 200px;
+}
Index: branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad.js
===================================================================
--- branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad.js	(revision 8232)
+++ branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad.js	(revision 8232)
@@ -0,0 +1,906 @@
+﻿/* http://keith-wood.name/keypad.html
+   Keypad field entry extension for jQuery v1.5.0.
+   Written by Keith Wood (kbwood{at}iinet.com.au) August 2008.
+   Dual licensed under the GPL (http://dev.jquery.com/browser/trunk/jquery/GPL-LICENSE.txt) and 
+   MIT (http://dev.jquery.com/browser/trunk/jquery/MIT-LICENSE.txt) licenses. 
+   Please attribute the author if you use it. */
+   
+(function($) { // hide the namespace
+
+/* Keypad manager.
+   Use the singleton instance of this class, $.keypad, to interact with the plugin.
+   Settings for keypad fields are maintained in instance objects,
+   allowing multiple different settings on the same page. */
+function Keypad() {
+	this._curInst = null; // The current instance in use
+	this._disabledFields = []; // List of keypad fields that have been disabled
+	this._keypadShowing = false; // True if the popup panel is showing , false if not
+	this._keyCode = 0;
+	this._specialKeys = [];
+	this.addKeyDef('CLOSE', 'close', function(inst) {
+		plugin._curInst = (inst._inline ? inst : plugin._curInst);
+		plugin._hidePlugin();
+	});
+	this.addKeyDef('CLEAR', 'clear', function(inst) { plugin._clearValue(inst); });
+	this.addKeyDef('BACK', 'back', function(inst) { plugin._backValue(inst); });
+	this.addKeyDef('SHIFT', 'shift', function(inst) { plugin._shiftKeypad(inst); });
+	this.addKeyDef('SPACE_BAR', 'spacebar', function(inst) { plugin._selectValue(inst, ' '); }, true);
+	this.addKeyDef('SPACE', 'space');
+	this.addKeyDef('HALF_SPACE', 'half-space');
+	this.addKeyDef('ENTER', 'enter', function(inst) { plugin._selectValue(inst, '\x0D'); }, true);
+	this.addKeyDef('TAB', 'tab', function(inst) { plugin._selectValue(inst, '\x09'); }, true);
+	// Standard US keyboard alphabetic layout
+	this.qwertyAlphabetic = ['qwertyuiop', 'asdfghjkl', 'zxcvbnm'];
+	// Standard US keyboard layout
+	this.qwertyLayout = ['!@#$%^&*()_=' + this.HALF_SPACE + this.SPACE + this.CLOSE,
+		this.HALF_SPACE + '`~[]{}<>\\|/' + this.SPACE + '789',
+		'qwertyuiop\'"' + this.HALF_SPACE + '456',
+		this.HALF_SPACE + 'asdfghjkl;:' + this.SPACE + '123',
+		this.SPACE + 'zxcvbnm,.?' + this.SPACE + this.HALF_SPACE + '-0+',
+		'' + this.TAB + this.ENTER + this.SPACE_BAR + this.SHIFT +
+		this.HALF_SPACE + this.BACK + this.CLEAR];
+	this.regional = []; // Available regional settings, indexed by language code
+	this.regional[''] = { // Default regional settings
+		buttonText: '...', // Display text for trigger button
+		buttonStatus: 'Open the keypad', // Status text for trigger button
+		closeText: 'Close', // Display text for close link
+		closeStatus: 'Close the keypad', // Status text for close link
+		clearText: 'Clear', // Display text for clear link
+		clearStatus: 'Erase all the text', // Status text for clear link
+		backText: 'Back', // Display text for back link
+		backStatus: 'Erase the previous character', // Status text for back link
+		spacebarText: '&nbsp;', // Display text for space bar
+		spacebarStatus: 'Space', // Status text for space bar
+		enterText: 'Enter', // Display text for carriage return
+		enterStatus: 'Carriage return', // Status text for carriage return
+		tabText: '→', // Display text for tab
+		tabStatus: 'Horizontal tab', // Status text for tab
+		shiftText: 'Shift', // Display text for shift link
+		shiftStatus: 'Toggle upper/lower case characters', // Status text for shift link
+		alphabeticLayout: this.qwertyAlphabetic, // Default layout for alphabetic characters
+		fullLayout: this.qwertyLayout, // Default layout for full keyboard
+		isAlphabetic: this.isAlphabetic, // Function to determine if character is alphabetic
+		isNumeric: this.isNumeric, // Function to determine if character is numeric
+		toUpper: this.toUpper, // Function to convert characters to upper case
+		isRTL: false // True if right-to-left language, false if left-to-right
+	};
+	this._defaults = { // Global defaults for all the keypad instances
+		showOn: 'focus', // 'focus' for popup on focus,
+			// 'button' for trigger button, or 'both' for either
+		buttonImage: '', // URL for trigger button image
+		buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
+		showAnim: 'show', // Name of jQuery animation for popup
+		showOptions: {}, // Options for enhanced animations
+		duration: 'normal', // Duration of display/closure
+		appendText: '', // Display text following the text field, e.g. showing the format
+		useThemeRoller: false, // True to add ThemeRoller classes
+		keypadClass: '', // Additional CSS class for the keypad for an instance
+		prompt: '', // Display text at the top of the keypad
+		layout: ['123' + this.CLOSE, '456' + this.CLEAR, '789' + this.BACK, this.SPACE + '0'], // Layout of keys
+		separator: '', // Separator character between keys
+		target: null, // Input target for an inline keypad
+		keypadOnly: true, // True for entry only via the keypad, false for real keyboard too
+		randomiseAlphabetic: false, // True to randomise the alphabetic key positions, false to keep in order
+		randomiseNumeric: false, // True to randomise the numeric key positions, false to keep in order
+		randomiseOther: false, // True to randomise the other key positions, false to keep in order
+		randomiseAll: false, // True to randomise all key positions, false to keep in order
+		beforeShow: null, // Callback before showing the keypad
+		onKeypress: null, // Callback when a key is selected
+		onClose: null // Callback when the panel is closed
+	};
+	$.extend(this._defaults, this.regional['']);
+	this.mainDiv = $('<div class="' + this._mainDivClass + '" style="display: none;"></div>');
+}
+
+$.extend(Keypad.prototype, {
+	/* Class name added to elements to indicate already configured with keypad. */
+	markerClassName: 'hasKeypad',
+	/* Name of the data property for instance settings. */
+	propertyName: 'keypad',
+
+	_mainDivClass: 'keypad-popup', // The main keypad division class
+	_inlineClass: 'keypad-inline', // The inline marker class
+	_appendClass: 'keypad-append', // The append marker class
+	_triggerClass: 'keypad-trigger', // The trigger marker class
+	_disableClass: 'keypad-disabled', // The disabled covering marker class
+	_inlineEntryClass: 'keypad-keyentry', // The inline entry marker class
+	_coverClass: 'keypad-cover', // The IE select cover marker class
+	_rtlClass: 'keypad-rtl', // The right-to-left marker class
+	_rowClass: 'keypad-row', // The keypad row marker class
+	_promptClass: 'keypad-prompt', // The prompt marker class
+	_specialClass: 'keypad-special', // The special key marker class
+	_namePrefixClass: 'keypad-', // The key name marker class prefix
+	_keyClass: 'keypad-key', // The key marker class
+	_keyDownClass: 'keypad-key-down', // The key down marker class
+
+	/* Override the default settings for all keypad instances.
+	   @param  settings  (object) the new settings to use as defaults
+	   @return  (Keypad) this object */
+	setDefaults: function(settings) {
+		$.extend(this._defaults, settings || {});
+		return this;
+	},
+
+	/* Add the definition of a special key.
+	   @param  id           (string) the identifier for this key - access via $.keypad.<id>
+	   @param  name         (string) the prefix for localisation strings and
+	                        the suffix for a class name
+	   @param  action       (function) the action performed for this key -
+	                        receives inst as a parameter
+	   @param  noHighlight  (boolean) true to suppress highlight when using ThemeRoller
+	   @return  (Keypad) this object */
+	addKeyDef: function(id, name, action, noHighlight) {
+		if (this._keyCode == 32) {
+			throw 'Only 32 special keys allowed';
+		}
+		this[id] = String.fromCharCode(this._keyCode++);
+		this._specialKeys.push({code: this[id], id: id, name: name,
+			action: action, noHighlight: noHighlight});
+		return this;
+	},
+
+	/* Attach the keypad to a jQuery selection.
+	   @param  target   (element) the control to affect
+	   @param  options  (object) the custom options for this instance */
+	_attachPlugin: function(target, options) {
+		target = $(target);
+		if (target.hasClass(this.markerClassName)) {
+			return;
+		}
+		var inline = !target[0].nodeName.toLowerCase().match(/input|textarea/);
+		var inst = {options: $.extend({}, this._defaults, options), _inline: inline,
+			_mainDiv: (inline ? $('<div class="' + this._inlineClass + '"></div>') : plugin.mainDiv),
+			ucase: false};
+		this._setInput(target, inst);
+		this._connectKeypad(target, inst);
+		if (inline) {
+			target.append(inst._mainDiv).
+				bind('click.' + this.propertyName, function() { inst._input.focus(); });
+			this._updateKeypad(inst);
+		}
+		else if (target.is(':disabled')) {
+			this._disablePlugin(target);
+		}
+	},
+
+	/* Determine the input field for the keypad.
+	   @param  target  (jQuery) the target control
+	   @param  inst    (object) the instance settings */
+	_setInput: function(target, inst) {
+		inst._input = $(!inst._inline ? target : inst.options.target ||
+			'<input type="text" class="' + this._inlineEntryClass + '" disabled="disabled"/>');
+		if (inst._inline) {
+			target.find('input').remove();
+			if (!inst.options.target) {
+				target.append(inst._input);
+			}
+		}
+	},
+
+	/* Attach the keypad to a text field.
+	   @param  target  (jQuery) the target text field
+	   @param  inst    (object) the instance settings */
+	_connectKeypad: function(target, inst) {
+		target = $(target);
+		var appendText = inst.options.appendText;
+		if (appendText) {
+			target[inst.options.isRTL ? 'before' : 'after'](
+				'<span class="' + this._appendClass + '">' + appendText + '</span>');
+		}
+		if (!inst._inline) {
+			if (inst.options.showOn == 'focus' || inst.options.showOn == 'both') {
+				// pop-up keypad when in the marked field
+				target.bind('focus.' + this.propertyName, this._showPlugin).
+					bind('keydown.' + this.propertyName, this._doKeyDown);
+			}
+			if (inst.options.showOn == 'button' || inst.options.showOn == 'both') {
+				// pop-up keypad when button clicked
+				var buttonStatus = inst.options.buttonStatus;
+				var buttonImage = inst.options.buttonImage;
+				var trigger = $(inst.options.buttonImageOnly ? 
+					$('<img src="' + buttonImage + '" alt="' +
+					buttonStatus + '" title="' + buttonStatus + '"/>') :
+				$('<button type="button" title="' + buttonStatus + '"></button>').
+					html(buttonImage == '' ? inst.options.buttonText :
+					$('<img src="' + buttonImage + '" alt="' +
+					buttonStatus + '" title="' + buttonStatus + '"/>')));
+				target[inst.options.isRTL ? 'before' : 'after'](trigger);
+				trigger.addClass(this._triggerClass).click(function() {
+					if (plugin._keypadShowing && plugin._lastField == target[0]) {
+						plugin._hidePlugin();
+					}
+					else {
+						plugin._showPlugin(target[0]);
+					}
+					return false;
+				});
+			}
+		}
+		inst.saveReadonly = target.attr('readonly');
+		target.addClass(this.markerClassName).
+			data(this.propertyName, inst)
+			[inst.options.keypadOnly ? 'attr' : 'removeAttr']('readonly', true).
+			bind('setData.' + this.propertyName, function(event, key, value) {
+				inst.options[key] = value;
+			}).bind('getData.' + this.propertyName, function(event, key) {
+				return inst.options[key];
+			});
+	},
+
+	/* Retrieve or reconfigure the settings for a control.
+	   @param  target   (element) the control to affect
+	   @param  options  (object) the new options for this instance or
+	                    (string) an individual property name
+	   @param  value    (any) the individual property value (omit if options
+	                    is an object or to retrieve the value of a setting)
+	   @return  (any) if retrieving a value */
+	_optionPlugin: function(target, options, value) {
+		target = $(target);
+		var inst = target.data(this.propertyName);
+		if (!options || (typeof options == 'string' && value == null)) { // Get option
+			var name = options;
+			options = (inst || {}).options;
+			return (options && name ? options[name] : options);
+		}
+
+		if (!target.hasClass(this.markerClassName)) {
+			return;
+		}
+		options = options || {};
+		if (typeof options == 'string') {
+			var name = options;
+			options = {};
+			options[name] = value;
+		}
+		if (this._curInst == inst) {
+			this._hidePlugin();
+		}
+		$.extend(inst.options, options);
+		this._setInput(target, inst);
+		this._updateKeypad(inst);
+	},
+
+	/* Detach keypad from its control.
+	   @param  target  (element) the target text field */
+	_destroyPlugin: function(target) {
+		target = $(target);
+		if (!target.hasClass(this.markerClassName)) {
+			return;
+		}
+		var inst = target.data(this.propertyName);
+		if (this._curInst == inst) {
+			this._hidePlugin();
+		}
+		target.siblings('.' + this._appendClass).remove().end().
+			siblings('.' + this._triggerClass).remove().end().
+			prev('.' + this._inlineEntryClass).remove();
+		target.removeClass(this.markerClassName).empty().
+			unbind('.' + this.propertyName).
+			removeData(this.propertyName)
+			[inst.saveReadonly ? 'attr' : 'removeAttr']('readonly', true);
+		inst._input.removeData(this.propertyName);
+	},
+
+	/* Enable the keypad for a jQuery selection.
+	   @param  target  (element) the target text field */
+	_enablePlugin: function(target) {
+		target = $(target);
+		if (!target.hasClass(this.markerClassName)) {
+			return;
+		}
+		var nodeName = target[0].nodeName.toLowerCase();
+		if (nodeName.match(/input|textarea/)) {
+			target[0].disabled = false;
+			target.siblings('button.' + this._triggerClass).
+				each(function() { this.disabled = false; }).end().
+				siblings('img.' + this._triggerClass).
+				css({opacity: '1.0', cursor: ''});
+		}
+		else if (nodeName.match(/div|span/)) {
+			target.children('.' + this._disableClass).remove();
+			var inst = target.data(this.propertyName);
+			inst._mainDiv.find('button').removeAttr('disabled');
+		}
+		this._disabledFields = $.map(this._disabledFields,
+			function(value) { return (value == target[0] ? null : value); }); // delete entry
+	},
+
+	/* Disable the keypad for a jQuery selection.
+	   @param  target  (element) the target text field */
+	_disablePlugin: function(target) {
+		target = $(target);
+		if (!target.hasClass(this.markerClassName)) {
+			return;
+		}
+		var nodeName = target[0].nodeName.toLowerCase();
+		if (nodeName.match(/input|textarea/)) {
+			target[0].disabled = true;
+			target.siblings('button.' + this._triggerClass).
+				each(function() { this.disabled = true; }).end().
+				siblings('img.' + this._triggerClass).
+				css({opacity: '0.5', cursor: 'default'});
+		}
+		else if (nodeName.match(/div|span/)) {
+			var inline = target.children('.' + this._inlineClass);
+			var offset = inline.offset();
+			var relOffset = {left: 0, top: 0};
+			inline.parents().each(function() {
+				if ($(this).css('position') == 'relative') {
+					relOffset = $(this).offset();
+					return false;
+				}
+			});
+			target.prepend('<div class="' + this._disableClass + '" style="width: ' +
+				inline.outerWidth() + 'px; height: ' + inline.outerHeight() +
+				'px; left: ' + (offset.left - relOffset.left) +
+				'px; top: ' + (offset.top - relOffset.top) + 'px;"></div>');
+			var inst = target.data(this.propertyName);
+			inst._mainDiv.find('button').attr('disabled', 'disabled');
+		}
+		this._disabledFields = $.map(this._disabledFields,
+			function(value) { return (value == target[0] ? null : value); }); // delete entry
+		this._disabledFields[this._disabledFields.length] = target[0];
+	},
+
+	/* Is the text field disabled as a keypad?
+	   @param  target  (element) the target text field
+	   @return  (boolean) true if disabled, false if enabled */
+	_isDisabledPlugin: function(target) {
+		return (target && $.inArray(target, this._disabledFields) > -1);
+	},
+
+	/* Pop-up the keypad for a given text field.
+	   @param  field  (element) the text field attached to the keypad or
+	                  (event) if triggered by focus */
+	_showPlugin: function(field) {
+		field = field.target || field;
+		if (plugin._isDisabledPlugin(field) ||
+				plugin._lastField == field) { // already here
+			return;
+		}
+		var inst = $.data(field, plugin.propertyName);
+		plugin._hidePlugin(null, '');
+		plugin._lastField = field;
+		plugin._pos = plugin._findPos(field);
+		plugin._pos[1] += field.offsetHeight; // add the height
+		var isFixed = false;
+		$(field).parents().each(function() {
+			isFixed |= $(this).css('position') == 'fixed';
+			return !isFixed;
+		});
+		if (isFixed && $.browser.opera) { // correction for Opera when fixed and scrolled
+			plugin._pos[0] -= document.documentElement.scrollLeft;
+			plugin._pos[1] -= document.documentElement.scrollTop;
+		}
+		var offset = {left: plugin._pos[0], top: plugin._pos[1]};
+		plugin._pos = null;
+		// determine sizing offscreen
+		inst._mainDiv.css({position: 'absolute', display: 'block', top: '-1000px',
+			width: ($.browser.opera ? '1000px' : 'auto')});
+		plugin._updateKeypad(inst);
+		// and adjust position before showing
+		offset = plugin._checkOffset(inst, offset, isFixed);
+		inst._mainDiv.css({position: (isFixed ? 'fixed' : 'absolute'), display: 'none',
+			left: offset.left + 'px', top: offset.top + 'px'});
+		var duration = inst.options.duration;
+		duration = (duration == 'normal' && $.ui && $.ui.version >= '1.8' ? '_default' : duration);
+		var showAnim = inst.options.showAnim;
+		var postProcess = function() {
+			plugin._keypadShowing = true;
+			var borders = plugin._getBorders(inst._mainDiv);
+			inst._mainDiv.find('iframe.' + plugin._coverClass). // IE6- only
+				css({left: -borders[0], top: -borders[1],
+					width: inst._mainDiv.outerWidth(), height: inst._mainDiv.outerHeight()});
+		};
+		if ($.effects && ($.effects[showAnim] || ($.effects.effect && $.effects.effect[showAnim]))) {
+			var data = inst._mainDiv.data(); // Update old effects data
+			for (var key in data) {
+				if (key.match(/^ec\.storage\./)) {
+					data[key] = inst._mainDiv.css(key.replace(/ec\.storage\./, ''));
+				}
+			}
+			inst._mainDiv.data(data).show(showAnim,
+				inst.options.showOptions, duration, postProcess);
+		}
+		else {
+			inst._mainDiv[showAnim || 'show']((showAnim ? duration : ''), postProcess);
+		}
+		if (!showAnim) {
+			postProcess();
+		}
+		if (inst._input[0].type != 'hidden') {
+			inst._input[0].focus();
+		}
+		plugin._curInst = inst;
+	},
+
+	/* Generate the keypad content.
+	   @param  inst  (object) the instance settings */
+	_updateKeypad: function(inst) {
+		var borders = this._getBorders(inst._mainDiv);
+		inst._mainDiv.empty().append(this._generateHTML(inst)).
+			find('iframe.' + this._coverClass). // IE6- only
+			css({left: -borders[0], top: -borders[1],
+				width: inst._mainDiv.outerWidth(), height: inst._mainDiv.outerHeight()});
+		inst._mainDiv.removeClass().addClass(inst.options.keypadClass +
+			(inst.options.useThemeRoller ? ' ui-widget ui-widget-content' : '') +
+			(inst.options.isRTL ? ' ' + this._rtlClass : '') + ' ' +
+			(inst._inline ? this._inlineClass : this._mainDivClass));
+		if ($.isFunction(inst.options.beforeShow)) {
+			inst.options.beforeShow.apply((inst._input ? inst._input[0] : null),
+				[inst._mainDiv, inst]);
+		}
+	},
+
+	/* Retrieve the size of left and top borders for an element.
+	   @param  elem  (jQuery object) the element of interest
+	   @return  (number[2]) the left and top borders */
+	_getBorders: function(elem) {
+		var convert = function(value) {
+			var extra = ($.browser.msie ? 1 : 0);
+			return {thin: 1 + extra, medium: 3 + extra, thick: 5 + extra}[value] || value;
+		};
+		return [parseFloat(convert(elem.css('border-left-width'))),
+			parseFloat(convert(elem.css('border-top-width')))];
+	},
+
+	/* Check positioning to remain on screen.
+	   @param  inst    (object) the instance settings
+	   @param  offset  (object) the current offset
+	   @param  isFixed  (boolean) true if the text field is fixed in position
+	   @return  (object) the updated offset */
+	_checkOffset: function(inst, offset, isFixed) {
+		var pos = inst._input ? this._findPos(inst._input[0]) : null;
+		var browserWidth = window.innerWidth || document.documentElement.clientWidth;
+		var browserHeight = window.innerHeight || document.documentElement.clientHeight;
+		var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
+		var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
+		if (($.browser.msie && parseInt($.browser.version, 10) < 7) || $.browser.opera) {
+			// recalculate width as otherwise set to 100%
+			var width = 0;
+			inst._mainDiv.find(':not(div,iframe)').each(function() {
+				width = Math.max(width, this.offsetLeft + $(this).outerWidth() +
+					parseInt($(this).css('margin-right'), 10));
+			});
+			inst._mainDiv.css('width', width);
+		}
+		// reposition keypad panel horizontally if outside the browser window
+		if (inst.options.isRTL ||
+				(offset.left + inst._mainDiv.outerWidth() - scrollX) > browserWidth) {
+			offset.left = Math.max((isFixed ? 0 : scrollX),
+				pos[0] + (inst._input ? inst._input.outerWidth() : 0) -
+				(isFixed ? scrollX : 0) - inst._mainDiv.outerWidth() -
+				(isFixed && $.browser.opera ? document.documentElement.scrollLeft : 0));
+		}
+		else {
+			offset.left -= (isFixed ? scrollX : 0);
+		}
+		// reposition keypad panel vertically if outside the browser window
+		if ((offset.top + inst._mainDiv.outerHeight() - scrollY) > browserHeight) {
+			offset.top = Math.max((isFixed ? 0 : scrollY),
+				pos[1] - (isFixed ? scrollY : 0) - inst._mainDiv.outerHeight() -
+				(isFixed && $.browser.opera ? document.documentElement.scrollTop : 0));
+		}
+		else {
+			offset.top -= (isFixed ? scrollY : 0);
+		}
+		return offset;
+	},
+	
+	/* Find an object's position on the screen.
+	   @param  obj  (element) the element to find the position for
+	   @return  (int[2]) the element's position */
+	_findPos: function(obj) {
+        while (obj && (obj.type == 'hidden' || obj.nodeType != 1)) {
+            obj = obj.nextSibling;
+        }
+        var position = $(obj).offset();
+	    return [position.left, position.top];
+	},
+
+	/* Hide the keypad from view.
+	   @param  field     (element) the text field attached to the keypad
+	   @param  duration  (string) the duration over which to close the keypad */
+	_hidePlugin: function(field, duration) {
+		var inst = this._curInst;
+		if (!inst || (field && inst != $.data(field, this.propertyName))) {
+			return;
+		}
+		if (this._keypadShowing) {
+			duration = (duration != null ? duration : inst.options.duration);
+			duration = (duration == 'normal' && $.ui && $.ui.version >= '1.8' ? '_default' : duration);
+			var showAnim = inst.options.showAnim;
+			if ($.effects && ($.effects[showAnim] || ($.effects.effect && $.effects.effect[showAnim]))) {
+				inst._mainDiv.hide(showAnim, inst.options.showOptions, duration);
+			}
+			else {
+				inst._mainDiv[(showAnim == 'slideDown' ? 'slideUp' :
+					(showAnim == 'fadeIn' ? 'fadeOut' : 'hide'))](showAnim ? duration : '');
+			}
+		}
+		if ($.isFunction(inst.options.onClose)) {
+			inst.options.onClose.apply((inst._input ? inst._input[0] : null),  // trigger custom callback
+				[inst._input.val(), inst]);
+		}
+		if (this._keypadShowing) {
+			this._keypadShowing = false;
+			this._lastField = null;
+		}
+		if (inst._inline) {
+			inst._input.val('');
+		}
+		this._curInst = null;
+	},
+
+	/* Handle keystrokes.
+	   @param  e  (event) the key event */
+	_doKeyDown: function(e) {
+		if (e.keyCode == 9) { // Tab out
+			plugin.mainDiv.stop(true, true);
+			plugin._hidePlugin();
+		}
+	},
+
+	/* Close keypad if clicked elsewhere.
+	   @param  event  (event) the mouseclick details */
+	_checkExternalClick: function(event) {
+		if (!plugin._curInst) {
+			return;
+		}
+		var target = $(event.target);
+		if (!target.parents().andSelf().hasClass(plugin._mainDivClass) &&
+				!target.hasClass(plugin.markerClassName) &&
+				!target.parents().andSelf().hasClass(plugin._triggerClass) &&
+				plugin._keypadShowing) {
+			plugin._hidePlugin();
+		}
+	},
+
+	/* Toggle between upper and lower case.
+	   @param  inst  (object) the instance settings */
+	_shiftKeypad: function(inst) {
+		inst.ucase = !inst.ucase;
+		this._updateKeypad(inst);
+		inst._input.focus(); // for further typing
+	},
+
+	/* Erase the text field.
+	   @param  inst  (object) the instance settings */
+	_clearValue: function(inst) {
+		this._setValue(inst, '', 0);
+		this._notifyKeypress(inst, plugin.DEL);
+	},
+
+	/* Erase the last character.
+	   @param  inst  (object) the instance settings */
+	_backValue: function(inst) {
+		var field = inst._input[0];
+		var value = inst._input.val();
+		var range = [value.length, value.length];
+		if (field.setSelectionRange) { // Mozilla
+			range = (inst._input.attr('readonly') || inst._input.attr('disabled') ?
+				range : [field.selectionStart, field.selectionEnd]);
+		}
+		else if (field.createTextRange) { // IE
+			range = (inst._input.attr('readonly') || inst._input.attr('disabled') ?
+				range : this._getIERange(field));
+		}
+		this._setValue(inst, (value.length == 0 ? '' :
+			value.substr(0, range[0] - 1) + value.substr(range[1])), range[0] - 1);
+		this._notifyKeypress(inst, plugin.BS);
+	},
+
+	/* Update the text field with the selected value.
+	   @param  inst   (object) the instance settings
+	   @param  value  (string) the new character to add */
+	_selectValue: function(inst, value) {
+		this.insertValue(inst._input[0], value);
+		this._setValue(inst, inst._input.val());
+		this._notifyKeypress(inst, value);
+	},
+
+	/* Update the text field with the selected value.
+	   @param  input  (element) the input field or
+	                  (jQuery) jQuery collection
+	   @param  value  (string) the new character to add */
+	insertValue: function(input, value) {
+		input = (input.jquery ? input : $(input));
+		var field = input[0];
+		var newValue = input.val();
+		var range = [newValue.length, newValue.length];
+		if (field.setSelectionRange) { // Mozilla
+			range = (input.attr('readonly') || input.attr('disabled') ?
+				range : [field.selectionStart, field.selectionEnd]);
+		}
+		else if (field.createTextRange) { // IE
+			range = (input.attr('readonly') || input.attr('disabled') ?
+				range : this._getIERange(field));
+		}
+		input.val(newValue.substr(0, range[0]) + value + newValue.substr(range[1]));
+		pos = range[0] + value.length;
+		if (input.is(':visible')) {
+			input.focus(); // for further typing
+		}
+		if (field.setSelectionRange) { // Mozilla
+			if (input.is(':visible')) {
+				field.setSelectionRange(pos, pos);
+			}
+		}
+		else if (field.createTextRange) { // IE
+			range = field.createTextRange();
+			range.move('character', pos);
+			range.select();
+		}
+	},
+
+	/* Get the coordinates for the selected area in the text field in IE.
+	   @param  field  (element) the target text field
+	   @return  (int[2]) the start and end positions of the selection */
+	_getIERange: function(field) {
+		field.focus();
+		var selectionRange = document.selection.createRange().duplicate();
+		// Use two ranges: before and selection
+		var beforeRange = this._getIETextRange(field);
+		beforeRange.setEndPoint('EndToStart', selectionRange);
+		// Check each range for trimmed newlines by shrinking the range by one
+		// character and seeing if the text property has changed. If it has not
+		// changed then we know that IE has trimmed a \r\n from the end.
+		var checkCRLF = function(range) {
+			var origText = range.text;
+			var text = origText;
+			var finished = false;
+			while (true) {
+				if (range.compareEndPoints('StartToEnd', range) == 0) {
+					break;
+				} 
+				else {
+					range.moveEnd('character', -1);
+					if (range.text == origText) {
+						text += '\r\n';
+					} 
+					else {
+						break;
+					}
+				}
+			}
+			return text;
+		};
+		var beforeText = checkCRLF(beforeRange);
+		var selectionText = checkCRLF(selectionRange);
+		return [beforeText.length, beforeText.length + selectionText.length];
+	},
+
+	/* Create an IE text range for the text field.
+	   @param  field  (element) the target text field
+	   @return  (object) the corresponding text range */
+	_getIETextRange: function(field) {
+		var isInput = (field.nodeName.toLowerCase() == 'input');
+		var range = (isInput ? field.createTextRange() : document.body.createTextRange());
+		if (!isInput) {
+			range.moveToElementText(field); // Selects all the text for a textarea
+		}
+		return range;
+	},
+
+	/* Set the text field to the selected value,
+	   and trigger any on change event.
+	   @param  inst   (object) the instance settings
+	   @param  value  (string) the new value for the text field */
+	_setValue: function(inst, value) {
+		var maxlen = inst._input.attr('maxlength');
+		if (maxlen > -1) {
+			value = value.substr(0, maxlen);
+		}
+		inst._input.val(value);
+		if (!$.isFunction(inst.options.onKeypress)) {
+			inst._input.trigger('change'); // fire the change event
+		}
+	},
+
+	_notifyKeypress: function(inst, key) {
+		if ($.isFunction(inst.options.onKeypress)) { // trigger custom callback
+			inst.options.onKeypress.apply((inst._input ? inst._input[0] : null),
+				[key, inst._input.val(), inst]);
+		}
+	},
+
+	/* Generate the HTML for the current state of the keypad.
+	   @param  inst  (object) the instance settings
+	   @return  (jQuery) the HTML for this keypad */
+	_generateHTML: function(inst) {
+		var html = (!inst.options.prompt ? '' : '<div class="' + this._promptClass +
+			(inst.options.useThemeRoller ? ' ui-widget-header ui-corner-all' : '') + '">' +
+			inst.options.prompt + '</div>');
+		var layout = this._randomiseLayout(inst);
+		for (var i = 0; i < layout.length; i++) {
+			html += '<div class="' + this._rowClass + '">';
+			var keys = layout[i].split(inst.options.separator);
+			for (var j = 0; j < keys.length; j++) {
+				if (inst.ucase) {
+					keys[j] = inst.options.toUpper(keys[j]);
+				}
+				var keyDef = this._specialKeys[keys[j].charCodeAt(0)];
+				if (keyDef) {
+					html += (keyDef.action ? '<button type="button" class="' + this._specialClass +
+						' ' + this._namePrefixClass + keyDef.name +
+						(inst.options.useThemeRoller ? ' ui-corner-all ui-state-default' +
+						(keyDef.noHighlight ? '' : ' ui-state-highlight') : '') +
+						'" title="' + inst.options[keyDef.name + 'Status'] + '">' +
+						(inst.options[keyDef.name + 'Text'] || '&nbsp;') + '</button>' :
+						'<div class="' + this._namePrefixClass + keyDef.name + '"></div>');
+				}
+				else {
+					html += '<button type="button" class="' + this._keyClass +
+						(inst.options.useThemeRoller ? ' ui-corner-all ui-state-default' : '') + '">' +
+						(keys[j] == ' ' ? '&nbsp;' : keys[j]) + '</button>';
+				}
+			}
+			html += '</div>';
+		}
+		html += '<div style="clear: both;"></div>' + 
+			(!inst._inline && $.browser.msie && parseInt($.browser.version, 10) < 7 ? 
+			'<iframe src="javascript:false;" class="' + plugin._coverClass + '"></iframe>' : '');
+		html = $(html);
+		var thisInst = inst;
+		var activeClasses = this._keyDownClass + (inst.options.useThemeRoller ? ' ui-state-active' : '');
+		html.find('button').mousedown(function() { $(this).addClass(activeClasses); }).
+			mouseup(function() { $(this).removeClass(activeClasses); }).
+			mouseout(function() { $(this).removeClass(activeClasses); }).
+			filter('.' + this._keyClass).click(function() { plugin._selectValue(thisInst, $(this).text()); });
+		$.each(this._specialKeys, function(i, keyDef) {
+			html.find('.' + plugin._namePrefixClass + keyDef.name).click(function() {
+				keyDef.action.apply(thisInst._input, [thisInst]);
+			});
+		});
+		return html;
+	},
+
+	/* Check whether characters should be randomised,
+	   and, if so, produce the randomised layout.
+	   @param  inst  (object) the instance settings
+	   @return  (string[]) the layout with any requested randomisations applied */
+	_randomiseLayout: function(inst) {
+		if (!inst.options.randomiseNumeric && !inst.options.randomiseAlphabetic &&
+				!inst.options.randomiseOther && !inst.options.randomiseAll) {
+			return inst.options.layout;
+		}
+		var numerics = [];
+		var alphas = [];
+		var others = [];
+		var newLayout = [];
+		// Find characters of different types
+		for (var i = 0; i < inst.options.layout.length; i++) {
+			newLayout[i] = '';
+			var keys = inst.options.layout[i].split(inst.options.separator);
+			for (var j = 0; j < keys.length; j++) {
+				if (this._isControl(keys[j])) {
+					continue;
+				}
+				if (inst.options.randomiseAll) {
+					others.push(keys[j]);
+				}
+				else if (inst.options.isNumeric(keys[j])) {
+					numerics.push(keys[j]);
+				}
+				else if (inst.options.isAlphabetic(keys[j])) {
+					alphas.push(keys[j]);
+				}
+				else {
+					others.push(keys[j]);
+				}
+			}
+		}
+		// Shuffle them
+		if (inst.options.randomiseNumeric) {
+			this._shuffle(numerics);
+		}
+		if (inst.options.randomiseAlphabetic) {
+			this._shuffle(alphas);
+		}
+		if (inst.options.randomiseOther || inst.options.randomiseAll) {
+			this._shuffle(others);
+		}
+		var n = 0;
+		var a = 0;
+		var o = 0;
+		// And replace them in the layout
+		for (var i = 0; i < inst.options.layout.length; i++) {
+			var keys = inst.options.layout[i].split(inst.options.separator);
+			for (var j = 0; j < keys.length; j++) {
+				newLayout[i] += (this._isControl(keys[j]) ? keys[j] :
+					(inst.options.randomiseAll ? others[o++] :
+					(inst.options.isNumeric(keys[j]) ? numerics[n++] :
+					(inst.options.isAlphabetic(keys[j]) ? alphas[a++] :
+					others[o++])))) + inst.options.separator;
+			}
+		}
+		return newLayout;
+	},
+
+	/* Is a given character a control character?
+	   @param  ch  (char) the character to test
+	   @return  (boolean) true if a control character, false if not */
+	_isControl: function(ch) {
+		return ch < ' ';
+	},
+
+	/* Is a given character alphabetic?
+	   @param  ch  (char) the character to test
+	   @return  (boolean) true if alphabetic, false if not */
+	isAlphabetic: function(ch) {
+		return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z');
+	},
+
+	/* Is a given character numeric?
+	   @param  ch  (char) the character to test
+	   @return  (boolean) true if numeric, false if not */
+	isNumeric: function(ch) {
+		return (ch >= '0' && ch <= '9');
+	},
+
+	/* Convert a character to upper case.
+	   @param  ch  (char) the character to convert
+	   @return  (char) its uppercase version */
+	toUpper: function(ch) {
+		return ch.toUpperCase();
+	},
+	/* Randomise the contents of an array.
+	   @param  values  (string[]) the array to rearrange */
+	_shuffle: function(values) {
+		for (var i = values.length - 1; i > 0; i--) {
+			var j = Math.floor(Math.random() * values.length);
+			var ch = values[i];
+			values[i] = values[j];
+			values[j] = ch;
+		}
+	}
+});
+
+// The list of commands that return values and don't permit chaining
+var getters = ['isDisabled'];
+
+/* Determine whether a command is a getter and doesn't permit chaining.
+   @param  command    (string, optional) the command to run
+   @param  otherArgs  ([], optional) any other arguments for the command
+   @return  true if the command is a getter, false if not */
+function isNotChained(command, otherArgs) {
+	if (command == 'option' && (otherArgs.length == 0 ||
+			(otherArgs.length == 1 && typeof otherArgs[0] == 'string'))) {
+		return true;
+	}
+	return $.inArray(command, getters) > -1;
+}
+
+/* Invoke the keypad functionality.
+   @param  options  (object) the new settings to use for these instances (optional) or
+                    (string) the command to run (optional)
+   @return  (jQuery) for chaining further calls or
+            (any) getter value */
+$.fn.keypad = function(options) {
+	var otherArgs = Array.prototype.slice.call(arguments, 1);
+	if (isNotChained(options, otherArgs)) {
+		return plugin['_' + options + 'Plugin'].apply(plugin, [this[0]].concat(otherArgs));
+	}
+	return this.each(function() {
+		if (typeof options == 'string') {
+			if (!plugin['_' + options + 'Plugin']) {
+				throw 'Unknown command: ' + options;
+			}
+			plugin['_' + options + 'Plugin'].apply(plugin, [this].concat(otherArgs));
+		}
+		else {
+			plugin._attachPlugin(this, options || {});
+		}
+	});
+};
+
+/* Initialise the keypad functionality. */
+var plugin = $.keypad = new Keypad(); // Singleton instance
+
+// Add the keypad division and external click check
+$(function() {
+	$(document.body).append(plugin.mainDiv).
+		mousedown(plugin._checkExternalClick);
+});
+
+})(jQuery);
Index: branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad-ca.js
===================================================================
--- branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad-ca.js	(revision 8232)
+++ branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad-ca.js	(revision 8232)
@@ -0,0 +1,21 @@
+﻿/* http://keith-wood.name/keypad.html
+   Catalan initialisation for the jQuery keypad extension
+   Written by Ignasi Nogues (inogues@clickartedu.com). */
+(function($) { // hide the namespace
+	$.keypad.regional['ca'] = {
+		buttonText: '...', buttonStatus: 'Obrir el teclat',
+		closeText: 'Tancar', closeStatus: 'Tancar el teclat',
+		clearText: 'Netejar', clearStatus: 'Eliminar tot el text',
+		backText: 'Tornar', backStatus: 'Borrar el caràcter anterior',
+		shiftText: 'Shift', shiftStatus: 'Canviar majúscules/minúscules',
+		spacebarText: '&nbsp;', spacebarStatus: '',
+		enterText: 'Entrar', enterStatus: '',
+		tabText: '→', tabStatus: '',
+		alphabeticLayout: $.keypad.qwertyAlphabetic,
+		fullLayout: $.keypad.qwertyLayout,
+		isAlphabetic: $.keypad.isAlphabetic,
+		isNumeric: $.keypad.isNumeric,
+		toUpper: $.keypad.toUpper,
+		isRTL: false};
+	$.keypad.setDefaults($.keypad.regional['ca']);
+})(jQuery);
Index: branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad-pt-BR.js
===================================================================
--- branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad-pt-BR.js	(revision 8232)
+++ branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad-pt-BR.js	(revision 8232)
@@ -0,0 +1,21 @@
+﻿/* http://keith-wood.name/keypad.html
+   brazilian portuguese initialisation for the jQuery keypad extension
+   Written by Israel Rodriguez (yzraeu{at}gmail.com) July 2009. */
+(function($) { // hide the namespace
+    $.keypad.regional['pt-BR'] = {
+        buttonText: '...', buttonStatus: 'Abrir o teclado',
+        closeText: 'Fechar', closeStatus: 'Fechar o teclado',
+        clearText: 'Limpar', clearStatus: 'Limpar todo o texto',
+        backText: 'Apagar', backStatus: 'Apagar o caractere anterior',
+        shiftText: 'Shift', shiftStatus: 'Ativar maiúsculas/minusculas',
+		spacebarText: '&nbsp;', spacebarStatus: '',
+		enterText: 'Enter', enterStatus: '',
+		tabText: '→', tabStatus: '',
+        alphabeticLayout: $.keypad.qwertyAlphabetic,
+        fullLayout: $.keypad.qwertyLayout,
+        isAlphabetic: $.keypad.isAlphabetic,
+        isNumeric: $.keypad.isNumeric,
+		toUpper: $.keypad.toUpper,
+        isRTL: false};
+    $.keypad.setDefaults($.keypad.regional['pt-BR']);
+})(jQuery);
Index: branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad.min.js
===================================================================
--- branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad.min.js	(revision 8232)
+++ branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad.min.js	(revision 8232)
@@ -0,0 +1,7 @@
+﻿/* http://keith-wood.name/keypad.html
+   Keypad field entry extension for jQuery v1.5.0.
+   Written by Keith Wood (kbwood{at}iinet.com.au) August 2008.
+   Dual licensed under the GPL (http://dev.jquery.com/browser/trunk/jquery/GPL-LICENSE.txt) and 
+   MIT (http://dev.jquery.com/browser/trunk/jquery/MIT-LICENSE.txt) licenses. 
+   Please attribute the author if you use it. */
+(function($){function Keypad(){this._curInst=null;this._disabledFields=[];this._keypadShowing=false;this._keyCode=0;this._specialKeys=[];this.addKeyDef('CLOSE','close',function(a){l._curInst=(a._inline?a:l._curInst);l._hidePlugin()});this.addKeyDef('CLEAR','clear',function(a){l._clearValue(a)});this.addKeyDef('BACK','back',function(a){l._backValue(a)});this.addKeyDef('SHIFT','shift',function(a){l._shiftKeypad(a)});this.addKeyDef('SPACE_BAR','spacebar',function(a){l._selectValue(a,' ')},true);this.addKeyDef('SPACE','space');this.addKeyDef('HALF_SPACE','half-space');this.addKeyDef('ENTER','enter',function(a){l._selectValue(a,'\x0D')},true);this.addKeyDef('TAB','tab',function(a){l._selectValue(a,'\x09')},true);this.qwertyAlphabetic=['qwertyuiop','asdfghjkl','zxcvbnm'];this.qwertyLayout=['!@#$%^&*()_='+this.HALF_SPACE+this.SPACE+this.CLOSE,this.HALF_SPACE+'`~[]{}<>\\|/'+this.SPACE+'789','qwertyuiop\'"'+this.HALF_SPACE+'456',this.HALF_SPACE+'asdfghjkl;:'+this.SPACE+'123',this.SPACE+'zxcvbnm,.?'+this.SPACE+this.HALF_SPACE+'-0+',''+this.TAB+this.ENTER+this.SPACE_BAR+this.SHIFT+this.HALF_SPACE+this.BACK+this.CLEAR];this.regional=[];this.regional['']={buttonText:'...',buttonStatus:'Open the keypad',closeText:'Close',closeStatus:'Close the keypad',clearText:'Clear',clearStatus:'Erase all the text',backText:'Back',backStatus:'Erase the previous character',spacebarText:'&nbsp;',spacebarStatus:'Space',enterText:'Enter',enterStatus:'Carriage return',tabText:'→',tabStatus:'Horizontal tab',shiftText:'Shift',shiftStatus:'Toggle upper/lower case characters',alphabeticLayout:this.qwertyAlphabetic,fullLayout:this.qwertyLayout,isAlphabetic:this.isAlphabetic,isNumeric:this.isNumeric,toUpper:this.toUpper,isRTL:false};this._defaults={showOn:'focus',buttonImage:'',buttonImageOnly:false,showAnim:'show',showOptions:{},duration:'normal',appendText:'',useThemeRoller:false,keypadClass:'',prompt:'',layout:['123'+this.CLOSE,'456'+this.CLEAR,'789'+this.BACK,this.SPACE+'0'],separator:'',target:null,keypadOnly:true,randomiseAlphabetic:false,randomiseNumeric:false,randomiseOther:false,randomiseAll:false,beforeShow:null,onKeypress:null,onClose:null};$.extend(this._defaults,this.regional['']);this.mainDiv=$('<div class="'+this._mainDivClass+'" style="display: none;"></div>')}$.extend(Keypad.prototype,{markerClassName:'hasKeypad',propertyName:'keypad',_mainDivClass:'keypad-popup',_inlineClass:'keypad-inline',_appendClass:'keypad-append',_triggerClass:'keypad-trigger',_disableClass:'keypad-disabled',_inlineEntryClass:'keypad-keyentry',_coverClass:'keypad-cover',_rtlClass:'keypad-rtl',_rowClass:'keypad-row',_promptClass:'keypad-prompt',_specialClass:'keypad-special',_namePrefixClass:'keypad-',_keyClass:'keypad-key',_keyDownClass:'keypad-key-down',setDefaults:function(a){$.extend(this._defaults,a||{});return this},addKeyDef:function(a,b,c,d){if(this._keyCode==32){throw'Only 32 special keys allowed';}this[a]=String.fromCharCode(this._keyCode++);this._specialKeys.push({code:this[a],id:a,name:b,action:c,noHighlight:d});return this},_attachPlugin:function(a,b){a=$(a);if(a.hasClass(this.markerClassName)){return}var c=!a[0].nodeName.toLowerCase().match(/input|textarea/);var d={options:$.extend({},this._defaults,b),_inline:c,_mainDiv:(c?$('<div class="'+this._inlineClass+'"></div>'):l.mainDiv),ucase:false};this._setInput(a,d);this._connectKeypad(a,d);if(c){a.append(d._mainDiv).bind('click.'+this.propertyName,function(){d._input.focus()});this._updateKeypad(d)}else if(a.is(':disabled')){this._disablePlugin(a)}},_setInput:function(a,b){b._input=$(!b._inline?a:b.options.target||'<input type="text" class="'+this._inlineEntryClass+'" disabled="disabled"/>');if(b._inline){a.find('input').remove();if(!b.options.target){a.append(b._input)}}},_connectKeypad:function(d,e){d=$(d);var f=e.options.appendText;if(f){d[e.options.isRTL?'before':'after']('<span class="'+this._appendClass+'">'+f+'</span>')}if(!e._inline){if(e.options.showOn=='focus'||e.options.showOn=='both'){d.bind('focus.'+this.propertyName,this._showPlugin).bind('keydown.'+this.propertyName,this._doKeyDown)}if(e.options.showOn=='button'||e.options.showOn=='both'){var g=e.options.buttonStatus;var h=e.options.buttonImage;var i=$(e.options.buttonImageOnly?$('<img src="'+h+'" alt="'+g+'" title="'+g+'"/>'):$('<button type="button" title="'+g+'"></button>').html(h==''?e.options.buttonText:$('<img src="'+h+'" alt="'+g+'" title="'+g+'"/>')));d[e.options.isRTL?'before':'after'](i);i.addClass(this._triggerClass).click(function(){if(l._keypadShowing&&l._lastField==d[0]){l._hidePlugin()}else{l._showPlugin(d[0])}return false})}}e.saveReadonly=d.attr('readonly');d.addClass(this.markerClassName).data(this.propertyName,e)[e.options.keypadOnly?'attr':'removeAttr']('readonly',true).bind('setData.'+this.propertyName,function(a,b,c){e.options[b]=c}).bind('getData.'+this.propertyName,function(a,b){return e.options[b]})},_optionPlugin:function(a,b,c){a=$(a);var d=a.data(this.propertyName);if(!b||(typeof b=='string'&&c==null)){var e=b;b=(d||{}).options;return(b&&e?b[e]:b)}if(!a.hasClass(this.markerClassName)){return}b=b||{};if(typeof b=='string'){var e=b;b={};b[e]=c}if(this._curInst==d){this._hidePlugin()}$.extend(d.options,b);this._setInput(a,d);this._updateKeypad(d)},_destroyPlugin:function(a){a=$(a);if(!a.hasClass(this.markerClassName)){return}var b=a.data(this.propertyName);if(this._curInst==b){this._hidePlugin()}a.siblings('.'+this._appendClass).remove().end().siblings('.'+this._triggerClass).remove().end().prev('.'+this._inlineEntryClass).remove();a.removeClass(this.markerClassName).empty().unbind('.'+this.propertyName).removeData(this.propertyName)[b.saveReadonly?'attr':'removeAttr']('readonly',true);b._input.removeData(this.propertyName)},_enablePlugin:function(b){b=$(b);if(!b.hasClass(this.markerClassName)){return}var c=b[0].nodeName.toLowerCase();if(c.match(/input|textarea/)){b[0].disabled=false;b.siblings('button.'+this._triggerClass).each(function(){this.disabled=false}).end().siblings('img.'+this._triggerClass).css({opacity:'1.0',cursor:''})}else if(c.match(/div|span/)){b.children('.'+this._disableClass).remove();var d=b.data(this.propertyName);d._mainDiv.find('button').removeAttr('disabled')}this._disabledFields=$.map(this._disabledFields,function(a){return(a==b[0]?null:a)})},_disablePlugin:function(b){b=$(b);if(!b.hasClass(this.markerClassName)){return}var c=b[0].nodeName.toLowerCase();if(c.match(/input|textarea/)){b[0].disabled=true;b.siblings('button.'+this._triggerClass).each(function(){this.disabled=true}).end().siblings('img.'+this._triggerClass).css({opacity:'0.5',cursor:'default'})}else if(c.match(/div|span/)){var d=b.children('.'+this._inlineClass);var e=d.offset();var f={left:0,top:0};d.parents().each(function(){if($(this).css('position')=='relative'){f=$(this).offset();return false}});b.prepend('<div class="'+this._disableClass+'" style="width: '+d.outerWidth()+'px; height: '+d.outerHeight()+'px; left: '+(e.left-f.left)+'px; top: '+(e.top-f.top)+'px;"></div>');var g=b.data(this.propertyName);g._mainDiv.find('button').attr('disabled','disabled')}this._disabledFields=$.map(this._disabledFields,function(a){return(a==b[0]?null:a)});this._disabledFields[this._disabledFields.length]=b[0]},_isDisabledPlugin:function(a){return(a&&$.inArray(a,this._disabledFields)>-1)},_showPlugin:function(b){b=b.target||b;if(l._isDisabledPlugin(b)||l._lastField==b){return}var c=$.data(b,l.propertyName);l._hidePlugin(null,'');l._lastField=b;l._pos=l._findPos(b);l._pos[1]+=b.offsetHeight;var d=false;$(b).parents().each(function(){d|=$(this).css('position')=='fixed';return!d});if(d&&$.browser.opera){l._pos[0]-=document.documentElement.scrollLeft;l._pos[1]-=document.documentElement.scrollTop}var e={left:l._pos[0],top:l._pos[1]};l._pos=null;c._mainDiv.css({position:'absolute',display:'block',top:'-1000px',width:($.browser.opera?'1000px':'auto')});l._updateKeypad(c);e=l._checkOffset(c,e,d);c._mainDiv.css({position:(d?'fixed':'absolute'),display:'none',left:e.left+'px',top:e.top+'px'});var f=c.options.duration;f=(f=='normal'&&$.ui&&$.ui.version>='1.8'?'_default':f);var g=c.options.showAnim;var h=function(){l._keypadShowing=true;var a=l._getBorders(c._mainDiv);c._mainDiv.find('iframe.'+l._coverClass).css({left:-a[0],top:-a[1],width:c._mainDiv.outerWidth(),height:c._mainDiv.outerHeight()})};if($.effects&&($.effects[g]||($.effects.effect&&$.effects.effect[g]))){var i=c._mainDiv.data();for(var j in i){if(j.match(/^ec\.storage\./)){i[j]=c._mainDiv.css(j.replace(/ec\.storage\./,''))}}c._mainDiv.data(i).show(g,c.options.showOptions,f,h)}else{c._mainDiv[g||'show']((g?f:''),h)}if(!g){h()}if(c._input[0].type!='hidden'){c._input[0].focus()}l._curInst=c},_updateKeypad:function(a){var b=this._getBorders(a._mainDiv);a._mainDiv.empty().append(this._generateHTML(a)).find('iframe.'+this._coverClass).css({left:-b[0],top:-b[1],width:a._mainDiv.outerWidth(),height:a._mainDiv.outerHeight()});a._mainDiv.removeClass().addClass(a.options.keypadClass+(a.options.useThemeRoller?' ui-widget ui-widget-content':'')+(a.options.isRTL?' '+this._rtlClass:'')+' '+(a._inline?this._inlineClass:this._mainDivClass));if($.isFunction(a.options.beforeShow)){a.options.beforeShow.apply((a._input?a._input[0]:null),[a._mainDiv,a])}},_getBorders:function(c){var d=function(a){var b=($.browser.msie?1:0);return{thin:1+b,medium:3+b,thick:5+b}[a]||a};return[parseFloat(d(c.css('border-left-width'))),parseFloat(d(c.css('border-top-width')))]},_checkOffset:function(a,b,c){var d=a._input?this._findPos(a._input[0]):null;var e=window.innerWidth||document.documentElement.clientWidth;var f=window.innerHeight||document.documentElement.clientHeight;var g=document.documentElement.scrollLeft||document.body.scrollLeft;var h=document.documentElement.scrollTop||document.body.scrollTop;if(($.browser.msie&&parseInt($.browser.version,10)<7)||$.browser.opera){var i=0;a._mainDiv.find(':not(div,iframe)').each(function(){i=Math.max(i,this.offsetLeft+$(this).outerWidth()+parseInt($(this).css('margin-right'),10))});a._mainDiv.css('width',i)}if(a.options.isRTL||(b.left+a._mainDiv.outerWidth()-g)>e){b.left=Math.max((c?0:g),d[0]+(a._input?a._input.outerWidth():0)-(c?g:0)-a._mainDiv.outerWidth()-(c&&$.browser.opera?document.documentElement.scrollLeft:0))}else{b.left-=(c?g:0)}if((b.top+a._mainDiv.outerHeight()-h)>f){b.top=Math.max((c?0:h),d[1]-(c?h:0)-a._mainDiv.outerHeight()-(c&&$.browser.opera?document.documentElement.scrollTop:0))}else{b.top-=(c?h:0)}return b},_findPos:function(a){while(a&&(a.type=='hidden'||a.nodeType!=1)){a=a.nextSibling}var b=$(a).offset();return[b.left,b.top]},_hidePlugin:function(a,b){var c=this._curInst;if(!c||(a&&c!=$.data(a,this.propertyName))){return}if(this._keypadShowing){b=(b!=null?b:c.options.duration);b=(b=='normal'&&$.ui&&$.ui.version>='1.8'?'_default':b);var d=c.options.showAnim;if($.effects&&($.effects[d]||($.effects.effect&&$.effects.effect[d]))){c._mainDiv.hide(d,c.options.showOptions,b)}else{c._mainDiv[(d=='slideDown'?'slideUp':(d=='fadeIn'?'fadeOut':'hide'))](d?b:'')}}if($.isFunction(c.options.onClose)){c.options.onClose.apply((c._input?c._input[0]:null),[c._input.val(),c])}if(this._keypadShowing){this._keypadShowing=false;this._lastField=null}if(c._inline){c._input.val('')}this._curInst=null},_doKeyDown:function(e){if(e.keyCode==9){l.mainDiv.stop(true,true);l._hidePlugin()}},_checkExternalClick:function(a){if(!l._curInst){return}var b=$(a.target);if(!b.parents().andSelf().hasClass(l._mainDivClass)&&!b.hasClass(l.markerClassName)&&!b.parents().andSelf().hasClass(l._triggerClass)&&l._keypadShowing){l._hidePlugin()}},_shiftKeypad:function(a){a.ucase=!a.ucase;this._updateKeypad(a);a._input.focus()},_clearValue:function(a){this._setValue(a,'',0);this._notifyKeypress(a,l.DEL)},_backValue:function(a){var b=a._input[0];var c=a._input.val();var d=[c.length,c.length];if(b.setSelectionRange){d=(a._input.attr('readonly')||a._input.attr('disabled')?d:[b.selectionStart,b.selectionEnd])}else if(b.createTextRange){d=(a._input.attr('readonly')||a._input.attr('disabled')?d:this._getIERange(b))}this._setValue(a,(c.length==0?'':c.substr(0,d[0]-1)+c.substr(d[1])),d[0]-1);this._notifyKeypress(a,l.BS)},_selectValue:function(a,b){this.insertValue(a._input[0],b);this._setValue(a,a._input.val());this._notifyKeypress(a,b)},insertValue:function(a,b){a=(a.jquery?a:$(a));var c=a[0];var d=a.val();var e=[d.length,d.length];if(c.setSelectionRange){e=(a.attr('readonly')||a.attr('disabled')?e:[c.selectionStart,c.selectionEnd])}else if(c.createTextRange){e=(a.attr('readonly')||a.attr('disabled')?e:this._getIERange(c))}a.val(d.substr(0,e[0])+b+d.substr(e[1]));pos=e[0]+b.length;if(a.is(':visible')){a.focus()}if(c.setSelectionRange){if(a.is(':visible')){c.setSelectionRange(pos,pos)}}else if(c.createTextRange){e=c.createTextRange();e.move('character',pos);e.select()}},_getIERange:function(e){e.focus();var f=document.selection.createRange().duplicate();var g=this._getIETextRange(e);g.setEndPoint('EndToStart',f);var h=function(a){var b=a.text;var c=b;var d=false;while(true){if(a.compareEndPoints('StartToEnd',a)==0){break}else{a.moveEnd('character',-1);if(a.text==b){c+='\r\n'}else{break}}}return c};var i=h(g);var j=h(f);return[i.length,i.length+j.length]},_getIETextRange:function(a){var b=(a.nodeName.toLowerCase()=='input');var c=(b?a.createTextRange():document.body.createTextRange());if(!b){c.moveToElementText(a)}return c},_setValue:function(a,b){var c=a._input.attr('maxlength');if(c>-1){b=b.substr(0,c)}a._input.val(b);if(!$.isFunction(a.options.onKeypress)){a._input.trigger('change')}},_notifyKeypress:function(a,b){if($.isFunction(a.options.onKeypress)){a.options.onKeypress.apply((a._input?a._input[0]:null),[b,a._input.val(),a])}},_generateHTML:function(b){var c=(!b.options.prompt?'':'<div class="'+this._promptClass+(b.options.useThemeRoller?' ui-widget-header ui-corner-all':'')+'">'+b.options.prompt+'</div>');var d=this._randomiseLayout(b);for(var i=0;i<d.length;i++){c+='<div class="'+this._rowClass+'">';var e=d[i].split(b.options.separator);for(var j=0;j<e.length;j++){if(b.ucase){e[j]=b.options.toUpper(e[j])}var f=this._specialKeys[e[j].charCodeAt(0)];if(f){c+=(f.action?'<button type="button" class="'+this._specialClass+' '+this._namePrefixClass+f.name+(b.options.useThemeRoller?' ui-corner-all ui-state-default'+(f.noHighlight?'':' ui-state-highlight'):'')+'" title="'+b.options[f.name+'Status']+'">'+(b.options[f.name+'Text']||'&nbsp;')+'</button>':'<div class="'+this._namePrefixClass+f.name+'"></div>')}else{c+='<button type="button" class="'+this._keyClass+(b.options.useThemeRoller?' ui-corner-all ui-state-default':'')+'">'+(e[j]==' '?'&nbsp;':e[j])+'</button>'}}c+='</div>'}c+='<div style="clear: both;"></div>'+(!b._inline&&$.browser.msie&&parseInt($.browser.version,10)<7?'<iframe src="javascript:false;" class="'+l._coverClass+'"></iframe>':'');c=$(c);var g=b;var h=this._keyDownClass+(b.options.useThemeRoller?' ui-state-active':'');c.find('button').mousedown(function(){$(this).addClass(h)}).mouseup(function(){$(this).removeClass(h)}).mouseout(function(){$(this).removeClass(h)}).filter('.'+this._keyClass).click(function(){l._selectValue(g,$(this).text())});$.each(this._specialKeys,function(i,a){c.find('.'+l._namePrefixClass+a.name).click(function(){a.action.apply(g._input,[g])})});return c},_randomiseLayout:function(b){if(!b.options.randomiseNumeric&&!b.options.randomiseAlphabetic&&!b.options.randomiseOther&&!b.options.randomiseAll){return b.options.layout}var c=[];var d=[];var e=[];var f=[];for(var i=0;i<b.options.layout.length;i++){f[i]='';var g=b.options.layout[i].split(b.options.separator);for(var j=0;j<g.length;j++){if(this._isControl(g[j])){continue}if(b.options.randomiseAll){e.push(g[j])}else if(b.options.isNumeric(g[j])){c.push(g[j])}else if(b.options.isAlphabetic(g[j])){d.push(g[j])}else{e.push(g[j])}}}if(b.options.randomiseNumeric){this._shuffle(c)}if(b.options.randomiseAlphabetic){this._shuffle(d)}if(b.options.randomiseOther||b.options.randomiseAll){this._shuffle(e)}var n=0;var a=0;var o=0;for(var i=0;i<b.options.layout.length;i++){var g=b.options.layout[i].split(b.options.separator);for(var j=0;j<g.length;j++){f[i]+=(this._isControl(g[j])?g[j]:(b.options.randomiseAll?e[o++]:(b.options.isNumeric(g[j])?c[n++]:(b.options.isAlphabetic(g[j])?d[a++]:e[o++]))))+b.options.separator}}return f},_isControl:function(a){return a<' '},isAlphabetic:function(a){return(a>='A'&&a<='Z')||(a>='a'&&a<='z')},isNumeric:function(a){return(a>='0'&&a<='9')},toUpper:function(a){return a.toUpperCase()},_shuffle:function(a){for(var i=a.length-1;i>0;i--){var j=Math.floor(Math.random()*a.length);var b=a[i];a[i]=a[j];a[j]=b}}});var k=['isDisabled'];function isNotChained(a,b){if(a=='option'&&(b.length==0||(b.length==1&&typeof b[0]=='string'))){return true}return $.inArray(a,k)>-1}$.fn.keypad=function(a){var b=Array.prototype.slice.call(arguments,1);if(isNotChained(a,b)){return l['_'+a+'Plugin'].apply(l,[this[0]].concat(b))}return this.each(function(){if(typeof a=='string'){if(!l['_'+a+'Plugin']){throw'Unknown command: '+a;}l['_'+a+'Plugin'].apply(l,[this].concat(b))}else{l._attachPlugin(this,a||{})}})};var l=$.keypad=new Keypad();$(function(){$(document.body).append(l.mainDiv).mousedown(l._checkExternalClick)})})(jQuery);
Index: branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad-cs.js
===================================================================
--- branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad-cs.js	(revision 8232)
+++ branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad-cs.js	(revision 8232)
@@ -0,0 +1,21 @@
+﻿/* http://keith-wood.name/keypad.html
+   Czech initialisation for the jQuery keypad extension
+   Written by Amadeo Mareš. */
+(function($) { // hide the namespace
+    $.keypad.regional['cs'] = {
+        buttonText: '...', buttonStatus: 'Otevřít',
+        closeText: 'Zavřít', closeStatus: 'Zavře klávesnici',
+        clearText: 'Vymazat', clearStatus: 'Smaže text',
+        backText: 'Smazat', backStatus: 'Smaže poslední písmeno',
+        shiftText: 'Velikost', shiftStatus: 'Nastaví velká/malá písmena',
+		spacebarText: '&nbsp;', spacebarStatus: '',
+		enterText: 'Enter', enterStatus: '',
+		tabText: '→', tabStatus: '',
+        alphabeticLayout: $.keypad.qwertyAlphabetic,
+        fullLayout: $.keypad.qwertyLayout,
+        isAlphabetic: $.keypad.isAlphabetic,
+        isNumeric: $.keypad.isNumeric,
+		toUpper: $.keypad.toUpper,
+        isRTL: false};
+    $.keypad.setDefaults($.keypad.regional['cs']);
+})(jQuery);
Index: branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad-tr.js
===================================================================
--- branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad-tr.js	(revision 8232)
+++ branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad-tr.js	(revision 8232)
@@ -0,0 +1,21 @@
+﻿/* http://keith-wood.name/keypad.html
+   Turkish localisation for the jQuery keypad extension
+   Written by Yücel Kandemir(yucel{at}21bilisim.com) September 2010. */
+(function($) { // hide the namespace
+	$.keypad.regional['tr'] = {
+		buttonText: '...', buttonStatus: 'Aç',
+		closeText: 'Kapat', closeStatus: 'Klavyeyi Kapatýr',
+		clearText: 'Sil', clearStatus: 'Ýçerisini Temizler',
+		backText: 'Geri Al', backStatus: 'Son Karakteri Siler.',
+		shiftText: 'Büyüt', shiftStatus: 'Büyük Harfle Yazmak Ýçin Seçiniz.',
+		spacebarText: '&nbsp;', spacebarStatus: '',
+		enterText: 'Enter', enterStatus: '',
+		tabText: '→', tabStatus: '',
+    	alphabeticLayout: $.keypad.qwertyAlphabetic,
+	    fullLayout: $.keypad.qwertyLayout,
+    	isAlphabetic: $.keypad.isAlphabetic,
+	    isNumeric: $.keypad.isNumeric,
+		toUpper: $.keypad.toUpper,
+    	isRTL: false};
+	$.keypad.setDefaults($.keypad.regional['tr']);
+})(jQuery);
Index: branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad-es.js
===================================================================
--- branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad-es.js	(revision 8232)
+++ branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad-es.js	(revision 8232)
@@ -0,0 +1,21 @@
+﻿/* http://keith-wood.name/keypad.html
+   Spanish initialisation for the jQuery keypad extension
+   Written by Cristhian Benitez (cbenitez@gmail.com). */
+(function($) { // hide the namespace
+	$.keypad.regional['es'] = {
+		buttonText: '...', buttonStatus: 'Abrir el teclado',
+		closeText: 'Cerrar', closeStatus: 'Cerrar el teclado',
+		clearText: 'Limpiar', clearStatus: 'Eliminar todo el texto',
+		backText: 'Volver', backStatus: 'Borrar el caracter anterior',
+		shiftText: 'Shift', shiftStatus: 'Cambiar mayusculas/minusculas',
+		spacebarText: '&nbsp;', spacebarStatus: '',
+		enterText: 'Enter', enterStatus: '',
+		tabText: '→', tabStatus: '',
+		alphabeticLayout: $.keypad.qwertyAlphabetic,
+		fullLayout: $.keypad.qwertyLayout,
+		isAlphabetic: $.keypad.isAlphabetic,
+		isNumeric: $.keypad.isNumeric,
+		toUpper: $.keypad.toUpper,
+		isRTL: false};
+	$.keypad.setDefaults($.keypad.regional['es']);
+})(jQuery);
Index: branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad-fr.js
===================================================================
--- branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad-fr.js	(revision 8232)
+++ branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad-fr.js	(revision 8232)
@@ -0,0 +1,37 @@
+﻿/* http://keith-wood.name/keypad.html
+   French initialisation for the jQuery keypad extension
+   Written by Keith Wood (kbwood{at}iinet.com.au) August 2008. */
+(function($) { // hide the namespace
+
+	$.keypad.azertyAlphabetic = ['àâçéèêîôùû', 'azertyuiop', 'qsdfghjklm', 'wxcvbn'];
+	$.keypad.azertyLayout = ['&~#{([_@])}' + $.keypad.HALF_SPACE + '£$€',
+		'<>|`°^!?\'"\\' + $.keypad.HALF_SPACE + '/*=',
+		$.keypad.HALF_SPACE + $.keypad.azertyAlphabetic[0] + $.keypad.SPACE + '789',
+		$.keypad.azertyAlphabetic[1] + '%' + $.keypad.HALF_SPACE + '456',
+		$.keypad.HALF_SPACE + $.keypad.azertyAlphabetic[2] + $.keypad.SPACE + '123',
+		'§' + $.keypad.azertyAlphabetic[3] + ',.;:' + $.keypad.HALF_SPACE + '-0+',
+		$.keypad.SHIFT + $.keypad.SPACE_BAR + $.keypad.HALF_SPACE +
+		$.keypad.BACK + $.keypad.CLEAR + $.keypad.CLOSE];
+	$.keypad.regional['fr'] = {
+		buttonText: '...', buttonStatus: 'Ouvrir',
+		closeText: 'Fermer', closeStatus: 'Fermer le pavé numérique',
+		clearText: 'Effacer', clearStatus: 'Effacer la valeur',
+		backText: 'Défaire', backStatus: 'Effacer la dernière touche',
+		shiftText: 'Maj', shiftStatus: '',
+		spacebarText: '&nbsp;', spacebarStatus: '',
+		enterText: 'Enter', enterStatus: '',
+		tabText: '→', tabStatus: '',
+		alphabeticLayout: $.keypad.azertyAlphabetic,
+		fullLayout: $.keypad.azertyLayout,
+		isAlphabetic: $.keypad.isAlphabetic,
+		isNumeric: $.keypad.isNumeric,
+		toUpper: $.keypad.toUpper,
+		isRTL: false};
+	$.keypad.setDefaults($.keypad.regional['fr']);
+
+	function isAlphabetic(ch) {
+		return ($.keypad.isAlphabetic(ch) ||
+			'áàäãâçéèëêíìïîóòöõôúùüû'.indexOf(ch) > -1);
+	}
+
+})(jQuery);
Index: branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad-de.js
===================================================================
--- branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad-de.js	(revision 8232)
+++ branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad-de.js	(revision 8232)
@@ -0,0 +1,36 @@
+﻿/* http://keith-wood.name/keypad.html
+   German localisation for the jQuery keypad extension
+   Written by Uwe Jakobs(u.jakobs{at}imageco.de) September 2009. */
+(function($) { // hide the namespace
+
+	$.keypad.qwertzAlphabetic = ['qwertzuiopüß', 'asdfghjklöä', 'yxcvbnm'];
+	$.keypad.qwertzLayout = 
+		['!"§$%&/()=?`' + $.keypad.BACK + $.keypad.HALF_SPACE + '$£€/',
+		'<>°^@{[]}\\~´;:' + $.keypad.HALF_SPACE + '789*',
+		$.keypad.qwertzAlphabetic[0] + '+*' +
+		$.keypad.HALF_SPACE + '456-',
+		$.keypad.HALF_SPACE + $.keypad.qwertzAlphabetic[1] +
+		'#\'' + $.keypad.SPACE + '123+',
+		'|' + $.keypad.qwertzAlphabetic[2] + 'µ,.-_' +
+		$.keypad.SPACE + $.keypad.HALF_SPACE +'.0,=', 
+		$.keypad.SHIFT + $.keypad.SPACE + $.keypad.SPACE_BAR +
+		$.keypad.SPACE + $.keypad.SPACE + $.keypad.SPACE + $.keypad.CLEAR +
+		$.keypad.SPACE + $.keypad.SPACE + $.keypad.HALF_SPACE + $.keypad.CLOSE];
+	$.keypad.regional['de'] = {
+		buttonText: '...', buttonStatus: 'Öffnen',
+		closeText: 'schließen', closeStatus: 'schließen',
+		clearText: 'löschen', clearStatus: 'Gesamten Inhalt löschen',
+		backText: 'zurück', backStatus: 'Letzte Eingabe löschen',
+		shiftText: 'umschalten', shiftStatus: 'Zwischen Groß- und Kleinschreibung wechseln',
+		spacebarText: '&nbsp;', spacebarStatus: '',
+		enterText: 'Enter', enterStatus: '',
+		tabText: '→', tabStatus: '',
+		alphabeticLayout: $.keypad.qwertzAlphabetic,
+		fullLayout: $.keypad.qwertzLayout,
+		isAlphabetic: $.keypad.isAlphabetic,
+		isNumeric: $.keypad.isNumeric,
+		toUpper: $.keypad.toUpper,
+		isRTL: false};
+	$.keypad.setDefaults($.keypad.regional['de']);
+
+})(jQuery);
Index: branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad-nl.js
===================================================================
--- branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad-nl.js	(revision 8232)
+++ branches/2.5/prototype/plugins/jquery.keyboard/jquery.keypad-nl.js	(revision 8232)
@@ -0,0 +1,21 @@
+﻿/* http://keith-wood.name/keypad.html
+   dutch initialisation for the jQuery keypad extension
+   Written by Michiel Mussies (mail{at}webcrafts.nl) November 2009. */
+(function($) { // hide the namespace
+    $.keypad.regional['nl'] = {
+        buttonText: '...', buttonStatus: 'Open',
+        closeText: 'Sluit', closeStatus: 'Sluit',
+        clearText: 'Wissen', clearStatus: 'Wis alle tekens',
+        backText: 'Terug', backStatus: 'Wis laatste teken',
+        shiftText: 'Shift', shiftStatus: 'Activeer hoofd-/kleine letters',
+		spacebarText: '&nbsp;', spacebarStatus: '',
+		enterText: 'Enter', enterStatus: '',
+		tabText: '→', tabStatus: '',
+        alphabeticLayout: $.keypad.qwertyAlphabetic,
+        fullLayout: $.keypad.qwertyLayout,
+        isAlphabetic: $.keypad.isAlphabetic,
+        isNumeric: $.keypad.isNumeric,
+		toUpper: $.keypad.toUpper,
+        isRTL: false};
+    $.keypad.setDefaults($.keypad.regional['nl']);
+})(jQuery);
Index: branches/2.5/prototype/services/PostgreSQL.php
===================================================================
--- branches/2.5/prototype/services/PostgreSQL.php	(revision 7961)
+++ branches/2.5/prototype/services/PostgreSQL.php	(revision 8232)
@@ -47,70 +47,70 @@
     private $config; //Configuração
     public  $error = false; //Armazena um erro caso ocorra
-    private $maps; //Cache de maps 
-    private $tables; 
- 
-    public function find ( $uri, $justthese = false, $criteria = false ) 
-    { 
-        $condition = ''; 
- 
-        if(!isset($this->maps[$uri['concept']]) || !isset($this->tables[$uri['concept']])) 
-        { 
-            $this->maps[$uri['concept']] = Config::get($uri['concept'], 'PostgreSQL.mapping'); 
-            $this->tables[$uri['concept']] =  Config::get($uri['concept'],'PostgreSQL.concept'); 
-        } 
- 
-        $tables = $this->tables[$uri['concept']]; 
- 
-        $justthese = self::parseJustthese($justthese, $this->maps[$uri['concept']] , $this->tables[$uri['concept']]); 
- 
-        if(isset($criteria['condition'])) 
-        { 
-            $pc = $this->parseCondition($criteria['condition']); 
- 
-            if(is_array($pc)) 
-            { 
-                if(!in_array($this->tables[$uri['concept']], $pc['tables'])) 
-                    $pc['tables'][] = $this->tables[$uri['concept']]; 
- 
-                $tables = implode(',', $pc['tables'] ); 
-                $condition .= ' WHERE ' . $pc['conditions']; 
-            } 
- 
-        } 
- 
-        $criteria = ($criteria !== false) ? $this->parseCriteria ( $criteria , $this->maps[$uri['concept']] , $condition , $this->tables[$uri['concept']]) : $condition; 
- 
-        return $this->execSql( 'SELECT '.$justthese['select'].' FROM '. $tables .' '.$criteria ); 
-    } 
- 
-   public function read ( $uri, $justthese = false , $criteria = false) 
-   { 
-       if(!isset($this->maps[$uri['concept']]) || !isset($this->tables[$uri['concept']])) 
-       { 
-           $this->maps[$uri['concept']] = Config::get($uri['concept'], 'PostgreSQL.mapping'); 
-           $this->tables[$uri['concept']] =  Config::get($uri['concept'],'PostgreSQL.concept'); 
-       } 
- 
-       $condition = ' WHERE '.$this->tables[$uri['concept']].'.'.$this->maps[$uri['concept']]['id'].' = \''.addslashes( $uri['id'] ).'\''; 
-       $justthese = self::parseJustthese($justthese, $this->maps[$uri['concept']] , $this->tables[$uri['concept']]); 
-       $tables = $this->tables[$uri['concept']]; 
- 
-       if(isset($criteria['condition'])) 
-       { 
-           $pc = $this->parseCondition($criteria['condition']); 
- 
-           if(is_array($pc)) 
-           { 
-               if(!in_array($this->tables[$uri['concept']], $pc['tables'])) 
-                   $pc['tables'][] = $this->tables[$uri['concept']]; 
- 
-               $tables = implode(',', $pc['tables'] ); 
-               $condition .= ' AND ' .  $pc['conditions']; 
-           } 
-       } 
- 
-       $criteria = ($criteria !== false) ? $this->parseCriteria ( $criteria , $this->maps[$uri['concept']] , $condition , $this->tables[$uri['concept']]) : $condition; 
- 
-       return $this->execSql( 'SELECT '.$justthese['select'].' FROM '. $tables . ' ' . $criteria , true ); 
+    private $maps; //Cache de maps
+    private $tables;
+
+    public function find ( $uri, $justthese = false, $criteria = false )
+    {
+        $condition = '';
+
+        if(!isset($this->maps[$uri['concept']]) || !isset($this->tables[$uri['concept']]))
+        {
+            $this->maps[$uri['concept']] = Config::get($uri['concept'], 'PostgreSQL.mapping');
+            $this->tables[$uri['concept']] =  Config::get($uri['concept'],'PostgreSQL.concept');
+        }
+
+        $tables = $this->tables[$uri['concept']];
+
+        $justthese = self::parseJustthese($justthese, $this->maps[$uri['concept']] , $this->tables[$uri['concept']]);
+
+        if(isset($criteria['condition']))
+        {
+            $pc = $this->parseCondition($criteria['condition']);
+
+            if(is_array($pc))
+            {
+                if(!in_array($this->tables[$uri['concept']], $pc['tables']))
+                    $pc['tables'][] = $this->tables[$uri['concept']];
+
+                $tables = implode(',', $pc['tables'] );
+                $condition .= ' WHERE ' . $pc['conditions'];
+            }
+
+        }
+
+        $criteria = ($criteria !== false) ? $this->parseCriteria ( $criteria , $this->maps[$uri['concept']] , $condition , $this->tables[$uri['concept']]) : $condition;
+
+        return $this->execSql( 'SELECT '.$justthese['select'].' FROM '. $tables .' '.$criteria );
+    }
+
+   public function read ( $uri, $justthese = false , $criteria = false)
+   {
+       if(!isset($this->maps[$uri['concept']]) || !isset($this->tables[$uri['concept']]))
+       {
+           $this->maps[$uri['concept']] = Config::get($uri['concept'], 'PostgreSQL.mapping');
+           $this->tables[$uri['concept']] =  Config::get($uri['concept'],'PostgreSQL.concept');
+       }
+
+       $condition = ' WHERE '.$this->tables[$uri['concept']].'.'.$this->maps[$uri['concept']]['id'].' = \''.addslashes( $uri['id'] ).'\'';
+       $justthese = self::parseJustthese($justthese, $this->maps[$uri['concept']] , $this->tables[$uri['concept']]);
+       $tables = $this->tables[$uri['concept']];
+
+       if(isset($criteria['condition']))
+       {
+           $pc = $this->parseCondition($criteria['condition']);
+
+           if(is_array($pc))
+           {
+               if(!in_array($this->tables[$uri['concept']], $pc['tables']))
+                   $pc['tables'][] = $this->tables[$uri['concept']];
+
+               $tables = implode(',', $pc['tables'] );
+               $condition .= ' AND ' .  $pc['conditions'];
+           }
+       }
+
+       $criteria = ($criteria !== false) ? $this->parseCriteria ( $criteria , $this->maps[$uri['concept']] , $condition , $this->tables[$uri['concept']]) : $condition;
+
+       return $this->execSql( 'SELECT '.$justthese['select'].' FROM '. $tables . ' ' . $criteria , true );
     }
     
@@ -132,9 +132,9 @@
         return $this->execSql('UPDATE '.(Config::get($uri['concept'],'PostgreSQL.concept')).' '. self::parseUpdateData( $data ,$map).' '.self::parseCriteria($criteria , $map));
     }
- 
+
     public function update ( $uri,  $data, $criteria = false ){
             $map = Config::get($uri['concept'], 'PostgreSQL.mapping');
-        $criteria = ($criteria !== false) ? 
-            $this->parseCriteria ( $criteria , $map , ' WHERE '.$map['id'].' = \''.pg_escape_string( $uri['id'] ).'\'') : ' WHERE '.$map['id'].' = \''.pg_escape_string( $uri['id'] ).'\''; 
+        $criteria = ($criteria !== false) ?
+            $this->parseCriteria ( $criteria , $map , ' WHERE '.$map['id'].' = \''.pg_escape_string( $uri['id'] ).'\'') : ' WHERE '.$map['id'].' = \''.pg_escape_string( $uri['id'] ).'\'';
 
         return $this->execSql('UPDATE '.(Config::get($uri['concept'],'PostgreSQL.concept')).' '. self::parseUpdateData( $data ,$map).$criteria);
@@ -252,5 +252,5 @@
     
     private static function parseUpdateData( $data , &$map){
- 
+
         $d = array();
         foreach ($data as $i => $v)
@@ -265,5 +265,5 @@
 
     private static function parseCriteria( $criteria  , &$map , $query = '' ){
-    
+
         if( isset($criteria["filter"]) && $criteria["filter"] !== NULL )
         {
@@ -278,6 +278,6 @@
           *     array( '=' , 'campo' , 'valor' )
         */
-               if($fc = self::parseFilter( $criteria['filter'] , $map)) 
-                    $query .= ($query === '') ?  'WHERE ('.$fc.')' : ' AND ('.$fc.')'; 
+               if($fc = self::parseFilter( $criteria['filter'] , $map))
+                    $query .= ($query === '') ?  'WHERE ('.$fc.')' : ' AND ('.$fc.')';
         }
         /*
@@ -372,8 +372,8 @@
     }
     }
-    
+
     static function parseJustthese($justthese , &$map , $table = '')
     {
-                  
+
         if(!is_array($justthese)) //Caso seja um full select pegar todas as keys
             $justthese = array_keys($map);
@@ -381,8 +381,8 @@
         $return = array();
 
-        if($table) 
-            $table .= '.'; 
- 
-        foreach ($justthese as &$value) 
+        if($table)
+            $table .= '.';
+
+        foreach ($justthese as &$value)
         {
             if(!isset($map[$value])) continue; //Escapa itens não existentes no mapa
@@ -393,65 +393,65 @@
                 $return['select'][] = $table . $map[$value] .' as "'. $value. '"';
         }
-        
+
         $return['select'] = implode(', ', $return['select']);
-        return $return; 
-    } 
- 
-    private function parseCondition( $condition ) 
-    { 
-        $tables = array(); 
-        $conditions = ''; 
- 
-            $matches = array(); 
-            if(preg_match_all('/\s*(AND|^)\s*([a-z]+)\.([a-z]+)\s+\=\s+([a-z]+)\.([a-z]+)(\s|$)+/i', $condition ,$matches,PREG_SET_ORDER)) 
-            { 
-               foreach ($matches as $i => $v) 
-               { 
-                   if(!isset($this->maps[$v[2]]) || !isset($this->tables[$v[2]])) 
-                   { 
-                       $this->maps[$v[2]] = Config::get($v[2], 'PostgreSQL.mapping'); 
-                       $this->tables[$v[2]] =  Config::get($v[2],'PostgreSQL.concept'); 
-                   } 
-                   if(!isset($this->maps[$v[4]]) || !isset($this->tables[$v[4]])) 
-                   { 
-                       $this->maps[$v[4]] = Config::get($v[4], 'PostgreSQL.mapping'); 
-                       $this->tables[$v[4]] =  Config::get($v[4],'PostgreSQL.concept'); 
-                   } 
- 
-                   if(isset($this->maps[$v[2]][$v[3]]) && isset($this->maps[$v[4]][$v[5]])) 
-                       $conditions .= ' '. $v[1] .' '. $this->tables[$v[2]] . '.' . $this->maps[$v[2]][$v[3]] .' = '. $this->tables[$v[4]] . '.' . $this->maps[$v[4]][$v[5]]; 
-                   else 
-                       continue; 
- 
-                   if(!in_array( $this->tables[$v[2]], $tables)) 
-                       $tables[] = $this->tables[$v[2]]; 
- 
-                   if(!in_array( $this->tables[$v[4]], $tables)) 
-                       $tables[] = $this->tables[$v[4]]; 
-               } 
- 
-            } 
- 
-            if(preg_match_all('/\s*(AND|OR|^)\s*([a-z]+)\.([a-z]+)\s+([\=\>\<\!]+|like)+\s+([a-z0-9\/\+\=]+)(\s|$)+/i', $condition , $matches ,PREG_SET_ORDER)) 
-            { 
-                foreach ($matches as $i => $v) 
-                { 
-                    if(!isset($this->maps[$v[2]]) || !isset($this->tables[$v[2]])) 
-                    { 
-                        $this->maps[$v[2]] = Config::get($v[2], 'PostgreSQL.mapping'); 
-                        $this->tables[$v[2]] =  Config::get($v[2],'PostgreSQL.concept'); 
-                    } 
- 
-                    if(isset($this->maps[$v[2]][$v[3]])) 
-                        $conditions .= ' '. $v[1] .' '. $this->tables[$v[2]] . '.' . $this->maps[$v[2]][$v[3]] .' '.$v[4].' \''. pg_escape_string(base64_decode($v[5])) .'\''; 
-                    else 
-                        continue; 
- 
-                    if(!in_array( $this->tables[$v[2]], $tables)) 
-                        $tables[] = $this->tables[$v[2]]; 
-                } 
-            } 
- 
-        return (count($tables) > 0 && count($conditions ) > 0) ? array('tables' => $tables , 'conditions' => $conditions ) : '' ; 
+        return $return;
+    }
+
+    private function parseCondition( $condition )
+    {
+        $tables = array();
+        $conditions = '';
+
+            $matches = array();
+            if(preg_match_all('/\s*(AND|^)\s*([a-z]+)\.([a-z]+)\s+\=\s+([a-z]+)\.([a-z]+)(\s|$)+/i', $condition ,$matches,PREG_SET_ORDER))
+            {
+               foreach ($matches as $i => $v)
+               {
+                   if(!isset($this->maps[$v[2]]) || !isset($this->tables[$v[2]]))
+                   {
+                       $this->maps[$v[2]] = Config::get($v[2], 'PostgreSQL.mapping');
+                       $this->tables[$v[2]] =  Config::get($v[2],'PostgreSQL.concept');
+                   }
+                   if(!isset($this->maps[$v[4]]) || !isset($this->tables[$v[4]]))
+                   {
+                       $this->maps[$v[4]] = Config::get($v[4], 'PostgreSQL.mapping');
+                       $this->tables[$v[4]] =  Config::get($v[4],'PostgreSQL.concept');
+                   }
+
+                   if(isset($this->maps[$v[2]][$v[3]]) && isset($this->maps[$v[4]][$v[5]]))
+                       $conditions .= ' '. $v[1] .' '. $this->tables[$v[2]] . '.' . $this->maps[$v[2]][$v[3]] .' = '. $this->tables[$v[4]] . '.' . $this->maps[$v[4]][$v[5]];
+                   else
+                       continue;
+
+                   if(!in_array( $this->tables[$v[2]], $tables))
+                       $tables[] = $this->tables[$v[2]];
+
+                   if(!in_array( $this->tables[$v[4]], $tables))
+                       $tables[] = $this->tables[$v[4]];
+               }
+
+            }
+
+            if(preg_match_all('/\s*(AND|OR|^)\s*([a-z]+)\.([a-z]+)\s+([\=\>\<\!]+|like)+\s+([a-z0-9\/\+\=]+)(\s|$)+/i', $condition , $matches ,PREG_SET_ORDER))
+            {
+                foreach ($matches as $i => $v)
+                {
+                    if(!isset($this->maps[$v[2]]) || !isset($this->tables[$v[2]]))
+                    {
+                        $this->maps[$v[2]] = Config::get($v[2], 'PostgreSQL.mapping');
+                        $this->tables[$v[2]] =  Config::get($v[2],'PostgreSQL.concept');
+                    }
+
+                    if(isset($this->maps[$v[2]][$v[3]]))
+                        $conditions .= ' '. $v[1] .' '. $this->tables[$v[2]] . '.' . $this->maps[$v[2]][$v[3]] .' '.$v[4].' \''. pg_escape_string(base64_decode($v[5])) .'\'';
+                    else
+                        continue;
+
+                    if(!in_array( $this->tables[$v[2]], $tables))
+                        $tables[] = $this->tables[$v[2]];
+                }
+            }
+
+        return (count($tables) > 0 && count($conditions ) > 0) ? array('tables' => $tables , 'conditions' => $conditions ) : '' ;
     }
 
Index: branches/2.5/prototype/services/ImapServiceAdapter.php
===================================================================
--- branches/2.5/prototype/services/ImapServiceAdapter.php	(revision 7863)
+++ branches/2.5/prototype/services/ImapServiceAdapter.php	(revision 8232)
@@ -178,5 +178,4 @@
                             $criteria[ $filter[$i][0] ] = array( 'criteria' => $filter[$i][2], 'filter' => $filter[$i][1] );
                         }
-
                         return $this->searchSieveRule($criteria);
 					}
Index: branches/2.5/prototype/services/iCal.php
===================================================================
--- branches/2.5/prototype/services/iCal.php	(revision 7969)
+++ branches/2.5/prototype/services/iCal.php	(revision 8232)
@@ -573,14 +573,14 @@
 			    $schedulable = self::_getSchedulable($uid);
                 $calendar = false;
-                $accpeted = true; 
-                            if ($schedulable) { 
-                    ///Verifica se o usuario e um participante e se este aceitou o pedido. 
-                    foreach ($schedulable['participants'] as $value){ 
-                        if ($value['user']['id'] == $params['owner'] &&  ($value['status'] == STATUS_UNANSWERED || $value['status'] == STATUS_DECLINED)){ 
-                            $accpeted  = false; 
-                        } 
-                    } 
-                             //Caso o evento exista 
-                    if (!($calendar = self::_existInMyCalendars($schedulable['id'], $params['owner'])) || !$accpeted ) { 
+                $accpeted = true;
+			    if ($schedulable) {
+                    ///Verifica se o usuario e um participante e se este aceitou o pedido.
+                    foreach ($schedulable['participants'] as $value){
+                        if ($value['user']['id'] == $params['owner'] &&  ($value['status'] == STATUS_UNANSWERED || $value['status'] == STATUS_DECLINED)){
+                            $accpeted  = false;
+                        }
+                    }
+			     //Caso o evento exista
+                    if (!($calendar = self::_existInMyCalendars($schedulable['id'], $params['owner'])) || !$accpeted ) {
                         $calendarToSchedulable = array();
                         $calendarToSchedulable['calendar'] = $params['calendar'];
@@ -1239,13 +1239,13 @@
                             }
                             else
-                            { 
-                                if (self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence']) //Organizador esta requisitando que você atualize o evento 
-                                    $interation = ($isOrganizer) ? ICAL_ACTION_ORGANIZER_UPDATE : ICAL_ACTION_UPDATE; 
-                                else 
-                                    $interation = ($isOrganizer) ? ICAL_ACTION_ORGANIZER_NONE : ICAL_ACTION_NONE; 
- 
-                            } 
+                            {
+                                if (self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence']) //Organizador esta requisitando que você atualize o evento
+                                    $interation = ($isOrganizer) ? ICAL_ACTION_ORGANIZER_UPDATE : ICAL_ACTION_UPDATE;
+                                else
+                                    $interation = ($isOrganizer) ? ICAL_ACTION_ORGANIZER_NONE : ICAL_ACTION_NONE;
+
+                            }
                         }
-                      } 
+                      }
                     if (!$isParticipant){
                         if( self::_existInMyCalendars($schedulable['id'], $params['owner']) ){
Index: branches/2.5/prototype/config/participant.ini
===================================================================
--- branches/2.5/prototype/config/participant.ini	(revision 8003)
+++ branches/2.5/prototype/config/participant.ini	(revision 8232)
Index: branches/2.5/prototype/config/schedulable.ini
===================================================================
--- branches/2.5/prototype/config/schedulable.ini	(revision 7958)
+++ branches/2.5/prototype/config/schedulable.ini	(revision 8232)
@@ -17,5 +17,5 @@
 
 [before.find]
-schedulableSecurity = modules/calendar/interceptors/DBMapping.php 
+schedulableSecurity = modules/calendar/interceptors/DBMapping.php
 findDeepnessOne = modules/calendar/interceptors/DBMapping.php
 findSchedulable = modules/calendar/interceptors/DBMapping.php
@@ -35,7 +35,7 @@
 createHistoric = modules/calendar/interceptors/DBMapping.php
 
-[before.read] 
-schedulableSecurity = modules/calendar/interceptors/DBMapping.php 
- 
+[before.read]
+schedulableSecurity = modules/calendar/interceptors/DBMapping.php
+
 [after.read]
 deepnessReadEvent = modules/calendar/interceptors/DBMapping.php
@@ -44,5 +44,5 @@
 deleteSchedulable = modules/calendar/interceptors/DBMapping.php
 deleteEvent = modules/calendar/interceptors/Notifications.php
- 
+
 
 [PostgreSQL.mapping]
Index: branches/2.5/prototype/config/calendarSignature.ini
===================================================================
--- branches/2.5/prototype/config/calendarSignature.ini	(revision 7958)
+++ branches/2.5/prototype/config/calendarSignature.ini	(revision 8232)
@@ -14,10 +14,10 @@
 deepnessFindCalendarSignature = modules/calendar/interceptors/DBMapping.php
 createDefaultGroup = modules/calendar/interceptors/DBMapping.php
- 
-[before.read] 
-calendarSignatureSecurity = modules/calendar/interceptors/DBMapping.php 
- 
-[before.find] 
-calendarSignatureSecurity = modules/calendar/interceptors/DBMapping.php 
+
+[before.read]
+calendarSignatureSecurity = modules/calendar/interceptors/DBMapping.php
+
+[before.find]
+calendarSignatureSecurity = modules/calendar/interceptors/DBMapping.php
 
 [after.read]
Index: branches/2.5/prototype/modules/mail/css/followupflag.css
===================================================================
--- branches/2.5/prototype/modules/mail/css/followupflag.css	(revision 6996)
+++ branches/2.5/prototype/modules/mail/css/followupflag.css	(revision 8232)
@@ -242,4 +242,5 @@
 .alert-options {
 	border: none;
+	min-width:80%;
 }
 .confirm-alarm {
Index: branches/2.5/prototype/modules/mail/js/foldertree.js
===================================================================
--- branches/2.5/prototype/modules/mail/js/foldertree.js	(revision 8117)
+++ branches/2.5/prototype/modules/mail/js/foldertree.js	(revision 8232)
@@ -108,27 +108,51 @@
 }
 
-function draw_new_tree_folder(callback, force){
-
-    var folders =  normalizeFolder( Folder.get( false, force ) );
-
-if(preferences.use_local_messages == 1){
-
-    if(expresso_mail_archive.folders && !expresso_offline && expresso_mail_archive.enabled == true) { //MailArchive
-        //pega pastas locais do mailarchiver e insere no array de pastas
+function refreshTreeview(){
+    //Atualização e correção dos ícones expandir/contrair
+    $.each($('.treeview').find('.expandable, .collapsable').filter(':not(.lastExpandable,.lastCollapsable)'),function(i,v){
+      if ( $(v).find('ul').css('display') == "block" ){
+        $(v).removeClass().addClass('collapsable'); 
+        $(v).find('.hitarea:first').removeClass().addClass('hitarea collapsable-hitarea')
+      }
+    });
+    //Última árvore de pastas
+    $.each($('.treeview').find('.lastExpandable,.lastCollapsable'),function(i,v){
+      if ( $(v).find('ul').css('display') == "block" ){
+        $(v).removeClass().addClass('collapsable lastCollapsable'); 
+        $(v).find('.hitarea:first').removeClass('expandable-hitarea').addClass('collapsable-hitarea');
+        $(v).find('.hitarea:first').removeClass('lastExpandable-hitarea').addClass('lastCollapsable-hitarea');
+      }
+    });
+}
+
+function draw_new_tree_folder(callback, force)
+{
+
+    var folders = normalizeFolder(Folder.get(false, force));
+
+    if(preferences.use_local_messages == 1)
+    {
+
+        if(expresso_mail_archive.folders && !expresso_offline && expresso_mail_archive.enabled == true)
+        { //MailArchive
+            //pega pastas locais do mailarchiver e insere no array de pastas
             expresso_mail_archive.getFoldersList("home");
             treeFolders = expresso_mail_archive.folders;
 
-            for(var i=0; i<treeFolders.length; i++ ){
+            for(var i = 0; i < treeFolders.length; i++)
+            {
                 mount_children_localfolders_list(treeFolders[i]);
             }
-            
-            for(var i = 0; i < treeFolders.length; i++){
+
+            for(var i = 0; i < treeFolders.length; i++)
+            {
                 folders.push(treeFolders[i]);
             }
- 
-    }
-}
-
-    if(!selected){
+
+        }
+    }
+
+    if(!selected)
+    {
         selected = "INBOX";
     }
@@ -137,9 +161,12 @@
     var tree2 = new Array();
     var tree3 = new Array();
-     
-    for (var i=0; i<folders.length; i++) {
-         
-        if(/*/^INBOX/.test(folders[i].id)*/folders[i].id.substr(0,5) == "INBOX") {
-            if (!unorphanize(tree1, folders[i])) {
+    
+    for(var i = 0; i < folders.length; i++)
+    {
+        
+        if(/*/^INBOX/.test(folders[i].id)*/folders[i].id.substr(0,5) == "INBOX")
+        {
+            if(!unorphanize(tree1, folders[i]))
+            {
                 folders[i].children = new Array();
 
@@ -147,24 +174,30 @@
             }
         }
-        else if (/*/^user/.test(folders[i].id)*/folders[i].id.substr(0,4) == "user") {
-            if (!unorphanize(tree2, folders[i])) {
+        else if(/*/^user/.test(folders[i].id)*/folders[i].id.substr(0,4) == "user")
+        {
+            if(!unorphanize(tree2, folders[i]))
+            {
                 folders[i].children = new Array();
                 tree2.push(folders[i]);
             }
         }
-        else if (/*/^local_messages/.test(folders[i].id)*/folders[i].id.substr(0,14) == "local_messages") {
-           
-                tree3.push(folders[i]);
-            
-        }
-    }
-    
-    for(var i =0; i<tree1.length; i++){
+        else if(/*/^local_messages/.test(folders[i].id)*/folders[i].id.substr(0,14) == "local_messages")
+        {
+
+            tree3.push(folders[i]);
+
+        }
+    }
+
+    for(var i = 0; i < tree1.length; i++)
+    {
         count_unseen_children(tree1[i]);
     }
-    for(var i =0; i<tree2.length; i++){
+    for(var i = 0; i < tree2.length; i++)
+    {
         count_unseen_children(tree2[i]);
     }
-    for(var i =0; i<tree3.length; i++){
+    for(var i = 0; i < tree3.length; i++)
+    {
         count_unseen_children(tree3[i]);
     }
@@ -174,49 +207,72 @@
     var shared_acls = {};
 
-    $.each(cp_tree2, function(index, value){
+    $.each(cp_tree2, function(index, value)
+    {
         shared_acls[value.id] = value.acl_share;
     });
-    
-    if(preferences.use_local_messages == 1){
-      $("#content_folders").removeClass("menu-degrade").parent().removeClass("image-menu");
-      mail_archive_url = mail_archive_protocol + "://" + mail_archive_host + ":" + mail_archive_port + "/admin";
-    }
-    
-    var html = DataLayer.render('../prototype/modules/mail/templates/detailedfoldertree.ejs', {folders: [tree1, tree2, tree3]});
-    var folders_html = $("#content_folders").html(html).find(".mainfoldertree").treeview({
-            persist: "cookie",
-            animated: "fast"
-    }).find(".folder").unbind("click").click(function(event){
-
-        if ($(this).next().hasClass("local-connect")) {
+
+    if(preferences.use_local_messages == 1)
+    {
+        $("#content_folders").removeClass("menu-degrade").parent().removeClass("image-menu");
+        mail_archive_url = mail_archive_protocol + "://" + mail_archive_host + ":" + mail_archive_port + "/admin";
+    }
+
+    var html = DataLayer.render('../prototype/modules/mail/templates/detailedfoldertree.ejs', {
+        folders: [tree1, tree2, tree3]
+    });
+    var folders_html = $("#content_folders").html(html).find(".mainfoldertree").treeview(
+    {
+        persist: "cookie",
+        animated: "fast"
+    }).find(".folder").unbind("click").click(function(event)
+    {
+
+        if($(this).next().hasClass("local-connect"))
+        {
             return;
         }
 
-        if ($(this).hasClass("local-folder")) {
+        if($(this).hasClass("local-folder"))
+        {
             return;
         }
-        
+
         // MUDANÇA DE PASTAS!
-        var target = $(this);   
-        
+        var target = $(this);
+
         if($(".folders-loading").length)
+        {
             return;
-        
+        }
+
         if($(event.target).parent().is(".float-menu"))
+        {
             return;
-            
-        if( target.is('.collapsable-hitarea, .expandable-hitarea, .lastCollapsable-hitarea, .lastExpandable-hitarea, .treeview ,.folder_unseen,.ui-icon, .float-menu, .new_folder, .folders-loading, .head_folder, .shared-folders') )
+        }
+
+        if(target.is('.collapsable-hitarea, .expandable-hitarea, .lastCollapsable-hitarea, .lastExpandable-hitarea, .treeview ,.folder_unseen,.ui-icon, .float-menu, .new_folder, .folders-loading, .head_folder, .shared-folders'))
+        {
             return;
-        
-        if( target.parent().find(".new_folder").length)
+        }
+
+        if(target.parent().find(".new_folder").length)
+        {
             return;
-            
-        if( !target.attr('id') )
+        }
+
+        if(!target.attr('id'))
+        {
             target = target.parent();
-        if (target[0] == $(".mainfoldertree")[0]) return;
+        }
+        if(target[0] == $(".mainfoldertree")[0])
+        {
+            return;
+        }
+
         var uiId = target.attr('id');
         var child = target.find('.folder');
-          
-        if(!target.is('.mainfoldertree > .expandable-hitarea, .mainfoldertree > .collapsable-hitarea')){
+
+        if(!target.is('.mainfoldertree > .expandable-hitarea, .mainfoldertree > .collapsable-hitarea'))
+        {
             $('.filetree span.folder.selected').removeClass('selected');
             $(target).children('.folder').addClass('selected');
@@ -224,23 +280,37 @@
         $(this).addClass("folders-loading");
         selected = target.attr('id');
-        change_folder(target.attr('id'), child.attr('title'));  
-
-        $.ajax({
-              url : "controller.php?"+ $.param( { action: "$this.imap_functions.get_folders_list", folder: target.attr('id') } ),
-              success : function(data){
-                  data = connector.unserialize(data);
-
-                  if(data)
+        change_folder(target.attr('id'), child.attr('title'));
+    
+        $.ajax(
+        {
+            url: "controller.php?" + $.param(
+            {
+                action: "$this.imap_functions.get_folders_list",
+                folder: target.attr('id')
+            }),
+            success: function(data)
+            {
+                data = connector.unserialize(data);
+
+                if(data)
+                {
                     build_quota(data);
-              }
+                }
+            }
         });
 
-    }).filter('.followup-messages').click(function(event, ui){
+    }).filter('.followup-messages').click(function(event, ui)
+    {
         search_emails("UNDELETED KEYWORD \"$Followupflagged\"");
     }).end().end();
-
-    $('.upper').droppable({
-        over: function(event, ui){
-            $('#content_folders').autoscroll({
+    
+    refreshTreeview();
+    
+    $('.upper').droppable(
+    {
+        over: function(event, ui)
+        {
+            $('#content_folders').autoscroll(
+            {
                 direction: 'up',
                 step: 150,
@@ -248,12 +318,16 @@
             });
         },
-        out: function(event, ui){
+        out: function(event, ui)
+        {
             $('#content_folders').autoscroll('destroy');
         }
     });
 
-    $('.lower').droppable({
-        over: function(event, ui){
-            $('#content_folders').autoscroll({
+    $('.lower').droppable(
+    {
+        over: function(event, ui)
+        {
+            $('#content_folders').autoscroll(
+            {
                 direction: 'down',
                 step: 150,
@@ -261,5 +335,6 @@
             });
         },
-        out: function(event, ui){
+        out: function(event, ui)
+        {
             $('#content_folders').autoscroll('destroy');
         }
@@ -268,25 +343,41 @@
 
 
-    folders_html.find('[id="'+selected+'"]').children().addClass("selected");
-    $(".folder").not(".head_folder").not(".shared-folders").not(".shared-folders + ul .folder").parent().find(".folder").not(".head_folder,.inbox,.drafts,.sent,.spam,.trash").draggable({
+    folders_html.find('[id="' + selected + '"]').children().addClass("selected");
+    $(".folder")
+    .not(".head_folder")
+    .not(".shared-folders")
+    .not(".shared-folders + ul .folder")
+    .parent()
+    .find(".folder")
+    .not(".head_folder,.inbox,.drafts,.sent,.spam,.trash")
+    .draggable(
+    {
         // DRAG DE PASTAS
-        start : function(){
+        start: function()
+        {
             $(this).css("color", "gray");
             $('.upper, .lower').show();
-            $(".lower").css("top", ($("#content_folders").height()-18) + $("#content_folders").offset().top);
+            $(".lower").css("top", ($("#content_folders").height() - 18) + $("#content_folders").offset().top);
         },
-        stop : function(){
+        stop: function()
+        {
             $(this).css("color", "");
             $('.upper, .lower').hide();
         },
         revert: "invalid",
-        helper: function(event){
-            if($.trim(($(this).text().split("["))[0]).length > 18)
-                return $(DataLayer.render('../prototype/modules/mail/templates/draggin_box.ejs', {texto : (($(this).text().split("["))[0]).substring(0,18) + "...", type: "folder"}));
-            return $(DataLayer.render('../prototype/modules/mail/templates/draggin_box.ejs', {texto : (($(this).text().split("["))[0]), type: "folder"}));
+        helper: function(event)
+        {
+            if($.trim(($(this).text().split("["))[0]).length > 18) return $(DataLayer.render('../prototype/modules/mail/templates/draggin_box.ejs', {
+                texto: (($(this).text().split("["))[0]).substring(0, 18) + "...",
+                type: "folder"
+            }));
+            return $(DataLayer.render('../prototype/modules/mail/templates/draggin_box.ejs', {
+                texto: (($(this).text().split("["))[0]),
+                type: "folder"
+            }));
         },
         delay: 150,
         refreshPositions: true,
-        zIndex : 2700,
+        zIndex: 2700,
         //scroll: true,
         //scrollSensitivity: 100,
@@ -294,46 +385,64 @@
         containment: $("#divAppbox")
     });
-    $(".folder").not(".head_folder").not(".shared-folders").parent().find(".folder").not(".head_folder,.inbox,.drafts,.sent,.spam,.trash").end().droppable({
+    $(".folder")
+    .not(".head_folder")
+    .not(".shared-folders")
+    .parent()
+    .find(".folder")
+    .not(".head_folder,.inbox,.drafts,.sent,.spam,.trash")
+    .end()
+    .droppable(
+    {
         //DROP DE PASTAS
-        over : function(a, b){
+        over: function(a, b)
+        {
             //INICIO : SE A PASTA CONTER FILHAS EXPANDE 
+            $(b.helper).find(".draggin-folder,.draggin-mail").css("color", "green");
             over = $(this);
             $(this).addClass("folder-over");
-            if(($(this)[0] != $(this).parent().find(".head_folder")[0]))
-                if($(this).prev()[0])
-                    if($(this).parent().find(".expandable-hitarea")[0] == $(this).prev()[0]){
-                        setTimeout(function(){
-                            if(over.hasClass("folder-over")){
-                                over.prev().trigger("click");
-                            }
-                        }, 500);
-                        
+            if(($(this)[0] != $(this).parent().find(".head_folder")[0])) if($(this).prev()[0]) if($(this).parent().find(".expandable-hitarea")[0] == $(this).prev()[0])
+            {
+                setTimeout(function()
+                {
+                    if(over.hasClass("folder-over"))
+                    {
+                        over.prev().trigger("click");
                     }
+                }, 500);
+
+            }
             //FIM : SE A PASTA CONTER FILHAS EXPANDE           
-            //$("#content_folders").stop().scrollTo($(this), {axis:'y', margin:true, offset:-50, duration:400});      
             //SETA BORDA EM VOLTA DA PASTA
             //
         },
-        out : function(){
+        out: function(a, b)
+        {
             //RETIRA BORDA EM VOLTA DA PASTA
+            $(b.helper).find(".draggin-folder,.draggin-mail").css("color", "");
             $(this).removeClass("folder-over");
         },
-        drop : function(event, ui){
+        drop: function(event, ui)
+        {
             $(this).removeClass("folder-over");
 
-            if($(this).parent().attr('id') == undefined){
+            if($(this).parent().attr('id') == undefined)
+            {
                 var folder_to = 'INBOX';
                 var to_folder_title = get_lang("Inbox");
-            }else{
+            }
+            else
+            {
                 var folder_to = $(this).parent().attr('id');
                 var to_folder_title = $(this).attr('title');
-            }       
+            }
             var folder_to_move = ui.draggable.parent().attr('id');
             var border_id = ui.draggable.find("input[type=hidden]").attr("name");
             // eventnsagens : SE O DROP VIER DA LISTA DE eventNSAGENS :
-            if(folder_to_move == "tbody_box"){
-                move_msgs2(get_current_folder(), 'selected', 0, folder_to, to_folder_title,true);
+            if(folder_to_move == "tbody_box")
+            {
+                move_msgs2(get_current_folder(), 'selected', 0, folder_to, to_folder_title, true);
                 //Correção para realinhamento da grid de mensagens no navegador Chrome.
-                if(is_webkit){
+                if(is_webkit)
+                {
                     var table = $('#table_box');
                     $('#divScrollMain_0').html('');
@@ -344,79 +453,101 @@
             }
             //SE FOR DE UMA PESQUISA RAPIDA
-            else if(ui.draggable.parents('[id^="content_id_"]')[0]){
-                move_search_msgs("content_id_"+border_id, folder_to, to_folder_title);
+            else if(ui.draggable.parents('[id^="content_id_"]')[0])
+            {
+                move_search_msgs("content_id_" + border_id, folder_to, to_folder_title);
                 return;
             }
             // eventnsagens : SE O DROP VIER DE UMA ABA ABERTA
-            else if(folder_to_move == "border_tr"){
+            else if(folder_to_move == "border_tr")
+            {
                 var id_msg = border_id.split("_")[0];
-                folder = $("#input_folder_"+border_id+"_r")[0] ? $("#input_folder_"+border_id+"_r").val() : (openTab.imapBox[border_id] ? openTab.imapBox[border_id]:get_current_folder());
+                folder = $("#input_folder_" + border_id + "_r")[0] ? $("#input_folder_" + border_id + "_r").val() : (openTab.imapBox[border_id] ? openTab.imapBox[border_id] : get_current_folder());
                 alternate_border(border_id);
-                move_msgs2(folder, id_msg, border_id, folder_to, to_folder_title,true);
+                move_msgs2(folder, id_msg, border_id, folder_to, to_folder_title, true);
                 return;
             }
             // SE O DROP VIER DA LISTA DE PASTAS
-            else{
-				if($(ui.draggable[0]).parent().find("input").val() == "localFolder" && $(this).parents("li").find("input").first().val() != "localFolder") 
-                { 
-                    return write_msg(get_lang("It isn't possible to send a folder by Archiver to My folders")); 
-                } 
-                else if(!$(ui.draggable[0]).parent().find("input").val() && $(this).parents("li").find("input").first().val() == "localFolder") 
-                { 
-                    return write_msg(get_lang("It isn't possible to send a folder by My folders to Archiver")); 
-                } 
-                var folder_to_exist = folder_to_move.split(cyrus_delimiter);    
-                folder_to_exist = folder_to+cyrus_delimiter+folder_to_exist[folder_to_exist.length-1];
-                
+            else
+            {
+                if($(ui.draggable[0]).parent().find("input").val() == "localFolder" && $(this).parents("li").find("input").first().val() != "localFolder")
+                {
+                    return write_msg(get_lang("It isn't possible to send a folder by Archiver to My folders"));
+                }
+                else if(!$(ui.draggable[0]).parent().find("input").val() && $(this).parents("li").find("input").first().val() == "localFolder")
+                {
+                    return write_msg(get_lang("It isn't possible to send a folder by My folders to Archiver"));
+                }
+                var folder_to_exist = folder_to_move.split(cyrus_delimiter);
+                folder_to_exist = folder_to + cyrus_delimiter + folder_to_exist[folder_to_exist.length - 1];
+
                 //VERIFICA SE EXISTE UMA eventNSAGENS ABERTA NESTA PASTA E NAS SUAS FILHAS
-
-                if(valid_tabs(ui.draggable.parent().find("li"), folder_to_move)){
+                if(valid_tabs(ui.draggable.parent().find("li"), folder_to_move))
+                {
                     return;
                 }
                 //FIM : VERIFICA SE EXISTE UMA eventNSAGENS ABERTA NESTA PASTA E NAS SUAS FILHAS;
-                
                 // VALIDA SE O USUARIO ESTA TENTANDO MOVER A PASTA PARA O eventSMO LOCAL
-                if(folder_to_exist == folder_to_move){
+                if(folder_to_exist == folder_to_move)
+                {
                     return write_msg(get_lang("Thie folder is already in this place"));
                 }
-                
+
                 // VALIDA SE O USUARIO ESTA TENTANDO MOVER A PASTA ABERTA NO momentO
-                if(folder_to_move == get_current_folder()){
+                if(folder_to_move == get_current_folder())
+                {
                     return write_msg(get_lang("It's not possible move this folder, because it is being used in the moment!"));
                 }
-                
+
                 // VALIDA SE O USUARIO ESTA TENTANDO MOVER UMA PASTA FILHA DA PASTA ABERTA NO momentO
-                if(ui.draggable.parent().find(".selected")[0]){
+                if(ui.draggable.parent().find(".selected")[0])
+                {
                     return write_msg(get_lang("It's not possible move this folder, because its subfolder is being used in the moment!"));
                 }
-                
+
                 // VALIDA SE O USUARIO ESTA TENTANDO MOVER UMA PASTA PAI PARA DENTRO DE UMA FILHA
-                if(ui.draggable.parent().find('[id="'+folder_to+'"]')[0]){
+                if(ui.draggable.parent().find('[id="' + folder_to + '"]')[0])
+                {
                     return write_msg(get_lang("It's not possible to move this folder to its subfolders!"));
-                }                   
-                
-                if($('[id="'+folder_to_exist+'"]').length){
+                }
+
+                if($('[id="' + folder_to_exist + '"]').length)
+                {
                     return write_msg(get_lang("Can not move this folder to this location, because the target has already a folder with this name"));
                 }
-                
+
                 $(this).addClass("folders-loading");
 
 
-                if($(this).parents("li").find("input").first().val() == "localFolder"){
+                if($(this).parents("li").find("input").first().val() == "localFolder")
+                {
                     var idFolder = $(this).parent().attr("id").split("_")[2];
 
                     expresso_mail_archive.moveFolder(idFolder, folder_to_move.split("_")[2]);
-                     cExecute("$this.imap_functions.get_folders_list&onload=true", update_menu);
-                } else {
-                    $.ajax({
-                        url : "controller.php?"+ $.param( { action: "$this.imap_functions.move_folder", folder_to_move: folder_to_move, folder_to: folder_to } ),
-                        success : function(data){
+                    cExecute("$this.imap_functions.get_folders_list&onload=true", update_menu);
+                }
+                else
+                {
+                    $.ajax(
+                    {
+                        url: "controller.php?" + $.param(
+                        {
+                            action: "$this.imap_functions.move_folder",
+                            folder_to_move: folder_to_move,
+                            folder_to: folder_to
+                        }),
+                        success: function(data)
+                        {
                             cExecute("$this.imap_functions.get_folders_list&onload=true", force_update_menu);
                             data = connector.unserialize(data);
-                            if(data == "Permission denied"){
+                            if(data == "Permission denied")
+                            {
                                 write_msg(get_lang("Permission denied"));
-                            }else if(data){
+                            }
+                            else if(data)
+                            {
                                 write_msg(get_lang("The folder was successfully moved"));
-                            } else {
+                            }
+                            else
+                            {
                                 write_msg(get_lang("ERROR moving your folder."));
                             }
@@ -427,70 +558,100 @@
         }
     });
-    $(".folder").not(".shared-folders, .followup-messages").parent().find(".folder").hover(
-        function(){
-            //CASO A LI NÃO TENHA UM eventNU FLUTUANTE AINDA, O eventNU É ADICIONADO!
-            if(!$(this).children(":last").hasClass("float-menu") && !$(this).children(":last").hasClass("new_folder") && !($(this).next().hasClass("local-connect"))){ /*se houver a classe local-connect, nÃ£o adiciona o botÃ£o de conectar*/
-                var folder_ = $(this);
-                var folder_name;
-                var shared = {
-                    head : false,
-                    valid : false
-                };
-                if(folder_.parent().attr('id')){
-                    folder_name = folder_.parent().attr('id').split(cyrus_delimiter);
-                    folder_name = folder_name[folder_name.length -1];
-                    shared.valid = folder_.parent().attr('id').search("user/") == 0 ? true : false;
-                }else
-                    folder_name = "Root";
-                
-                if(shared.valid){
-                    shared.head = folder_.parent().attr('id').split(cyrus_delimiter).length == 2 ?  true : false;
-                    var folder_name_parts = folder_.parent().attr('id').split(cyrus_delimiter);
-                    var acls = shared_acls[folder_name_parts[0]+cyrus_delimiter+folder_name_parts[1]];
-                }
-
-                html = DataLayer.render("../prototype/modules/mail/templates/float_folder_menu.ejs", {name_folder : folder_name, flag : shared, acl : acls});                   
-                    //FUNÇÃO DO eventNU FLUTUANTE EDITAR < BEGIN
-                var esc = false;
-                $(folder_).append(html).find(".float-menu-edit").click(function(){
-                    var folder_id = $(this).parents(".closed:first").attr('id');
-                    var name = $.trim($(this).parents(".closed:first").find("span:first").text().split("[")[0]);
-                    if($(this).parents(".closed:first").find("span:first").hasClass("selected"))
-                        return write_msg(get_lang("It's not possible rename this folder, because it is being used in the moment!"));
-                    if($(this).parents(".closed:first").find("span.selected").length)
-                        return write_msg(get_lang("It's not possible rename this folder, because its subfolder is being used in the moment!")); 
-                    if(valid_tabs($(this).parents("li:first").find("li"), folder_id))
-                        return;
-                    $(this).parents(".closed:first").find("span:first").empty().append("<input class='new_folder folder' type='text' maxlength='100'></input>");
-                    $(".new_folder").focus().keydown(function(event){
-                        event.stopPropagation();
-                        if(event.keyCode == 13){
-                            if($(this).val() != ""){
-                                /* Verifica se existe caracteres especiais no nome da pasta ou se existe "local_"
-                                 * em parte do nome (palavra reservada para pastas locais) */
-                                if($(this).val().match(/[\`\~\^\<\>\|\\\"\!\@\#\$\%\&\*\+\(\)\[\]\{\}\?;:]/gi) || $(this).val().indexOf("local_") != -1){
-                                    return write_msg(get_lang("cannot create folder. try other folder name"));
-                                }
-                                var new_name = folder_id.replace(/[a-zA-Z0-9á-úÁ-Ú,=^\s_-]+$/, $(this).val());
-                                if($('[id="'+new_name+'"]').length){
-                                    $(".folders-loading").removeClass("folders-loading");
-                                    write_msg(get_lang("Mailbox already exists"));
-                                    return draw_new_tree_folder();
-                                }
-                                $(".new_folder").parent().addClass("folders-loading");
-                                
-                                if($(this).parents("li").first().attr("id").indexOf("local_messages_") != -1){
-                                    var idFolder = $(this).parents("li").first().attr("id").split("_")[2];
-                                    expresso_mail_archive.renameFolder(idFolder, new_name);
-                                     cExecute("$this.imap_functions.get_folders_list&onload=true", update_menu);
-                                } else {
-
-                                $.ajax({
-                                    url : "controller.php?action=$this.imap_functions.ren_mailbox",
-                                    type : "POST",
-                                    data : "current="+folder_id+"&rename="+new_name,
-                                    success : function(data){
+    $(".folder")
+    .not(".shared-folders, .followup-messages")
+    .parent()
+    .find(".folder")
+    .not($('#message-attach-dialog').find('.folder'))
+    .hover(
+    function()
+    {
+        //CASO A LI NÃO TENHA UM eventNU FLUTUANTE AINDA, O eventNU É ADICIONADO!
+        if(!$(this).children(":last").hasClass("float-menu") && !$(this).children(":last").hasClass("new_folder") && !($(this).next().hasClass("local-connect")))
+        { /*se houver a classe local-connect, não adiciona o botão de conectar*/
+            var folder_ = $(this);
+            var folder_name;
+            var shared = {
+                head: false,
+                valid: false
+            };
+            if(folder_.parent().attr('id'))
+            {
+                folder_name = folder_.parent().attr('id').split(cyrus_delimiter);
+                folder_name = folder_name[folder_name.length - 1];
+                shared.valid = folder_.parent().attr('id').search("user"+cyrus_delimiter) == 0 ? true : false;
+            }
+            else folder_name = "Root";
+
+            if(shared.valid)
+            {
+                shared.head = folder_.parent().attr('id').split(cyrus_delimiter).length == 2 ? true : false;
+                var folder_name_parts = folder_.parent().attr('id').split(cyrus_delimiter);
+                var acls = shared_acls[folder_name_parts[0] + cyrus_delimiter + folder_name_parts[1]];
+            }
+
+            html = DataLayer.render("../prototype/modules/mail/templates/float_folder_menu.ejs", {
+                name_folder: folder_name,
+                flag: shared,
+                acl: acls
+            });
+            //FUNÇÃO DO eventNU FLUTUANTE EDITAR < BEGIN
+            var esc = false;
+            $(folder_).append(html).find(".float-menu-edit").click(function()
+            {
+                var folder_id = $(this).parents(".closed:first").attr('id');
+                var name = $.trim($(this).parents(".closed:first").find("span:first").text().split("[")[0]);
+                if($(this).parents(".closed:first").find("span:first").hasClass("selected"))
+                {
+                    return write_msg(get_lang("It's not possible rename this folder, because it is being used in the moment!"));
+                }
+                if($(this).parents(".closed:first").find("span.selected").length)
+                {
+                    return write_msg(get_lang("It's not possible rename this folder, because its subfolder is being used in the moment!"));
+                }
+                if(valid_tabs($(this).parents("li:first").find("li"), folder_id))
+                {
+                    return;
+                }
+                $(this).parents(".closed:first").find("span:first").empty().append("<input class='new_folder folder' type='text' maxlength='100'></input>");
+                $(".new_folder").focus().keydown(function(event)
+                {
+                    event.stopPropagation();
+                    if(event.keyCode == 13)
+                    {
+                        if($(this).val() != "")
+                        {
+                            /* Verifica se existe caracteres especiais no nome da pasta ou se existe "local_"
+                             * em parte do nome (palavra reservada para pastas locais) */
+                            if($(this).val().match(/[\`\~\^\<\>\|\\\"\!\@\#\$\%\&\*\+\(\)\[\]\{\}\?;:]/gi) || $(this).val().indexOf("local_") != -1)
+                            {
+                                return write_msg(get_lang("cannot create folder. try other folder name"));
+                            }
+                            var new_name = folder_id.replace(/[a-zA-Z0-9á-úÁ-Ú,=^\s_-]+$/, $(this).val());
+                            if($('[id="' + new_name + '"]').length)
+                            {
+                                $(".folders-loading").removeClass("folders-loading");
+                                write_msg(get_lang("Mailbox already exists"));
+                                return draw_new_tree_folder();
+                            }
+                            $(".new_folder").parent().addClass("folders-loading");
+
+                            if($(this).parents("li").first().attr("id").indexOf("local_messages_") != -1)
+                            {
+                                var idFolder = $(this).parents("li").first().attr("id").split("_")[2];
+                                expresso_mail_archive.renameFolder(idFolder, new_name);
+                                cExecute("$this.imap_functions.get_folders_list&onload=true", update_menu);
+                            }
+                            else
+                            {
+                                $.ajax(
+                                {
+                                    url: "controller.php?action=$this.imap_functions.ren_mailbox",
+                                    type: "POST",
+                                    data: "current=" + folder_id + "&rename=" + new_name,
+                                    success: function(data)
+                                    {
                                         data = connector.unserialize(data);
-                                        if(data == "Permission denied"){
+                                        if(data == "Permission denied")
+                                        {
                                             $(".folders-loading").removeClass("folders-loading");
                                             cExecute("$this.imap_functions.get_folders_list&onload=true", update_menu);
@@ -502,60 +663,80 @@
                                 });
 
-                                }
-                            }else{
-                                $(".new_folder").focusout();
-                            }
-                        }else if( event.keyCode == 27){
-                            draw_new_tree_folder();
-                        }
-                    }).focusout(function(){
+                            }
+                        }
+                        else
+                        {
+                            $(".new_folder").focusout();
+                        }
+                    }
+                    else if(event.keyCode == 27)
+                    {
                         draw_new_tree_folder();
-                    }).val(name);
-                })
-                //FUNÇÃO DO eventNU FLUTUANTE EDITAR < END
-                //FUNÇÃO DO eventNU FLUTUANTE EXCLUIR < BEGIN
-                .end().find(".float-menu-remove").click(function(){
-                    
-                    var folder_id = $(this).parents(".closed:first").attr('id');
-                    var folder_name = "<strong>"+$.trim($(this).parents(".closed:first").find(".folder").text().split("[")[0])+"</strong>";
-                    
-                    if(valid_tabs($(this).parents("li:first").find("li"), folder_id))
-                        return;
-                    $(this).parents(".closed:first").find(".folder").addClass("folders-loading"); 
-                    
-                    if($(this).parents(".closed:first").find("ul").length){
-                        $(this).parents(".closed:first").find(".folder").removeClass("folders-loading");
-                        return write_msg(get_lang("Delete/move subfolders first"));
                     }
-                    if($(this).parents(".closed:first").find("span.selected").length){
-                        $(this).parents(".closed:first").find(".folder").removeClass("folders-loading");
-                        return write_msg(get_lang("It's not possible delete this folder, because it is being used in the moment!")); 
-                    }
-                    var folder_span = $(this);
-                    var confirm_text = get_lang("Do you wish to exclude the folder ");
-
-                    $.Zebra_Dialog(confirm_text+folder_name, {
-                        'type': 'question',
-                        'overlay_opacity': '0.5',
-						'custom_class': 'custom-zebra-filter',
-                        'buttons':  [get_lang('Yes'), get_lang('No')],
-                        'onClose':  function(caption) {
-
-                            if(caption == get_lang('Yes')){
-                                if(folder_span.parents("li").find("input").first().val() == "localFolder"){
-                                    var idFolder = folder_span.parents("li").first().attr("id").split("_")[2];
-                                    expresso_mail_archive.deleteFolder(idFolder, folder_name);
-                                     cExecute("$this.imap_functions.get_folders_list&onload=true", update_menu);
-                                } else {
-                                $.ajax({
-                                    url : "controller.php?action=$this.imap_functions.delete_mailbox",
+                }).focusout(function()
+                {
+                    draw_new_tree_folder();
+                }).val(name);
+            })
+            //FUNÇÃO DO eventNU FLUTUANTE EDITAR < END
+            //FUNÇÃO DO eventNU FLUTUANTE EXCLUIR < BEGIN
+            .end().find(".float-menu-remove").click(function()
+            {
+
+                var folder_id = $(this).parents(".closed:first").attr('id');
+                var folder_name = "<strong>" + $.trim($(this).parents(".closed:first").find(".folder").text().split("[")[0]) + "</strong>";
+
+                if(valid_tabs($(this).parents("li:first").find("li"), folder_id))
+                {
+                    return;
+                }
+                $(this).parents(".closed:first").find(".folder").addClass("folders-loading");
+
+                if($(this).parents(".closed:first").find("ul").length)
+                {
+                    $(this).parents(".closed:first").find(".folder").removeClass("folders-loading");
+                    return write_msg(get_lang("Delete/move subfolders first"));
+                }
+                if($(this).parents(".closed:first").find("span.selected").length)
+                {
+                    $(this).parents(".closed:first").find(".folder").removeClass("folders-loading");
+                    return write_msg(get_lang("It's not possible delete this folder, because it is being used in the moment!"));
+                }
+                var folder_span = $(this);
+                var confirm_text = get_lang("Do you wish to exclude the folder ");
+
+                $.Zebra_Dialog(confirm_text + folder_name, {
+                    'type': 'question',
+                    'overlay_opacity': '0.5',
+                    'custom_class': 'custom-zebra-filter',
+                    'buttons': [get_lang('Yes'), get_lang('No')],
+                    'onClose': function(caption)
+                    {
+
+                        if(caption == get_lang('Yes'))
+                        {
+                            if(folder_span.parents("li").find("input").first().val() == "localFolder")
+                            {
+                                var idFolder = folder_span.parents("li").first().attr("id").split("_")[2];
+                                expresso_mail_archive.deleteFolder(idFolder, folder_name);
+                                cExecute("$this.imap_functions.get_folders_list&onload=true", update_menu);
+                            }
+                            else
+                            {
+                                $.ajax(
+                                {
+                                    url: "controller.php?action=$this.imap_functions.delete_mailbox",
                                     type: "POST",
-                                    data : "del_past="+folder_id,
-                                    success : function(data){
+                                    data: "del_past=" + folder_id,
+                                    success: function(data)
+                                    {
                                         data = connector.unserialize(data);
-                                        if(data == "Mailbox does not exist"){
+                                        if(data == "Mailbox does not exist")
+                                        {
                                             $(".folders-loading").removeClass("folders-loading");
                                             return write_msg(get_lang("Mailbox does not exist"));
-                                        }else if(data == "Permission denied"){
+                                        }
+                                        else if(data == "Permission denied")
+                                        {
                                             $(".folders-loading").removeClass("folders-loading");
                                             cExecute("$this.imap_functions.get_folders_list&onload=true", update_menu);
@@ -566,176 +747,216 @@
                                     }
                                 });
+                            }
+                        }
+                        else
+                        {
+                            folder_span.parents(".closed:first").find(".folder").removeClass("folders-loading");
+                            return;
+                        }
+                    }
+                });
+            })
+            //FUNÇÃO DO eventNU FLUTUANTE EXCLUIR < END
+            //FUNÇÃO DO eventNU FLUTUANTE NOVA PASTA < BEGIN
+            .end().find(".float-menu-new").click(function()
+            {
+                $(this).parents(".float-menu").hide();
+                var selected_li = $(this).parents(".closed:first");
+                if(selected_li.find("ul:first").length)
+                {
+                    var new_folder = $("<li><input class='new_folder folder' type='text' maxlength='100'></input></li>").appendTo(selected_li.find("ul:first"));
+                    if(selected_li.find(".expandable-hitarea").length)
+                    {
+                        selected_li.find(".expandable-hitarea").trigger('click');
+                    }
+                    selected_li.find("ul:first").treeview(
+                    {
+                        add: new_folder
+                    });
+                }
+                else if(selected_li.length)
+                {
+                    var new_folder = $("<ul><li><input class='new_folder folder' type='text' maxlength='100'></input></li></ul>").appendTo(selected_li);
+                    selected_li.treeview(
+                    {
+                        add: new_folder
+                    });
+                }
+                else
+                {
+                    selected_li = $(this).parents("li:first");
+                    if($(this).parents(".head_folder").parent().find(".expandable-hitarea").length)
+                    {
+                        $(this).parents(".head_folder").parent().find(".expandable-hitarea").trigger('click');
+                    }
+                    var new_folder = $("<ul><li><input class='new_folder folder' type='text' maxlength='100'></input></li></ul>").appendTo(selected_li);
+                    selected_li.treeview(
+                    {
+                        add: new_folder
+                    });
+                }
+                var existsIdenticalFolder = false;
+                selected_li.find(".new_folder").Watermark("Nova Pasta").focus().keydown(function(event)
+                {
+                    event.stopPropagation();
+
+                    existsIdenticalFolder = false;
+
+                    var ok = false;
+                    var makeChildren = function(auxNameFolder, father)
+                        {
+                            if(auxNameFolder.length == 0) return true;
+
+
+                            if(auxNameFolder[0] == "")
+                            {
+                                auxNameFolder.shift();
+                                makeChildren(auxNameFolder, father);
+                                return true;
+                            }
+                            if(ok == false)
+                            {
+                                expresso_mail_archive.createFolder((father ? father : "inbox"), auxNameFolder[0]);
+                            }
+
+                            expresso_mail_archive.getFoldersList(father);
+
+                            for(var ii = 0; ii < expresso_mail_archive.folders.length; ii++)
+                            {
+                                if(auxNameFolder[0] == expresso_mail_archive.folders[ii].name)
+                                {
+                                    auxNameFolder.shift();
+                                    save = expresso_mail_archive.folders;
+                                    expresso_mail_archive.createFolder(expresso_mail_archive.folders[ii].id, auxNameFolder[0]);
+                                    expresso_mail_archive.folders = save;
+                                    ok = true;
+                                    makeChildren(auxNameFolder, expresso_mail_archive.folders[ii].id);
+                                    return true;
                                 }
-                            }else{
-                                folder_span.parents(".closed:first").find(".folder").removeClass("folders-loading");
-                                return;
-                            }
-                        }
-                    });
-                    /* if(!confirm(confirm_text + folder_name)){
-                        $(this).parents(".closed:first").find(".folder").removeClass("folders-loading");
-                        return;
-                    } */
-                })
-                //FUNÇÃO DO eventNU FLUTUANTE EXCLUIR < END
-                //FUNÇÃO DO eventNU FLUTUANTE NOVA PASTA < BEGIN
-                .end().find(".float-menu-new").click(function(){
-                    $(this).parents(".float-menu").hide();
-                    var selected_li = $(this).parents(".closed:first");
-                    if(selected_li.find("ul:first").length){
-                        var new_folder = $("<li><input class='new_folder folder' type='text' maxlength='100'></input></li>").appendTo(selected_li.find("ul:first"));                                
-                        if(selected_li.find(".expandable-hitarea").length){
-                            selected_li.find(".expandable-hitarea").trigger('click');
-                        }
-                        selected_li.find("ul:first").treeview({
-                            add: new_folder
-                        });
-                    }else if(selected_li.length){
-                        var new_folder = $("<ul><li><input class='new_folder folder' type='text' maxlength='100'></input></li></ul>").appendTo(selected_li);                                
-                        selected_li.treeview({
-                            add: new_folder
-                        });
-                    }else{
-                        selected_li = $(this).parents(".head_folder").parent();
-                        if($(this).parents(".head_folder").parent().find(".expandable-hitarea").length){
-                            $(this).parents(".head_folder").parent().find(".expandable-hitarea").trigger('click');
-                        }
-                        var new_folder = $("<ul><li><input class='new_folder folder' type='text' maxlength='100'></input></li></ul>").appendTo(selected_li);                                
-                        selected_li.treeview({
-                            add: new_folder
-                        });
+                            }
+                        }
+
+
+                    if(event.keyCode == 13)
+                    {
+                        /* Verifica se existe caracteres especiais no nome da pasta ou se existe "local_"
+                         * em parte do nome (palavra reservada para pastas locais) */
+                        if($(this).val().match(/[\`\~\^\<\>\|\\\"\!\@\#\$\%\&\*\+\(\)\[\]\{\}\?;:]/gi) || $(this).val().indexOf("local_") != -1)
+                        {
+                            return write_msg(get_lang("cannot create folder. try other folder name"));
+                        }
+                        if($(this).parents("li").find("input[type=hidden]").val() == "localFolder")
+                        {
+
+                            $(".new_folder").parent().addClass("folders-loading");
+
+                            var folderName = $(this).val();
+                            var folder = (folderName != "" ? folderName : get_lang("New Folder"));
+                            var father = typeof(selected_li.attr('id')) != "undefined" ? selected_li.attr('id').split("_")[2] : "home";
+
+                            $(this).parents(".treeview:first").find("li").each(function()
+                            {
+                                var eachFolder = $(this).find("span:first").text().trim();
+                                if(folder == eachFolder)
+                                {
+                                    existsIdenticalFolder = true;
+                                    return false;
+                                }
+                            });
+
+                            if(existsIdenticalFolder)
+                            {
+                                event.stopPropagation();
+                                write_msg(get_lang("Mailbox already exists"));
+                                draw_new_tree_folder();
+                                return false;
+                            }
+
+                            if(folderName.indexOf("/") != -1)
+                            {
+                                auxNameFolder = folderName.split("/");
+
+                                makeChildren(auxNameFolder, father);
+                            }
+                            else
+                            {
+                                var folder = (folderName != "" ? folderName : get_lang("New Folder"));
+                                create_new_local_folder((selected_li.attr('id') ? selected_li.attr('id') : "inbox"), folder);
+                            }
+
+                            cExecute("$this.imap_functions.get_folders_list&onload=true", update_menu);
+                        }
+                        else
+                        {
+                            if($('[id="' + (selected_li.attr('id') ? selected_li.attr('id') : "INBOX") + cyrus_delimiter + $(this).val() + '"]').length)
+                            {
+                                $(".folders-loading").removeClass("folders-loading");
+                                write_msg(get_lang("Mailbox already exists"));
+                                return draw_new_tree_folder();
+                            }
+                            $(".new_folder").parent().addClass("folders-loading");
+                            create_new_folder(($(this).val() != "" ? $(this).val() : get_lang("New Folder")), (selected_li.attr('id') ? selected_li.attr('id') : "INBOX"));
+                        }
+
                     }
-                    var existsIdenticalFolder = false;
-                    selected_li.find(".new_folder").Watermark("Nova Pasta").focus().keydown(function(event){
-                        event.stopPropagation();
-
-                        existsIdenticalFolder = false;
-
-                    var ok = false;
-                    var makeChildren = function(auxNameFolder, father){
-                        if(auxNameFolder.length == 0) return true;
-
-
-                        if(auxNameFolder[0] == ""){
-                            auxNameFolder.shift();
-                            makeChildren(auxNameFolder, father);
-                            return true;
-                        }
-                        if(ok == false)
-                            expresso_mail_archive.createFolder((father ? father : "inbox"), auxNameFolder[0]);
-                        
-                        expresso_mail_archive.getFoldersList(father);
-
-                        for(var ii =0; ii<expresso_mail_archive.folders.length; ii++){
-                            if(auxNameFolder[0] == expresso_mail_archive.folders[ii].name){
-                                 auxNameFolder.shift();
-                                 save = expresso_mail_archive.folders;
-                                 expresso_mail_archive.createFolder(expresso_mail_archive.folders[ii].id, auxNameFolder[0]);
-                                 expresso_mail_archive.folders = save; 
-                                 ok = true;
-                                 makeChildren(auxNameFolder, expresso_mail_archive.folders[ii].id);
-                                 return true;
-                            }
-                        }
+                    else if(event.keyCode == 27)
+                    {
+                        draw_new_tree_folder();
                     }
 
-
-                        if(event.keyCode == 13){
-                            /* Verifica se existe caracteres especiais no nome da pasta ou se existe "local_"
-                             * em parte do nome (palavra reservada para pastas locais) */
-                            if($(this).val().match(/[\`\~\^\<\>\|\\\"\!\@\#\$\%\&\*\+\(\)\[\]\{\}\?;:]/gi) || $(this).val().indexOf("local_") != -1){
-                                return write_msg(get_lang("cannot create folder. try other folder name"));
-                            }
-                            if($(this).parents("li").find("input[type=hidden]").val() == "localFolder"){
-
-                                 $(".new_folder").parent().addClass("folders-loading");
-
-                                 var folderName = $(this).val();
-                                 var folder = (folderName != "" ? folderName : get_lang("New Folder"));
-                                 var father = typeof(selected_li.attr('id')) != "undefined" ? selected_li.attr('id').split("_")[2] : "home";
-
-                                 $(this).parents(".treeview:first").find("li").each(function(){
-                                     var eachFolder = $(this).find("span:first").text().trim();
-                                     if(folder == eachFolder){
-                                        existsIdenticalFolder = true;
-                                        return false;
-                                     }  
-                                 });
-
-                                 if(existsIdenticalFolder){
-                                    event.stopPropagation();
-                                    write_msg(get_lang("Mailbox already exists"));
-                                    draw_new_tree_folder();
-                                    return false;
-                                 }
-
-                                 if(folderName.indexOf("/") != -1){
-                                    auxNameFolder = folderName.split("/");
-
-                                    makeChildren(auxNameFolder, father);
-                                 } else {
-                                     var folder = (folderName != "" ? folderName : get_lang("New Folder"));
-                                     create_new_local_folder((selected_li.attr('id') ? selected_li.attr('id') : "inbox") , folder);
-                                 }
-
-                                 cExecute("$this.imap_functions.get_folders_list&onload=true", update_menu);
-                            } else {
-                                if($('[id="'+ (selected_li.attr('id')? selected_li.attr('id') : "INBOX") + cyrus_delimiter + $(this).val()+'"]').length){
-                                    $(".folders-loading").removeClass("folders-loading");
-                                    write_msg(get_lang("Mailbox already exists"));
-                                    return draw_new_tree_folder();
-                                }
-                                $(".new_folder").parent().addClass("folders-loading");
-                                create_new_folder(($(this).val() != "" ? $(this).val() : get_lang("New Folder")), (selected_li.attr('id')? selected_li.attr('id') : "INBOX"));
-                            }
-
-                        }else if( event.keyCode == 27){
-                            draw_new_tree_folder();
-                        }
-
-                    }).focusout(function(){
-                        if(!existsIdenticalFolder){
-                            draw_new_tree_folder();
-                        }
-                        
-                    });
-                }).end().find(".float-menu-export").click(function(){
-                    //proxy_mensagens.export_all_messages($(this).parents("li:first").attr("id"))
-
-                    var name_box = $(this).parents("li:first").attr("id");
-
-                    var name_folder = name_box.split(cyrus_delimiter)[name_box.split(cyrus_delimiter).length-1];
-
-
-                    var hand_export = function(data){
-						clean_msg();
-                        if(!data){
+                }).focusout(function()
+                {
+                    if(!existsIdenticalFolder)
+                    {
+                        draw_new_tree_folder();
+                    }
+
+                });
+            }).end().find(".float-menu-export").click(function()
+            {
+                var name_box = $(this).parents("li:first").attr("id");
+
+                var name_folder = name_box.split(cyrus_delimiter)[name_box.split(cyrus_delimiter).length - 1];
+
+
+                var hand_export = function(data)
+                    {
+                        clean_msg();
+                        if(!data)
+                        {
                             write_msg(get_lang('Error compressing messages (ZIP). Contact the administrator.'))
-                        }else if(data["empty_folder"] || data == "empty_folder"){
+                        }
+                        else if(data["empty_folder"] || data == "empty_folder")
+                        {
                             write_msg(get_lang("The selected folder is empty."));
-                        }else
-							download_attachments(null, null, data, null,null, name_folder +'.zip');						
+                        }
+                        else download_attachments(null, null, data, null, null, name_folder + '.zip');
                     }
-                    if($(this).parents("li:first").find("input[type=hidden]:first").val() == "localFolder"){                        
-                          expresso_mail_archive.listMessages(name_box.split("_")[2]);
-                          var msgsArchive = expresso_mail_archive.messageslisted;
-                        
-                           buildExportArchiver(msgsArchive, name_box);
-
-                    } else {
-                          cExecute("$this.exporteml.export_all",hand_export,"folder="+name_box);  
-                    }
-                    write_msg(get_lang('You must wait while the messages will be exported...'),true);        
-                });
-                //FUNÇÃO DO eventNU FLUTUANTE NOVA PASTA < END
-            }
-            if(!$(".new_folder").length){
-                $(this).find(".float-menu:first").css("display", "");
-            }
-        },
-        function(){
-            $(this).find(".float-menu:first").hide();
-        }
-    );
-    $("#new_m").html($('.selected').find(".folder_unseen").html() ? $('.selected').find(".folder_unseen").html() : "0").css("color", "red");
+                if($(this).parents("li:first").find("input[type=hidden]:first").val() == "localFolder")
+                {
+                    expresso_mail_archive.listMessages(name_box.split("_")[2]);
+                    var msgsArchive = expresso_mail_archive.messageslisted;
+
+                    buildExportArchiver(msgsArchive, name_box);
+
+                }
+                else
+                {
+                    cExecute("$this.exporteml.export_all", hand_export, "folder=" + name_box);
+                }
+                write_msg(get_lang('You must wait while the messages will be exported...'), true);
+            });
+            //FUNÇÃO DO eventNU FLUTUANTE NOVA PASTA < END
+        }
+        if(!$(".new_folder").length)
+        {
+            $(this).find(".float-menu:first").css("display", "");
+        }
+    }, function()
+    {
+        $(this).find(".float-menu:first").hide();
+    });
+    $("#new_m")
+    .html($('.selected .message_unseen_count:first .folder_unseen').html() ? $('.selected .message_unseen_count:first .folder_unseen').html() : "0")
+    .css("color", "red");
 }
Index: branches/2.5/prototype/modules/mail/js/label.js
===================================================================
--- branches/2.5/prototype/modules/mail/js/label.js	(revision 7750)
+++ branches/2.5/prototype/modules/mail/js/label.js	(revision 8232)
@@ -83,8 +83,43 @@
 }
 
+function returnLabels(msgsReference){
+	var folderIndex = {};
+   for (var i=0; i < msgsReference.length; i++) {       
+       if( folderIndex[ msgsReference[i].folderName] ){        
+           folderIndex[ msgsReference[i].folderName].push( msgsReference[i].messageNumber );          
+       }else{
+           folderIndex[ msgsReference[i].folderName] = [ msgsReference[i].messageNumber ];
+       }      
+   }
+   var labels = []; 
+   for(var folder in folderIndex){
+   		var currentLabes = DataLayer.get('labeled',{ filter:[
+               'AND',
+               ['=', 'folderName', folder ],
+               ['IN', 'messageNumber', folderIndex[ folder ] ]
+               ], criteria: {deepness: '2'}});
+
+   		if( $.isArray( currentLabes ) )
+			labels = labels.concat( currentLabes );
+   }
+   var labelsIndex = {};
+   $.each( labels, function(i, e){
+       if( labelsIndex[ e.messageNumber ] ){
+           labelsIndex[ e.messageNumber ][ 'labels' ].push( e.label );
+       }else{
+           labelsIndex[ e.messageNumber ] = e;
+           labelsIndex[ e.messageNumber ][ 'labels' ] = [];
+           labelsIndex[ e.messageNumber ][ 'labels' ].push( e.label );
+       }
+   });
+   return labelsIndex;
+}
+
+
 function updateMessageLabels(msgsReference){
-	for(var i = 0; i < msgsReference.length; i++){
-		updateLabelsColumn({msg_number: msgsReference[i].messageNumber, boxname: msgsReference[i].folderName});
-	}	
+	var labelsIndex = returnLabels(msgsReference);
+   $.each(labelsIndex,function(index,e){
+           updateLabelsColumn({msg_number: e.messageNumber, boxname: e.folderName,labels: e.labels, forceIcon: true});
+   });
 }
 
@@ -164,6 +199,6 @@
 						winElement.find('.edit').unbind("click").click(editLabel);				
 						winElement.find('.close').click(deleteLabel);
-						
-						draw_tree_labels();
+                        if( preferences['use_followupflags_and_labels'] == "1" )
+						    draw_tree_labels();
 						var msgsReference = DataLayer.get('labeled', {filter: ['=', 'labelId', ''+labelEdited.id]}, true);
 						updateMessageLabels(msgsReference);
@@ -291,6 +326,6 @@
 			.find("li:first")
 			.fadeIn("slow").click(configureLabel);
-			
-			draw_tree_labels();
+            if( preferences['use_followupflags_and_labels'] == "1" )
+			    draw_tree_labels();
 
 			$(".label-list-container .label-list li").not(".empty-item").click(function(){
Index: branches/2.5/prototype/modules/mail/js/followupflag.js
===================================================================
--- branches/2.5/prototype/modules/mail/js/followupflag.js	(revision 7780)
+++ branches/2.5/prototype/modules/mail/js/followupflag.js	(revision 8232)
@@ -73,5 +73,5 @@
 		winElement.dialog("close");
 		$.each(selectedMessageIds, function(index, value){	
-			$('tr#' + value + ' .td-followup-flag').find('img').remove();
+			$('tr#' + value + ' .td-followup-flag')//.find('img').remove();
 		});
 		
@@ -173,15 +173,34 @@
 							 alert('Uma ou mais mensagens não puderam ser sinalizadas. \nDetalhes do erro: limite de flags atingido para esta pasta.');	
 						}
-						$.each(selectedMessageIds,function(index,value){	
-							var flagged = DataLayer.get('followupflagged', {filter: [
-								'AND', 
-								['=', 'messageNumber', value], 
-								['=', 'folderName', folder_name]
-							]});
-							if (!flagged)
-								$('#td_message_followup_'+value).find(".flag-edited").css("background","#cccccc").find('img').remove();
-							
-							$('tr#' + value + ' .td-followup-flag').find('img').remove();
-						});					
+						/*DIVIDE O ARRAY EM ARRAYS MENORES*/
+						var splice = function(arr){
+							var newArray = [];
+							while (arr.length > 500){
+								newArray[newArray.length] = arr.splice(0,500);
+							}
+							if (arr.length) 
+								newArray[newArray.length] = arr;
+							return newArray;
+						}
+						if (selectedMessageIds.length > 500){
+							var arrayIndex = selectedMessageIds;
+							$.each(splice(arrayIndex),function(iterator,subarray){
+								var flaggeds = DataLayer.get('followupflagged', {filter: [
+										'AND', 
+										['IN', 'messageNumber', subarray], 
+										['IN', 'folderName', folder_name]
+								]});
+								$.each(subarray,function(index,value){	
+									var flagged = false;
+									$.each(flaggeds,function(i,v){
+										if (v.messageNumber == value)
+											flagged = true;
+									});
+									if (!flagged)
+										$('#td_message_followup_'+value).find(".flag-edited").css("background","#cccccc").find('img').remove();						
+									$('tr#' + value + ' .td-followup-flag').find('img').remove();
+								});
+							});	
+						}					
 					});
 					winElement.find('.menu-configure-followupflag .save').button("option", "disabled", true);
@@ -267,5 +286,5 @@
 			
 			$.each(selectedMessageIds, function(index, value){	
-				$('tr#' + value + ' .td-followup-flag').find('img').remove();
+				$('tr#' + value + ' .td-followup-flag').find('img')//.remove();
 			});
 			
@@ -756,11 +775,15 @@
 
 }
-		
-$('#main_table').ready(function(){
-	handlerMessageFilter = function (data) {
-		alarmFollowupflagged(null, data);
-	}
-	/* Busca  nas pastas indexadas para ver se há novas mensagens com a flag $FilteredMessage */
-	cExecute ("$this.imap_functions.getFlaggedAlertMessages&folders="+fromRules, handlerMessageFilter);
-});
-
+
+if(preferences['use_alert_filter_criteria'] == "1")
+{
+    $('#main_table').ready(function(){
+        handlerMessageFilter = function (data) {
+            alarmFollowupflagged(null, data);
+        }
+        /* Busca  nas pastas indexadas para ver se há novas mensagens com a flag $FilteredMessage */
+        cExecute ("$this.imap_functions.getFlaggedAlertMessages&folders="+fromRules, handlerMessageFilter);
+    });
+}
+
+
Index: branches/2.5/prototype/modules/mail/templates/detailedfoldertree.ejs
===================================================================
--- branches/2.5/prototype/modules/mail/templates/detailedfoldertree.ejs	(revision 8113)
+++ branches/2.5/prototype/modules/mail/templates/detailedfoldertree.ejs	(revision 8232)
@@ -5,5 +5,5 @@
 			Inbox: {name:'Caixa de Entrada', classe:'inbox'}, 
 		};
-    specialFolders[outboxfolder] = {name: 'Caixa de Saída', classe:'outbox'};
+    specialFolders[outboxfolder] = {name: 'Caixa de Saï¿œda', classe:'outbox'};
 	specialFolders[trashfolder] = {name:'Lixeira', classe:'trash'};
 	specialFolders[draftsfolder] = {name:'Rascunhos', classe:'drafts'};
@@ -26,8 +26,8 @@
 		  %><li id="<%= array_trees[i].id %>" class="closed"><span class="folder <%= folder_class %>" title="<%= folder_name %>" style="text-align : left; position : static;"><%= folder_name %>
 		  <% if(array_trees[i].messageCount.unseen > 0){	%>
-			<span style="text-align : left;">[<label id="dftree_<%= array_trees[i].id%>_unseen" class="folder_unseen" style="color : red; text-align : left;"><%= array_trees[i].messageCount.unseen %></label>]</span>
-		  <% }	%>
+			<span class="message_unseen_count" style="text-align : left;">[<label id="dftree_<%= array_trees[i].id%>_unseen" class="folder_unseen" style="color : red; text-align : left;"><%= array_trees[i].messageCount.unseen %></label>]</span>
+          <% }	%>
 		  <% if(array_trees[i].children_unseen > 0){	%>
-			<span style="text-align : left;">[<label id="dftree_<%= array_trees[i].id%>_children_unseen" class="folder_unseen" style="color : blue; text-align : left;"><%= array_trees[i].children_unseen %></label>]</span>
+			<span style="text-align : left;">[<label id="dftree_<%= array_trees[i].id%>_children_unseen" class="folder_children_unseen" style="color : blue; text-align : left;"><%= array_trees[i].children_unseen %></label>]</span>
 		  <% }	%>
 		  </span>
@@ -67,5 +67,7 @@
 
 	  <%}%>
+        <% if(preferences['use_followupflags_and_labels'] == "1"){%>
 	  <li><span class="folder head_folder all_accomp followup-messages">Para acompanhamento</span>
+          <%}%>
 	  </li>
 	</ul>
Index: branches/2.5/prototype/modules/mail/templates/attachment.ejs
===================================================================
--- branches/2.5/prototype/modules/mail/templates/attachment.ejs	(revision 7697)
+++ branches/2.5/prototype/modules/mail/templates/attachment.ejs	(revision 8232)
@@ -1,12 +1,16 @@
-<div id="fileupload_msg<%=data.ID%>" class="fileupload" style="margin : 5px 0px 0px 0px; padding-bottom : 5px;">
-    <div class="button-files-upload">
-    <button class="fileUploadButton">Anexar Arquivos</button>
-			<INPUT type="file" id="fileInput<%=data.ID%>" name="files[]" style="display:none;" multiple></INPUT>
+<div id="fileupload_msg<%=data.ID%>" class="fileupload" style="margin : 15px 0px -5px -10px; padding-bottom : 5px;">
+	<div class="row fileupload-buttonbar">
+		<div class="button-files-upload">
+			<<%= is_webkit ? 'button' : 'span style="height: 22px; cursor:pointer;"' %>  class="fileinput-button button small">
+				<span style="margin-top: 4px; cursor:pointer;"><i class="icon-plus icon-white"></i>Anexar arquivos</span>
+				<INPUT type="file" id="fileInput<%=data.ID%>" name="files[]" multiple></INPUT>
 			</<%= is_webkit ? 'button' : 'span' %>>
-			<button class="message-attach-link button-small">
+			<button class="message-attach-link button small">
 				<span>Anexar mensagens</span>
 			</button>
-    </div>
-<div class="files-list">
+		</div>
+	</div>
+	<br />
+	<div class="files-list">
 		<div class="attachments-list ui-corner-all" style="display:none;"></div>
 	</div>
Index: branches/2.5/prototype/modules/attach_message/attach_message.css
===================================================================
--- branches/2.5/prototype/modules/attach_message/attach_message.css	(revision 5831)
+++ branches/2.5/prototype/modules/attach_message/attach_message.css	(revision 8232)
@@ -36,5 +36,5 @@
 #mailpreview_container {margin:5px;padding:0px;height:220px; width:907px; float:left; margin:5px 5px 5px 5px;}
 #mailpreview_container .ui-tabs-panel {height:183px;overflow:auto;padding:0px; width:905px;}
-/*#mailpreview_tabs { max-height: 20px; }*/
+#mailpreview_tabs { max-height: 25px; }
 #buttons-container {text-align: right;margin:5px 5px 5px 5px;float:right;}
 #selected_messages_counter {text-align:right;padding:0;}
Index: branches/2.5/prototype/modules/attach_message/attach_message.js
===================================================================
--- branches/2.5/prototype/modules/attach_message/attach_message.js	(revision 7543)
+++ branches/2.5/prototype/modules/attach_message/attach_message.js	(revision 8232)
@@ -216,5 +216,5 @@
 		for (var message in selectedMessages[folder]) {
 			if (selectedMessages[folder][message]) {
-				byte_size += parseInt(onceOpenedMessages[folder][message].size);
+				byte_size += parseInt(onceOpenedHeadersMessages[folder][message].size);
 				total_messages++;
 			}
@@ -227,8 +227,30 @@
 var msgAttacherGrid = $("#message_attacher_grid"), msgsTotal = $("#selected_messages_number");
 var lastLoadedMessages = [];
-var onceOpenedMessages = [];
 var selectedMessages   = {};
 var selectedFolder     = {};
 
+function mount_children_localfolders_list(folder){ 
+    folder.children = new Array();
+    folder.id_search = folder.id;
+    folder.id = 'local_messages_'+folder.id,
+    folder.commonName =  folder.name,
+    folder.parentId = folder.parentid,
+    folder.type = 'localFolder',
+    folder.name = folder.id,
+    folder.messageCount = {
+                             total: folder.messages,
+                             unseen: folder.unseen
+                          }
+
+    if(folder.haschild){
+        expresso_mail_archive.getFoldersList(folder.id_search);
+        folder.children = expresso_mail_archive.folders;
+
+        for(var i = 0; i < folder.children.length; i++){
+            mount_children_localfolders_list(folder.children[i]);
+        }
+
+    }
+}
 function adaptOffline( data )
 {
@@ -254,6 +276,42 @@
 	
     return( data );
-	
-}
+}
+
+function archive_flag( flagObj ){
+
+    var flags = {};
+    var returns = '';
+
+    $.each( flagObj.tag , function(i, flag){
+        flags[ flag['@value'] ] = true;
+    });
+
+	returns += (flags['seen'] ? '0,' : '1,') ;
+	returns += (flags['answered'] && !flags['forwarded'] ? '1,' : '0,') ;
+	returns += (flags['forwarded'] ? '1,' : '0,') ;
+	returns += (flags['flagged'] || flags['importance_high'] ? '1,' : '0,') ;
+	returns += '0,0';
+            
+    return returns;
+}
+
+function archive_flag_search( flagObj ){
+    var flags = {};
+    var returns = '';
+
+    flagObj = flagObj.split("");
+    $.each( flagObj , function(i, flag){
+        flags[ flag ] = true;
+    });
+
+    returns += (flags['U'] ? '1,' : '0,') ;
+    returns += (flags['A'] && !flags['X'] ? '1,' : '0,') ;
+    returns += (flags['X'] ? '1,' : '0,') ;
+    returns += (flags['F'] ? '1,' : '0,') ;
+    returns += '0,0';
+            
+    return returns;
+}
+
 
 $mailpreview_tabs_label_length = 15;
@@ -271,4 +329,21 @@
 		var tree2 = new Array();
 		var tree3 = new Array();
+
+        if(preferences.use_local_messages == 1){
+            if(expresso_mail_archive.folders && !expresso_offline && expresso_mail_archive.enabled == true) { //MailArchive
+                //pega pastas locais do mailarchiver e insere no array de pastas
+                    expresso_mail_archive.getFoldersList("home");
+                    treeFolders = expresso_mail_archive.folders;
+
+                    for(var i=0; i<treeFolders.length; i++ ){
+                        mount_children_localfolders_list(treeFolders[i]);
+                    }
+                    
+                    for(var i = 0; i < treeFolders.length; i++){
+                        data.push(treeFolders[i]);
+                    }
+            }
+        }
+
 		for (var i=0; i<data.length; i++) {
 
@@ -286,8 +361,5 @@
 			}
 			else if (/^local_messages/.test(data[i].id)) {
-				if (!unorphanize(tree3, data[i])) {
-					data[i].children = new Array();
 					tree3.push(data[i]);
-				}
 			}
 			
@@ -299,4 +371,5 @@
 		.find("#foldertree").treeview()
 		.click(function(event){
+
 			//request new selected folder messages
 			var target = $(event.target);
@@ -325,14 +398,56 @@
 			var grid = $("#message_attacher_grid"), offlineCase = "";
 			
-			if( !targetId.indexOf( 'local_messages/' ) )
-			    offlineCase = ":offline";
-			
-
-			grid.jqGrid('setGridParam',{url:BASE_PATH + 'REST.php'+offlineCase+'?q=folder/'+targetId.replace(dashes, '.')+'/message'})
-			    .trigger("reloadGrid")
-			    .jqGrid('setCaption', '<span class="'+child.attr('class')+'">'+child.attr('title')+'</span>');
+            if(targetId.indexOf( 'local_messages' ) == 0){
+                 //Entrar caso: Clicar em uma pasta que seja do arquivamento local
+                targetId = targetId.split("_")[2];
+
+                expresso_mail_archive.getMessagesByFolder(targetId,"ALL");
+
+                msgAll = expresso_mail_archive.msgAll;                
+
+                var msgs = new Array();
+                var from = '';
+                var flag = '';
+                
+                $.each(msgAll, function(i, msg){
+                    from = $.parseJSON(msg['_from']);
+
+                    if(!from){
+                        from = {"mailbox":{"name":"null","route":"null","localPart":"null","domain":"null"}};
+                    }
+
+                    flag = $.parseJSON(msg['_tags']);
+                    id = msg['_id'];
+
+                    var message = {};
+                    
+                    
+                    message['msg_number'] = id;
+                    message['flags'] = archive_flag( flag );
+                    message['from.name'] = from['mailbox']['@name'];
+                    message['subject'] = msg['_subject'];
+                    message['timestamp'] = msg['_receivedDate'];
+                    message['size'] = msg['_size'];
+                    message['id'] = id;
+                    msgs.push( message );
+
+                });
+
+            grid.jqGrid("clearGridData", true);
+            grid.jqGrid('setGridParam',{datatype: "local",data: msgs})
+                    .trigger("reloadGrid")
+                    .jqGrid('setCaption', '<span class="'+child.attr('class')+'">'+child.attr('title')+'</span>');
+
+            } else {
+                if( !targetId.indexOf( 'local_messages/' ) )
+                    offlineCase = ":offline";
+
+                grid.jqGrid('setGridParam',{datatype: "json", url:BASE_PATH + 'REST.php'+offlineCase+'?q=folder/'+targetId.replace(dashes, '.')+'/message'})
+                    .trigger("reloadGrid")
+                    .jqGrid('setCaption', '<span class="'+child.attr('class')+'">'+child.attr('title')+'</span>');
+            }
 		})
 		.find('span:first-child');
-		$('span.folder.inbox').addClass('selected');
+		$('span.folder.inbox').parents(".ui-dialog").find("li#INBOX span").addClass('selected');
 		selectedFolder = {
 			id: firstFolder.parent().attr('id'), 
@@ -360,5 +475,46 @@
 			],
 			jsonReader : {
-				  root:"rows",
+				  root: function(obj){
+				  	obj['data'] = {};
+		            obj.data = {rows : obj.rows};
+				  	if(obj.rows){
+				  		if(!obj.rows[0].flag){
+					  		var msgs = [];
+						  	$.each(obj.rows, function(i, msg){
+								flag = msg['flags'];
+		                        id = msg['msg_number'];
+		                        var message = {};
+		                     
+		                        message['msg_number'] = id;
+		                        message['flags'] = flag;
+		                        message['to'] = {
+		                                name: msg['toaddress2'],
+		                                email: msg['toaddress2']
+		                        };
+		
+		                        if(msg['from'] != undefined &&  msg['header']['from'] != undefined){
+		                                message['from'] = {
+		                                        'email' : msg['from']['email'],
+		                                        'name' : msg['header']['from']['name']
+		                                }
+		                            }else{
+		                                message['from'] = {
+		                                        'email' : '',
+		                                        'name' : 'Rascunho'
+		                                }
+		                            }
+		                        //message['from']['name'] = msg['from']['name'];
+		                        message['subject'] = msg['subject'] ? msg['subject'] : "(sem assunto)";
+		                        message['timestamp'] = parseInt(msg['timestamp']);
+		                        message['size'] = msg['size'];
+		                        message['id'] = id;
+		                        msgs.push( message );
+			                });
+							obj['data'] = {};
+			                obj.data = {rows : msgs};
+			            }
+	                }
+				  	return obj.data.rows;
+				  },
 				  page: "page",
 				  total: "total",
@@ -367,4 +523,5 @@
 				  id: "0"
 			},
+			hidegrid:false,
 			rowNum:10,
 			rowList:[10,25,50],
@@ -377,5 +534,6 @@
 			loadComplete: function(data) {
 				lastLoadedMessages = data.rows;
-				
+				$("#mailgrid-container").find(".loading").hide();
+
 				// aplica o contador
 				jQuery('.timable').each(function (i) {
@@ -401,119 +559,362 @@
 				
 			},
-			onSelectRow: function (id, selected) {
-				var message = false;
-				for (var i=0; i<lastLoadedMessages.length; i++){
-					if (lastLoadedMessages[i].msg_number == id) {
-						message = lastLoadedMessages[i];
-						break;
-					}
-				}
-				
-				var tabPanelTemplateId = 'mailpreview_tab_' + selectedFolder.id.replace(/[.\/]/g, '_') + '_' + message.msg_number;
-				var tabPanelTemplateId = tabPanelTemplateId.replace(/[\s\/]/g, '-'); 
-				
-				if (selected) {	
-					if (onceOpenedMessages[selectedFolder.id] && onceOpenedMessages[selectedFolder.id][message.msg_number]) {
-						if (!selectedMessages[selectedFolder.id])
-							selectedMessages[selectedFolder.id] = {};
-							
-						selectedMessages[selectedFolder.id][message.msg_number] = true;
-						$('#mailpreview-container').unblock();						
-
-						var tabPanelTemplateLabel = html_entities(onceOpenedMessages[selectedFolder.id][message.msg_number].subject);
-						if (tabPanelTemplateLabel.length > $mailpreview_tabs_label_length + 3)
-							tabPanelTemplateLabel = tabPanelTemplateLabel.substring(0, $mailpreview_tabs_label_length) + '...';
-						
-						if (!$('#' + tabPanelTemplateId).length) {								
-							$mailpreview_tabs.tabs("add", '#' + tabPanelTemplateId, tabPanelTemplateLabel)
-							.find('.message.empty-container').hide().end()
-							.find('#' + tabPanelTemplateId).html(onceOpenedMessages[selectedFolder.id][message.msg_number].body);
-						} else {
-							$mailpreview_tabs.tabs('select', '#' + tabPanelTemplateId)
-							.find('#' + tabPanelTemplateId + ', [href="#' + tabPanelTemplateId + '"]').removeClass('preview-message-unselected');
-						}
-						
-					} else {
-						jQuery('#mailpreview_container').block({  
-							message: '<div id="loading-content"><div class="image"></div></div>',  
-							css: {  
-								backgroundImage: 'url('+BASE_PATH+'modules/attach_message/images/loading.gif)',  
-								backgroundRepeat: 'no-repeat', 
-								backgroundPosition: 'center', 
-								backgroundColor: 'transparent', 
-								width: '32px', 
-								height: '32px', 
-								border:'none'  
-							}, 
-							overlayCSS: {  
-								backgroundColor: '#CCC',  
-								opacity:         0.5 
-							}  
-						}); 
-
-						var offlineCase = "";
-						
-						if( !selectedFolder.id.indexOf( 'local_messages/' ) )
-						    offlineCase = ":offline";
-					  
-						if (!selectedMessages[selectedFolder.id])
-							selectedMessages[selectedFolder.id] = {};
-						selectedMessages[selectedFolder.id][message.msg_number] = true;
-						$.ajax({
-							accepts: 'text/html',
-							url: BASE_PATH + 'REST.php'+offlineCase+'?q=folder/'+selectedFolder.id.replace(dashes, '.')+'/message/'+id,
-							dataType: 'json',
-							success: function( mail_preview ){		
-								//selectedMessagesCount();
-								if (!onceOpenedMessages[selectedFolder.id])
-									onceOpenedMessages[selectedFolder.id] = {};
-								onceOpenedMessages[selectedFolder.id][message.msg_number] = jQuery.extend(true, message, mail_preview);
-
-								$('#mailpreview_container').unblock();
-
-								var tabPanelTemplateLabel = html_entities(onceOpenedMessages[selectedFolder.id][message.msg_number].subject);
-								if (tabPanelTemplateLabel.length > $mailpreview_tabs_label_length + 3)
-									tabPanelTemplateLabel = tabPanelTemplateLabel.substring(0, $mailpreview_tabs_label_length) + '...';
-							selectedMessagesCount();
-								
-								if (!$('#' + tabPanelTemplateId).length) {								
-									$mailpreview_tabs.tabs("add", '#' + tabPanelTemplateId, tabPanelTemplateLabel)
-									.find('.message.empty-container').hide().end()
-									.find('#' + tabPanelTemplateId).html(onceOpenedMessages[selectedFolder.id][message.msg_number].body)
-									.prepend(
-										'<div class="mailpreview-message-info">' + 
-											get_lang('Subject') + ': ' +
-											html_entities(onceOpenedMessages[selectedFolder.id][message.msg_number].subject) + 
-										'</div>'
-									)
-									.find('[class^="ExpressoCssWrapper"]').addClass("mailpreview-message-body");
-								} else {
-									$mailpreview_tabs.tabs('select', '#' + tabPanelTemplateId)
-									.find('#' + tabPanelTemplateId + ', [href="#' + tabPanelTemplateId + '"]').removeClass('preview-message-unselected');
-								}
-							}
-						});
-					}
-				} else {
-					/**
-					 * if you wants to remove tab on unselect message,
-					 * but still needs to uselect message on remove tab.
-					 * 
-					 */
-					/*
-					if ($('#' + tabPanelTemplateId).length) {
-						$mailpreview_tabs.tabs('remove', '#' + tabPanelTemplateId);
-					}
-					 */
-					selectedMessages[selectedFolder.id][message.msg_number] = false;
-					$mailpreview_tabs.find('#' + tabPanelTemplateId + ', [href="#' + tabPanelTemplateId + '"]').addClass('preview-message-unselected');
-				}
-				
-				if (onceOpenedMessages[selectedFolder.id] && onceOpenedMessages[selectedFolder.id][message.msg_number])
-					selectedMessagesCount();
-			},
+            onSelectRow: function(id, selected)
+            {
+                /* Funções auxiliares:*/
+
+                /*
+                    Marca a mensagem como selecionada no grid de anexar mensagena.
+                    Parâmetros:
+                        folder: folder em que a mensagem a ser selecionada se encontra.
+                        msg_number: id da mensagem a ser selecionada.
+                */
+                var mark_as_selected = function (folder, msg_number) {
+                    if(!selectedMessages[folder])
+                    {
+                        selectedMessages[folder] = {};
+                    }
+                    selectedMessages[folder][msg_number] = true;
+                }
+
+                /*
+                    Adiciona uma mensagem ao cache de mensagens.
+                        cache: vetor de cache de mensagens.
+                        msg: mensagem a ser armazenada.
+                */
+                var add_msg_to_cache = function (cache, msg) {
+                    if(!cache[selectedFolder.id])
+                    {
+                        cache[selectedFolder.id] = {};
+                    }
+                    cache[selectedFolder.id][msg.msg_number] = msg;
+                }
+
+                /*
+                    Adiciona uma aba de preview para cada mensagem selecionada.
+                        subject: assunto da mensagem.
+                        body: corpo da mensagem.
+                */
+                var add_preview_tab = function (subject, body) {
+                    // Trunca o assunto, para caber na aba de preview:
+                    var tabPanelTemplateLabel = html_entities(subject);
+                    if(tabPanelTemplateLabel.length > $mailpreview_tabs_label_length + 3)
+                    {
+                        tabPanelTemplateLabel = tabPanelTemplateLabel.substring(0, $mailpreview_tabs_label_length) + '...';
+                    }
+
+                    // Se a aba não tiver sido adicionada:
+                    if(!$('#' + tabPanelTemplateId).length)
+                    {
+                        // adiciona-a:
+                        $mailpreview_tabs
+                        .tabs("add", '#' + tabPanelTemplateId, tabPanelTemplateLabel)
+                        .find('.message.empty-container')
+                        .hide()
+                        .end()
+                        .find('#' + tabPanelTemplateId)
+                        .html(body)
+                        .prepend('<div class="mailpreview-message-info">' + get_lang('Subject') + ': ' + html_entities(subject) + '</div>')
+                        .find('[class^="ExpressoCssWrapper"]')
+                        .addClass("mailpreview-message-body");
+                    }
+                    else
+                    {
+                        // Senão, só a seleciona:
+                        $mailpreview_tabs
+                        .tabs('select', '#' + tabPanelTemplateId)
+                        .find('#' + tabPanelTemplateId + ', [href="#' + tabPanelTemplateId + '"]')
+                        .removeClass('preview-message-unselected');
+                    }
+                }
+
+                var message = false;
+                for(var i = 0; i < lastLoadedMessages.length; i++)
+                {
+                    if(lastLoadedMessages[i].msg_number == id)
+                    {
+                        message = lastLoadedMessages[i];
+                        break;
+                    }
+                }
+                var tabPanelTemplateId = 'mailpreview_tab_' + selectedFolder.id.replace(/[.\/]/g, '_') + '_' + message.msg_number;
+                var tabPanelTemplateId = tabPanelTemplateId.replace(/[\s\/]/g, '-');
+
+                if(selected)
+                {
+                    // Se a já mensagem (com preview) já estiver no cache:
+                    if(onceOpenedHeadersMessages[selectedFolder.id] && onceOpenedHeadersMessages[selectedFolder.id][message.msg_number]  && onceOpenedHeadersMessages[selectedFolder.id][message.msg_number].body)
+                    {
+
+                        mark_as_selected(selectedFolder.id, message.msg_number);
+
+                        add_preview_tab(
+                            onceOpenedHeadersMessages[selectedFolder.id][message.msg_number].subject,
+                            onceOpenedHeadersMessages[selectedFolder.id][message.msg_number].body
+                        );
+                    }
+                    else // Mensagem não está no cache:
+                    {
+                        jQuery('#mailpreview_container').block(
+                        {
+                            message: '<div id="loading-content"><div class="image"></div></div>',
+                            css: {
+                                backgroundImage: 'url(' + BASE_PATH + 'modules/attach_message/images/loading.gif)',
+                                backgroundRepeat: 'no-repeat',
+                                backgroundPosition: 'center',
+                                backgroundColor: 'transparent',
+                                width: '32px',
+                                height: '32px',
+                                border: 'none'
+                            },
+                            overlayCSS: {
+                                backgroundColor: '#CCC',
+                                opacity: 0.5
+                            }
+                        });
+
+                        mark_as_selected(selectedFolder.id, message.msg_number);
+
+                        // Se for mensagem local:
+                        if(selectedFolder['id'].indexOf("local_messages_") != -1)
+                        {
+                            expresso_mail_archive.getPreviewToAttach(id);
+
+                            var body = expresso_mail_archive.bodyPreview;
+                            var subject = expresso_mail_archive.subjectPreview;
+
+                            add_preview_tab(subject, body);
+
+                            $('#mailpreview_container').unblock();
+
+                            add_msg_to_cache(onceOpenedHeadersMessages, message);
+                        }
+                        else
+                        {
+                            proxy_mensagens.get_msg(id, selectedFolder.id, '', function (data) {
+                                message = $.extend(true, message, data);
+
+                                add_preview_tab(message.subject, message.body);
+
+                                $('#mailpreview_container').unblock();
+
+                                add_msg_to_cache(onceOpenedHeadersMessages, message);
+
+
+                            })
+                        }
+                    }
+                }
+                else
+                {
+                    /**
+                     * if you wants to remove tab on unselect message,
+                     * but still needs to uselect message on remove tab.
+                     *
+                     */
+                    selectedMessages[selectedFolder.id][message.msg_number] = false;
+                    $mailpreview_tabs
+                    .find('#' + tabPanelTemplateId + ', [href="#' + tabPanelTemplateId + '"]')
+                    .addClass('preview-message-unselected');
+                }
+
+                selectedMessagesCount();
+            },
+            
 			caption: '<span class="'+selectedFolder['class']+'">'+selectedFolder.name+'</span>'
 		});
-		//.jqGrid('navGrid','#message_attacher_grid_pager',{edit:false,add:false,del:false});
+
+        var search_local_messsages = function(param, folder){
+            if(preferences.use_local_messages != 0)
+            {
+                folder = folder.split("_")[2];
+
+                var local_folders   = [];
+                expresso_mail_archive.search_queryresult = null;
+                
+                local_folders.push(folder);
+                
+                tmp = [];
+
+                groupResult = [];
+                    expresso_mail_archive.search(local_folders, "SUBJECT " +  "<=>" +url_encode(param) + "##");
+                        groupResult.push( expresso_mail_archive.search_queryresult );
+                    expresso_mail_archive.search(local_folders, "FROM " + "<=>" + url_encode(param) + "##");
+                        groupResult.push( expresso_mail_archive.search_queryresult );
+                    expresso_mail_archive.search(local_folders, "TO " + "<=>" + url_encode(param) + "##");
+                        groupResult.push( expresso_mail_archive.search_queryresult );
+                    expresso_mail_archive.search(local_folders, "CC " + "<=>" + url_encode(param) + "##");
+                        groupResult.push( expresso_mail_archive.search_queryresult );
+                    
+                if($("#gbox_message_attacher_grid .attach-message-search-checkbox").is(":checked")){
+                    expresso_mail_archive.search(local_folders, "BODY " + "<=>" + url_encode(param) + "##");
+                        groupResult.push( expresso_mail_archive.search_queryresult );
+                }
+
+                
+                 $.each(groupResult, function(i, result){
+                        if(result != null){
+
+                                var existsMessage = true;
+
+                                $.each(result, function(i, each){
+
+                                        $.each(tmp, function(i, ids){
+
+                                            if(each.msg_number == ids.msg_number){
+
+                                                    existsMessage = false;
+                                                    return false;
+
+                                            }
+
+                                        });
+
+                                        if(existsMessage) tmp.push(each);
+                                });
+
+                        }
+                });
+
+
+                if(tmp == null)
+                {
+                    tmp = new Object();
+                    tmp.length = 0;
+                }
+
+                msgs = [];
+
+                $.each(tmp, function(i, msg){
+
+                    flag = msg['flag'];
+                    id = msg['msg_number'];
+
+                    var message = {};
+
+                    var stamp =  msg['timestamp'];
+                    stamp = stamp.toString() + "000";
+                    stamp = parseInt(stamp);
+
+                    message['msg_number'] = id;
+                    message['flags'] = archive_flag_search(flag);//"1,1,1,1,1,1";//
+                    message['from.name'] = msg['from'];
+                    message['subject'] = msg['subject'];
+                    message['timestamp'] = stamp;
+                    message['size'] = msg['size'];
+                    message['id'] = id;
+                    msgs.push( message );
+                });
+                return msgs;
+            }
+        }
+        var search_imap_messages = function(param, folder){
+        	var grid = $("#message_attacher_grid");
+
+        	DataLayer.storage.cache = {};
+        	if( $(".attach-message-search-checkbox:checked").length > 0 ){
+	            var filters = [
+	        		[
+	        		 	'from',
+	        			'*',
+	        			param
+	        		],       	
+	        		[
+	            		'OR',
+	            		'to',
+	            		'*',
+	            		param
+	            	],
+	        		[
+	            		'OR',
+	            		'subject',
+	            		'*',
+	            		param
+	            	],
+	            	[
+	            		'OR',
+	            		'folder',
+	            		'*',
+	            		folder
+	            	],
+	            	[
+	            		'OR',
+	            		'body',
+	            		'*',
+	            		param
+	            	]
+	            ];
+	        }else{
+	        	var filters = [
+	        		[
+	        		 	'from',
+	        			'*',
+	        			param
+	        		],       	
+	        		[
+	            		'OR',
+	            		'to',
+	            		'*',
+	            		param
+	            	],
+	        		[
+	            		'OR',
+	            		'subject',
+	            		'*',
+	            		param
+	            	],
+	            	[
+	            		'OR',
+	            		'folder',
+	            		'*',
+	            		folder
+	            	]
+	            ];
+	        }
+			
+            var data = DataLayer.get( 'message', { filter: filters, criteria: { properties: { context: { folder: folder } } } }, true );
+
+            if(DataLayer.criterias['message:jqGridSearch']){
+				delete DataLayer.criterias['message:jqGridSearch'];	
+			}
+
+        	DataLayer.register( 'criterias', 'message:jqGridSearch', function( crit ){
+			    crit.properties = { context: { folder: folder } };
+
+			    return { filter: [ "msgNumber", "IN", data ], criteria: crit };
+			});
+            if(typeof(data) == 'object'){
+				grid.jqGrid("clearGridData", true);
+				grid.jqGrid('setGridParam',{datatype: "json", url: 'message:jqGridSearch'}).trigger("reloadGrid");
+
+            }else{
+            	$("#mailgrid-container").find(".loading").hide();
+            	grid.jqGrid("clearGridData", true);
+            }
+        }
+
+		var search_messages = function(param){
+            var grid = $("#message_attacher_grid");
+            var folder = $("#foldertree li span.selected").parent().attr("id");
+            
+            if(param == ""){
+                $('#foldertree [id="'+folder+'"]').trigger("click");
+                return;
+            }
+            $(".attach-message-search-input").val("");
+            if(folder.indexOf("local_messages_") == 0){
+                // Pesquisa pelas mensagens locais...
+                msgs = search_local_messsages(param, folder);
+            } else {
+                // Pesquisa pelo Imap...
+                return search_imap_messages(param, folder);
+            }
+
+            // Monta as mensagens na grid...
+            grid.jqGrid("clearGridData", true);
+            grid.jqGrid('setGridParam',{datatype: "local",data: msgs})
+            .trigger("reloadGrid");
+            //.jqGrid('setCaption', '<span class="'+child.attr('class')+'">'+child.attr('title')+'</span>');
+		}
+
 		var title = [get_lang("First page"), get_lang("Prev page"), get_lang("Next page"), get_lang("Last page")];
 		$("#first_message_attacher_grid_pager").attr("title",title[0]);
@@ -521,4 +922,43 @@
 		$("#next_message_attacher_grid_pager").attr("title",title[2]);
 		$("#last_message_attacher_grid_pager").attr("title",title[3]);
+		$("#mailgrid-container .ui-jqgrid-titlebar")
+		.append( DataLayer.render("../prototype/modules/attach_message/attachment_search.ejs") ).find(".ui-jqgrid-titlebar-close").hide()
+		.end().find(".attach-message-search-input").Watermark("Pesquisa...").keydown(function(e){
+			var param = $(this).val();
+			if($.ui.keyCode.ENTER == e.keyCode){
+				$("#mailgrid-container").find(".loading").show("fast", function(){
+					search_messages(param);
+				});
+			}
+			
+		}).end().find(".attach-message-search-checkbox").click(function(){
+            var msg;
+            if($(this).is(":checked")){
+                msg = get_lang("take off this option to disregard the message body in the search.");
+            } else {
+                msg = get_lang("take on this option to regard the message body in the search.");
+            }
+            $(".attach-message-search-div .button-body-msg-title").attr("title",msg);
+        });
+
+		$("#attach-message-search").button({
+			text: false,
+			icons: {
+				primary: "ui-icon-search"
+			}
+		}).next().button({
+			text: false,
+			icons: {
+				primary: "ui-icon-script"
+			}
+		});
+		$("#attach-message-search").parent().buttonset();
+
+		$("#attach-message-search").click(function(){
+			var param = $(this).parents(".attach-message-search-div:first").find(".attach-message-search-input").val();
+			$("#mailgrid-container").find(".loading").show("fast", function(){
+				search_messages(param);
+			});	
+		});
 	}
 });
Index: branches/2.5/prototype/modules/attach_message/attachment_search.ejs
===================================================================
--- branches/2.5/prototype/modules/attach_message/attachment_search.ejs	(revision 8232)
+++ branches/2.5/prototype/modules/attach_message/attachment_search.ejs	(revision 8232)
@@ -0,0 +1,21 @@
+<div class="attach-message-search-div" style="position: absolute;right: 0px;top: 50%;margin: -10px 0 0 0;padding: 1px;height: 18px;">
+	<fieldset class="attach-message-search-field ui-corner-all" style="border: 0;margin: -10px 0 0 0;padding: 1px;height: 18px;position: relative;top: 50%;">
+        
+		<!--<span class="ui-icon ui-icon-search" style="position: absolute;right: 6px;top: 10%;"></span>
+		<input class="attach-message-search-checkbox" title="Selecione para buscar pelo conteudo da mensagem" type="checkbox" style="position: absolute;right: 20px;top: 10%;"> -->
+		<input class="attach-message-search-input" type="text" style="border-radius: 5px;border-right-color: white;border-right: 60px solid white;border-bottom: 1px solid white;border-top: 1px solid white;position: absolute;right: 9px;width: 170px;">
+		<span style="position: absolute; right: 5px; 
+		<% if(is_ie){ %>
+			top: 1px;">
+		<% }else if(is_webkit){ %>	
+			top: 4px;">
+		<% } else { %>	
+			top: 2px;">
+		<% } %>	
+			<button id="attach-message-search" title="Buscar mensagens" class="ui-icon ui-icon-search" style="position: absolute; right: 28px;"></button>
+    		<input type="checkbox" id="attach-message-search-options" class="attach-message-search-checkbox">
+            <label class="button-body-msg-title" style="width: 26px; height: 14px;" for="attach-message-search-options"><%= get_lang("take on this option to regard the message body in the search.") %></label>
+
+    	</span>
+	</fieldset>
+</div>
Index: branches/2.5/prototype/modules/filters/filters.css
===================================================================
--- branches/2.5/prototype/modules/filters/filters.css	(revision 7612)
+++ branches/2.5/prototype/modules/filters/filters.css	(revision 8232)
@@ -47,9 +47,10 @@
 
 .rule-list .rule .menu-control {
-	max-width:  100px;
+	max-width:  80px;
     float: right;
-	margin-top: -50px;
+	margin: -50px 5px;
 	white-space: nowrap;
 }
+
 .rule-list .rule .menu-control .select { vertical-align: bottom; }
 .rule-list .rule .menu-control .select input { margin: 5px 0 0 1px; }
@@ -122,4 +123,7 @@
 }
 .rule .menu-control .ui-button.disable,.rule .menu-control .ui-button.enable, .rule .menu-control .ui-button.update, .rule .menu-control .ui-button.close  { top:5px; }
+
+.rule .menu-control .ui-button.hidden { display: none; }
+
 .filter-manager-window .ui-accordion-icons .ui-accordion-header a { padding-left: 2.2em; }
 
Index: branches/2.5/prototype/modules/filters/interceptors/FilterMapping.php
===================================================================
--- branches/2.5/prototype/modules/filters/interceptors/FilterMapping.php	(revision 7726)
+++ branches/2.5/prototype/modules/filters/interceptors/FilterMapping.php	(revision 8232)
@@ -550,6 +550,8 @@
 		$actions['type'] = $rule_apply['actions'][0]['type'];
 		$actions['parameter'] = $rule_apply['actions'][0]['parameter'];
-		/* Hardcoded */
-		$actions['keep'] = false;
+
+		$actions['keep'] = is_array($rule_apply['actions'][1]);
+		if ($actions['keep'])
+			$actions['value'] = $rule_apply['actions'][0]['parameter'];
 
 		//$messages = $rule_apply['applyMessages'];
Index: branches/2.5/prototype/modules/filters/filters.js
===================================================================
--- branches/2.5/prototype/modules/filters/filters.js	(revision 7863)
+++ branches/2.5/prototype/modules/filters/filters.js	(revision 8232)
@@ -2,18 +2,22 @@
  * Retorna as regras por remetente e que o usuário deseja ser avisado 
  */
-function getFromAlertRules() { 
-	var filters = DataLayer.get("filter");
-	fromRules = [];
-	var alertMessage;
-	var active;
-	for (var index in filters) {
-		alertMessage = filters[index]['alertMessage'];		
-		active = filters[index]['enabled'];
-		for(var criterias in filters[index]['actions']) {
-			if (filters[index]['actions'][criterias]['type'] == 'fileinto' && alertMessage == 'true' && active == 'true')
-				fromRules[fromRules.length] = filters[index]['actions'][criterias]['parameter'];
-		}
-	}
-	return fromRules;
+function getFromAlertRules() {
+    fromRules = [];
+    if(preferences['use_alert_filter_criteria'] == "1")
+    {
+        var filters = DataLayer.get("filter");
+        var alertMessage;
+        var active;
+        for (var index in filters) {
+            alertMessage = filters[index]['alertMessage'];
+            active = filters[index]['enabled'];
+            for(var criterias in filters[index]['actions']) {
+                if (filters[index]['actions'][criterias]['type'] == 'fileinto' && alertMessage == 'true' && active == 'true')
+                    fromRules[fromRules.length] = filters[index]['actions'][criterias]['parameter'];
+            }
+        }
+
+    }
+    return fromRules;
 }
 
@@ -401,6 +405,8 @@
 });
 
-
-fromRules = getFromAlertRules();
+if(preferences['use_alert_filter_criteria'] == "1")
+{
+    fromRules = getFromAlertRules();
+}
 
 var BASE_PATH = '../prototype/';
@@ -439,8 +445,20 @@
 	}
 	if(confirm(get_lang("Want to block the user") + " " + email + "?")){
+        var has_folder_spam = false;
+        var folder_spam = "INBOX"+cyrus_delimiter+"Spam";
+        $.each(cp_tree1, function(index, value){
+            if(value.id == folder_spam){
+                has_folder_spam = true;
+                return;
+            }
+        });
+        if(!has_folder_spam){
+            connector.loadScript('TreeS');
+            create_new_folder("Spam","INBOX");
+        }
 		DataLayer.put( 'filter', idd,
 					{ name: email, isExact: false,
 						criteria:{ 0: {value: email, operator: "=", field: "from"} },
-						actions: { 0: {parameter: "INBOX" + cyrus_delimiter + "Spam", type: "fileinto"}},
+						actions: { 0: {parameter: folder_spam, type: "fileinto"}},
 						enabled: true,
 						id: email,
@@ -461,4 +479,13 @@
 
 DataLayer.codec( 'message', 'jqGrid', {
+
+      encoder: function( data ){
+
+	  return( data );
+
+      }
+});
+
+DataLayer.codec( 'message', 'jqGridSearch', {
 
       encoder: function( data ){
@@ -491,6 +518,6 @@
 	var criterias_ = new Array();
 
-    var isExact = (list_container.find('[name="isExact"]:checked').val() == 'and') ? 'yes' : 'no'; 
- 
+    var isExact = (list_container.find('[name="isExact"]:checked').val() == 'and') ? 'yes' : 'no';
+
 	for (i in criteria_)
 		if(criteria_[i] != "")
@@ -605,51 +632,21 @@
  * Lista os filtros para o usuário
  */
-function list_filters(html){
+function list_filters(html) { 
 	outOfficeVerify();
-	for (var index in selectedMessages) {
+	for (var index in selectedMessages) 
+	{
 		delete selectedMessages[index];
 	}
-	if(html){
-		if( ! $(".filters-windows").length )
-			container = $('.expressomail-module-container').append("<div class='filters-windows'></div>").find(".filters-windows").html( html ).find(".expresso-window-container");
-		list_container = $('.expressomail-module-container').find(".rule-list-container");
-	}
-	list_container = $(".expresso-window-filters").dialog({
-		title: get_lang('Filters'),
-	    width:700,
-	    modal: true,
-		resizable: false,
-	    closeOnEscape:true,
-	    close:function(event, ui) {
-		    event.stopPropagation();
-			if(list_container.find(".cancel").length)
-				list_container.find(".cancel").trigger('click');
-			$(".dialog-head-buttonpane").hide();
-	    },
-		open: function () {
-			$(".ui-dialog .ui-dialog-titlebar")
-			.append('<a href="#" class="ui-dialog-titlebar-minimize ui-corner-all" role="button"><span class="ui-icon ui-icon-minusthick">minimize</span></a>')
-			.find('.ui-dialog-titlebar-minimize').click(function() {
-				$(".ui-dialog-buttonpane, .ui-dialog-content").toggle();
-				$(".ui-icon-minusthick, .ui-icon-newwin").toggleClass('ui-icon-minusthick').toggleClass('ui-icon-newwin');
-			});
-			$(".dialog-head-buttonpane").show();
-		},
-	    autoOpen: false,
-		buttons: [{
-			text : get_lang("Close"),
-			click : function() {
-				$( this ).dialog( "close" );
-			}
-		}]
-    });
-	$(".ui-dialog-titlebar").after("<div class='dialog-head-buttonpane ui-dialog-buttonpane ui-widget-content ui-helper-clearfix' style='background-color: rgb(224, 238, 238); '><div class='ui-dialog-buttonset header-buttonpane'></div></div>");
-	$(".dialog-head-buttonpane").css("padding", "5px").
-	find(".header-buttonpane").html("<a href='#' class='button add' title='"+get_lang("Add new rule")+"'>"+get_lang("New rule")+"</a>"+(!outoffice ? "<a href='#' class='button add vacation' title='"+get_lang("Add rule out of office")+"'>"+get_lang("Out of office")+"</a>" : "")).find(".button").button();
-
-	$(".ui-dialog-buttonpane.ui-widget-content").css("background-color", "#E0EEEE");
+ 
+	initialize_container(html); // Inicializa o container do diálogo de filtros 
+ 
+	list_container = create_filter_dialog(); // Cria a estrutura básica do diálogo 
+	
 	var list = DataLayer.render( BASE_PATH + 'modules/filters/filter-list.ejs', DataLayer.get("filter:detail", true));
 	list_container.html(list).find(".button").button();
-
+    list_container.find(".alldelete").button("disable");
+    list_container.find(".alldisable").button("disable");
+    list_container.find(".allenable").button("disable");
+    
 	list_container.find(".rule-list").selectable({
 		selecting: function(event, ui) {
@@ -660,4 +657,16 @@
 		}
 	});
+
+    list_container.find(".rule-list li").click(function(){
+        if(list_container.find(".select").children("input:checked").length){
+            list_container.find(".alldelete").button("enable");
+            list_container.find(".alldisable").button("enable");
+            list_container.find(".allenable").button("enable");
+        } else {
+            list_container.find(".alldelete").button("disable");
+            list_container.find(".alldisable").button("disable");
+            list_container.find(".allenable").button("disable");
+        }
+    });
 
 	list_container.find( ".menu-control .button" ).filter(".update").button({
@@ -716,4 +725,6 @@
 						DataLayer.render( BASE_PATH + 'modules/filters/init.ejs', {},list_filters);
 						getFromAlertRules();
+						if (get_current_folder() == "INBOX")
+							cExecute ("$this.imap_functions.get_range_msgs2&folder=INBOX&msg_range_begin=1&msg_range_end="+preferences.max_email_per_page+"&sort_box_type=SORTARRIVAL&search_box_type=ALL&sort_box_reverse=1", handler_draw_box);
 					});
 
@@ -868,39 +879,5 @@
 
 	list_container.parent().find(".button.add:first").click(function(){
-		list_container.parent().find(".dialog-head-buttonpane").addClass("hidden");
-		DataLayer.render( BASE_PATH + 'modules/filters/edit-filter.ejs', {folders : DataLayer.get("folder", true), delimiter: cyrus_delimiter},function(html){
-			list_container.html(html);
-			var accord = list_container.find(".rule-details-container").accordion({autoHeight: false});
-			list_container.find(".button").button().filter(".forth").click(function(){
-				accord.accordion('activate',1);
-			}).end().filter(".forth2").click(function(){
-				accord.accordion('activate',2);
-			}).end().filter(".back").click(function(){
-				accord.accordion('activate',0);
-			}).end().filter(".back2").click(function(){
-				accord.accordion('activate',1);
-			}).end().filter(".cancel").click(function(){
-				DataLayer.render( BASE_PATH + 'modules/filters/init.ejs', {},list_filters);
-			}).end().filter(".submit").click(function() {
-				if(valid_save())
-					$(this).submit();
-				else
-					return;
-				DataLayer.commit( 'filter',false,function(){
-					if($('#gbox_fields-search-messages-grid').length > 0 && action != '') {
-						for (var index in selectedMessages) {
-							set_message_flag(index, action, false);
-						}
-					}
-					DataLayer.render( BASE_PATH + 'modules/filters/init.ejs', {},list_filters);
-					getFromAlertRules();
-				});
-			}).end().filter('.button.search').click(function() {
-				if(valid_save())
-					showGridMessages($(this));
-				else
-					return;
-			}); // end function click
-		});	// end DataLayer.render
+		render_new_rule(); // Renderiza a tela de criação de nova regra de filtragem. 
 	});
 	list_container.parent().find(".button.add.vacation").click(function(){
@@ -932,4 +909,120 @@
 }
 
+/* 
+	Inicializa o container do diálogo de gerenciamento de filtros. 
+*/ 
+function initialize_container (html) { 
+	if(html) 
+	{ 
+		if(!$(".filters-windows").length)  
+		{ 
+			container = $('.expressomail-module-container').append("<div class='filters-windows'></div>").find(".filters-windows").html(html).find(".expresso-window-container"); 
+		} 
+	} 
+} 
+ 
+/* 
+	Cria a estrutura básica do diálogo de gerenciamento de filtros. 
+*/ 
+function create_filter_dialog () { 
+	var dialog = $(".expresso-window-filters").dialog( 
+	{ 
+		title: get_lang('Filters'), 
+		width: 700, 
+		modal: true, 
+		resizable: false, 
+		closeOnEscape: true, 
+		close: function(event, ui) 
+		{ 
+			event.stopPropagation(); 
+			if(list_container.find(".cancel").length) list_container.find(".cancel").trigger('click'); 
+			$(".dialog-head-buttonpane").hide(); 
+		}, 
+		open: function() 
+		{ 
+			$(".ui-dialog .ui-dialog-titlebar").append('<a href="#" class="ui-dialog-titlebar-minimize ui-corner-all" role="button"><span class="ui-icon ui-icon-minusthick">minimize</span></a>').find('.ui-dialog-titlebar-minimize').click(function() 
+			{ 
+				$(".ui-dialog-buttonpane, .ui-dialog-content").toggle(); 
+				$(".ui-icon-minusthick, .ui-icon-newwin").toggleClass('ui-icon-minusthick').toggleClass('ui-icon-newwin'); 
+			}); 
+			$(".dialog-head-buttonpane").show(); 
+		}, 
+		autoOpen: false, 
+		buttons: [ 
+		{ 
+			text: get_lang("Close"), 
+			click: function() 
+			{ 
+				$(this).dialog("close"); 
+			} 
+		}] 
+	}); 
+ 
+	$(".ui-dialog-titlebar").after("<div class='dialog-head-buttonpane ui-dialog-buttonpane ui-widget-content ui-helper-clearfix' style='background-color: rgb(224, 238, 238); '><div class='ui-dialog-buttonset header-buttonpane'></div></div>"); 
+	$(".dialog-head-buttonpane").css("padding", "5px"). 
+	find(".header-buttonpane").html("<a href='#' class='button add' title='" + get_lang("Add new rule") + "'>" + get_lang("New rule") + "</a>" + (!outoffice ? "<a href='#' class='button add vacation' title='" + get_lang("Add rule out of office") + "'>" + get_lang("Out of office") + "</a>" : "")).find(".button").button(); 
+	$(".ui-dialog-buttonpane.ui-widget-content").css("background-color", "#E0EEEE"); 
+ 
+	return dialog; 
+} 
+ 
+/* 
+	Renderiza a tela de adição de uma nova regra de filtragem,  
+	dentro do diálogo de gerenciamento de filtros. 
+*/ 
+function render_new_rule (from, subject) { 
+	list_container.parent().find(".dialog-head-buttonpane").addClass("hidden"); 
+	var data = { 
+		folders: DataLayer.get("folder", true), 
+		delimiter: cyrus_delimiter, 
+		from: from, 
+		subject: subject ? html_entities(subject) : subject 
+	} 
+ 
+	DataLayer.render(BASE_PATH + 'modules/filters/edit-filter.ejs', data, function(html) 
+	{ 
+		list_container.html(html); 
+		var accord = list_container.find(".rule-details-container").accordion( 
+		{ 
+			autoHeight: false 
+		}); 
+		list_container.find(".button").button().filter(".forth").click(function() 
+		{ 
+			accord.accordion('activate', 1); 
+		}).end().filter(".forth2").click(function() 
+		{ 
+			accord.accordion('activate', 2); 
+		}).end().filter(".back").click(function() 
+		{ 
+			accord.accordion('activate', 0); 
+		}).end().filter(".back2").click(function() 
+		{ 
+			accord.accordion('activate', 1); 
+		}).end().filter(".cancel").click(function() 
+		{ 
+			DataLayer.render(BASE_PATH + 'modules/filters/init.ejs', {}, list_filters); 
+		}).end().filter(".submit").click(function() 
+		{ 
+			if(valid_save()) $(this).submit(); 
+			else return; 
+			DataLayer.commit('filter', false, function() 
+			{ 
+				if($('#gbox_fields-search-messages-grid').length > 0 && action != '') 
+				{ 
+					for(var index in selectedMessages) 
+					{ 
+						set_message_flag(index, action, false); 
+					} 
+				} 
+				DataLayer.render(BASE_PATH + 'modules/filters/init.ejs', {}, list_filters); 
+				getFromAlertRules(); 
+			}); 
+		}).end().filter('.button.search').click(function() 
+		{ 
+			if(valid_save()) showGridMessages($(this)); 
+			else return; 
+		}); // end function click 
+	}); // end DataLayer.render 
+}
 
 /* Inicializa os filtros e chama o list_filters 
@@ -955,14 +1048,18 @@
 		}
 	}
-	$.each(fromRules, function(index, value) {
-		if(value == folder){
-			for(var i=0; i < filters_c['criteria'].length; i++){
-				if(filters_c['criteria'][i].field == 'from'){
-					from = filters_c['criteria'][i].value;
-				}
-			}
-			cExecute ("$this.imap_functions.removeFlagMessagesFilter&folder="+folder+"&from="+from, function(){}); 
-			return false;
-		}
-	});
-}
+
+    if(preferences['use_alert_filter_criteria'] == "1")
+    {
+        $.each(fromRules, function(index, value) {
+            if(value == folder){
+                for(var i=0; i < filters_c['criteria'].length; i++){
+                    if(filters_c['criteria'][i].field == 'from'){
+                        from = filters_c['criteria'][i].value;
+                    }
+                }
+                cExecute ("$this.imap_functions.removeFlagMessagesFilter&folder="+folder+"&from="+from, function(){});
+                return false;
+            }
+        });
+    }
+}
Index: branches/2.5/prototype/modules/filters/edit-filter.ejs
===================================================================
--- branches/2.5/prototype/modules/filters/edit-filter.ejs	(revision 7703)
+++ branches/2.5/prototype/modules/filters/edit-filter.ejs	(revision 8232)
@@ -28,5 +28,5 @@
 
 				</select>
-				<input type="text" name="criteriaValue[]" />
+				<input type="text" name="criteriaValue[]" value="<%= data.from %>" />
 				<input type="hidden" name="criteriaType[]" value="from"/>
 			</fieldset>
@@ -53,5 +53,5 @@
 
 				</select>
-				<input type="text" name="criteriaValue[]" />
+				<input type="text" name="criteriaValue[]" value="<%= data.subject %>" />
 				<input type="hidden" name="criteriaType[]" value="subject"/>
 			</fieldset>
@@ -128,6 +128,10 @@
 					%>
 				</select>
-				<input type="checkbox" name="actionType[]" value="alertMessage" class="alertMessage"/>
-				<label><%= get_lang("Alert message filter by sender")%></label>
+                <%
+                if(preferences['use_alert_filter_criteria'] == "1")
+                {%>
+                    <input type="checkbox" name="actionType[]" value="alertMessage" class="alertMessage"/>
+                    <label><%= get_lang("Alert message filter by sender")%></label>
+                <%}%>
 			</fieldset>
 			<fieldset>
Index: branches/2.5/prototype/modules/calendar/assetic.php
===================================================================
--- branches/2.5/prototype/modules/calendar/assetic.php	(revision 7664)
+++ branches/2.5/prototype/modules/calendar/assetic.php	(revision 8232)
@@ -87,6 +87,6 @@
 
 if (strpos($javaVersion,"java version") !== false){
-    $filterManager->set('yui_js', $compressor);    
-    $js->ensureFilter($filterManager->get('yui_js'));    
+    $filterManager->set('yui_js', $compressor);
+    $js->ensureFilter($filterManager->get('yui_js'));
 }
 
Index: branches/2.5/prototype/modules/calendar/interceptors/Notifications.php
===================================================================
--- branches/2.5/prototype/modules/calendar/interceptors/Notifications.php	(revision 8003)
+++ branches/2.5/prototype/modules/calendar/interceptors/Notifications.php	(revision 8232)
@@ -34,6 +34,6 @@
 	if (Config::regGet('noAlarm') !== false)
 	    return; //Escapa notificações caso a flag de noAlarm esteja ativa.
- 
- 
+
+
 
 	$organizers = array(); //Cache Organizadores
@@ -99,5 +99,5 @@
 	    $psUpdated = Controller::find(array('concept' => 'participant'), false, array('deepness' => '1', 'filter' => array('IN', 'id', $updated)));
 
- 
+
 	    foreach ($psUpdated as $i => $pUpdated) {
 		if ($pUpdated['isOrganizer'] == '1' && $pUpdated['delegatedFrom'] == '0'){
@@ -491,14 +491,14 @@
 
 	    if (count($part) > 0)
-        { 
-            $from = false; 
-            foreach($schedulable['participants'] as $v) 
-            { 
-                if($v['isOrganizer'] == 1) 
-                    $from =  $v; 
-            } 
- 
-            self::sendMail($data, $ical, implode(',', $part), $subject, 'notify_cancel_body' , $from ); 
-        } 
+        {
+            $from = false;
+            foreach($schedulable['participants'] as $v)
+            {
+                if($v['isOrganizer'] == 1)
+                    $from =  $v;
+            }
+
+            self::sendMail($data, $ical, implode(',', $part), $subject, 'notify_cancel_body' , $from );
+        }
 	}
     }
@@ -522,14 +522,14 @@
 	    $method = 'CANCEL';
 	    $notificationType = 'Cancelamento de Calendario';
-            $part = 'me'; 
-            self::mountStruture($schedulable['id'], $schedulable, false, $data, $subject, $ical, $part, $method, $notificationType); 
- 
-        $from = false; 
-        foreach($schedulable['participants'] as $v) 
-        { 
-            if($v['isOrganizer'] == 1) 
-                $from =  $v; 
-        } 
-            self::sendMail($data, $ical, $participant['user']['mail'], $subject, 'notify_cancel_body' , $from); 
+	    $part = 'me';
+	    self::mountStruture($schedulable['id'], $schedulable, false, $data, $subject, $ical, $part, $method, $notificationType);
+
+        $from = false;
+        foreach($schedulable['participants'] as $v)
+        {
+            if($v['isOrganizer'] == 1)
+                $from =  $v;
+        }
+ 	    self::sendMail($data, $ical, $participant['user']['mail'], $subject, 'notify_cancel_body' , $from);
 	}
     }
Index: branches/2.5/prototype/modules/calendar/interceptors/DBMapping.php
===================================================================
--- branches/2.5/prototype/modules/calendar/interceptors/DBMapping.php	(revision 8059)
+++ branches/2.5/prototype/modules/calendar/interceptors/DBMapping.php	(revision 8232)
@@ -164,35 +164,35 @@
 
     public function encodeSignatureAlarmType(&$uri, &$params, &$criteria, $original) {
-            $params['type'] = self::codeAlarmType($params['type']); 
-    } 
- 
-    public function schedulableSecurity(&$uri, &$params, &$criteria, $original) 
+	    $params['type'] = self::codeAlarmType($params['type']);
+    }
+
+    public function schedulableSecurity(&$uri, &$params, &$criteria, $original)
     {
- 
-        if( !isset($criteria['filter'][1]) || !$criteria['filter'][1] == 'uid') 
-        { 
-            $security = 'schedulable.id = calendarToSchedulable.schedulable'; 
-            $security .= ' AND calendar.id = calendarToSchedulable.calendar'; 
-            $security .= ' AND calendar.id = calendarSignature.calendar'; 
-            $security .= ' AND calendarSignature.user = ' . base64_encode(Config::me('uidNumber')); 
- 
-            $criteria['condition'] = $security; 
-        } 
-  
-    } 
- 
-    public function calendarSecurity(&$uri, &$params, &$criteria, $original) 
-    { 
-        $security = 'calendar.id = calendarSignature.calendar'; 
-        $security .= ' AND calendarSignature.user = ' . base64_encode(Config::me('uidNumber')); 
- 
-        $criteria['condition'] = $security; 
-    } 
- 
-    public function calendarSignatureSecurity(&$uri, &$params, &$criteria, $original) 
-    { 
-//        $security = 'calendarSignature.user = ' . base64_encode(Config::me('uidNumber')); 
-// 
-//        $criteria['condition'] = $security; 
+
+        if( !isset($criteria['filter'][1]) || !$criteria['filter'][1] == 'uid')
+        {
+            $security = 'schedulable.id = calendarToSchedulable.schedulable';
+            $security .= ' AND calendar.id = calendarToSchedulable.calendar';
+            $security .= ' AND calendar.id = calendarSignature.calendar';
+            $security .= ' AND calendarSignature.user = ' . base64_encode(Config::me('uidNumber'));
+
+            $criteria['condition'] = $security;
+        }
+
+    }
+
+    public function calendarSecurity(&$uri, &$params, &$criteria, $original)
+    {
+        $security = 'calendar.id = calendarSignature.calendar';
+        $security .= ' AND calendarSignature.user = ' . base64_encode(Config::me('uidNumber'));
+
+        $criteria['condition'] = $security;
+    }
+
+    public function calendarSignatureSecurity(&$uri, &$params, &$criteria, $original)
+    {
+//        $security = 'calendarSignature.user = ' . base64_encode(Config::me('uidNumber'));
+//
+//        $criteria['condition'] = $security;
     }
 
@@ -347,22 +347,22 @@
 	if (isset($original['properties']['exceptions'])) {
 	    $exceptions = explode(',', $original['properties']['exceptions']);
-            $event = Controller::read(array('concept' => 'schedulable', 'id' => $repeat['schedulable'])); 
- 
-        if(array_key_exists(0, $event)) $event = $event[0]; 
- 
-        $date = new DateTime('now', new DateTimeZone('UTC')); 
- 
-        foreach($exceptions as &$e){ 
-            $date->setTimestamp((int) ($e / 1000)); 
-            $date->setTimezone( new DateTimeZone( $event['timezone'] )); 
-            $e = ($date->getTimestamp() - $date->getOffset()).'000'; 
-        } 
- 
-        unset($repeat['exceptions']); 
+	    $event = Controller::read(array('concept' => 'schedulable', 'id' => $repeat['schedulable']));
+
+        if(array_key_exists(0, $event)) $event = $event[0];
+
+        $date = new DateTime('now', new DateTimeZone('UTC'));
+
+        foreach($exceptions as &$e){
+            $date->setTimestamp((int) ($e / 1000));
+            $date->setTimezone( new DateTimeZone( $event['timezone'] ));
+            $e = ($date->getTimestamp() - $date->getOffset()).'000';
+        }
+
+        unset($repeat['exceptions']);
 	}
 
-    unset($repeat['schedulable']); 
- 
-    $lastExceptions = Controller::find(array('concept' => 'repeatOccurrence'), array("occurrence"), array('filter' => array('AND', array('=', 'repeat', $id), array('=', 'exception', 1)))); 
+    unset($repeat['schedulable']);
+
+    $lastExceptions = Controller::find(array('concept' => 'repeatOccurrence'), array("occurrence"), array('filter' => array('AND', array('=', 'repeat', $id), array('=', 'exception', 1))));
 
 	//Recurepa as execeções anteriores caso exista
@@ -379,5 +379,5 @@
 	else if(!empty($exceptions))
 	    Controller::service('PostgreSQL')->execResultSql("INSERT INTO calendar_repeat_occurrence(repeat_id,exception,occurrence)VALUES ('" . $id . "','1','" . implode("'),('" . $id . "','1','", $exceptions) . "')" );
-    } 
+    }
 
     public function checkOccurrences($start, $end, $calendarIds) {
@@ -428,22 +428,22 @@
 
 	    foreach ($result as $id => $res){
- 
-            $ocurrences = array_unique($res); 
- 
-            /* 
-             * Check current range decoded 
-             * */ 
-            $current = Controller::find(array('concept' => 'repeatOccurrence'), array("occurrence"), array('filter' => array('=', 'repeat', $id))); 
-            $toDiff = array(); 
- 
-            if(!empty($current)) 
-                foreach($current as $c) $toDiff[] = $c['occurrence']; 
- 
-            $ocurrences = array_diff($ocurrences, $toDiff); 
- 
-            if(!empty($ocurrences)) 
+
+            $ocurrences = array_unique($res);
+
+            /*
+             * Check current range decoded
+             * */
+            $current = Controller::find(array('concept' => 'repeatOccurrence'), array("occurrence"), array('filter' => array('=', 'repeat', $id)));
+            $toDiff = array();
+
+            if(!empty($current))
+                foreach($current as $c) $toDiff[] = $c['occurrence'];
+
+            $ocurrences = array_diff($ocurrences, $toDiff);
+
+            if(!empty($ocurrences))
                 Controller::service('PostgreSQL')->execResultSql("INSERT INTO calendar_repeat_occurrence(repeat_id,occurrence)VALUES('" . $id . "','" . implode("'),('" . $id . "', '", $ocurrences) . "')");
- 
-        } 
+
+        }
 	    $data = array();
 
@@ -471,5 +471,5 @@
 	$result = array();
 	$params = array();
-    $realResult = array(); 
+    $realResult = array();
 	foreach ($return as $ret) {
 	    $currentId = $ret['schedulable'];
@@ -483,15 +483,15 @@
 	}
 
-    foreach($result as $i => $v) 
-    { 
-        $calendarToCalendarObj = self::schedulable2calendarToObject($v['id']); 
-            foreach($calendarToCalendarObj as $vv) 
-            { 
-                $v['calendar'] = $vv['calendar_id']; 
-                $realResult[] = $v; 
-            } 
-    } 
- 
-        return( $realResult ); 
+    foreach($result as $i => $v)
+    {
+        $calendarToCalendarObj = self::schedulable2calendarToObject($v['id']);
+            foreach($calendarToCalendarObj as $vv)
+            {
+                $v['calendar'] = $vv['calendar_id'];
+                $realResult[] = $v;
+            }
+    }
+
+	return( $realResult );
     }
 
@@ -633,7 +633,7 @@
             //necessário para atulizar a atividade de composta pela tarefa aqui sendo atualizada
             if(isset($criteria['historic']['startTime']) || isset($criteria['historic']['endTime'])){
-                /* 
-                 * Verify current task is built-in activity 
-                 * */ 
+                /*
+                 * Verify current task is built-in activity
+                 * */
                 $taskToActivity = Controller::find(array('concept' => 'taskToActivity'), false, array('filter' => array('AND', array('=', 'task', $uri['id']), array('=', 'owner', Config::me('uidNumber'))), 'deepness' => 2));
                 if(!empty($taskToActivity)){
@@ -641,20 +641,20 @@
                     $isAllDay = 1;
 
-                    /* 
-                     * Get all task in activity 
-                     * */ 
-                    $taskToActivity = Controller::find(array('concept' => 'taskToActivity'), false, array('filter' => array('AND', array('=', 'activity', $taskToActivity[0]['activity']), array('=', 'owner', Config::me('uidNumber'))), 'deepness' => 2)); 
- 
+                    /*
+                     * Get all task in activity
+                     * */
+                    $taskToActivity = Controller::find(array('concept' => 'taskToActivity'), false, array('filter' => array('AND', array('=', 'activity', $taskToActivity[0]['activity']), array('=', 'owner', Config::me('uidNumber'))), 'deepness' => 2));
+
                     if(!empty($activity)){
                         $start = $params['startTime'];
                         $end = $params['endTime'];
                         foreach($taskToActivity as $t){
- 
- 
-                            if($t['task']['id'] != $params['id']){ 
-                                $start = $t['task']['startTime'] < $start ? $t['task']['startTime'] : $start; 
-                                $end = $t['task']['endTime'] > $end ? $t['task']['endTime'] : $end; 
-                                $isAllDay = (($isAllDay == 1) && ($t['task']['allDay'] == '1')) ? 1 : 0; 
-                            } 
+
+
+                            if($t['task']['id'] != $params['id']){
+                                $start = $t['task']['startTime'] < $start ? $t['task']['startTime'] : $start;
+                                $end = $t['task']['endTime'] > $end ? $t['task']['endTime'] : $end;
+                                $isAllDay = (($isAllDay == 1) && ($t['task']['allDay'] == '1')) ? 1 : 0;
+                            }
                         }
 
@@ -680,7 +680,7 @@
                 }
             }
-            /* 
-             * Clean historic not used 
-             * */ 
+            /*
+             * Clean historic not used
+             * */
             unset($criteria['historic']['endTime']);
             unset($criteria['historic']['rangeEnd']);
@@ -771,25 +771,25 @@
 	    }
 	}
-    } 
- 
-    static function autoImportCalendar(&$uri, &$params, &$criteria, $original){ 
-        $autoCommit = Controller::service('PostgreSQL')->execResultSql('Select config_value FROM phpgw_config WHERE config_app = \'expressoCalendar\' AND config_name = \'expressoCalendar_autoImportCalendars\''); 
- 
- 
-        if(isset($autoCommit[0]) && $autoCommit[0]['config_value'] == 'true') 
-        { 
-            if(isset($original['properties']) && isset($original['properties']['user'])  && isset($original['properties']['isOrganizer']) &&  $original['properties']['isOrganizer'] != '1') 
-            { 
-                $defaultCalendar = Controller::find(array('concept' => 'modulePreference'), array('value') , array('filter' => array( 'and' , array('=' , 'name' , 'dafaultImportCalendar') , array('=' , 'module' , 'expressoCalendar') , array('=' , 'user' , $original['properties']['user'])  )) ); 
-                if(isset($defaultCalendar[0]) && $defaultCalendar[0]['value'] > 0) 
-                { 
-                    Controller::create(array('concept' => 'calendarToSchedulable'), 
-                        array('schedulable' => $original['properties']['schedulable'], 
-                            'calendar' => $defaultCalendar[0]['value'] 
-                        ) 
-                    ); 
-                } 
-            } 
-        } 
+    }
+
+    static function autoImportCalendar(&$uri, &$params, &$criteria, $original){
+        $autoCommit = Controller::service('PostgreSQL')->execResultSql('Select config_value FROM phpgw_config WHERE config_app = \'expressoCalendar\' AND config_name = \'expressoCalendar_autoImportCalendars\'');
+
+
+        if(isset($autoCommit[0]) && $autoCommit[0]['config_value'] == 'true')
+        {
+            if(isset($original['properties']) && isset($original['properties']['user'])  && isset($original['properties']['isOrganizer']) &&  $original['properties']['isOrganizer'] != '1')
+            {
+                $defaultCalendar = Controller::find(array('concept' => 'modulePreference'), array('value') , array('filter' => array( 'and' , array('=' , 'name' , 'dafaultImportCalendar') , array('=' , 'module' , 'expressoCalendar') , array('=' , 'user' , $original['properties']['user'])  )) );
+                if(isset($defaultCalendar[0]) && $defaultCalendar[0]['value'] > 0)
+                {
+                    Controller::create(array('concept' => 'calendarToSchedulable'),
+                        array('schedulable' => $original['properties']['schedulable'],
+                            'calendar' => $defaultCalendar[0]['value']
+                        )
+                    );
+                }
+            }
+        }
     }
 
@@ -913,27 +913,27 @@
     }
 
-    public function getCalendarTask( $task ){ 
- 
-        $sql = 'select co.calendar_id as "calendar" from calendar_to_calendar_object as "co", calendar_signature as "cs" where cs.user_uidnumber = '. Config::me('uidNumber') 
-            .' AND cs.is_owner = 1 AND cs.calendar_id = co.calendar_id AND co.calendar_object_id = '. $task; 
- 
- 
-        $returns = Controller::service('PostgreSQL')->execResultSql($sql); 
- 
-        return $returns[0]['calendar']; 
-    } 
- 
+    public function getCalendarTask( $task ){
+
+        $sql = 'select co.calendar_id as "calendar" from calendar_to_calendar_object as "co", calendar_signature as "cs" where cs.user_uidnumber = '. Config::me('uidNumber')
+            .' AND cs.is_owner = 1 AND cs.calendar_id = co.calendar_id AND co.calendar_object_id = '. $task;
+
+
+        $returns = Controller::service('PostgreSQL')->execResultSql($sql);
+
+        return $returns[0]['calendar'];
+    }
+
     //TODO: Remover apos suporte a deepness na api 
     public function deepnessFindTask(&$uri, &$result, &$criteria, $original) {
-        if (isset($criteria['deepness']) && $criteria['deepness'] != 0){ 
- 
-            foreach($result as &$value){ 
- 
+        if (isset($criteria['deepness']) && $criteria['deepness'] != 0){
+
+            foreach($result as &$value){
+
                 $value['task'] = Controller::read(array('concept' => 'schedulable', 'id' => $value['task']));
-                $value['task']['calendar'] = self::getCalendarTask( $value['task']['id'] ); 
-            } 
- 
-            return $result; 
-        } 
+                $value['task']['calendar'] = self::getCalendarTask( $value['task']['id'] );
+            }
+
+            return $result;
+        }
     }
 
@@ -972,24 +972,24 @@
                 .'calendar_object.tzid as "timezone", calendar_to_calendar_object.calendar_id as "calendar" '
                 .'FROM calendar_object, calendar_to_calendar_object '
-                .'WHERE ( calendar_object.id = '. $criteria['schedulable'] .' AND calendar_to_calendar_object.calendar_object_id = calendar_object.id' 
-                .' AND calendar_to_calendar_object.calendar_id IN (select calendar_id from calendar_signature where calendar_signature.user_uidnumber = '. Config::me('uidNumber') .' )         )'; 
+                .'WHERE ( calendar_object.id = '. $criteria['schedulable'] .' AND calendar_to_calendar_object.calendar_object_id = calendar_object.id'
+                .' AND calendar_to_calendar_object.calendar_id IN (select calendar_id from calendar_signature where calendar_signature.user_uidnumber = '. Config::me('uidNumber') .' )         )';
 
             $params = Controller::service('PostgreSQL')->execResultSql($sql);
- 
-            foreach( $params as &$event ){ 
- 
- 
-                if(isset( $event['repeat'] ) && isset( $event['repeat']['id'] ) ){ 
-                    $occurrences = Controller::service('PostgreSQL')->execResultSql('SELECT DISTINCT occurrence FROM calendar_object as "c", calendar_repeat_occurrence as "o", calendar_repeat as "r" WHERE r.object_id = '. $event['id'] .' AND o.repeat_id = r.id ' ); 
- 
-                    if($occurrences){ 
-                        $event['occurrences'] = array(); 
- 
-                        foreach($occurrences as $o) 
-                            $event['occurrences'][] = $o['occurrence']; 
-                    }else 
-                        unset( $event['occurrences'] ); 
-                } 
-            } 
+
+            foreach( $params as &$event ){
+
+
+                if(isset( $event['repeat'] ) && isset( $event['repeat']['id'] ) ){
+                    $occurrences = Controller::service('PostgreSQL')->execResultSql('SELECT DISTINCT occurrence FROM calendar_object as "c", calendar_repeat_occurrence as "o", calendar_repeat as "r" WHERE r.object_id = '. $event['id'] .' AND o.repeat_id = r.id ' );
+
+                    if($occurrences){
+                        $event['occurrences'] = array();
+
+                        foreach($occurrences as $o)
+                            $event['occurrences'][] = $o['occurrence'];
+                    }else
+                        unset( $event['occurrences'] );
+                }
+            }
 
             $params = self::deepnessFindEvent($uri, $params, $criteria, $original);
@@ -1047,10 +1047,10 @@
                 if(isset( $v['occurrences'] ) && count( $v['occurrences'] ) > 0){
 
-                    $date->setTimestamp((int) ($v['startTime'] / 1000)); 
-                    $date->setTimezone( new DateTimeZone( $v['timezone'] )); 
- 
+                    $date->setTimestamp((int) ($v['startTime'] / 1000));
+                    $date->setTimezone( new DateTimeZone( $v['timezone'] ));
+
                     foreach( $result[$i]['occurrences'] as &$o){
 
-                        $o = ($o + $date->getOffset()).'000'; 
+                        $o = ($o + $date->getOffset()).'000';
 
                     }
@@ -1421,20 +1421,20 @@
 
 	    Controller::delete(array('concept' => 'calendar', 'id' => $signature['calendar']));
- 
-        $autoCommit = Controller::service('PostgreSQL')->execResultSql('Select config_value FROM phpgw_config WHERE config_app = \'expressoCalendar\' AND config_name = \'expressoCalendar_autoImportCalendars\''); 
- 
-        if(isset($autoCommit[0]) && $autoCommit[0]['config_value'] == 'true') 
-        { 
-            $defaultCalendar = Controller::find(array('concept' => 'modulePreference'), array('value','id') , array('filter' => array( 'and' , array('=' , 'name' , 'dafaultImportCalendar') , array('=' , 'module' , 'expressoCalendar') , array('=' , 'user' , $signature['user'])  )) ); 
- 
- 
-            if(isset($defaultCalendar[0])  && $defaultCalendar[0]['value'] == $signature['calendar'] ) 
-            { 
-                Controller::delete(array('concept' => 'modulePreference', 'id' => $defaultCalendar[0]['id'])); 
-            } 
-        } 
- 
-        $permissions = Controller::find(array('concept' => 'calendarToPermission'), array('id'), array('filter' => array('=', 'calendar', $signature['calendar']))); 
- 
+
+        $autoCommit = Controller::service('PostgreSQL')->execResultSql('Select config_value FROM phpgw_config WHERE config_app = \'expressoCalendar\' AND config_name = \'expressoCalendar_autoImportCalendars\'');
+
+        if(isset($autoCommit[0]) && $autoCommit[0]['config_value'] == 'true')
+        {
+            $defaultCalendar = Controller::find(array('concept' => 'modulePreference'), array('value','id') , array('filter' => array( 'and' , array('=' , 'name' , 'dafaultImportCalendar') , array('=' , 'module' , 'expressoCalendar') , array('=' , 'user' , $signature['user'])  )) );
+
+
+            if(isset($defaultCalendar[0])  && $defaultCalendar[0]['value'] == $signature['calendar'] )
+            {
+                Controller::delete(array('concept' => 'modulePreference', 'id' => $defaultCalendar[0]['id']));
+            }
+        }
+
+        $permissions = Controller::find(array('concept' => 'calendarToPermission'), array('id'), array('filter' => array('=', 'calendar', $signature['calendar'])));
+
 		if($permissions && count($permissions) > 0){
 			$ids = array();
@@ -1583,14 +1583,14 @@
                 }
 
-                if($i == 0) 
-                { 
-                    $pref = array(); 
-                    $pref['user'] = $_SESSION['wallet']['user']['uidNumber']; 
-                    $pref['value'] = $calCreated['id']; 
-                    $pref['name'] = 'dafaultImportCalendar' ; 
-                    $pref['module'] = 'expressoCalendar'; 
-                    Controller::create(array('concept' => 'modulePreference'), $pref); 
-                } 
- 
+                if($i == 0)
+                {
+                    $pref = array();
+                    $pref['user'] = $_SESSION['wallet']['user']['uidNumber'];
+                    $pref['value'] = $calCreated['id'];
+                    $pref['name'] = 'dafaultImportCalendar' ;
+                    $pref['module'] = 'expressoCalendar';
+                    Controller::create(array('concept' => 'modulePreference'), $pref);
+                }
+
     		}
 	    } else {
@@ -1614,14 +1614,14 @@
 
     		$sigCreated = Controller::create(array('concept' => 'calendarSignature'), $sig);
- 
- 
-            $pref = array(); 
-            $pref['user'] = $_SESSION['wallet']['user']['uidNumber']; 
-            $pref['value'] = $calCreated['id']; 
-            $pref['name'] = 'dafaultImportCalendar' ; 
-            $pref['module'] = 'expressoCalendar'; 
-            Controller::create(array('concept' => 'modulePreference'), $pref); 
- 
- 
+
+
+            $pref = array();
+            $pref['user'] = $_SESSION['wallet']['user']['uidNumber'];
+            $pref['value'] = $calCreated['id'];
+            $pref['name'] = 'dafaultImportCalendar' ;
+            $pref['module'] = 'expressoCalendar';
+            Controller::create(array('concept' => 'modulePreference'), $pref);
+
+
         }
     
@@ -1634,64 +1634,64 @@
     //TODO - Criar conceito separado para participantes externos e remover o criterio notExternal
     public function findExternalPaticipants(&$uri, &$result, &$criteria, $original) {
-        if (Config::me('uidNumber') && !isset($criteria['notExternal'])) { 
-            $newuri['concept'] = 'user'; 
-            $newuri['service'] = 'PostgreSQL'; 
- 
-            $newCriteria = $original['criteria']; 
-            $valid = true; 
- 
-            $newCriteria['filter'] = array('AND', $newCriteria['filter'], array('=', 'owner', Config::me('uidNumber'))); 
-            $externalUsers = Controller::find($newuri, $original['properties'] ? $original['properties'] : null, $newCriteria ); 
- 
-            if (!is_array($result)) 
-                $result = array(); 
- 
-            if (is_array($externalUsers)) { 
-                foreach ($externalUsers as $i => $v) 
-                    $externalUsers[$i]['isExternal'] = '1'; 
-            } 
-            else 
-                $externalUsers = array(); 
- 
-            $result = array_merge($result, $externalUsers); 
- 
- 
-            if(isset($original['criteria']['externalCatalogs']) &&  $original['criteria']['externalCatalogs'] == true) 
-            { 
-                $externalCatalogs = self::findExternalCatalogContacts($original['criteria']['filter'][2]); 
- 
-                foreach($externalCatalogs as $i => $v) 
-                { 
-                    $exist = false; 
-                    foreach($result as $vv) 
-                    { 
-                        if($v['mail'] == $vv['mail'] ) 
-                            $exist = true; 
-                    } 
-                    if(!$exist) 
-                        $result[] = $v; 
-                } 
-            } 
- 
- 
-            if(isset($original['criteria']['personalContacts']) &&  $original['criteria']['personalContacts'] == true) 
-            { 
-                $personalContacts = self::findPersonalContacts($original['criteria']['filter'][2]); 
- 
-                foreach($personalContacts as $i => $v) 
-                { 
-                    $exist = false; 
-                    foreach($result as $vv) 
-                    { 
-                        if($v['mail'] == $vv['mail'] ) 
-                            $exist = true; 
-                    } 
-                    if(!$exist) 
-                        $result[] = $v; 
-                } 
-            } 
- 
-            return $result ; 
-        } 
+        if (Config::me('uidNumber') && !isset($criteria['notExternal'])) {
+            $newuri['concept'] = 'user';
+            $newuri['service'] = 'PostgreSQL';
+
+            $newCriteria = $original['criteria'];
+            $valid = true;
+
+            $newCriteria['filter'] = array('AND', $newCriteria['filter'], array('=', 'owner', Config::me('uidNumber')));
+            $externalUsers = Controller::find($newuri, $original['properties'] ? $original['properties'] : null, $newCriteria );
+
+            if (!is_array($result))
+                $result = array();
+
+            if (is_array($externalUsers)) {
+                foreach ($externalUsers as $i => $v)
+                    $externalUsers[$i]['isExternal'] = '1';
+            }
+            else
+                $externalUsers = array();
+
+            $result = array_merge($result, $externalUsers);
+
+
+            if(isset($original['criteria']['externalCatalogs']) &&  $original['criteria']['externalCatalogs'] == true)
+            {
+                $externalCatalogs = self::findExternalCatalogContacts($original['criteria']['filter'][2]);
+
+                foreach($externalCatalogs as $i => $v)
+                {
+                    $exist = false;
+                    foreach($result as $vv)
+                    {
+                        if($v['mail'] == $vv['mail'] )
+                            $exist = true;
+                    }
+                    if(!$exist)
+                        $result[] = $v;
+                }
+            }
+
+
+            if(isset($original['criteria']['personalContacts']) &&  $original['criteria']['personalContacts'] == true)
+            {
+                $personalContacts = self::findPersonalContacts($original['criteria']['filter'][2]);
+
+                foreach($personalContacts as $i => $v)
+                {
+                    $exist = false;
+                    foreach($result as $vv)
+                    {
+                        if($v['mail'] == $vv['mail'] )
+                            $exist = true;
+                    }
+                    if(!$exist)
+                        $result[] = $v;
+                }
+            }
+
+            return $result ;
+        }
     }
 
@@ -1812,245 +1812,245 @@
             && ($timestamp >= ~PHP_INT_MAX);
     }
- 
-    static function findExternalCatalogContacts( $search ) 
-    { 
-            $result = array(); 
-            $external_srcs = array(); 
-            $external_mappings = array(); 
- 
-            include_once dirname(__DIR__) .'/../../../contactcenter/setup/external_catalogs.inc.php'; 
- 
-            $search = str_replace(' ', '*', $search) ; 
-            $search = '*' . $search . '*'; 
- 
-            foreach($external_srcs as $i => $v) 
-            { 
-                $con = ldap_connect($v['host']); 
- 
-                ldap_set_option( $con , LDAP_OPT_PROTOCOL_VERSION , 3 ); 
- 
-                if( isset( $v['acc'] ) && isset( $v['pw'] ) ) 
-                    ldap_bind( $con, $v['acc'], $v['pw'] ); 
- 
-                $fields = array(); 
-                $fields[] = $external_mappings[$i]['contact.names_ordered'][0]; 
-                $fields[] = $external_mappings[$i]['contact.connection.typeof_connection.contact_connection_type_name']['email'][0]; 
- 
-                $ldapFilter = '(&(objectClass='.$v['obj'].')(|('.$fields[0].'='.$search.')('.$fields[1].'='.$search.')))'; 
-                $sr =  ldap_search( $con, utf8_encode($v['dn']) , $ldapFilter , $fields ); 
-                if($sr) 
-                { 
-                    $search = ldap_get_entries($con, $sr); 
- 
-                    for ($j = 0; $j < $search["count"]; ++$j) { 
-                        $tmp = array(); 
-                        $tmp['name'] = $search[$j][$fields[0]][0]; 
-                        $tmp['mail'] = $search[$j][$fields[1]][0]; 
-                        $tmp['isExternal'] = '1'; 
- 
-                        $result[] = $tmp; 
-                    } 
-                } 
-            } 
-            return $result; 
-    } 
- 
-    static function findPersonalContacts($search_for) 
-    { 
- 
-              $query = 'select' 
- 
-                . ' C.id_connection,' 
-                . ' A.id_contact,' 
-                . ' A.names_ordered,' 
-                . ' A.alias,' 
-                . ' A.birthdate,' 
-                . ' A.sex,' 
-                . ' A.pgp_key,' 
-                . ' A.notes,' 
-                . ' A.web_page,' 
-                . ' A.corporate_name,' 
-                . ' A.job_title,' 
-                . ' A.department,' 
-                . ' C.connection_name,' 
-                . ' C.connection_value,' 
-                . ' B.id_typeof_contact_connection,' 
-                . ' phpgw_cc_contact_addrs.id_typeof_contact_address,' 
-                . ' phpgw_cc_addresses.address1,' 
-                . ' phpgw_cc_addresses.address2,' 
-                . ' phpgw_cc_addresses.complement,' 
-                . ' phpgw_cc_addresses.postal_code,' 
-                . ' phpgw_cc_city.city_name,' 
-                . ' phpgw_cc_state.state_name,' 
-                . ' phpgw_cc_addresses.id_country' 
-            ; 
- 
-            $query .= ' from' 
-                . ' phpgw_cc_contact A' 
-                . ' inner join phpgw_cc_contact_conns B on ( A.id_contact = B.id_contact )' 
-                . ' inner join phpgw_cc_connections C on ( B.id_connection = C.id_connection )' 
-                . ' left join phpgw_cc_contact_addrs on ( A.id_contact = phpgw_cc_contact_addrs.id_contact )' 
-                . ' left join phpgw_cc_addresses on ( phpgw_cc_contact_addrs.id_address = phpgw_cc_addresses.id_address )' 
-                . ' left join phpgw_cc_city on ( phpgw_cc_addresses.id_city = phpgw_cc_city.id_city )' 
-                . ' left join phpgw_cc_state on ( phpgw_cc_addresses.id_state = phpgw_cc_state.id_state)' 
-            ; 
- 
-            $query .= ' where ' 
-                . 'A.id_owner=' . Config::me('uidNumber') 
-                . ' and lower(translate(names_ordered, \'áàâãäéèêëíìïóòôõöúùûüÁÀÂÃÄÉÈÊËÍÌÏÓÒÔÕÖÚÙÛÜçÇñÑ\',\'aaaaaeeeeiiiooooouuuuAAAAAEEEEIIIOOOOOUUUUcCnN\'))' 
-                . ' LIKE lower(translate(\'%' . $search_for . '%\', \'áàâãäéèêëíìïóòôõöúùûüÁÀÂÃÄÉÈÊËÍÌÏÓÒÔÕÖÚÙÛÜçÇñÑ\',\'aaaaaeeeeiiiooooouuuuAAAAAEEEEIIIOOOOOUUUUcCnN\'))'; 
- 
-            //Se não existir parametro na busca, limita os usuarios no resultado da pesquisa. 
-            if(!$search_for){ 
-                $query .= 'LIMIT 11'; 
-            } 
- 
-            $r = Controller::service('PostgreSQL')->execResultSql($query); 
- 
- 
-            $all_contacts = array(); 
-            foreach( $r as $i => $object ) 
-            { 
-                if ( ! array_key_exists( $object[ 'id_contact' ], $all_contacts ) ) 
-                    $all_contacts[ $object[ 'id_contact' ] ] = array( 
-                        'connection_value' => '', 
-                        'telephonenumber' => '', 
-                        'mobile' => '', 
-                        'cn' => '', 
-                        'id_contact' => '', 
-                        'id_connection' => '', 
-                        'alias' => '', 
-                        'birthdate' => '', 
-                        'sex' => '', 
-                        'pgp_key' => '', 
-                        'notes' => '', 
-                        'web_page' => '', 
-                        'corporate_name' => '', 
-                        'job_title' => '', 
-                        'department' => '', 
-                        'mail' => '', 
-                        'aternative-mail' => '', 
-                        'business-phone' => '', 
-                        'business-address' => '', 
-                        'business-complement' => '', 
-                        'business-postal_code' => '', 
-                        'business-city_name' => '', 
-                        'business-state_name' => '', 
-                        'business-id_country' => '', 
-                        'business-fax' => '', 
-                        'business-pager' => '', 
-                        'business-mobile' => '', 
-                        'business-address-2' => '', 
-                        'home-phone' => '', 
-                        'home-address' => '', 
-                        'home-complement' => '', 
-                        'home-postal_code' => '', 
-                        'home-city_name' => '', 
-                        'home-state_name' => '', 
-                        'home-fax' => '', 
-                        'home-pager' => '', 
-                        'home-address-2' => '' 
- 
- 
-                    ); 
- 
-                switch( $object[ 'id_typeof_contact_connection' ] ) 
-                { 
-                    case 1 : 
-                        $all_contacts[ $object[ 'id_contact' ] ][ 'connection_value' ] = $object[ 'connection_value' ]; 
-                        switch ( strtolower( $object[ 'connection_name' ] ) ) 
-                        { 
-                            case 'alternativo' : 
-                                $all_contacts[ $object[ 'id_contact' ] ][ 'alternative-mail' ] = $object[ 'connection_value' ]; 
-                                break; 
-                            case 'principal' : 
-                                $all_contacts[ $object[ 'id_contact' ] ][ 'mail' ] = $object[ 'connection_value' ]; 
-                                break; 
-                        } 
-                        break; 
-                    case 2 : 
-                        $all_contacts[ $object[ 'id_contact' ] ][ 'telephonenumber' ] = $object[ 'connection_value' ]; 
-                        switch ( strtolower( $object[ 'connection_name' ] ) ) 
-                        { 
-                            case 'casa' : 
-                                $all_contacts[ $object[ 'id_contact' ] ][ 'home-phone' ] = $object[ 'connection_value' ]; 
-                                break; 
-                            case 'celular' : 
-                                $all_contacts[ $object[ 'id_contact' ] ][ 'mobile' ] = $object[ 'connection_value' ]; 
-                                break; 
-                            case 'trabalho' : 
-                                $all_contacts[ $object[ 'id_contact' ] ][ 'business-phone' ] = $object[ 'connection_value' ]; 
-                                break; 
-                            case 'fax' : 
-                                $all_contacts[ $object[ 'id_contact' ] ][ 'home-fax' ] = $object[ 'connection_value' ]; 
-                                break; 
-                            case 'pager' : 
-                                $all_contacts[ $object[ 'id_contact' ] ][ 'home-pager' ] = $object[ 'connection_value' ]; 
-                                break; 
-                            case 'celular corporativo' : 
-                                $all_contacts[ $object[ 'id_contact' ] ][ 'business-mobile' ] = $object[ 'connection_value' ]; 
-                                break; 
-                            case 'pager corporativo' : 
-                                $all_contacts[ $object[ 'id_contact' ] ][ 'business-pager' ] = $object[ 'connection_value' ]; 
-                                break; 
-                            case 'fax corporativo' : 
-                                $all_contacts[ $object[ 'id_contact' ] ][ 'business-fax' ] = $object[ 'connection_value' ]; 
-                                break; 
-                        } 
-                        break; 
-                } 
- 
-                $all_contacts[ $object[ 'id_contact' ] ][ 'cn' ] = utf8_encode($object[ 'names_ordered' ]); 
-                $all_contacts[ $object[ 'id_contact' ] ][ 'id_contact' ]    = $object[ 'id_contact' ]; 
-                $all_contacts[ $object[ 'id_contact' ] ][ 'id_connection' ] = $object[ 'id_connection' ]; 
-                $all_contacts[ $object[ 'id_contact' ] ][ 'alias' ]         = $object[ 'alias' ]; 
-                $all_contacts[ $object[ 'id_contact' ] ][ 'birthdate' ]         = $object[ 'birthdate' ]; 
-                $all_contacts[ $object[ 'id_contact' ] ][ 'sex' ]               = $object[ 'sex' ]; 
-                $all_contacts[ $object[ 'id_contact' ] ][ 'pgp_key' ]           = $object[ 'pgp_key' ]; 
-                $all_contacts[ $object[ 'id_contact' ] ][ 'notes' ]         = $object[ 'notes' ]; 
-                $all_contacts[ $object[ 'id_contact' ] ][ 'web_page' ]          = $object[ 'web_page' ]; 
-                $all_contacts[ $object[ 'id_contact' ] ][ 'corporate_name' ]= $object[ 'corporate_name' ]; 
-                $all_contacts[ $object[ 'id_contact' ] ][ 'job_title' ]         = $object[ 'job_title' ]; 
-                $all_contacts[ $object[ 'id_contact' ] ][ 'department' ]    = $object[ 'department' ]; 
- 
-                switch( $object[ 'id_typeof_contact_address' ] ) 
-                { 
-                    case 1 : 
-                        $all_contacts[ $object[ 'id_contact' ] ][ 'business-address' ]     = $object[ 'address1' ]; 
-                        $all_contacts[ $object[ 'id_contact' ] ][ 'business-address-2' ]   = $object[ 'address2' ]; 
-                        $all_contacts[ $object[ 'id_contact' ] ][ 'business-complement' ]  = $object[ 'complement' ]; 
-                        $all_contacts[ $object[ 'id_contact' ] ][ 'business-postal_code' ] = $object[ 'postal_code' ]; 
-                        $all_contacts[ $object[ 'id_contact' ] ][ 'business-city_name' ]   = $object[ 'city_name' ]; 
-                        $all_contacts[ $object[ 'id_contact' ] ][ 'business-state_name' ]  = $object[ 'state_name' ]; 
-                        $all_contacts[ $object[ 'id_contact' ] ][ 'business-id_country' ]  = $object[ 'id_country' ]; 
-                        break; 
-                    case 2 : 
-                        $all_contacts[ $object[ 'id_contact' ] ][ 'home-address' ]     = $object[ 'address1' ]; 
-                        $all_contacts[ $object[ 'id_contact' ] ][ 'home-address-2' ]   = $object[ 'address2' ]; 
-                        $all_contacts[ $object[ 'id_contact' ] ][ 'home-complement' ]  = $object[ 'complement' ]; 
-                        $all_contacts[ $object[ 'id_contact' ] ][ 'home-postal_code' ] = $object[ 'postal_code' ]; 
-                        $all_contacts[ $object[ 'id_contact' ] ][ 'home-city_name' ]   = $object[ 'city_name' ]; 
-                        $all_contacts[ $object[ 'id_contact' ] ][ 'home-state_name' ]  = $object[ 'state_name' ]; 
-                        $all_contacts[ $object[ 'id_contact' ] ][ 'home-id_country' ]  = $object[ 'id_country' ]; 
-                        break; 
-                } 
-            } 
-            $all = array_values($all_contacts); 
- 
-            $result = array(); 
-            foreach($all as $i => $v) 
-            { 
-                if(!$v['mail']) continue; 
- 
-                $tmp = array(); 
-                $tmp['mail'] = $v['mail']; 
-                $tmp['name'] = $v['cn']; 
-                $tmp['isExternal'] = '1'; 
-                $result[] = $tmp; 
-            } 
- 
-            return $result; 
- 
-    } 
+
+    static function findExternalCatalogContacts( $search )
+    {
+            $result = array();
+            $external_srcs = array();
+            $external_mappings = array();
+
+            include_once dirname(__DIR__) .'/../../../contactcenter/setup/external_catalogs.inc.php';
+
+            $search = str_replace(' ', '*', $search) ;
+            $search = '*' . $search . '*';
+
+            foreach($external_srcs as $i => $v)
+            {
+                $con = ldap_connect($v['host']);
+
+                ldap_set_option( $con , LDAP_OPT_PROTOCOL_VERSION , 3 );
+
+                if( isset( $v['acc'] ) && isset( $v['pw'] ) )
+                    ldap_bind( $con, $v['acc'], $v['pw'] );
+
+                $fields = array();
+                $fields[] = $external_mappings[$i]['contact.names_ordered'][0];
+                $fields[] = $external_mappings[$i]['contact.connection.typeof_connection.contact_connection_type_name']['email'][0];
+
+                $ldapFilter = '(&(objectClass='.$v['obj'].')(|('.$fields[0].'='.$search.')('.$fields[1].'='.$search.')))';
+                $sr =  ldap_search( $con, utf8_encode($v['dn']) , $ldapFilter , $fields );
+                if($sr)
+                {
+                    $search = ldap_get_entries($con, $sr);
+
+                    for ($j = 0; $j < $search["count"]; ++$j) {
+                        $tmp = array();
+                        $tmp['name'] = $search[$j][$fields[0]][0];
+                        $tmp['mail'] = $search[$j][$fields[1]][0];
+                        $tmp['isExternal'] = '1';
+
+                        $result[] = $tmp;
+                    }
+                }
+            }
+            return $result;
+    }
+
+    static function findPersonalContacts($search_for)
+    {
+
+              $query = 'select'
+
+                . ' C.id_connection,'
+                . ' A.id_contact,'
+                . ' A.names_ordered,'
+                . ' A.alias,'
+                . ' A.birthdate,'
+                . ' A.sex,'
+                . ' A.pgp_key,'
+                . ' A.notes,'
+                . ' A.web_page,'
+                . ' A.corporate_name,'
+                . ' A.job_title,'
+                . ' A.department,'
+                . ' C.connection_name,'
+                . ' C.connection_value,'
+                . ' B.id_typeof_contact_connection,'
+                . ' phpgw_cc_contact_addrs.id_typeof_contact_address,'
+                . ' phpgw_cc_addresses.address1,'
+                . ' phpgw_cc_addresses.address2,'
+                . ' phpgw_cc_addresses.complement,'
+                . ' phpgw_cc_addresses.postal_code,'
+                . ' phpgw_cc_city.city_name,'
+                . ' phpgw_cc_state.state_name,'
+                . ' phpgw_cc_addresses.id_country'
+            ;
+
+            $query .= ' from'
+                . ' phpgw_cc_contact A'
+                . ' inner join phpgw_cc_contact_conns B on ( A.id_contact = B.id_contact )'
+                . ' inner join phpgw_cc_connections C on ( B.id_connection = C.id_connection )'
+                . ' left join phpgw_cc_contact_addrs on ( A.id_contact = phpgw_cc_contact_addrs.id_contact )'
+                . ' left join phpgw_cc_addresses on ( phpgw_cc_contact_addrs.id_address = phpgw_cc_addresses.id_address )'
+                . ' left join phpgw_cc_city on ( phpgw_cc_addresses.id_city = phpgw_cc_city.id_city )'
+                . ' left join phpgw_cc_state on ( phpgw_cc_addresses.id_state = phpgw_cc_state.id_state)'
+            ;
+
+            $query .= ' where '
+                . 'A.id_owner=' . Config::me('uidNumber')
+                . ' and lower(translate(names_ordered, \'áàâãäéèêëíìïóòôõöúùûüÁÀÂÃÄÉÈÊËÍÌÏÓÒÔÕÖÚÙÛÜçÇñÑ\',\'aaaaaeeeeiiiooooouuuuAAAAAEEEEIIIOOOOOUUUUcCnN\'))'
+                . ' LIKE lower(translate(\'%' . $search_for . '%\', \'áàâãäéèêëíìïóòôõöúùûüÁÀÂÃÄÉÈÊËÍÌÏÓÒÔÕÖÚÙÛÜçÇñÑ\',\'aaaaaeeeeiiiooooouuuuAAAAAEEEEIIIOOOOOUUUUcCnN\'))';
+
+            //Se não existir parametro na busca, limita os usuarios no resultado da pesquisa.
+            if(!$search_for){
+                $query .= 'LIMIT 11';
+            }
+
+            $r = Controller::service('PostgreSQL')->execResultSql($query);
+
+
+            $all_contacts = array();
+            foreach( $r as $i => $object )
+            {
+                if ( ! array_key_exists( $object[ 'id_contact' ], $all_contacts ) )
+                    $all_contacts[ $object[ 'id_contact' ] ] = array(
+                        'connection_value' => '',
+                        'telephonenumber' => '',
+                        'mobile' => '',
+                        'cn' => '',
+                        'id_contact' => '',
+                        'id_connection' => '',
+                        'alias' => '',
+                        'birthdate' => '',
+                        'sex' => '',
+                        'pgp_key' => '',
+                        'notes' => '',
+                        'web_page' => '',
+                        'corporate_name' => '',
+                        'job_title' => '',
+                        'department' => '',
+                        'mail' => '',
+                        'aternative-mail' => '',
+                        'business-phone' => '',
+                        'business-address' => '',
+                        'business-complement' => '',
+                        'business-postal_code' => '',
+                        'business-city_name' => '',
+                        'business-state_name' => '',
+                        'business-id_country' => '',
+                        'business-fax' => '',
+                        'business-pager' => '',
+                        'business-mobile' => '',
+                        'business-address-2' => '',
+                        'home-phone' => '',
+                        'home-address' => '',
+                        'home-complement' => '',
+                        'home-postal_code' => '',
+                        'home-city_name' => '',
+                        'home-state_name' => '',
+                        'home-fax' => '',
+                        'home-pager' => '',
+                        'home-address-2' => ''
+
+
+                    );
+
+                switch( $object[ 'id_typeof_contact_connection' ] )
+                {
+                    case 1 :
+                        $all_contacts[ $object[ 'id_contact' ] ][ 'connection_value' ] = $object[ 'connection_value' ];
+                        switch ( strtolower( $object[ 'connection_name' ] ) )
+                        {
+                            case 'alternativo' :
+                                $all_contacts[ $object[ 'id_contact' ] ][ 'alternative-mail' ] = $object[ 'connection_value' ];
+                                break;
+                            case 'principal' :
+                                $all_contacts[ $object[ 'id_contact' ] ][ 'mail' ] = $object[ 'connection_value' ];
+                                break;
+                        }
+                        break;
+                    case 2 :
+                        $all_contacts[ $object[ 'id_contact' ] ][ 'telephonenumber' ] = $object[ 'connection_value' ];
+                        switch ( strtolower( $object[ 'connection_name' ] ) )
+                        {
+                            case 'casa' :
+                                $all_contacts[ $object[ 'id_contact' ] ][ 'home-phone' ] = $object[ 'connection_value' ];
+                                break;
+                            case 'celular' :
+                                $all_contacts[ $object[ 'id_contact' ] ][ 'mobile' ] = $object[ 'connection_value' ];
+                                break;
+                            case 'trabalho' :
+                                $all_contacts[ $object[ 'id_contact' ] ][ 'business-phone' ] = $object[ 'connection_value' ];
+                                break;
+                            case 'fax' :
+                                $all_contacts[ $object[ 'id_contact' ] ][ 'home-fax' ] = $object[ 'connection_value' ];
+                                break;
+                            case 'pager' :
+                                $all_contacts[ $object[ 'id_contact' ] ][ 'home-pager' ] = $object[ 'connection_value' ];
+                                break;
+                            case 'celular corporativo' :
+                                $all_contacts[ $object[ 'id_contact' ] ][ 'business-mobile' ] = $object[ 'connection_value' ];
+                                break;
+                            case 'pager corporativo' :
+                                $all_contacts[ $object[ 'id_contact' ] ][ 'business-pager' ] = $object[ 'connection_value' ];
+                                break;
+                            case 'fax corporativo' :
+                                $all_contacts[ $object[ 'id_contact' ] ][ 'business-fax' ] = $object[ 'connection_value' ];
+                                break;
+                        }
+                        break;
+                }
+
+                $all_contacts[ $object[ 'id_contact' ] ][ 'cn' ] = utf8_encode($object[ 'names_ordered' ]);
+                $all_contacts[ $object[ 'id_contact' ] ][ 'id_contact' ]    = $object[ 'id_contact' ];
+                $all_contacts[ $object[ 'id_contact' ] ][ 'id_connection' ] = $object[ 'id_connection' ];
+                $all_contacts[ $object[ 'id_contact' ] ][ 'alias' ]         = $object[ 'alias' ];
+                $all_contacts[ $object[ 'id_contact' ] ][ 'birthdate' ] 	= $object[ 'birthdate' ];
+                $all_contacts[ $object[ 'id_contact' ] ][ 'sex' ]    		= $object[ 'sex' ];
+                $all_contacts[ $object[ 'id_contact' ] ][ 'pgp_key' ] 		= $object[ 'pgp_key' ];
+                $all_contacts[ $object[ 'id_contact' ] ][ 'notes' ]         = $object[ 'notes' ];
+                $all_contacts[ $object[ 'id_contact' ] ][ 'web_page' ] 		= $object[ 'web_page' ];
+                $all_contacts[ $object[ 'id_contact' ] ][ 'corporate_name' ]= $object[ 'corporate_name' ];
+                $all_contacts[ $object[ 'id_contact' ] ][ 'job_title' ] 	= $object[ 'job_title' ];
+                $all_contacts[ $object[ 'id_contact' ] ][ 'department' ]    = $object[ 'department' ];
+
+                switch( $object[ 'id_typeof_contact_address' ] )
+                {
+                    case 1 :
+                        $all_contacts[ $object[ 'id_contact' ] ][ 'business-address' ]     = $object[ 'address1' ];
+                        $all_contacts[ $object[ 'id_contact' ] ][ 'business-address-2' ]   = $object[ 'address2' ];
+                        $all_contacts[ $object[ 'id_contact' ] ][ 'business-complement' ]  = $object[ 'complement' ];
+                        $all_contacts[ $object[ 'id_contact' ] ][ 'business-postal_code' ] = $object[ 'postal_code' ];
+                        $all_contacts[ $object[ 'id_contact' ] ][ 'business-city_name' ]   = $object[ 'city_name' ];
+                        $all_contacts[ $object[ 'id_contact' ] ][ 'business-state_name' ]  = $object[ 'state_name' ];
+                        $all_contacts[ $object[ 'id_contact' ] ][ 'business-id_country' ]  = $object[ 'id_country' ];
+                        break;
+                    case 2 :
+                        $all_contacts[ $object[ 'id_contact' ] ][ 'home-address' ]     = $object[ 'address1' ];
+                        $all_contacts[ $object[ 'id_contact' ] ][ 'home-address-2' ]   = $object[ 'address2' ];
+                        $all_contacts[ $object[ 'id_contact' ] ][ 'home-complement' ]  = $object[ 'complement' ];
+                        $all_contacts[ $object[ 'id_contact' ] ][ 'home-postal_code' ] = $object[ 'postal_code' ];
+                        $all_contacts[ $object[ 'id_contact' ] ][ 'home-city_name' ]   = $object[ 'city_name' ];
+                        $all_contacts[ $object[ 'id_contact' ] ][ 'home-state_name' ]  = $object[ 'state_name' ];
+                        $all_contacts[ $object[ 'id_contact' ] ][ 'home-id_country' ]  = $object[ 'id_country' ];
+                        break;
+                }
+            }
+            $all = array_values($all_contacts);
+
+            $result = array();
+            foreach($all as $i => $v)
+            {
+                if(!$v['mail']) continue;
+
+                $tmp = array();
+                $tmp['mail'] = $v['mail'];
+                $tmp['name'] = $v['cn'];
+                $tmp['isExternal'] = '1';
+                $result[] = $tmp;
+            }
+
+            return $result;
+
+    }
 }
 
Index: branches/2.5/prototype/modules/calendar/interceptors/DAViCalAdapter.php
===================================================================
--- branches/2.5/prototype/modules/calendar/interceptors/DAViCalAdapter.php	(revision 7799)
+++ branches/2.5/prototype/modules/calendar/interceptors/DAViCalAdapter.php	(revision 8232)
@@ -206,5 +206,5 @@
         {  
             $args =  Controller::parse( array( 'service' => 'iCal' ) , $data , $params);
-            ob_start(); 
+            ob_start();
             include ROOTPATH.'/Sync.php';
             ob_end_clean();
Index: branches/2.5/prototype/modules/calendar/schedules.php
===================================================================
--- branches/2.5/prototype/modules/calendar/schedules.php	(revision 8049)
+++ branches/2.5/prototype/modules/calendar/schedules.php	(revision 8232)
@@ -18,5 +18,5 @@
 class Schedule{
 
-    function findEventsRange( $start, $end, $calendars, $timezones ){
+    function findEventsRange( $start, $end, $calendars, $timezones  ){
 
         $sql =
@@ -31,7 +31,10 @@
                 .'calendar_object.range_end as "rangeEnd", calendar_object.last_update as "lastUpdate", '
                 .'calendar_object.dtstamp as "dtstamp", calendar_object.sequence as "sequence", '
+
                 .'count(calendar_task_to_activity_object.id) as "tasks", '
+
                 .'calendar_object.tzid as "timezone" ,calendar_to_calendar_object.calendar_id as '
                 .'calendar FROM calendar_object left join calendar_task_to_activity_object on ( calendar_object.id = calendar_task_to_activity_object.calendar_object_activity_id  ), calendar_to_calendar_object '
+
                 .'WHERE ( calendar_to_calendar_object.calendar_id IN (\'' . implode('\',\'', $calendars) . '\')) '
                 .'AND calendar_to_calendar_object.calendar_object_id = calendar_object.id '
@@ -54,15 +57,15 @@
                 .'AND calendar_object.dtstart NOT IN (SELECT calendar_repeat_occurrence.occurrence from calendar_repeat_occurrence, '
                 .'calendar_repeat where (calendar_repeat_occurrence.repeat_id = calendar_repeat.id) '
-                .'AND (calendar_repeat.object_id = calendar_object.id)) ' 
-                .'group by 
-                    calendar_object.id, calendar_object.cal_uid, calendar_object.type_id, 
-                    calendar_object.dtstart, calendar_object.summary, calendar_object.description, 
-                    calendar_object.dtend, calendar_object.priority, calendar_object.due, calendar_object.percentage, 
-                    calendar_object.status, calendar_object.location, calendar_object.allday, calendar_object.transp, 
-                    calendar_object.class_id, calendar_object.repeat, calendar_object.range_start, calendar_object.range_end, 
-                    calendar_object.last_update, calendar_object.dtstamp, calendar_object.sequence, 
-                    calendar_object.tzid, calendar_to_calendar_object.calendar_id 
-                ORDER BY 
-                    calendar_object.dtstart'; 
+                .'AND (calendar_repeat.object_id = calendar_object.id)) '
+                .'group by
+                    calendar_object.id, calendar_object.cal_uid, calendar_object.type_id,
+                    calendar_object.dtstart, calendar_object.summary, calendar_object.description,
+                    calendar_object.dtend, calendar_object.priority, calendar_object.due, calendar_object.percentage,
+                    calendar_object.status, calendar_object.location, calendar_object.allday, calendar_object.transp,
+                    calendar_object.class_id, calendar_object.repeat, calendar_object.range_start, calendar_object.range_end,
+                    calendar_object.last_update, calendar_object.dtstamp, calendar_object.sequence,
+                    calendar_object.tzid, calendar_to_calendar_object.calendar_id
+                ORDER BY
+                    calendar_object.dtstart';
 
         $params = Controller::service('PostgreSQL')->execResultSql($sql.$where);
@@ -84,5 +87,7 @@
             .'calendar_object.range_end as "rangeEnd", calendar_object.last_update as "lastUpdate", '
             .'calendar_object.dtstamp as "dtstamp", calendar_object.sequence as "sequence", '
+
             .'count(calendar_task_to_activity_object.id) as "tasks", '
+
             .'calendar_object.tzid as "timezone" ,calendar_to_calendar_object.calendar_id as '
             .'calendar FROM calendar_object left join calendar_task_to_activity_object on ( calendar_object.id = calendar_task_to_activity_object.calendar_object_activity_id  ), calendar_to_calendar_object '
@@ -92,20 +97,18 @@
 
 
-            $where = 'AND (((upper("summary") like upper(\'%'.$summary.'%\') OR upper("description") like upper(\'%'.$description.'%\')))) 
-                group by 
-                    calendar_object.id, calendar_object.cal_uid, calendar_object.type_id, 
-                    calendar_object.dtstart, calendar_object.summary, calendar_object.description, 
-                    calendar_object.dtend, calendar_object.priority, calendar_object.due, calendar_object.percentage, 
-                    calendar_object.status, calendar_object.location, calendar_object.allday, calendar_object.transp, 
-                    calendar_object.class_id, calendar_object.repeat, calendar_object.range_start, calendar_object.range_end, 
-                    calendar_object.last_update, calendar_object.dtstamp, calendar_object.sequence, 
-                    calendar_object.tzid, calendar_to_calendar_object.calendar_id 
-                ORDER BY 
-                    dtstart LIMIT '.$limit.'  OFFSET '.$offset.' '; 
- 
+            $where = 'AND (((upper("summary") like upper(\'%'.$summary.'%\') OR upper("description") like upper(\'%'.$description.'%\'))))
+                group by
+                    calendar_object.id, calendar_object.cal_uid, calendar_object.type_id,
+                    calendar_object.dtstart, calendar_object.summary, calendar_object.description,
+                    calendar_object.dtend, calendar_object.priority, calendar_object.due, calendar_object.percentage,
+                    calendar_object.status, calendar_object.location, calendar_object.allday, calendar_object.transp,
+                    calendar_object.class_id, calendar_object.repeat, calendar_object.range_start, calendar_object.range_end,
+                    calendar_object.last_update, calendar_object.dtstamp, calendar_object.sequence,
+                    calendar_object.tzid, calendar_to_calendar_object.calendar_id
+                ORDER BY
+                    dtstart LIMIT '.$limit.'  OFFSET '.$offset.' ';
+
             $params = Controller::service('PostgreSQL')->execResultSql($sql.$where);
 
-
-
         return $this->normalizeEvents( $params, $timezones );
     }
@@ -113,14 +116,14 @@
     function normalizeEvents( &$result, $timezones ){
 
-        $mySig = Controller::find(array('concept' => 'calendarSignature') , array('calendar') , array('filter' => array( 'AND' , array('=' , 'type' , '0' ) , array( '=' , 'user' ,Config::me('uidNumber') ) , array('=' , 'isOwner' , '0' )))); 
- 
-        $signedCalendars = array(); 
-        if(is_array($mySig)) 
-            foreach($mySig as $v) 
-            { 
-                $tmp = Controller::find(array('concept' => 'calendarToPermission') , array('acl' ,'owner') , array('filter' => array( 'AND' ,array( '=' , 'calendar' , $v['calendar'] ) , array( '=' , 'user' , Config::me('uidNumber')  ) ))); 
-                $signedCalendars[$v['calendar']] = $tmp[0]; 
-            } 
- 
+        $mySig = Controller::find(array('concept' => 'calendarSignature') , array('calendar') , array('filter' => array( 'AND' , array('=' , 'type' , '0' ) , array( '=' , 'user' ,Config::me('uidNumber') ) , array('=' , 'isOwner' , '0' ))));
+
+        $signedCalendars = array();
+        if(is_array($mySig))
+            foreach($mySig as $v)
+            {
+                $tmp = Controller::find(array('concept' => 'calendarToPermission') , array('acl' ,'owner') , array('filter' => array( 'AND' ,array( '=' , 'calendar' , $v['calendar'] ) , array( '=' , 'user' , Config::me('uidNumber')  ) )));
+                $signedCalendars[$v['calendar']] = $tmp[0];
+            }
+
         $date = new DateTime('now', new DateTimeZone('UTC'));
         $DayLigth = array();
@@ -156,31 +159,31 @@
             if(isset( $v['occurrences'] ) && count( $v['occurrences'] ) > 0){
 
-                $date->setTimestamp((int) ($v['startTime'] / 1000)); 
-                $date->setTimezone( new DateTimeZone( $currentTimezone )); 
- 
+                $date->setTimestamp((int) ($v['startTime'] / 1000));
+                $date->setTimezone( new DateTimeZone( $currentTimezone ));
+
                 foreach( $result[$i]['occurrences'] as &$o){
 
-                    $o = ((int) ($o / 1000) + $date->getOffset()).'000'; 
+                    $o = ((int) ($o / 1000) + $date->getOffset()).'000';
 
                 }
             }
 
-            $attend = (isset($signedCalendars[$result[$i]['calendar']])) ? 
-                Controller::read(array('concept' => 'participant'), null, array('filter' => array('AND', array('=','schedulable',$v['id']), array('=','user', $signedCalendars[$result[$i]['calendar']]['owner'] )  ))): 
-                Controller::read(array('concept' => 'participant'), null, array('filter' => array('AND', array('=','schedulable',$v['id']), array('=','user', Config::me('uidNumber'))  ))); 
- 
-                $result[$i]['unanswered'] = 0; 
- 
+            $attend = (isset($signedCalendars[$result[$i]['calendar']])) ?
+                Controller::read(array('concept' => 'participant'), null, array('filter' => array('AND', array('=','schedulable',$v['id']), array('=','user', $signedCalendars[$result[$i]['calendar']]['owner'] )  ))):
+                Controller::read(array('concept' => 'participant'), null, array('filter' => array('AND', array('=','schedulable',$v['id']), array('=','user', Config::me('uidNumber'))  )));
+
+                $result[$i]['unanswered'] = 0;
+
             if(count($attend) > 0 && !empty($attend)){
-               if(array_key_exists(0, $attend)) 
-                  $attend = $attend[0]; 
- 
-                if(isset($signedCalendars[$result[$i]['calendar']])) //Caso agenda compartilhada verificar tmb se tem compartilhamento de escrita 
-                    $result[$i]['editable'] = (strpos($signedCalendars[$result[$i]['calendar']]['acl'],"w") >=0  &&  (strstr($attend['acl'],"w") || strstr($attend['acl'],"o") || $attend['isOrganizer'] == '1') ) ? 1 : 0; 
-                else 
-                   $result[$i]['editable'] = (strstr($attend['acl'],"w") || strstr($attend['acl'],"o") || $attend['isOrganizer'] == '1') ? 1 : 0; 
- 
-                if($attend['status'] == STATUS_UNANSWERED && !isset($signedCalendars[$result[$i]['calendar']]) ) 
-                   $result[$i]['unanswered'] = 1; 
+               if(array_key_exists(0, $attend))
+                  $attend = $attend[0];
+
+                if(isset($signedCalendars[$result[$i]['calendar']])) //Caso agenda compartilhada verificar tmb se tem compartilhamento de escrita
+                    $result[$i]['editable'] = (strpos($signedCalendars[$result[$i]['calendar']]['acl'],"w") >=0  &&  (strstr($attend['acl'],"w") || strstr($attend['acl'],"o") || $attend['isOrganizer'] == '1') ) ? 1 : 0;
+                else
+                   $result[$i]['editable'] = (strstr($attend['acl'],"w") || strstr($attend['acl'],"o") || $attend['isOrganizer'] == '1') ? 1 : 0;
+
+                if($attend['status'] == STATUS_UNANSWERED && !isset($signedCalendars[$result[$i]['calendar']]) )
+                   $result[$i]['unanswered'] = 1;
 
             }else{
Index: branches/2.5/prototype/modules/calendar/css/layout.css
===================================================================
--- branches/2.5/prototype/modules/calendar/css/layout.css	(revision 7968)
+++ branches/2.5/prototype/modules/calendar/css/layout.css	(revision 8232)
@@ -1408,6 +1408,6 @@
 	color: transparent;
 }
- 
-.occurrence-zebra{ 
-    width: 440px !important; 
-} 
+
+.occurrence-zebra{
+    width: 440px !important;
+}
Index: branches/2.5/prototype/modules/calendar/css/style.css
===================================================================
--- branches/2.5/prototype/modules/calendar/css/style.css	(revision 8050)
+++ branches/2.5/prototype/modules/calendar/css/style.css	(revision 8232)
@@ -51,5 +51,5 @@
 .new-event-win fieldset#calendar_addevent_details5 .button-files-upload, .new-task-win fieldset#calendar_addevent_details5 .button-files-upload{margin: 15px 0 0 0}
 .new-event-win fieldset fieldset, .new-event-win fieldset.tab-level2 fieldset, .new-task-win fieldset fieldset, .new-event-win fieldset.tab-level2 fieldset { padding: 5px 0; }
-.new-event-win .creation-date-label{ white-space: nowrap; float: right;} 
+.new-event-win .creation-date-label{ white-space: nowrap; float: right;}
 
 .new-activity-win fieldset { border: none; margin: 0; padding: 0; }
@@ -559,7 +559,7 @@
 .div-addtask #calendar_addtask_details1 .subitem .done { width: 45px;}
 
-@-moz-document url-prefix() {.div-addtask #calendar_addtask_details1 .ui-spinner-buttons{ top: -14px !important;}}
-
-@media screen and (-webkit-min-device-pixel-ratio:0){.div-addtask #calendar_addtask_details1 .ui-spinner-buttons{ top: -2px !important;}}
+.div-addtask #calendar_addtask_details1 .ui-spinner-buttons{ top: -2px !important;;}
+/*@-moz-document url-prefix() {.div-addtask #calendar_addtask_details1 .ui-spinner-buttons{ top: -2px !important;}}*/
+/*@media screen and (-webkit-min-device-pixel-ratio:0){.div-addtask #calendar_addtask_details1 .ui-spinner-buttons{ top: -2px !important;}}*/
 
 .div-addtask #calendar_addtask_details1 .ui-spinner-buttons .ui-spinner-up{height: 7px !important;}
Index: branches/2.5/prototype/modules/calendar/css/reset.css
===================================================================
--- branches/2.5/prototype/modules/calendar/css/reset.css	(revision 5341)
+++ branches/2.5/prototype/modules/calendar/css/reset.css	(revision 8232)
@@ -33,5 +33,5 @@
 }
 body {
-	line-height: 1;
+	/*line-height: 1;*/
 	color: black;
 	background: white;
Index: branches/2.5/prototype/modules/calendar/js/calendar.codecs.js
===================================================================
--- branches/2.5/prototype/modules/calendar/js/calendar.codecs.js	(revision 8051)
+++ branches/2.5/prototype/modules/calendar/js/calendar.codecs.js	(revision 8232)
@@ -75,15 +75,16 @@
 			Calendar.currentView =  DataLayer.encode('schedulable:calendar', DataLayer.dispatch('modules/calendar/schedules', DataLayer.criteria('schedulable:calendar', {start: start,end: end}))  );   //DataLayer.get( 'schedulable:calendar', {start: start,end: end} );
 		    }
-             if( !!Calendar.currentView[ signature.calendar.id ]) 
-            { 
-                if(signature.hidden == true  ) 
-                    Calendar.currentView[ signature.calendar.id ].hidden = true; 
-                else 
-                    Calendar.currentView[ signature.calendar.id ].hidden = false; 
-            } 
- 
+
+            if( !!Calendar.currentView[ signature.calendar.id ])
+            {
+                if(signature.hidden == true  )
+                    Calendar.currentView[ signature.calendar.id ].hidden = true;
+                else
+                    Calendar.currentView[ signature.calendar.id ].hidden = false;
+            }
+
 		    var view = Calendar.currentView[ signature.calendar.id ];
- 
- 
+
+
 		    callback( view && !view.hidden ? view : [] );
 		},
@@ -211,10 +212,10 @@
 
             Calendar.rerenderView(true);
-            if(updateActivity){ 
- 
-                DataLayer.remove('taskToActivity', false); 
+            if(updateActivity){
+
+                DataLayer.remove('taskToActivity', false);
                 refreshTaskActivity();
-            } 
- 
+            }
+
         });
     }
@@ -624,5 +625,5 @@
 		calendars: Calendar.calendars,
 		calendar: objEvent.calendar,
-        occurrences: objEvent.occurrences, 
+        occurrences: objEvent.occurrences,
 		summary: objEvent.summary,
         type: !!objEvent.type ? objEvent.type : 1,
@@ -632,5 +633,5 @@
 		startDate: Timezone.getDate( (objEvent.DayLigth ? objEvent.DayLigth.event.startTime : objEvent.startTime), 'start', objEvent.allDay , true),
         startHour: objEvent.DayLigth ? Timezone.getHour( objEvent.DayLigth.event.startTime) : Timezone.formateHour( objEvent.startTime ),
-        startUnixTime: objEvent.DayLigth ? objEvent.DayLigth.event.startTime : objEvent.startTime, 
+        startUnixTime: objEvent.DayLigth ? objEvent.DayLigth.event.startTime : objEvent.startTime,
         endDate: Timezone.getDate( (objEvent.DayLigth ? objEvent.DayLigth.event.endTime : objEvent.endTime), 'end', objEvent.allDay , true),
 		endHour: objEvent.DayLigth ? Timezone.getHour( objEvent.DayLigth.event.endTime) : Timezone.formateHour( objEvent.endTime ),
@@ -832,5 +833,5 @@
         location: objEvent.location,
         category: objEvent.category,
-        calendar: objEvent.calendar, 
+        calendar: objEvent.calendar,
         taskStatus: objEvent.status,
         groups: Calendar.groups,
@@ -840,5 +841,5 @@
         description: objEvent.description,
         timezone: objEvent.timezone,
-        startUnixTime: objEvent.startTime, 
+        startUnixTime: objEvent.startTime,
         timezones: Timezone.timezones,
         percentage: (objEvent.percentage) ? objEvent.percentage : '0',
@@ -1189,5 +1190,6 @@
 					percentage: task.percentage,
 					priority: task.priority,
-					summary: task.summary
+					summary: task.summary,
+					group: task.calendar
                 }
 
@@ -1217,5 +1219,5 @@
         percentage: (objEvent.percentage) ? objEvent.percentage : '0',
         priority: objEvent.priority,
-        startUnixTime: objEvent.startTime, 
+        startUnixTime: objEvent.startTime,
         startDate: new Date( parseInt(objEvent.startTime) ).setTimezoneOffset( Timezone.timezone( objEvent.timezone ) ).toString( User.preferences.dateFormat ),
         startHour: dateCalendar.formatDate(Timezone.getDateEvent(new Date( parseInt(objEvent.startTime)), objEvent.timezone, objEvent.calendar, objEvent.DayLigth, 'startTime'), User.preferences.hourFormat),
@@ -1637,23 +1639,23 @@
         }
 
-        var orderByStartUnixTime = function( a , b ) 
-        { 
-            return parseInt(a.startUnixTime) > parseInt(b.startUnixTime); 
-        } 
- 
+        var orderByStartUnixTime = function( a , b )
+        {
+            return parseInt(a.startUnixTime) > parseInt(b.startUnixTime);
+        }
+
         for (var i=0; i < res.length; i++) {
- 
-            if(Calendar.currentView[res[i].calendar].hidden == true) 
-                continue; 
- 
+
+            if(Calendar.currentView[res[i].calendar].hidden == true)
+                continue;
+
 			res[i].type = (res[i].type == '2' && !!res[i].tasks) ? '3' : res[i].type;
 		
             var startDate = Date.parseExact( res[i]['startDate'], User.preferences.dateFormat );
             var endDate   = Date.parseExact( res[i]['endDate'], User.preferences.dateFormat );
-                  
+
             var duration = parseInt( endDate.getTime() ) - parseInt( startDate.getTime() );
-            
+
             var occurrences = [  res[i].startUnixTime ];
- 
+
             if( res[i].occurrences )
             {
@@ -1671,6 +1673,6 @@
                 });
 
-                res2.startUnixTime = parseInt(occurrences[ii]); 
- 
+                res2.startUnixTime = parseInt(occurrences[ii]);
+
                 if(res[i].repeat)
                     res2.repeat = typeRepeat[res[i].repeat.frequency];
@@ -1683,6 +1685,6 @@
 
                 dates[index].events.push(res2);
- 
-                dates[index].events = dates[index].events.sort(orderByStartUnixTime); 
+
+                dates[index].events = dates[index].events.sort(orderByStartUnixTime);
                   
             }
@@ -1812,6 +1814,6 @@
                 return (evt.editable == '1' ) ?
                 {
+                    selectable: true,
                     editable: true,
-		    selectable: true,
                     className: 'fullcalendar-context-menu  event-type-1 event-id-'+idEvent+' calendar-id-'+calendar.id+ (isRecurrence ? ' isRecurrence Recurrence-id-'+Recurrence : '')
                 } : {
@@ -1874,6 +1876,7 @@
 				occurrence: occurrences[i],
 				type: typeEvent,
-                                calendar: evt.calendar, 
-                unanswered: evt.unanswered, 
+				calendar: evt.calendar,
+                unanswered: evt.unanswered,
+				status: evt.status
 				}, (parseInt(typeEvent) == 1 ? eventEditable(evt.id, isRepeat, i ) : (parseInt(typeEvent) == 2 ? taskEditable(evt.id) : {editable: false, disableResizing: true, disableDragging: true}))));
         }
Index: branches/2.5/prototype/modules/calendar/js/calendar.shared.js
===================================================================
--- branches/2.5/prototype/modules/calendar/js/calendar.shared.js	(revision 7217)
+++ branches/2.5/prototype/modules/calendar/js/calendar.shared.js	(revision 8232)
@@ -75,6 +75,14 @@
 	    });
 
-	    DataLayer.commit();
-	    UI.dialogs.sharedCalendar.dialog("close");
+	    DataLayer.commit(false, false, function(result){
+
+            /*
+             * Force clean cache
+             * */
+            DataLayer.storage.cache = {};
+            UI.dialogs.sharedCalendar.dialog("close");
+
+        });
+
 	};
 
@@ -295,43 +303,58 @@
 
     //Carrega os dados já cadastrados
-    var dataCurrent = DataLayer.get('calendarToPermission:detail', {
-	filter: ['=','calendar', calendarId]  , 
-	criteria: {
-	    deepness: 2
-	}
-    });
-    if(dataCurrent){
-	for(var i = 0; i < dataCurrent.length; i++){
-	    if(dataCurrent[i].user == "0"){
-		UI.dialogs.sharedCalendar.find('input[name="isPublic"]').attr('checked', 'checked')
-		.parent().find('.free-busy').toggleClass('hidden');
-		if(dataCurrent[i].acl['busy'])
-		    UI.dialogs.sharedCalendar.find('input[name="busy"]').attr('checked', 'checked');
-	    }else{
-		currentUsers[dataCurrent[i].user.id] = true;
-
-		UI.dialogs.sharedCalendar.find('dd.user-list ul.user-list')
-		.append(DataLayer.render('templates/user_shared_add_itemlist.ejs', [{
-		    id: dataCurrent[i].user.id, 
-		    name: dataCurrent[i].user.name, 
-		    mail: dataCurrent[i].user.mail, 
-		    acl:dataCurrent[i].acl, 
-		    aclValue: dataCurrent[i].aclValues, 
-		    current: true, 
-		    idPermission: dataCurrent[i].id
-		}]))
-		.scrollTo('max');
-		$('li.not-user').remove();
-		callbackSharedCotactsAdd();
-
-		for (var f in dataCurrent[i].acl){
-		    if(dataCurrent[i].acl[f]){
-			UI.dialogs.sharedCalendar.find('.'+f+':last').toggleClass('attendee-permissions-change-button')
-			.find('span:first').toggleClass('attendee-permissions-change').end();  
-		    }
-		}
-	    }
-	}
-    }
+    var loadOldData = function (calendar)
+    {
+        UI.dialogs.sharedCalendar.find('dd.user-list ul.user-list').empty();
+
+        var dataCurrent = DataLayer.get('calendarToPermission:detail', {
+            filter: ['=','calendar', calendar]  ,
+            criteria: {
+                deepness: 2
+            }
+        });
+
+        if(dataCurrent){
+            for(var i = 0; i < dataCurrent.length; i++){
+                if(dataCurrent[i].user == "0"){
+                    UI.dialogs.sharedCalendar.find('input[name="isPublic"]').attr('checked', 'checked')
+                        .parent().find('.free-busy').toggleClass('hidden');
+                    if(dataCurrent[i].acl['busy'])
+                        UI.dialogs.sharedCalendar.find('input[name="busy"]').attr('checked', 'checked');
+                }else{
+                    currentUsers[dataCurrent[i].user.id] = true;
+
+                    UI.dialogs.sharedCalendar.find('dd.user-list ul.user-list')
+                        .append(DataLayer.render('templates/user_shared_add_itemlist.ejs', [{
+                            id: dataCurrent[i].user.id,
+                            name: dataCurrent[i].user.name,
+                            mail: dataCurrent[i].user.mail,
+                            acl:dataCurrent[i].acl,
+                            aclValue: dataCurrent[i].aclValues,
+                            current: true,
+                            idPermission: dataCurrent[i].id
+                        }]))
+                        .scrollTo('max');
+                    $('li.not-user').remove();
+                    callbackSharedCotactsAdd();
+
+                    for (var f in dataCurrent[i].acl){
+                        if(dataCurrent[i].acl[f]){
+                            UI.dialogs.sharedCalendar.find('.'+f+':last').toggleClass('attendee-permissions-change-button')
+                                .find('span:first').toggleClass('attendee-permissions-change').end();
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+    loadOldData(calendarId);
+
+    //Bind calendar select change
+    var select = UI.dialogs.sharedCalendar.find('select[name="calendar"]');
+    select.change(function() {
+        loadOldData(select.val());
+    });
+
     UI.dialogs.sharedCalendar.dialog('open');
 }
@@ -526,4 +549,22 @@
     for (var i = 0; i < Calendar.signatures.length; i++)
 	if(Calendar.signatures[i].isOwner == "0"){
+
+        /*
+        * Verificar se o Owner é um objeto caso ao contrário é realizado a busca e adicionado ao mesmo o uid
+        * */
+        if (Calendar.signatures[i].permission.owner != "object"){
+
+            var result = DataLayer.get('calendarToPermission', {
+                filter: ['AND', ['=','id', Calendar.signatures[i].permission.id]]  ,
+                criteria: {
+                    deepness: 2
+                }
+            }, true);
+
+            Calendar.signatures[i].permission.owner = {};
+            Calendar.signatures[i].permission.owner['uid'] = result[0].owner.uid;
+
+        }
+
 	    var dataCurrent = Calendar.signatures[i].calendar;
 	    currentCalendars[Calendar.signatures[i].permission.id] = {
Index: branches/2.5/prototype/modules/calendar/js/timezone.js
===================================================================
--- branches/2.5/prototype/modules/calendar/js/timezone.js	(revision 8004)
+++ branches/2.5/prototype/modules/calendar/js/timezone.js	(revision 8232)
Index: branches/2.5/prototype/modules/calendar/js/activity.helpers.js
===================================================================
--- branches/2.5/prototype/modules/calendar/js/activity.helpers.js	(revision 7977)
+++ branches/2.5/prototype/modules/calendar/js/activity.helpers.js	(revision 8232)
@@ -222,9 +222,53 @@
     }
     */
-	UI.dialogs.addActivity.find('select[name="activityStatus"], input[name="allDay"]').removeAttr('disabled');
-    canDiscardActivityDialog = true;
-	
-	UI.dialogs.addActivity.children().find('form.form-addactivity').submit();
-	UI.dialogs.addActivity.dialog("close");
+	//Código o qual será chamado para o salvamento da Atividade. 
+	var handler_save = function (objsToSave){ 
+		UI.dialogs.addActivity.find('select[name="activityStatus"], input[name="allDay"]').removeAttr('disabled'); 
+		canDiscardActivityDialog = true; 
+
+		var activity_tst = DataLayer.form( UI.dialogs.addActivity.children().find('form') ); 
+		if(objsToSave) 
+			objsToSave[objsToSave.length] = activity_tst; 
+		
+		else  
+			objsToSave = activity_tst; 
+		DataLayer.put('schedulable', objsToSave); 
+		 
+		UI.dialogs.addActivity.dialog("close"); 
+	} 
+
+	//Verifica se o grupo da atividade mudou 
+	if (group.id != UI.dialogs.addActivity.children().find('form select[name="group"] :selected').val() && typeof group.id != 'undefined') { 
+		//Janela de dialogo 
+		$.Zebra_Dialog('Você alterou o grupo da atividade, deseja alterar também o grupo das tarefas pertencentes à essa atividade?', { 
+			'type':     'question', 
+			'overlay_opacity': '0.5', 
+			'modal': true, 
+			'buttons':  ['Não Alterar', 'Alterar'], 
+			'onClose':  function(clicked) { 
+				if(clicked == 'Não Alterar') { 
+				   
+					handler_save(); 
+				}else{ 
+					var objsToSave = []; 
+					//percorre as tarefas da atividade para verificar se o grupo mudou 
+					for(var t in objActivity.tasks){ 
+						if(typeof objActivity.tasks[t].group != 'undefined') 
+							if (objActivity.tasks[t].group != UI.dialogs.addActivity.children().find('form select[name="group"] :selected').val()){ 
+								objActivity.tasks[t].group = UI.dialogs.addActivity.children().find('form select[name="group"] :selected').val(); 
+								objsToSave[objsToSave.length] = {'calendar' : objActivity.tasks[t].group, 'id': t}; 
+							} 
+					} 
+					handler_save(objsToSave); 
+					 
+				} 
+				 
+			} 
+		}); 
+						 
+	 
+	} else { 
+		handler_save(); 
+	}
 
 }).end()
@@ -259,5 +303,5 @@
                     ['=', 'type', '2'], 
                     ['>=','startTime', $.now()], 
-                    ['in', 'calendar', [$('div.new-activity-win.active select[name="groupFilter"]').val()]] 
+                    ['in', 'calendar', [$('div.new-activity-win.active select[name="groupFilter"]').val()]]
                 ], criteria: {filterTasks: true, deepness: 2}
         };
@@ -410,9 +454,9 @@
     updateActivity = false;
 
-    var idTask = UI.dialogs.addActivity.find('input[name="idActivity"]').val(); 
- 
-    getSchedulable( idTask ); 
- 
-    var objActivity = DataLayer.get('schedulable:activity', idTask ); 
+    var idTask = UI.dialogs.addActivity.find('input[name="idActivity"]').val();
+
+    getSchedulable( idTask );
+
+    var objActivity = DataLayer.get('schedulable:activity', idTask );
     var blkAddTask = UI.dialogs.addActivity.find('#group_addactivity_details8');
     var blkAuto = UI.dialogs.addActivity.find('#group_addactivity_details1');
@@ -673,9 +717,9 @@
             text: false
         }).click(function () {
- 
-            var idTask = $(this).parents('li').find('input[name="idtask[]"]').val() 
-            getSchedulable(idTask); 
-            var task = DataLayer.get('schedulable:task', idTask); 
-            taskDetails(task, true, '',true, null, true); 
+
+            var idTask = $(this).parents('li').find('input[name="idtask[]"]').val()
+            getSchedulable(idTask);
+            var task = DataLayer.get('schedulable:task', idTask);
+            taskDetails(task, true, '',true, null, true);
         })
         .addClass('tiny disable ui-button-disabled ui-state-disabled')
Index: branches/2.5/prototype/modules/calendar/js/desktop.notification.js
===================================================================
--- branches/2.5/prototype/modules/calendar/js/desktop.notification.js	(revision 7693)
+++ branches/2.5/prototype/modules/calendar/js/desktop.notification.js	(revision 8232)
@@ -5,10 +5,12 @@
     initDesktopNotificationAddon: function(){
 		if(useDesktopNotification()){
-
+			if ($.cookie('no-notification') == 'true'){
+				return false;
+			}
 			if (!window.webkitNotifications && $.browser.mozilla)
 			this.installDektopNotificationAddon();
 
 			if(window.webkitNotifications && window.webkitNotifications.checkPermission()){
-			     if($.browser.safari){
+			    if($.browser.safari){
                      $.Zebra_Dialog('Deseja instalar o plugin de notificação desktop?', {
                         'custom_class': 'request-notification-permission',
@@ -19,10 +21,15 @@
 
                     $('div.ZebraDialog.request-notification-permission a').click(function() {
-                        if($(this).html() == 'Sim')
+                        if($(this).html() == 'Sim'){
                             window.webkitNotifications.requestPermission();       
+                    	}else if ($(this).html() == 'Não'){
+                    		$.cookie('no-notification','true');
+                    	}
                     });
                 }else
                     window.webkitNotifications.requestPermission();
             }
+		}else{
+			$.cookie('no-notification',null);
 		}
     },
@@ -40,7 +47,6 @@
     	    }
     	};
-
+	   ;
 	   InstallTrigger.install(params);
-
 	   return false;
     },
Index: branches/2.5/prototype/modules/calendar/js/helpers.js
===================================================================
--- branches/2.5/prototype/modules/calendar/js/helpers.js	(revision 8059)
+++ branches/2.5/prototype/modules/calendar/js/helpers.js	(revision 8232)
@@ -111,6 +111,6 @@
 	var end = $("#calendar").fullCalendar('getView').visEnd.getTime()/1000;
 	var criteria = DataLayer.criteria("schedulable:calendar", {'start':start, 'end':end} );
- 
-    var data = DataLayer.encode('schedulable:print', DataLayer.dispatch('modules/calendar/schedules', criteria )  ); 
+
+    var data = DataLayer.encode('schedulable:print', DataLayer.dispatch('modules/calendar/schedules', criteria )  );
 
 	if($("#calendar").fullCalendar('getView').name == "month"){				
@@ -163,5 +163,5 @@
 	print.removeClass('fc-button-year');
 	print.removeClass('fc-corner-left');
-        print.removeClass('fc-state-active'); 
+	print.removeClass('fc-state-active');
 	print.find('.fc-button-content').html('Imprimir');
 	$('.fc-header-right').append(print);
@@ -179,38 +179,37 @@
 function eventDetails( objEvent, decoded, path, isMail, repeat, buttonClicked)
 {
-
     $('.qtip.qtip-blue').remove();
 
     attendees = {};
- 
-    if(!!objEvent.participants) 
-    { 
-        $.each(objEvent.participants ,function(index, value) { 
-
-            var part = DataLayer.get('participant' , value ); 
-            var user = DataLayer.get('user' , part.user ); 
- 
-            attendees[part.user] = user.name; 
-        }); 
-    } 
- 
+
+    if(!!objEvent.participants)
+    {
+        $.each(objEvent.participants ,function(index, value) {
+
+            var part = DataLayer.get('participant' , value );
+            var user = DataLayer.get('user' , part.user );
+
+            attendees[part.user] = user.name;
+        });
+    }
+
     if(path == undefined)
 	path = "";
-         
+	
     if( !decoded )
-        objEvent = DataLayer.decode("schedulable:calendar", objEvent ); 
- 
-        var dtstamp = objEvent.dtstamp;  
+	objEvent = DataLayer.decode("schedulable:calendar", objEvent );
+
+	var dtstamp = objEvent.dtstamp;
     if(!isMail)
-                objEvent = DataLayer.encode( "schedulable:preview", objEvent ); 
-        if (!dtstamp) 
-                var date = new Date(); 
-        else 
-                var date = new Date(parseInt(dtstamp)); 
-        objEvent.creationDate = []; 
-        objEvent.creationDate[0] = dateFormat(parseInt(dtstamp),'dd/mm/yyyy'); 
-        objEvent.creationDate[1] = date.getHours(); 
-        objEvent.creationDate[2] = date.getMinutes();    
-     
+		objEvent = DataLayer.encode( "schedulable:preview", objEvent );
+	if (!dtstamp)
+		var date = new Date();
+	else
+		var date = new Date(parseInt(dtstamp));
+	objEvent.creationDate = [];
+	objEvent.creationDate[0] = dateFormat(parseInt(dtstamp),'dd/mm/yyyy');
+	objEvent.creationDate[1] = date.getHours();
+	objEvent.creationDate[2] = date.getMinutes();	
+    
     if(typeof(objEvent.id) == 'undefined'){
 	objEvent.alarms = Calendar.signatureOf[User.preferences.defaultCalendar || Calendar.calendarIds[0]].defaultAlarms || false;
@@ -270,5 +269,6 @@
 	}).click(function () {
         var participant = DataLayer.get('participant' , $(this).parents('li').find('[type=checkbox]').val()); 
-            DataLayer.remove('participant', participant.id); 
+        DataLayer.remove('participant', participant.id);
+        
 	    if($(this).parent().find('.button.delegate').hasClass('attendee-permissions-change-button')){
 		removeOthers();
@@ -278,9 +278,10 @@
 		blkAddAtendee.find('option[value=1]').attr('selected','selected').trigger('change');
 	    }
+			
 	    $(this).parents('li').remove();
 			
 	    if(blkAddAtendee.find(".attendee-list li").length == 1)
 		blkAddAtendee.find("li.not-attendee").removeClass('hidden');
-        delete attendees[participant.user]; 
+     delete attendees[participant.user];
 	})
 	.addClass('tiny disable ui-button-disabled ui-state-disabled')
@@ -467,4 +468,6 @@
     }
     );
+	
+		
 }
 
@@ -487,4 +490,5 @@
 			$('.qtip.qtip-blue.qtip-active').qtip('destroy');						
 		attendees  = {};
+        DataLayer.rollback();//Limpa cache do datalayer
 	},
 	beforeClose: function(event, ui) {
@@ -566,41 +570,41 @@
 }
 
- 
-dateSameValue = function(){ 
-    UI.dialogs.addEvent.find('input.start-date').datepicker({ 
-        dateFormat: User.preferences.dateFormat.replace(/M/g, 'm').replace(/yyyy/g, 'yy'), 
-        onSelect : function (selectedDate){ 
-            endDate = $(".end-date").val(); 
-            storeSelectedDate = selectedDate; 
- 
-            if ( User.preferences.dateFormat == "dd/MM/yyyy" || User.preferences.dateFormat == "dd-MM-yyyy" ) { 
-                if ( User.preferences.dateFormat == "dd/MM/yyyy" ) { 
-                    selectedDate = selectedDate.split("/"); 
-                    endDate = endDate.split("/"); 
-                } else if( User.preferences.dateFormat == "dd-MM-yyyy" ){ 
-                    selectedDate = selectedDate.split("-"); 
-                    endDate = endDate.split("-"); 
-                } 
- 
-                newDt = new Date(selectedDate[2],selectedDate[1], selectedDate[0]); 
-                endDate = new Date(endDate[2],endDate[1], endDate[0]); 
- 
-            } else if ( User.preferences.dateFormat == "MM/dd/yyyy" ) { 
-                selectedDate = selectedDate.split("/"); 
-                endDate = endDate.split("/"); 
- 
-                newDt = new Date(selectedDate[2],selectedDate[0], selectedDate[1]); 
-                endDate = new Date(endDate[2],endDate[0], endDate[1]); 
-            } 
- 
-            if( newDt > endDate ) 
-                $(".end-date").val(storeSelectedDate); 
-        }, 
-        onClose: function(){ 
-                UI.dialogs.addEvent.find(".end-date").val(UI.dialogs.addEvent.find(".start-date").val()); 
-        } 
-    }); 
-} 
- 
+
+dateSameValue = function(){
+    UI.dialogs.addEvent.find('input.start-date').datepicker({
+        dateFormat: User.preferences.dateFormat.replace(/M/g, 'm').replace(/yyyy/g, 'yy'),
+        onSelect : function (selectedDate){
+            endDate = $(".end-date").val();
+            storeSelectedDate = selectedDate;
+
+            if ( User.preferences.dateFormat == "dd/MM/yyyy" || User.preferences.dateFormat == "dd-MM-yyyy" ) {
+                if ( User.preferences.dateFormat == "dd/MM/yyyy" ) {
+                    selectedDate = selectedDate.split("/");
+                    endDate = endDate.split("/");
+                } else if( User.preferences.dateFormat == "dd-MM-yyyy" ){
+                    selectedDate = selectedDate.split("-");
+                    endDate = endDate.split("-");
+                }
+
+                newDt = new Date(selectedDate[2],selectedDate[1], selectedDate[0]);
+                endDate = new Date(endDate[2],endDate[1], endDate[0]);
+
+            } else if ( User.preferences.dateFormat == "MM/dd/yyyy" ) {
+                selectedDate = selectedDate.split("/");
+                endDate = endDate.split("/");
+
+                newDt = new Date(selectedDate[2],selectedDate[0], selectedDate[1]);
+                endDate = new Date(endDate[2],endDate[0], endDate[1]);
+            }
+
+            if( newDt > endDate )
+                $(".end-date").val(storeSelectedDate);
+        },
+        onClose: function(){
+                UI.dialogs.addEvent.find(".end-date").val(UI.dialogs.addEvent.find(".start-date").val());
+        }
+    });
+}
+
 DataLayer.render( path+'templates/event_repeat.ejs', {
     event:objEvent
@@ -608,11 +612,11 @@
 
     UI.dialogs.addEvent.find('#calendar_addevent_details3').html(repeatHtml);
- 
-    dateSameValue(); 
+
+    dateSameValue();
     $(".date").datepicker({
 		dateFormat: User.preferences.dateFormat.replace(/M/g, 'm').replace(/yyyy/g, 'yy')
-        }); 
- 
- 
+	});
+
+
     if(objEvent.repeat) 
     {
@@ -1010,120 +1014,120 @@
 });
 
-dateSameValue(); 
- 
-var fixHour = function(){ 
-    currentTimeStart = UI.dialogs.addEvent.find("input.start-time").val(); 
-    UI.dialogs.addEvent.find("input.start-time").val(currentTimeStart.replace(".","").replace(".","")); 
-}    
- 
-var setTime = function( selectedDateTime ) { 
-    if ((selectedDateTime.value == '__:__') || (selectedDateTime.value == '__:__ __')) 
-          selectedDateTime.value = ""; 
-    if(!(User.preferences.hourFormat.length == 5)) 
-        $(this).val(selectedDateTime.replace(/[\.]/gi, ""));                                 
-    updateMap(); 
- 
-    if( Date.parse(selectedDateTime) < Date.parse(oldTime) ) return true; 
- 
-    var time = selectedDateTime.split(":"); 
- 
-    var hh = time[0]; 
-    var mm = time[1].substring(0, 2); 
+dateSameValue();
+
+var fixHour = function(){
+    currentTimeStart = UI.dialogs.addEvent.find("input.start-time").val();
+    UI.dialogs.addEvent.find("input.start-time").val(currentTimeStart.replace(".","").replace(".",""));
+}   
+
+var setTime = function( selectedDateTime ) {
+    if ((selectedDateTime.value == '__:__') || (selectedDateTime.value == '__:__ __'))
+          selectedDateTime.value = "";
+    if(!(User.preferences.hourFormat.length == 5))
+        $(this).val(selectedDateTime.replace(/[\.]/gi, ""));                                
+    updateMap();
+
+    if( Date.parse(selectedDateTime) < Date.parse(oldTime) ) return true;
     
-      
-    dt = new Date(); 
-    dt.setHours(hh, mm); 
-    var startHours = dt.getHours(); 
-    add = parseInt(User.preferences.defaultDuration) + parseInt($("input.end-time").val().split(":")[1].substring(0,2)); 
-    dt.addMinutes(add); 
+    var time = selectedDateTime.split(":");
+
+    var hh = time[0];
+    var mm = time[1].substring(0, 2);
+   
      
- 
-    var minutes = dt.getMinutes().toString(); 
-    var hours = dt.getHours(); 
-UI.dialogs.addEvent.find("input.start-time").val(selectedDateTime.replace(".","").replace(".","")); 
-     
-     
-    if (time[1].indexOf("p.m.") != -1 ) { 
-        var startHours = startHours == 12 ? 12 : startHours; 
-        var startHours = startHours == 1 ? 13 : startHours; 
-        var startHours = startHours == 2 ? 14 : startHours; 
-        var startHours = startHours == 3 ? 15 : startHours; 
-        var startHours = startHours == 4 ? 16 : startHours; 
-        var startHours = startHours == 5 ? 17 : startHours; 
-        var startHours = startHours == 6 ? 18 : startHours; 
-        var startHours = startHours == 7 ? 19 : startHours; 
-        var startHours = startHours == 8 ? 20 : startHours; 
-        var startHours = startHours == 9 ? 21 : startHours; 
-        var startHours = startHours == 10 ? 22 : startHours; 
-        var startHours = startHours == 11 ? 23 : startHours; 
-    } else if (time[1].indexOf("a.m.") ) { 
-        var startHours = startHours == 12 ? 00 : startHours; 
-    } 
- 
- 
-    dtFormat = (time[1].indexOf("p.m.") != -1 || time[1].indexOf("a.m.") != -1) ? ((((User.preferences.defaultDuration / 60) + startHours) >= 12 && (startHours + (User.preferences.defaultDuration / 60)) < 24) ? " pm" : " am") : ""; 
-        
-    var newHours = ""; 
-    if(dtFormat){ 
-        hours = hours == 13 ? 01 : hours; 
-        hours = hours == 14 ? 02 : hours; 
-        hours = hours == 15 ? 03 : hours; 
-        hours = hours == 16 ? 04 : hours; 
-        hours = hours == 17 ? 05 : hours; 
-        hours = hours == 18 ? 06 : hours; 
-        hours = hours == 19 ? 07 : hours; 
-        hours = hours == 20 ? 08 : hours; 
-        hours = hours == 21 ? 09 : hours; 
-        hours = hours == 22 ? 10 : hours; 
-        hours = hours == 23 ? 11 : hours; 
-        hours = hours == 24 ? 12 : hours; 
-    } else { 
-        newHours = hours <= 9 ? "0" : ""; 
-    } 
- 
-    minutes = minutes.length == 1 ? "0"+minutes+dtFormat : minutes+dtFormat; 
-    newHours +=  hours.toString() + ":" +minutes; 
-    UI.dialogs.addEvent.find("input.end-time").val(newHours); 
- 
-} 
- 
-    UI.dialogs.addEvent.find(".start-date").focusout(function(data){  
-        UI.dialogs.addEvent.find(".end-date").val($(this).val()); 
-    }); 
+    dt = new Date();
+    dt.setHours(hh, mm);
+    var startHours = dt.getHours();
+    add = parseInt(User.preferences.defaultDuration) + parseInt($("input.end-time").val().split(":")[1].substring(0,2));
+    dt.addMinutes(add);
+    
+
+    var minutes = dt.getMinutes().toString();
+    var hours = dt.getHours();
+UI.dialogs.addEvent.find("input.start-time").val(selectedDateTime.replace(".","").replace(".",""));
+    
+    
+    if (time[1].indexOf("p.m.") != -1 ) {
+        var startHours = startHours == 12 ? 12 : startHours;
+        var startHours = startHours == 1 ? 13 : startHours;
+        var startHours = startHours == 2 ? 14 : startHours;
+        var startHours = startHours == 3 ? 15 : startHours;
+        var startHours = startHours == 4 ? 16 : startHours;
+        var startHours = startHours == 5 ? 17 : startHours;
+        var startHours = startHours == 6 ? 18 : startHours;
+        var startHours = startHours == 7 ? 19 : startHours;
+        var startHours = startHours == 8 ? 20 : startHours;
+        var startHours = startHours == 9 ? 21 : startHours;
+        var startHours = startHours == 10 ? 22 : startHours;
+        var startHours = startHours == 11 ? 23 : startHours;
+    } else if (time[1].indexOf("a.m.") ) {
+        var startHours = startHours == 12 ? 00 : startHours;
+    }
+
+
+    dtFormat = (time[1].indexOf("p.m.") != -1 || time[1].indexOf("a.m.") != -1) ? ((((User.preferences.defaultDuration / 60) + startHours) >= 12 && (startHours + (User.preferences.defaultDuration / 60)) < 24) ? " pm" : " am") : "";
+       
+    var newHours = "";
+    if(dtFormat){
+        hours = hours == 13 ? 01 : hours;
+        hours = hours == 14 ? 02 : hours;
+        hours = hours == 15 ? 03 : hours;
+        hours = hours == 16 ? 04 : hours;
+        hours = hours == 17 ? 05 : hours;
+        hours = hours == 18 ? 06 : hours;
+        hours = hours == 19 ? 07 : hours;
+        hours = hours == 20 ? 08 : hours;
+        hours = hours == 21 ? 09 : hours;
+        hours = hours == 22 ? 10 : hours;
+        hours = hours == 23 ? 11 : hours;
+        hours = hours == 24 ? 12 : hours;
+    } else {
+        newHours = hours <= 9 ? "0" : "";
+    }
+
+    minutes = minutes.length == 1 ? "0"+minutes+dtFormat : minutes+dtFormat;
+    newHours +=  hours.toString() + ":" +minutes;
+    UI.dialogs.addEvent.find("input.end-time").val(newHours);
+
+}
+
+    UI.dialogs.addEvent.find(".start-date").focusout(function(data){ 
+        UI.dialogs.addEvent.find(".end-date").val($(this).val());
+    });
 
     var oldTime = UI.dialogs.addEvent.find('input.start-time').val();
-    $(".start-time").focusout(function(data){ 
-        if($("#calendar").fullCalendar('getView').name == "month" || buttonClicked) { 
-            setTime( $(this).val() ); 
-        } 
-    }); 
-  
-    UI.dialogs.addEvent.find('input.start-time').timepicker({ 
-        ampm : ((User.preferences.hourFormat.length > 5) ? true: false), 
-        timeFormat: "hh:mm tt", 
-        onSelect: function( selectedDateTime ){ 
-            if($("#calendar").fullCalendar('getView').name == "month" || buttonClicked) { 
-                if ( selectedDateTime.indexOf("p.m.") == -1 || !selectedDateTime.indexOf("a.m.") == -1 ) { 
-                    var selectedTime = selectedDateTime.split(":"); 
-                    var endTime = UI.dialogs.addEvent.find(".end-time").val(); 
-                    endTime = endTime.split(":"); 
- 
-                    var t1 = new Date(false,false,false,selectedTime[0],selectedTime[1],false); 
-                    var t2 = new Date(false,false,false,endTime[0],endTime[1],false); 
- 
-                    if (t1 < t2) return true; 
-                } 
- 
-                setTime( selectedDateTime ); 
-            } 
-        }, 
-        onClose : function (selectedDateTime){ 
-            fixHour(); 
-        } 
- 
-    }); 
- 
-
- 
+    $(".start-time").focusout(function(data){
+        if($("#calendar").fullCalendar('getView').name == "month" || buttonClicked) {
+            setTime( $(this).val() );
+        }
+    });
+
+    UI.dialogs.addEvent.find('input.start-time').timepicker({
+        ampm : ((User.preferences.hourFormat.length > 5) ? true: false),
+        timeFormat: "hh:mm tt",
+        onSelect: function( selectedDateTime ){
+            if($("#calendar").fullCalendar('getView').name == "month" || buttonClicked) {
+                if ( selectedDateTime.indexOf("p.m.") == -1 || !selectedDateTime.indexOf("a.m.") == -1 ) {
+                    var selectedTime = selectedDateTime.split(":");
+                    var endTime = UI.dialogs.addEvent.find(".end-time").val();
+                    endTime = endTime.split(":");
+
+                    var t1 = new Date(false,false,false,selectedTime[0],selectedTime[1],false);
+                    var t2 = new Date(false,false,false,endTime[0],endTime[1],false);
+
+                    if (t1 < t2) return true;
+                }
+
+                setTime( selectedDateTime );
+            }
+        },
+        onClose : function (selectedDateTime){
+            fixHour();
+        }
+
+    });
+
+
+
 UI.dialogs.addEvent.find('input.end-time').timepicker({ 
     closeText: 'Ok',
@@ -1138,37 +1142,38 @@
 	    	$(this).val(selectedDateTime.replace(/[\.]/gi, ""));								
 		updateMap();
- 
-        if ( selectedDateTime.indexOf("p.m.") == -1 || !selectedDateTime.indexOf("a.m.") == -1 ) { 
-            var startT = UI.dialogs.addEvent.find('input.start-time'); 
- 
-            var lessZeroTime = function( sTime ) { 
-                sTime = sTime.split(":"); 
-                sTime = new Date(false,false,false,sTime[0],sTime[1],false); 
-                sTimeReady = parseInt(sTime.getHours() - (User.preferences.defaultDuration / 60)); 
- 
-                if( sTimeReady < 0 ) 
-                    return false; // If the value is less than 0, return false. 
-                     
-                return sTimeReady.toString().length == 1 ? "0"+sTimeReady+":00" : sTimeReady+":00"; 
-            } 
- 
-            var hEnd = new Date(false,false,false,selectedDateTime.split(":")[0],selectedDateTime.split(":")[1],false); 
-            var hStart = new Date(false,false,false,startT.val().split(":")[0],startT.val().split(":")[1],false); 
-             
-            if ( hEnd <= hStart ){ 
-                var lessTime = lessZeroTime( selectedDateTime ); 
-                if ( !lessTime ){ 
-                    startT.val( "00:00" ); 
-                    return true; 
-                } 
-                startT.val( lessTime ); 
-            } 
-        } 
+
+        if ( selectedDateTime.indexOf("p.m.") == -1 || !selectedDateTime.indexOf("a.m.") == -1 ) {
+            var startT = UI.dialogs.addEvent.find('input.start-time');
+
+            var lessZeroTime = function( sTime ) {
+                sTime = sTime.split(":");
+                sTime = new Date(false,false,false,sTime[0],sTime[1],false);
+                sTimeReady = parseInt(sTime.getHours() - (User.preferences.defaultDuration / 60));
+
+                if( sTimeReady < 0 )
+                    return false; // If the value is less than 0, return false.
+                    
+                return sTimeReady.toString().length == 1 ? "0"+sTimeReady+":00" : sTimeReady+":00";
+            }
+
+            var hEnd = new Date(false,false,false,selectedDateTime.split(":")[0],selectedDateTime.split(":")[1],false);
+            var hStart = new Date(false,false,false,startT.val().split(":")[0],startT.val().split(":")[1],false);
+            
+            if ( hEnd <= hStart ){
+                var lessTime = lessZeroTime( selectedDateTime );
+                if ( !lessTime ){
+                    startT.val( "00:00" );
+                    return true;
+                }
+                startT.val( lessTime );
+            }
+        }
     },
     onClose : function (selectedDateTime){
 	if(!(User.preferences.hourFormat.length == 5))
 	    $(this).val(selectedDateTime.replace(/[\.]/gi, ""));
-    fixHour(); 
+    fixHour();
     },
+
     beforeShow: function (selectedDateTime) {
 		if ((selectedDateTime.value == '__:__') || (selectedDateTime.value == '__:__ __'))
@@ -1216,9 +1221,9 @@
 var attendeeHtml = DataLayer.render( path+'templates/attendee_add.ejs', {
     event:objEvent
-});
+});		
 	
 // load template of attendees
 var blkAddAtendee = UI.dialogs.addEvent.find('#calendar_addevent_details6').append(attendeeHtml);
-if(objEvent.attendee.length)
+if(objEvent.attendee.length) 
 	 	callbackAttendee(); 
 /**
@@ -1598,16 +1603,16 @@
 	    if ($(event.target).is('input')) {
 		old_item = $(event.target).parents('li');
- 
-        var  userId = old_item.find('.id').html(); 
- 
-        if(userId == '') 
-        { 
-           var  userId = DataLayer.put('user', { 
-                name: old_item.find('.name').html(), 
-                mail: old_item.find('.mail').html(), 
-                isExternal: '1' 
-            }); 
-        } 
- 
+
+        var  userId = old_item.find('.id').html();
+
+        if(userId == '')
+        {
+           var  userId = DataLayer.put('user', {
+                name: old_item.find('.name').html(),
+                mail: old_item.find('.mail').html(),
+                isExternal: '1'
+            });
+        }
+
 		newAttendeeId = DataLayer.put('participant', {
 		    user: userId,
@@ -1768,14 +1773,13 @@
 	DataLayer.render( 'templates/preferences_calendar.ejs', {
 	    preferences:User.preferences, 
-            calendars: Calendar.calendars, 
-        signatureOf : Calendar.signatureOf 
+	    calendars: Calendar.calendars,
+        signatureOf : Calendar.signatureOf
 	    }, function( template ){
 	    var tabPrefCalendar = jQuery('#preference_tab').html( template ).find('.preferences-win');
 		
-            tabPrefCalendar.find('select[name="defaultCalendar"] option[value="'+User.preferences.defaultCalendar+'"]').attr('selected','selected').trigger('change'); 
+	    tabPrefCalendar.find('select[name="defaultCalendar"] option[value="'+User.preferences.defaultCalendar+'"]').attr('selected','selected').trigger('change'); 
         tabPrefCalendar.find('select[name="dafaultImportCalendar"] option[value="'+User.preferences.dafaultImportCalendar+'"]').attr('selected','selected').trigger('change'); 
- 
-        DataLayer.render( 'templates/timezone_list.ejs', {}, function( timezones_options ){ 
-
+
+	    DataLayer.render( 'templates/timezone_list.ejs', {}, function( timezones_options ){
 		tabPrefCalendar.find('select[name="timezone"]').html(timezones_options).find('option[value="'+User.preferences.timezone+'"]').attr('selected','selected').trigger('change');
 	    });
@@ -2103,18 +2107,34 @@
 
 function getSelectedCalendars( reverse, type ){
-    var selector = !!type ? "div.my-groups-task .calendar-view" : "div.my-calendars .calendar-view, div.signed-calendars .calendar-view"; 
-    var returns = []; 
- 
-    $.each( $(selector), function(i , c){ 
- 
-        if( reverse ? !c.checked : c.checked ) 
-            returns.push( c.value ); 
- 
+
+    var selector = "";
+
+    switch(type)
+    {
+        case 0:
+            selector = "div.my-calendars .calendar-view, div.signed-calendars .calendar-view";
+            break;
+        case 1:
+            selector = "div.my-groups-task .calendar-view";
+            break;
+        case 2:
+            selector = ".calendar-view";
+            break;
+    }
+
+//  var selector = !!type ? "div.my-groups-task .calendar-view" : "div.my-calendars .calendar-view, div.signed-calendars .calendar-view";
+    var returns = [];
+
+    $.each( $(selector), function(i , c){
+
+        if( reverse ? !c.checked : c.checked )
+            returns.push( c.value );
+
     });
- 
-    if (!returns.length) 
-            return false; 
- 
-    return returns; 
+
+    if (!returns.length)
+	    return false;
+
+    return returns;
 }
 
@@ -2173,10 +2193,7 @@
 		var schudableDecode = DataLayer.encode( "schedulable:preview", schedulable);
 		var me = schudableDecode.me.user ? schudableDecode.me.user.id : schudableDecode.me.id;
-
-        var filter = {filter: ['AND', ['=','id',eventId], ['=','calendar',idCalendar], ['=','user', me]]};
-
+        var filter = {filter: ['AND', ['=','id',eventId], ['=','calendar',idCalendar], ['=','user', me] ] };
         if(type)
             filter.filter.push(['=','type',type]);
-
 		DataLayer.removeFilter('schedulable', filter);
 		Calendar.rerenderView(true);
@@ -2306,6 +2323,6 @@
 		
 	});
- 
-     $('ul.list-calendars .cal-list-options-btn').on('click',function(){doMenu();});         
+
+     $('ul.list-calendars .cal-list-options-btn').on('click',function(){doMenu();});
 	
 
@@ -2479,6 +2496,6 @@
 	show_modal_search_shared();
     });
-	
- 	
+		
+
     meu_container.find('.title-signed-calendars').click(function(evt){
 	var status = $(this).parent().find('.status-list-shared');
@@ -2491,28 +2508,28 @@
 		
     $('.calendar-view').click(function(evt){
- 
-        var checkBox = $(this); 
-        var calendarId = $(this).val(); 
- 
-        Calendar.signatureOf[ calendarId ].hidden =  (checkBox.is(':checked') ? 0 : 1 ); 
- 
-        DataLayer.put('calendarSignature', {id: Calendar.signatureOf[ calendarId ].id , hidden: Calendar.signatureOf[ calendarId ].hidden }  ); 
-        DataLayer.commit(); 
- 
- 
-         if($tabs.tabs('option' ,'selected') == 0){ 
- 
-             if(Calendar.currentView && !!Calendar.currentView[ calendarId ]){ 
- 
-                 Calendar.currentView[ calendarId ].hidden = !checkBox.is(':checked'); 
-                 $('#calendar').fullCalendar( 'refetchEvents' ); 
-             } 
- 
-         }else{ 
-             type = $tabs.tabs('option' ,'selected'); 
-             type = type > 2 ? 2 : (type - 1) 
- 
-             pageselectCallback('', 0, false, type); 
-         } 
+
+        var checkBox = $(this);
+        var calendarId = $(this).val();
+
+        Calendar.signatureOf[ calendarId ].hidden =  (checkBox.is(':checked') ? 0 : 1 );
+
+        DataLayer.put('calendarSignature', {id: Calendar.signatureOf[ calendarId ].id , hidden: Calendar.signatureOf[ calendarId ].hidden }  );
+        DataLayer.commit();
+
+
+         if($tabs.tabs('option' ,'selected') == 0){
+
+             if(Calendar.currentView && !!Calendar.currentView[ calendarId ]){
+
+                 Calendar.currentView[ calendarId ].hidden = !checkBox.is(':checked');
+                 $('#calendar').fullCalendar( 'refetchEvents' );
+             }
+
+         }else{
+             type = $tabs.tabs('option' ,'selected');
+             type = type > 2 ? 2 : (type - 1)
+
+             pageselectCallback('', 0, false, type);
+         }
     });
 });
@@ -2624,5 +2641,5 @@
 	    $(this).addClass('fc-state-hover');
 	},
- 
+
 	function(){
 	    $(this).removeClass('fc-state-hover');
@@ -2658,7 +2675,7 @@
 	else
 	    pageselectCallback($(currentView+' [name = keyword]').val(), ((parseInt($(currentView+' [name = page_index]').val())) -1), view, type);
-    }); 
-    if (currentView == "#tab_events_list_" || currentView == "#tab_tasks_list_") 
-        $(currentView+' .events-list.events-list-win.active .header-paginator .fc-header-left').find('span.fc-button-agendaWeek, span.fc-button-agendaDay').remove(); 
+    });
+    if (currentView == "#tab_events_list_" || currentView == "#tab_tasks_list_")
+    	$(currentView+' .events-list.events-list-win.active .header-paginator .fc-header-left').find('span.fc-button-agendaWeek, span.fc-button-agendaDay').remove();
 }
 
@@ -2725,7 +2742,7 @@
 	case 'agendaWeek':
 	    var dateStart = new Date().moveToDayOfWeek(dateCalendar.dayOfWeek[User.preferences.weekStart]); 
-            var dateEnd = new Date().moveToDayOfWeek(dateCalendar.dayOfWeek[User.preferences.weekStart]); 
-            dateEnd.setHours(0,0,0); 
-            dateStart.setHours(0,0,0);  
+	    var dateEnd = new Date().moveToDayOfWeek(dateCalendar.dayOfWeek[User.preferences.weekStart]);
+	    dateEnd.setHours(0,0,0);
+	    dateStart.setHours(0,0,0);
 	    rangeStart = dateStart.add({ days: (7 * page_index)	}).getTime();
 	    rangeEnd = dateEnd.add({ days: (7 * page_index)+7 }).getTime();
@@ -2739,6 +2756,6 @@
 	    var dateStart = new Date().add({ years: page_index });
 	    var dateEnd = new Date().add({ years: page_index });
-            dateEnd.setHours(0,0,0); 
-            dateStart.setHours(0,0,0); 
+	    dateEnd.setHours(0,0,0);
+	    dateStart.setHours(0,0,0);
 	    if(dateStart.getMonth() != 0)
 		    dateStart.moveToMonth(0, -1)
@@ -2804,7 +2821,7 @@
             };
         }
-         
+	
         var results = DataLayer.encode('schedulable:list', DataLayer.dispatch('modules/calendar/schedules', criteria));
-        //var results = DataLayer.get('schedulable:detail', criteria);
+	//var results = DataLayer.get('schedulable:detail', criteria);
         keyword = ( keyword || '' ).replace( /\s+/g, "_" );
 	}
@@ -2858,5 +2875,5 @@
 				var eventId = $(this).siblings('[name="eventid"]').val();
 				var calendarId = $(this).siblings('[name="calendarid"]').val();
-				remove_event(eventId, calendarId, 2);
+				remove_event(eventId, calendarId, ( $(this).siblings('[name="eventtype"]').val() ));
 				event.stopImmediatePropagation()
 			})
@@ -3131,23 +3148,23 @@
         delete schedulable['historic'];
 
-        schedulable.participants =  $.map( participants, function( attendee, i ){ 
- 
-            var participant = DataLayer.get('participant', attendee, false); 
- 
-            if(typeof(participant) == 'array') 
-                participant = participant[0]; 
- 
-            if(owner.id != participant.user) 
-                delete participant.status; 
- 
-            delete participant.delegatedFrom; 
-            delete participant.id; 
-            delete participant.schedulable; 
- 
-            participant.id = DataLayer.put('participant', participant); 
- 
-            return  (parseInt(type) == 3) ? participant.id : participant ; 
-        }); 
- 
+        schedulable.participants =  $.map( participants, function( attendee, i ){
+
+            var participant = DataLayer.get('participant', attendee, false);
+
+            if(typeof(participant) == 'array')
+                participant = participant[0];
+
+            if(owner.id != participant.user)
+                delete participant.status;
+
+            delete participant.delegatedFrom;
+            delete participant.id;
+            delete participant.schedulable;
+
+            participant.id = DataLayer.put('participant', participant);
+
+            return  (parseInt(type) == 3) ? participant.id : participant ;
+        });
+
 	//Edit ocurrence
 	if(parseInt(type) == 3){
Index: branches/2.5/prototype/modules/calendar/js/init.js
===================================================================
--- branches/2.5/prototype/modules/calendar/js/init.js	(revision 8054)
+++ branches/2.5/prototype/modules/calendar/js/init.js	(revision 8232)
@@ -317,5 +317,5 @@
 		axisFormat: User.preferences.hourFormat,
 		eventSources: Calendar.sources,
-
+		
 		header: {
 			left: 'prev,next today,agendaWeek,' + ((User.preferences.defaultCalView == "basicDay") ? "basicDay" : "agendaDay"),
@@ -353,26 +353,44 @@
 		},
 
-
         eventRender: function( event, element, view ){
 		    $('#calendar td.fc-year-have-event').removeClass('fc-year-have-event');
 
 			var img_icon = "";
- 
-            if( !!parseInt(event.unanswered)  ){ 
- 
-                img_icon = "mini-attention.png"; 
- 
-            }else{ 
- 
-			if(event.type == 1)
-				img_icon = "mini-event.png";
-			if(event.type == 2)
-				img_icon = "mini-task.png";
-			if(event.type == 3)
-				img_icon = "mini-activity.png";
-
-	}
-		
-    	    element.find(".fc-event-inner.fc-event-skin").prepend($('<img style="width: 11px; height: 13px;" class="" src="../prototype/modules/calendar/img/' + img_icon + '"></img>'));
+			var status_ball = ""; //nome da imagem a ser inserida
+			var status_img = "";
+
+            if( !!parseInt(event.unanswered) && event.type == 1 ){
+
+                img_icon = "mini-attention.png";
+
+            }else{
+
+                if(event.type == 1)
+                    img_icon = "mini-event.png";
+                if(event.type == 2)
+                    img_icon = "mini-task.png";
+                if(event.type == 3)
+                    img_icon = "mini-activity.png";
+
+                //se for diferente de evento(type 1).
+                if(event.type != 1){
+                    if(event.status == "1"){
+                        status_ball = "gray.png";
+                    }else if(event.status == "2"){
+                        status_ball = "yellow.png";
+                    }else if(event.status == "3"){
+                        status_ball = "green.png";
+                    }else if(event.status == "4"){
+                        status_ball = "red.png";
+                    }
+
+                    status_img = '<img style="width: 8px; height: 8px; margin-bottom: 2px;" src="../prototype/modules/calendar/img/' + status_ball + '"></img>';
+                }
+
+            }
+
+
+			//html que exibe a imagem do type e do status
+    	    element.find(".fc-event-inner.fc-event-skin").prepend($('<img style="width: 11px; height: 13px;" class="" src="../prototype/modules/calendar/img/' + img_icon + '"></img>' + status_img));
 		},
 
@@ -477,12 +495,12 @@
                                 'type':     'question',
                                 'overlay_opacity': '0.5',
-                                'custom_class':  'occurrence-zebra', 
+                                'custom_class':  'occurrence-zebra',
                                 'width': 427,
                                 'buttons':  ['Editar todas ocorrências', 'Editar essa ocorrência', 'Cancelar'],
                                 'onClose':  function(clicked) {
                                     if(clicked == 'Editar todas ocorrências') {
-                                        var schedule = getSchedulable(evt.id, ''); 
-                                        schedule.calendar = evt.calendar; 
-                                        eventDetails( schedule , true); 
+                                        var schedule = getSchedulable(evt.id, '');
+                                        schedule.calendar = evt.calendar;
+                                        eventDetails( schedule , true);
 
                                     }else if (clicked == 'Editar essa ocorrência'){
@@ -493,5 +511,5 @@
                                         */      
                                         var repeat = mount_exception(evt.id, evt.occurrence);
-                                                                                          
+
                                         $('.calendar-copy-move input[name="typeEvent"]').val("3");
                                         
@@ -513,4 +531,5 @@
                     break;
                 case 3:
+					DataLayer.remove('taskToActivity', false);//Limpa o cache
                     var activity = getSchedulable(evt.id, '');
                     activity.group = evt.calendar;
@@ -565,6 +584,6 @@
 
     if( $.browser.msie ){
-
-        $('#divAppbox').css('width', $(window).width());
+        //$('#divAppbox').css('width', $(window).width());
+    	$('#divAppbox').css({'height':'600px','max-width':'100%'});
     }
 
Index: branches/2.5/prototype/modules/calendar/js/task.helpers.js
===================================================================
--- branches/2.5/prototype/modules/calendar/js/task.helpers.js	(revision 7864)
+++ branches/2.5/prototype/modules/calendar/js/task.helpers.js	(revision 8232)
Index: branches/2.5/prototype/modules/calendar/templates/event_repeat.ejs
===================================================================
--- branches/2.5/prototype/modules/calendar/templates/event_repeat.ejs	(revision 7978)
+++ branches/2.5/prototype/modules/calendar/templates/event_repeat.ejs	(revision 8232)
@@ -32,8 +32,8 @@
 		<label for="repeatweekly[]">Domingo</label>
 
-		<input type="checkbox" name="repeatweekly[]" value="MO"  <%= ((data.event.acl.write || data.event.acl.organization) && data.event.isAttendee) ? '' : 'disabled="disabled"'%>>
+		<input type="checkbox" name="repeatweekly[]" value="MO" <%= ((data.event.acl.write || data.event.acl.organization) && data.event.isAttendee) ? '' : 'disabled="disabled"'%>>
 		<label for="repeatweekly[]">Segunda</label>
 
-		<input type="checkbox" name="repeatweekly[]" value="TU"  <%= ((data.event.acl.write || data.event.acl.organization) && data.event.isAttendee) ? '' : 'disabled="disabled"'%>>
+		<input type="checkbox" name="repeatweekly[]" value="TU" <%= ((data.event.acl.write || data.event.acl.organization) && data.event.isAttendee) ? '' : 'disabled="disabled"'%>>
 		<label for="repeatweekly[]">Terça</label>
 
Index: branches/2.5/prototype/modules/calendar/templates/attendee_add.ejs
===================================================================
--- branches/2.5/prototype/modules/calendar/templates/attendee_add.ejs	(revision 7982)
+++ branches/2.5/prototype/modules/calendar/templates/attendee_add.ejs	(revision 8232)
@@ -11,6 +11,6 @@
 						<option value="3" <%= data.event.status=='3' ? 'selected="selected"':'' %>>Eu não vou</option>
 						<option value="2" <%= data.event.status=='2' ? 'selected="selected"':'' %>>Talvez</option>
-                        <option value="4" <%= data.event.status=='4' ? 'selected="selected"':'' %>>Sem resposta </option> 
-                                            <option class="hidden" value="5" >Delegado</option> 
+                        <option value="4" <%= data.event.status=='4' ? 'selected="selected"':'' %>>Sem resposta </option>
+					    <option class="hidden" value="5" >Delegado</option>
 					<%}%>
 				<%}else{%>
Index: branches/2.5/prototype/modules/calendar/templates/shared_calendar.ejs
===================================================================
--- branches/2.5/prototype/modules/calendar/templates/shared_calendar.ejs	(revision 7019)
+++ branches/2.5/prototype/modules/calendar/templates/shared_calendar.ejs	(revision 8232)
@@ -7,12 +7,17 @@
 				<dd class="calendar">
 					<select class="calendar" name="calendar">
-							<%							
-							for(var i = 0; i < data.calendar.length; i++){
-								if(data.signature[i].permission){
-									if(data.signature[i].permission.acl.shared == false)
-										continue;
-								}
-							%>
-								<option value="<%=data.calendar[i].id%>"><%=data.calendar[i].name%></option>
+                        <%
+                        for(var i = 0; i < data.calendar.length; i++)
+                        {
+                            for(var ii = 0; ii < data.signature.length; ii++)
+                            {
+                                if(data.signature[ii].calendar.id === data.calendar[i].id && data.signature[ii].permission)
+                                {
+                                    if(data.signature[ii].permission.acl.shared == false)
+                                        continue;
+                                }
+                            }
+                        %>
+						<option value="<%=data.calendar[i].id%>"><%=data.calendar[i].name%></option>
 									
 							<% 
@@ -24,22 +29,5 @@
 			<dd class="<%=data.calendar ? "user-list" : "calendar-list"%>">
 				<ul class="user-list">
-				<% if (false) {
-					for (var i=0; i< data.event.user.length; i++) {%>
-						<li class="user"> 
-							<div style="overflow:hidden; width:100%; display:table;">
-								<input type="checkbox" value="">
-								<input type="hidden" name="user[]" value="">
-								<label class="name"></label>
-								<label class="mail"></label>
-							</div> 
-							<div class="shared-acl">
-									<a class="button edit user-options-button-edit new">Editar permissões</a>
-									<a class="button close new">Remover</a>
-							</div>
-						</li>	
-					<%} 
-				} else { %>
 					<li class="not-user"><%=data.calendar ? "Não compartilhado." : "Nenhuma agenda selecionada"%></li>
-				<% } %>
 				</ul>
 			</dd>	
Index: branches/2.5/prototype/modules/calendar/templates/event_add.ejs
===================================================================
--- branches/2.5/prototype/modules/calendar/templates/event_add.ejs	(revision 8050)
+++ branches/2.5/prototype/modules/calendar/templates/event_add.ejs	(revision 8232)
@@ -78,23 +78,23 @@
 				continue;
 			%>
-                            <% if( data.event.isShared ){ %> 
-                    <% if(data.event.calendars[i].id == data.event.calendar){ %> 
-                        <option value="<%= data.event.calendars[i].id %>"><%= data.event.calendars[i].name %></option> 
-                    <%}%> 
- 
-                <% }else { %> 
- 
-                <option value="<%= data.event.calendars[i].id %>" <%= data.event.calendars[i].id == data.event.calendar ? 'selected="selected"':'' %>><%= data.event.calendars[i].name %></option> 
-                <% } %> 
- 
- 
+			    <% if( data.event.isShared ){ %>
+                    <% if(data.event.calendars[i].id == data.event.calendar){ %>
+                        <option value="<%= data.event.calendars[i].id %>"><%= data.event.calendars[i].name %></option>
+                    <%}%>
+
+                <% }else { %>
+
+                <option value="<%= data.event.calendars[i].id %>" <%= data.event.calendars[i].id == data.event.calendar ? 'selected="selected"':'' %>><%= data.event.calendars[i].name %></option>
+                <% } %>
+
+
 			<% } %>
 			</select>
-                                <span class="creation-date-label">Evento criado em <%= data.event.creationDate[0] %> às 
-                                        <%= data.event.creationDate[1] %> horas e <%= data.event.creationDate[2] %> minutos. 
-                                </span> 
-                </p> 
- 
- 
+				<span class="creation-date-label">Evento criado em <%= data.event.creationDate[0] %> às
+					<%= data.event.creationDate[1] %> horas e <%= data.event.creationDate[2] %> minutos.
+				</span>
+		</p>
+
+
 		<fieldset class="hidden">
 			<legend class="hidden">Publicidade</legend>
Index: branches/2.5/prototype/modules/calendar/templates/preferences_calendar.ejs
===================================================================
--- branches/2.5/prototype/modules/calendar/templates/preferences_calendar.ejs	(revision 8021)
+++ branches/2.5/prototype/modules/calendar/templates/preferences_calendar.ejs	(revision 8232)
@@ -36,6 +36,6 @@
 				<label for="defaultCalView">Visualização padrão do calendário:</label>
 				<select name="defaultCalView" >
-                                        <option value="agendaDay" <%= data.preferences.defaultCalView =='agendaDay' ? 'selected="selected"':'' %>>Diária com horário</option> 
-                                        <option value="basicDay" <%= data.preferences.defaultCalView =='basicDay' ? 'selected="selected"':'' %>>Diária sem horário</option> 
+					<option value="agendaDay" <%= data.preferences.defaultCalView =='agendaDay' ? 'selected="selected"':'' %>>Diária com horário</option>
+					<option value="basicDay" <%= data.preferences.defaultCalView =='basicDay' ? 'selected="selected"':'' %>>Diária sem horário</option>
 					<option value="agendaWeek" <%= data.preferences.defaultCalView =='agendaWeek' ? 'selected="selected"':'' %>>Semanal</option>
 					<option value="month" <%= data.preferences.defaultCalView =='month' ? 'selected="selected"':'' %>>Mensal</option>
@@ -72,5 +72,5 @@
 
 			<p class="input-group"> 
-                <label for="defaultCalendar">Agenda padrão para Criação de Eventos:</label> 
+                <label for="defaultCalendar">Agenda padrão para Criação de Eventos:</label>
                 <select name="defaultCalendar" > 
                     <%for(var i = 0; i < data.calendars.length; i++){%> 
@@ -79,16 +79,16 @@
                 </select>
 			</p>
- 
-            <p class="input-group"> 
-                <label for="dafaultImportCalendar">Agenda padrão para Importação de Eventos :</label> 
-                <select name="dafaultImportCalendar" > 
-                    <option value=""> </option> 
-                    <%for(var i = 0; i < data.calendars.length; i++){ 
-                     if(data.signatureOf[data.calendars[i].id].isOwner == '1'){ 
-                    %> 
-                    <option value="<%=data.calendars[i].id%>"> <%= data.calendars[i].name %></option> 
-                    <%}}%> 
-                </select> 
-            </p> 
+
+            <p class="input-group">
+                <label for="dafaultImportCalendar">Agenda padrão para Importação de Eventos :</label>
+                <select name="dafaultImportCalendar" >
+                    <option value=""> </option>
+                    <%for(var i = 0; i < data.calendars.length; i++){
+                     if(data.signatureOf[data.calendars[i].id].isOwner == '1'){
+                    %>
+                    <option value="<%=data.calendars[i].id%>"> <%= data.calendars[i].name %></option>
+                    <%}}%>
+                </select>
+            </p>
 
 			<p class="input-group">
Index: branches/2.5/prototype/modules/calendar/templates/event_detail_list.ejs
===================================================================
--- branches/2.5/prototype/modules/calendar/templates/event_detail_list.ejs	(revision 7982)
+++ branches/2.5/prototype/modules/calendar/templates/event_detail_list.ejs	(revision 8232)
Index: branches/2.5/prototype/api/datalayer.js
===================================================================
--- branches/2.5/prototype/api/datalayer.js	(revision 6444)
+++ branches/2.5/prototype/api/datalayer.js	(revision 8232)
@@ -657,4 +657,8 @@
 
 	}
+
+     if( typeof DataLayer.storage.cache[':diff'] != 'object')
+         DataLayer.storage.cache[':diff'] = {};
+
     },
     
Index: branches/2.5/prototype/api/templates/foldertree.ejs
===================================================================
--- branches/2.5/prototype/api/templates/foldertree.ejs	(revision 8113)
+++ branches/2.5/prototype/api/templates/foldertree.ejs	(revision 8232)
@@ -4,9 +4,9 @@
 			Inbox: {name:'Caixa de Entrada', classe:'inbox'}, 
 		};
-    specialFolders[outboxfolder] = {name: 'Caixa de Saída', classe:'outbox'}; 
-        specialFolders[trashfolder] = {name:'Lixeira', classe:'trash'}; 
-        specialFolders[draftsfolder] = {name:'Rascunhos', classe:'drafts'}; 
-        specialFolders[spamfolder] = {name:'Spam', classe:'spam'}; 
-        specialFolders[sentfolder] = {name:'Enviados', classe:'sent'}; 
+    specialFolders[outboxfolder] = {name: 'Caixa de Saída', classe:'outbox'};
+	specialFolders[trashfolder] = {name:'Lixeira', classe:'trash'};
+	specialFolders[draftsfolder] = {name:'Rascunhos', classe:'drafts'};
+	specialFolders[spamfolder] = {name:'Spam', classe:'spam'};
+	specialFolders[sentfolder] = {name:'Enviados', classe:'sent'};
 
 	function recursive_forest(array_trees)
Index: branches/2.5/prototype/rest/catalog/SharedGroupResource.php
===================================================================
--- branches/2.5/prototype/rest/catalog/SharedGroupResource.php	(revision 6578)
+++ branches/2.5/prototype/rest/catalog/SharedGroupResource.php	(revision 8232)
@@ -85,6 +85,5 @@
 
 	    //Recupera os grupos do usuario
-	    $groups = Controller::find(array('concept' => 'contactGroup'), false, array('filter' => array('=', 'user', $ownerId), 'order' => array('name')));
-
+        $groups = Controller::find(array('concept' => 'contactGroup'), false, array('filter' => array('=','id', $id), 'AND' => array('=','user', $ownerId) , 'order' => array('name')));
 	    if($groups){
                 foreach($groups[0]['contacts'] as $value){
Index: branches/2.5/calendar/setup/tables_update.inc.php
===================================================================
--- branches/2.5/calendar/setup/tables_update.inc.php	(revision 7516)
+++ branches/2.5/calendar/setup/tables_update.inc.php	(revision 8232)
@@ -154,4 +154,10 @@
         	return $GLOBALS['setup_info']['calendar']['currentver'];
     	}
+  	$test[] = '2.5.0';
+        function calendar_upgrade2_5_0()
+        {
+                $GLOBALS['setup_info']['calendar']['currentver'] = '2.5.1';
+                return $GLOBALS['setup_info']['calendar']['currentver'];
+        }
 
 
Index: branches/2.5/calendar/setup/setup.inc.php
===================================================================
--- branches/2.5/calendar/setup/setup.inc.php	(revision 7516)
+++ branches/2.5/calendar/setup/setup.inc.php	(revision 8232)
@@ -12,5 +12,5 @@
 
 	$setup_info['calendar']['name']    = 'calendar';
-	$setup_info['calendar']['version'] = '2.5.0';
+	$setup_info['calendar']['version'] = '2.5.1';
 	$setup_info['calendar']['app_order'] = 3;
 	$setup_info['calendar']['enable']  = 1;
@@ -52,4 +52,4 @@
 	$setup_info['calendar']['depends'][] = array(
 		 'appname' => 'phpgwapi',
-		 'versions' => Array('2.5.0')
+		 'versions' => Array('2.5.1.0')
 	);
Index: branches/2.5/workflow/setup/tables_update.inc.php
===================================================================
--- branches/2.5/workflow/setup/tables_update.inc.php	(revision 7516)
+++ branches/2.5/workflow/setup/tables_update.inc.php	(revision 8232)
@@ -360,10 +360,18 @@
         return $GLOBALS['setup_info']['workflow']['currentver'];
     }
-	$test[] = '2.4.2';
-    	function workflow_upgrade2_4_2()
-    	{
-        	$GLOBALS['setup_info']['workflow']['currentver'] = '2.5.0';
-        	return $GLOBALS['setup_info']['workflow']['currentver'];
-    	}
+
+    $test[] = '2.4.2';
+    function workflow_upgrade2_4_2()
+    {
+        $GLOBALS['setup_info']['workflow']['currentver'] = '2.5.0';
+        return $GLOBALS['setup_info']['workflow']['currentver'];
+    }
+
+    $test[] = '2.5.0';
+    function workflow_upgrade2_5_0()
+    {
+        $GLOBALS['setup_info']['workflow']['currentver'] = '2.5.1';
+        return $GLOBALS['setup_info']['workflow']['currentver'];
+    }
 
 
Index: branches/2.5/workflow/setup/setup.inc.php
===================================================================
--- branches/2.5/workflow/setup/setup.inc.php	(revision 7516)
+++ branches/2.5/workflow/setup/setup.inc.php	(revision 8232)
@@ -13,5 +13,5 @@
 	$setup_info['workflow']['name']			= 'workflow';
 	$setup_info['workflow']['title']		= 'Workflow Management';
-	$setup_info['workflow']['version']		= '2.5.0';
+	$setup_info['workflow']['version']		= '2.5.1';
 	$setup_info['workflow']['app_order']	= 10;
 	$setup_info['workflow']['enable']		= 1;
@@ -59,9 +59,9 @@
 	$setup_info['workflow']['depends'][] = array(
 		'appname' => 'phpgwapi',
-		'versions' => Array('1.2', '2.0', '2.2', '2.4', '2.5')
+		'versions' => Array('2.5.1.1')
 	);
 	$setup_info['workflow']['depends'][] = array(
 		'appname' => 'preferences',
-		'versions' => Array('0.9.13.002', '2.0', '2.2', '2.5.0')
+		'versions' => Array('2.5.1')
 	);
 ?>
Index: branches/2.5/workflow/inc/local/classes/class.wf_instance.php
===================================================================
--- branches/2.5/workflow/inc/local/classes/class.wf_instance.php	(revision 5928)
+++ branches/2.5/workflow/inc/local/classes/class.wf_instance.php	(revision 8232)
@@ -443,4 +443,22 @@
 
 	/**
+	* Busca uma instância pelo id
+	* @param int $wf_instance_id O id da instância
+	* @return array As instâncias que satisfazem o critério de seleção.
+	* @access public
+	*/
+	public function getById($wf_instance_id)
+	{
+		/* build the SQL query */
+		$query = 'SELECT i.wf_instance_id AS wf_instance_id, ia.wf_activity_id AS wf_activity_id, ia.wf_started AS wf_started, i.wf_name AS wf_name, i.wf_status AS wf_status, ia.wf_user AS wf_user, i.wf_priority AS wf_priority ';
+		$query .= 'FROM egw_wf_instances i LEFT JOIN egw_wf_instance_activities ia ON (ia.wf_instance_id = i.wf_instance_id)';
+		$query .= 'WHERE (i.wf_p_id = ?) AND i.wf_instance_id = ?';
+
+		$resultSet = $this->db->query($query, array($this->processID, intval($wf_instance_id)));
+		
+		return $resultSet->GetArray();
+	}
+
+	/**
 	* Busca todas as instâncias que possuem esse nome (identificador).
 	* @param string $name O nome da instância que se quer encontrar.
@@ -456,4 +474,22 @@
 
 		$resultSet = $this->db->query($query, array($this->processID, $name));
+		return $resultSet->GetArray();
+	}
+
+	/**
+	* Busca todas as instâncias que possuem um trecho do nome (identificador).
+	* @param string $name O trecho do nome da instância que se quer encontrar.
+	* @return array As instâncias que satisfazem o critério de seleção.
+	* @access public
+	*/
+	public function getLikeName($name)
+	{
+		/* build the SQL query */
+		$query = 'SELECT i.wf_instance_id AS wf_instance_id, ia.wf_activity_id AS wf_activity_id, ia.wf_started AS wf_started, i.wf_name AS wf_name, i.wf_status AS wf_status, ia.wf_user AS wf_user, i.wf_priority AS wf_priority ';
+		$query .= 'FROM egw_wf_instances i LEFT JOIN egw_wf_instance_activities ia ON (ia.wf_instance_id = i.wf_instance_id)';
+		$query .= "WHERE (i.wf_p_id = ?) AND i.wf_name ILIKE '%$name%'";
+
+		$resultSet = $this->db->query($query, array($this->processID));
+
 		return $resultSet->GetArray();
 	}
@@ -584,4 +620,29 @@
 		return $this->setUser($instanceID, $activityID, 'p' . $roleID);
 	}
+
+	/**
+	* Altera o wf_name das instâncias, fazendo o replace no nome da categoria de serviço. 
+	* Método chamado quando é alterada a categoria de um serviço e existem ocorrências atrelados a esse serviço.
+	* @param int | array $instanceID se for um array, concatena os instances ids
+	* @param string @currentServiceName Nome da categoria de serviço atual
+	* @param string @newServiceName Nome da nova categoria de serviço
+	* @return resultSet em caso de sucesso ou false
+	* @access public 
+	*/
+	public function updateReplaceName($instanceID, $currentServiceName, $newServiceName)
+	{
+		$success = true;
+
+		// Se for array, faz implode concatenando os ids
+		if (is_array($instanceID))
+		{
+			$instanceID = implode(',', $instanceID);
+		}
+
+		$query = "UPDATE egw_wf_instances SET wf_name = REPLACE(wf_name, '" . $currentServiceName . "', '" . $newServiceName . "') WHERE wf_instance_id IN (" . $instanceID . ")";
+		$success = $this->db->execute($query);
+
+		return $success;
+	}
 }
 ?>
Index: branches/2.5/workflow/inc/smarty/wf_plugins/function.wf_select_user.php
===================================================================
--- branches/2.5/workflow/inc/smarty/wf_plugins/function.wf_select_user.php	(revision 4740)
+++ branches/2.5/workflow/inc/smarty/wf_plugins/function.wf_select_user.php	(revision 8232)
@@ -115,5 +115,5 @@
 
 	$output .= <<<EOF
-		<a alt="$title" title="$title" href="javascript:void(0)" onclick="openParticipants('$name', '$extraParams');"><img border="0" alt="" src="$image" /></a>
+		<a alt="$title" title="$title" href="javascript:void(0)" onclick="openParticipantsWindow('$name', '$extraParams');"><img border="0" alt="" src="$image" /></a>
 EOF;
 	return $output;
Index: branches/2.5/workflow/inc/class.Logger.inc.php
===================================================================
--- branches/2.5/workflow/inc/class.Logger.inc.php	(revision 3167)
+++ branches/2.5/workflow/inc/class.Logger.inc.php	(revision 8232)
@@ -29,4 +29,10 @@
 
 	/**
+	 * @var object $db Objeto de banco de dados do modulo workflow
+	 * @access private
+	 */
+	private $dbGalaxia = null;
+
+	/**
 	 * @var string $logPath Caminho onde será salvo o arquivo de log, caso o tipo de log Log_file seja adicionado à composição
 	 * @access private
@@ -81,6 +87,8 @@
 
 		$this->db =& Factory::getInstance('WorkflowObjects')->getDBExpresso()->Link_ID;
+		$this->dbGalaxia =& Factory::getInstance('WorkflowObjects')->getDBGalaxia()->Link_ID;
 
 		if(!empty($curProcessName)){
+
 			$query = '
 				SELECT
@@ -89,5 +97,5 @@
 					egw_wf_processes';
 
-			if(!($result = $this->db->query($query)))
+			if(!($result = $this->dbGalaxia->query($query)))
 				throw new Exception(lang('Cannot execute query'));
 
@@ -131,5 +139,5 @@
 						wf_config_name like 'log_level'
 						";
-			$config_value = array_pop($this->db->query($query)->GetArray(-1));
+			$config_value = array_pop($this->dbGalaxia->query($query)->GetArray(-1));
 			$this->logLevel = $config_value['wf_config_value_int'];
 		} else {
Index: branches/2.5/workflow/js/jscode/participants.js
===================================================================
--- branches/2.5/workflow/js/jscode/participants.js	(revision 3729)
+++ branches/2.5/workflow/js/jscode/participants.js	(revision 8232)
@@ -364,5 +364,5 @@
 }
 
-function openParticipants(target, option)
+function openParticipantsWindow(target, option)
 {
 	newWidth   = 500;
Index: branches/2.5/workflow/js/orgchart/organization.js
===================================================================
--- branches/2.5/workflow/js/orgchart/organization.js	(revision 7379)
+++ branches/2.5/workflow/js/orgchart/organization.js	(revision 8232)
@@ -736,5 +736,5 @@
 	content += '<input type="hidden" name="funcionario_id" id="funcionario_id" value="" />';
 	content += '<input type="input" name="funcionario_id_desc" id="funcionario_id_desc" value="" readonly="true" size="40" />';
-	content += '<a href="javascript:void(0)" onclick="openParticipants(\'funcionario_id\', \'uid=1&hidegroups=1\');" id="addEmployeeLink"><img border="0" width="16" height="16" src="workflow/templateFile.php?file=images/add_user.png" /></a>';
+	content += '<a href="javascript:void(0)" onclick="openParticipantsWindow(\'funcionario_id\', \'uid=1&hidegroups=1\');" id="addEmployeeLink"><img border="0" width="16" height="16" src="workflow/templateFile.php?file=images/add_user.png" /></a>';
 	content += '</td></tr>';
 	content += '<tr><td><label for="funcionario_status_id">Status</label></td><td id="comboStatus"><i>carregando</i></td></tr>';
@@ -801,5 +801,5 @@
 	content += '<input type="hidden" name="titular_funcionario_id" id="titular_funcionario_id" value="" />';
 	content += '<input type="input" name="titular_funcionario_id_desc" id="titular_funcionario_id_desc" value="" readonly="true" size="40" />';
-	content += '<a href="javascript:void(0)" onclick="openParticipants(\'titular_funcionario_id\', \'uid=1&hidegroups=1\');"><img border="0" width="16" height="16" src="workflow/templateFile.php?file=images/add_user.png" /></a>';
+	content += '<a href="javascript:void(0)" onclick="openParticipantsWindow(\'titular_funcionario_id\', \'uid=1&hidegroups=1\');"><img border="0" width="16" height="16" src="workflow/templateFile.php?file=images/add_user.png" /></a>';
 	content += ' <a href="javascript:void(0)" onclick="$(\'titular_funcionario_id\').value=\'\'; $(\'titular_funcionario_id_desc\').value=\'\'; return false;"><img border="0" width="16" height="16" src="workflow/templateFile.php?file=images/delete_user.png" /></a>';
 	content += '</td></tr>';
@@ -807,5 +807,5 @@
 	content += '<input type="hidden" name="auxiliar_funcionario_id" id="auxiliar_funcionario_id" value="" />';
 	content += '<input type="input" name="auxiliar_funcionario_id_desc" id="auxiliar_funcionario_id_desc" value="" readonly="true" size="40" />';
-	content += '<a href="javascript:void(0)" onclick="openParticipants(\'auxiliar_funcionario_id\', \'uid=1&hidegroups=1\');"><img border="0" width="16" height="16" src="workflow/templateFile.php?file=images/add_user.png" /></a>';
+	content += '<a href="javascript:void(0)" onclick="openParticipantsWindow(\'auxiliar_funcionario_id\', \'uid=1&hidegroups=1\');"><img border="0" width="16" height="16" src="workflow/templateFile.php?file=images/add_user.png" /></a>';
 	content += ' <a href="javascript:void(0)" onclick="$(\'auxiliar_funcionario_id\').value=\'\'; $(\'auxiliar_funcionario_id_desc\').value=\'\'; return false;"><img border="0" width="16" height="16" src="workflow/templateFile.php?file=images/delete_user.png" /></a>';
 	content += '</td></tr>';
@@ -882,5 +882,5 @@
 	content += '<input type="hidden" name="substituto_funcionario_id" id="substituto_funcionario_id" value="" />';
 	content += '<input type="input" name="substituto_funcionario_id_desc" id="substituto_funcionario_id_desc" value="" readonly="true" size="40" />';
-	content += '<a href="javascript:void(0)" onclick="openParticipants(\'substituto_funcionario_id\', \'uid=1&hidegroups=1\');"><img border="0" width="16" height="16" src="workflow/templateFile.php?file=images/add_user.png" /></a>';
+	content += '<a href="javascript:void(0)" onclick="openParticipantsWindow(\'substituto_funcionario_id\', \'uid=1&hidegroups=1\');"><img border="0" width="16" height="16" src="workflow/templateFile.php?file=images/add_user.png" /></a>';
 	content += ' <a href="javascript:void(0)" onclick="$(\'substituto_funcionario_id\').value=\'\'; $(\'substituto_funcionario_id_desc\').value=\'\'; return false;"><img border="0" width="16" height="16" src="workflow/templateFile.php?file=images/delete_user.png" /></a>';
 	content += '</td></tr>';
Index: branches/2.5/workflow/js/adminaccess/control_folder.js
===================================================================
--- branches/2.5/workflow/js/adminaccess/control_folder.js	(revision 3255)
+++ branches/2.5/workflow/js/adminaccess/control_folder.js	(revision 8232)
@@ -416,5 +416,5 @@
 	bt.setAttribute('name','Selecionar');
 	bt.setAttribute('value','Selecionar');
-	bt.onclick = function() { openParticipants('sel_org_user', 'hidegroups=1'); };
+	bt.onclick = function() { openParticipantsWindow('sel_org_user', 'hidegroups=1'); };
 	td.appendChild(bt);
 
@@ -575,5 +575,5 @@
 	bt.setAttribute('name','Selecionar');
 	bt.setAttribute('value','Selecionar');
-	bt.onclick = function() { openParticipants('sel_proc_user', ''); };
+	bt.onclick = function() { openParticipantsWindow('sel_proc_user', ''); };
 	td.appendChild(bt);
 
@@ -726,5 +726,5 @@
 	bt.setAttribute('name','Selecionar');
 	bt.setAttribute('value','Selecionar');
-	bt.onclick = function() { openParticipants('sel_mon_user', ''); };
+	bt.onclick = function() { openParticipantsWindow('sel_mon_user', ''); };
 	td.appendChild(bt);
 
@@ -785,5 +785,5 @@
 	content += '<td align="right"><input type="button" name="Remover" value="Remover" onclick="deleteExternalApplicationAdmin();"/></td>';
 	content += '<td></td>';
-	content += '<td align="right"><input type="button" name="Selecionar" value="Selecionar" onclick="openParticipants(\'sel_exa_user\', \'\')"/><input type="button" name="Remover" value="Remover" onclick="del_selected_reg(\'sel_exa_user\');"/></td>';
+	content += '<td align="right"><input type="button" name="Selecionar" value="Selecionar" onclick="openParticipantsWindow(\'sel_exa_user\', \'\')"/><input type="button" name="Remover" value="Remover" onclick="del_selected_reg(\'sel_exa_user\');"/></td>';
 	content += '</tr>';
 	content += '<tr><td colspan="3"></td></tr>';
@@ -849,5 +849,5 @@
 	content += '<td align="right"><input type="button" name="Remover" value="Remover" onclick="deleteWorkflowAdministrators();"/></td>';
 	content += '<td></td>';
-	content += '<td align="right"><input type="button" name="Selecionar" value="Selecionar" onclick="openParticipants(\'selectWorkflowUsers\', \'\')"/><input type="button" name="Remover" value="Remover" onclick="del_selected_reg(\'selectWorkflowUsers\');"/></td>';
+	content += '<td align="right"><input type="button" name="Selecionar" value="Selecionar" onclick="openParticipantsWindow(\'selectWorkflowUsers\', \'\')"/><input type="button" name="Remover" value="Remover" onclick="del_selected_reg(\'selectWorkflowUsers\');"/></td>';
 	content += '</tr>';
 	content += '<tr><td colspan="3"></td></tr>';
@@ -901,5 +901,5 @@
 	content += '<td align="right"><input type="button" name="Remover" value="Remover" onclick="deleteDevelopmentAdministrators();"/></td>';
 	content += '<td></td>';
-	content += '<td align="right"><input type="button" name="Selecionar" value="Selecionar" onclick="openParticipants(\'selectDevelopmentUsers\', \'\')"/><input type="button" name="Remover" value="Remover" onclick="del_selected_reg(\'selectDevelopmentUsers\');"/></td>';
+	content += '<td align="right"><input type="button" name="Selecionar" value="Selecionar" onclick="openParticipantsWindow(\'selectDevelopmentUsers\', \'\')"/><input type="button" name="Remover" value="Remover" onclick="del_selected_reg(\'selectDevelopmentUsers\');"/></td>';
 	content += '</tr>';
 	content += '<tr><td colspan="3"></td></tr>';
Index: branches/2.5/workflow/js/monitors/processes.js
===================================================================
--- branches/2.5/workflow/js/monitors/processes.js	(revision 795)
+++ branches/2.5/workflow/js/monitors/processes.js	(revision 8232)
@@ -101,5 +101,5 @@
 				content += '<td><input type="hidden" name="newUser" id="newUser" value="" />';
 				content += '<input type="input" name="newUser_desc" id="newUser_desc" value="" readonly="true" size="32" />';
-				content += '<a href="javascript:void(0)" onclick="openParticipants(\'newUser\', \'uid=1&hidegroups=1\');"><img border="0" width="16" height="16" src="workflow/templateFile.php?file=images/add_user.png"/></a></td></tr>';
+				content += '<a href="javascript:void(0)" onclick="openParticipantsWindow(\'newUser\', \'uid=1&hidegroups=1\');"><img border="0" width="16" height="16" src="workflow/templateFile.php?file=images/add_user.png"/></a></td></tr>';
 				content += '<tr><td colspan="2"><button onclick="clickLoadActivities(' + pid + ');return false;">Próximo >></button></td></tr></table>';
 				content += '</td>';
Index: branches/2.5/workflow/templates/default/admin_roles.tpl
===================================================================
--- branches/2.5/workflow/templates/default/admin_roles.tpl	(revision 795)
+++ branches/2.5/workflow/templates/default/admin_roles.tpl	(revision 8232)
@@ -123,7 +123,7 @@
 				</select>
 			</td><td valign=center align=center>
-				<a href='javascript:void(0)' onclick="openParticipants('user_list', 'entities=ug&usePreffix=1');"><img border=0 src={src_img_add_users}></a>
+				<a href='javascript:void(0)' onclick="openParticipantsWindow('user_list', 'entities=ug&usePreffix=1');"><img border=0 src={src_img_add_users}></a>
 				<br>
-				<a href='javascript:void(0)' onclick="openParticipants('user_list', 'entities=ug&usePreffix=1');">{lang_Add}</a>
+				<a href='javascript:void(0)' onclick="openParticipantsWindow('user_list', 'entities=ug&usePreffix=1');">{lang_Add}</a>
 				<br><br>
 				<a href="javascript:void(0)" onclick="participantsRemoveUser(document.getElementById('user_list'));"><img border=0 src={src_img_del_users}></a>
Index: branches/2.5/workflow/templates/default/admin_activities.tpl
===================================================================
--- branches/2.5/workflow/templates/default/admin_activities.tpl	(revision 1710)
+++ branches/2.5/workflow/templates/default/admin_activities.tpl	(revision 8232)
@@ -178,5 +178,5 @@
 			<div id="div_default_user_option_0" style="display:none;">
 				<input type="input" name="default_user_desc" id="default_user_desc" value="{wf_default_user_desc}" readonly="true" size="40" />
-				<a href="javascript:void(0)" onclick="openParticipants('default_user', 'uid=1&hidegroups=1');"><img border="0" src="workflow/templateFile.php?file=images/add_user.png" /></a>
+				<a href="javascript:void(0)" onclick="openParticipantsWindow('default_user', 'uid=1&hidegroups=1');"><img border="0" src="workflow/templateFile.php?file=images/add_user.png" /></a>
 				<button onclick="document.getElementById('default_user_desc').value=''; document.getElementById('default_user').value='*'; return false">{lang_without_default_user}</button>
 				<br>
Index: branches/2.5/expressoMail1_2/assetic.php
===================================================================
--- branches/2.5/expressoMail1_2/assetic.php	(revision 7919)
+++ branches/2.5/expressoMail1_2/assetic.php	(revision 8232)
@@ -47,5 +47,5 @@
         new FileAsset('../prototype/plugins/watermark/jquery.watermarkinput.js'),
         new FileAsset('../prototype/plugins/fileupload/jquery.iframe-transport.js'),
-        new FileAsset('../prototype/plugins/qtip/jquery.qtip-1.0.0-rc3.min.js'), 
+        new FileAsset('../prototype/plugins/qtip/jquery.qtip-1.0.0-rc3.min.js'),
         new FileAsset('../prototype/plugins/treeview/jquery.treeview.js'),
         new FileAsset('../prototype/plugins/treeview/lib/jquery.cookie.js'),    
Index: branches/2.5/expressoMail1_2/index.php
===================================================================
--- branches/2.5/expressoMail1_2/index.php	(revision 7919)
+++ branches/2.5/expressoMail1_2/index.php	(revision 8232)
@@ -16,5 +16,5 @@
 		'enable_nextmatchs_class' => True
 	);
-	
+
 	require_once('../header.inc.php');
 	include_once dirname(__FILE__) . '/../header.inc.php';
@@ -25,8 +25,13 @@
 	$AlternateEmailExpresso = $alternativeMailService->getMailAlternateByUidNumber($_SESSION['phpgw_info']['expressomail']['user']['account_id']);
 	$template->set_var("user_email_alternative", implode(",", $AlternateEmailExpresso));	
+  	
+  	if (execmethod('emailadmin.ui.countProfiles') == 0){
+        execmethod('emailadmin.ui.addDefaultProfile');
+    }
 
 	$update_version = $GLOBALS['phpgw_info']['apps']['expressoMail1_2']['version'];
 	$_SESSION['phpgw_info']['expressomail']['user'] = $GLOBALS['phpgw_info']['user'];
 	echo "<script type='text/javascript'>var template = '".$_SESSION['phpgw_info']['expressoMail1_2']['user']['preferences']['common']['template_set']."';</script>";
+
 
 	//jquery and Editor 
@@ -74,5 +79,21 @@
 		  <script type="text/javascript" src="js/DropDownContacts.js"></script>
 		  ';
-	
+
+//
+//    include_once(__DIR__.'/inc/class.imap_functions.inc.php');
+//
+//    $param = array();
+//    $param['folder'] = 'INBOX';
+//    $param['msg_range_begin'] = '1';
+//    $param['msg_range_end'] = '50';
+//    $param['sort_box_type'] = 'SORTARRIVAL';
+//    $param['search_box_type'] = 'ALL';
+//    $param['sort_box_reverse'] = '1';
+//
+//    $imapf = new imap_functions();
+//    $initialMessages = $imapf->get_range_msgs2($param);
+//
+//    echo '<script type="text/javascript"> var initialMessages  = '.json_encode($initialMessages).'</script>';
+
 	/*
 	 * TODO: implementar o controle como preferência do usuário 
@@ -251,6 +272,6 @@
     }
 
-    echo '<script type="text/javascript"> var preferences  = '.json_encode($_SESSION['phpgw_info']['user']['preferences']['expressoMail']).'</script>'; 
- 
+    echo '<script type="text/javascript"> var preferences  = '.json_encode($_SESSION['phpgw_info']['user']['preferences']['expressoMail']).'</script>';
+
     echo '
 	<script> var special_folders = new Array(4);
@@ -334,5 +355,5 @@
 	//echo $obj -> getFilesJs("js/common_functions.js",$update_version);
 	include("inc/load_lang.php");
-    
+
     // INCLUDE these JS Files:
 	if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_local_messages']) 
@@ -349,6 +370,6 @@
 	echo "<script> use_local_messages = ".$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_local_messages']."</script>";		
 	if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_local_messages'])
-		$scripts .= "js/local_messages.js";	
-		
+		$scripts .= "js/local_messages.js";
+
 	echo '
 		<!--<script type="text/javascript" src="../prototype/modules/mail/js/followupflag.js"></script>-->
@@ -360,9 +381,26 @@
 	';
 
-	echo 
+//////////////////////////////////////////// Carregar Timezones para o javascript /////////////////////////////////////////
+
+    $zones = timezone_identifiers_list();
+    $Time = new DateTime('now', new DateTimeZone('UTC'));
+    $timezone = array();
+
+    foreach ($zones as $zone)
+    {
+        $timezone['timezones'][$zone] = $Time->setTimezone(new DateTimeZone($zone))->format('O');
+    }
+
+    $localtime = localtime(time(), true);
+    $timezone['isDaylightSaving'] =  !!$localtime['tm_isdst'] ? 1 : 0;
+
+    echo '<script type="text/javascript"> var Timezone  = '.json_encode($timezone).'</script>';
+
+////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+	echo
 	    '<script src="../prototype/plugins/datejs/date-pt-BR.js" language="javascript" ></script>
-		<script src="../prototype/modules/calendar/js/timezone.js" language="javascript" ></script>
-                <script src="../prototype/plugins/dateFormat/dateFormat.js" language="javascript" ></script> 
-                <script src="../prototype/modules/calendar/js/calendar.date.js" language="javascript" ></script> 
+		<script src="../prototype/plugins/dateFormat/dateFormat.js" language="javascript" ></script>
+		<script src="../prototype/modules/calendar/js/calendar.date.js" language="javascript" ></script>
 		<script src="../prototype/modules/calendar/js/calendar.codecs.js" language="javascript" ></script>
 		<script src="../prototype/modules/calendar/js/calendar.alarms.js" language="javascript" ></script>
@@ -371,7 +409,31 @@
 	echo $obj -> getFilesJs($scripts, $update_version);
 	echo '<script type="text/javascript">connector.updateVersion = "'.$update_version.'";</script>';
-		
 	echo '<script type="text/javascript" src="assetic.php"></script>';
-	
+
+/////////   Verifica se o usuario esta fora do escritorio imprime a variavel javascript "outOfficeFlag" /////////////////////////////
+
+    include_once(__DIR__ .'/../library/Net/Sieve.php');
+    $sieveConf  =  parse_ini_file( __DIR__."/../prototype/config/Sieve.srv", true );
+    $sieveConf = $sieveConf['config'];
+    $sieve = new Net_Sieve();
+    $inVacation = false;
+    @$sieve->connect( $sieveConf['host'] , $sieveConf['port'] , $sieveConf['options'] , $sieveConf['useTLS'] );
+    @$sieve->login( $_SESSION['wallet']['Sieve']['user'], $_SESSION['wallet']['Sieve']['password'] , $sieveConf['loginType']);
+    $script = $sieve->getScript($sieve->getActive());
+    $pos = strripos($script, "#PseudoScript#");
+    $pseudo_script = substr( $script, $pos+17 );
+    $sieveRules = json_decode( $pseudo_script, true );
+    foreach( $sieveRules as $i => $v)
+        if($v['id'] == 'vacation' && $v['enabled'] == 'true')
+            $inVacation = true;
+
+    if($inVacation)
+        echo '<script language="javascript"> write_msg(get_lang("Attention, you are in out of office mode."), true);   </script>';
+
+//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+
+
+
 
 	// Get Preferences or redirect to preferences page.
Index: branches/2.5/expressoMail1_2/templates/default/index.tpl
===================================================================
--- branches/2.5/expressoMail1_2/templates/default/index.tpl	(revision 8113)
+++ branches/2.5/expressoMail1_2/templates/default/index.tpl	(revision 8232)
@@ -209,5 +209,5 @@
 <div class="expressomail-module-container" style="display: none;"></div>
 <div id="importEmails" style="display:none;padding:5px;"></div>
-<div id="importEmailsLocal" style="display:none;padding:5px;"></div> 
+<div id="importEmailsLocal" style="display:none;padding:5px;"></div>
 <div id="sendFileMessages" style="display:none;"></div>
 <div id="quickAddContact" style="display:none;"></div>
Index: branches/2.5/expressoMail1_2/templates/default/main.css
===================================================================
--- branches/2.5/expressoMail1_2/templates/default/main.css	(revision 7762)
+++ branches/2.5/expressoMail1_2/templates/default/main.css	(revision 8232)
@@ -1245,5 +1245,6 @@
 	font-weight : bold;
 	padding-right : 5px;
-	padding-left : 25px;	
+	padding-left : 5px;	
+	padding-top : 2px;	
 	font-family : Lucida Grande, Lucida Sans, Arial, sans-serif;
 	font-size : 11px;
@@ -1255,9 +1256,10 @@
 	background-position: 0 -923px;
 	background-repeat:no-repeat;
-	padding-left : 20px;
+	padding-right : 5px;
+	padding-left : 5px;	
+	padding-top : 2px;	
 	color : red;
 	text-align: right;
 	font-weight : bold;
-	padding-right : 5px;
 }
 
@@ -1641,2 +1643,9 @@
 	top: 585px;
 }		
+
+@media screen and (max-width: 1100px){
+	#span_options, #span_D span
+	{
+		font-size: 0.8333em; /*10/12px*/
+	}
+}
Index: branches/2.5/expressoMail1_2/setup/phpgw_pt-br.lang
===================================================================
--- branches/2.5/expressoMail1_2/setup/phpgw_pt-br.lang	(revision 8117)
+++ branches/2.5/expressoMail1_2/setup/phpgw_pt-br.lang	(revision 8232)
@@ -972,4 +972,8 @@
 MailArchiver user logged out	expressoMail1_2	pt-br	Usuário desconectado do MailArchiver
 Error trying to send the message. Retry in a few seconds...	expressoMail1_2	pt-br	Erro ao tentar enviar a mensagem. Nova tentativa em alguns segundos...
+Create filter from message	expressoMail1_2	pt-br	Criar filtro a partir da mensagem
 Sending the message...	expressoMail1_2	pt-br	Enviando a mensagem...
-Local Archive	expressoMail1_2	pt-br	Arquivamento Local
+Please, Wait the messages from archieve be ready.	expressoMail1_2	pt-br	Por favor, Aguarde as mensagens arquivadas ficarem prontas.
+take on this option to regard the message body in the search.	expressoMail1_2	pt-br	Considerar o corpo da mensagem como filtro na busca
+take off this option to disregard the message body in the search.	expressoMail1_2	pt-br	Desconsiderar o corpo da mensagem como filtro na busca
+Local Archive	expressoMail1_2	pt-br	Arquivamento Local 
Index: branches/2.5/expressoMail1_2/setup/tables_update.inc.php
===================================================================
--- branches/2.5/expressoMail1_2/setup/tables_update.inc.php	(revision 7516)
+++ branches/2.5/expressoMail1_2/setup/tables_update.inc.php	(revision 8232)
@@ -330,8 +330,13 @@
 
 	$test[] = '2.4.8.2';
-    	function expressoMail1_2_upgrade2_4_8_2() {
-        	$GLOBALS['setup_info']['expressoMail1_2']['currentver'] = '2.5.0';
-        	return $GLOBALS['setup_info']['expressoMail1_2']['currentver'];
-    	}
-
+    function expressoMail1_2_upgrade2_4_8_2() {
+        $GLOBALS['setup_info']['expressoMail1_2']['currentver'] = '2.5.0';
+        return $GLOBALS['setup_info']['expressoMail1_2']['currentver'];
+    }
+
+    $test[] = '2.5.0';
+    function expressoMail1_2_upgrade2_5_0() {
+        $GLOBALS['setup_info']['expressoMail1_2']['currentver'] = '2.5.1';
+        return $GLOBALS['setup_info']['expressoMail1_2']['currentver'];
+    }
 ?>
Index: branches/2.5/expressoMail1_2/setup/setup.inc.php
===================================================================
--- branches/2.5/expressoMail1_2/setup/setup.inc.php	(revision 7516)
+++ branches/2.5/expressoMail1_2/setup/setup.inc.php	(revision 8232)
@@ -13,5 +13,5 @@
 $setup_info['expressoMail1_2']['name'] = 'expressoMail1_2';
 $setup_info['expressoMail1_2']['title'] = 'Expresso Mail';
-$setup_info['expressoMail1_2']['version'] = '2.5.0';
+$setup_info['expressoMail1_2']['version'] = '2.5.1';
 $setup_info['expressoMail1_2']['app_order'] = 2;
 $setup_info['expressoMail1_2']['tables'][] = 'phpgw_certificados';
@@ -46,5 +46,5 @@
 $setup_info['expressoMail1_2']['depends'][] = array(
     'appname' => 'phpgwapi',
-    'versions' => Array('2.5.0')
+    'versions' => Array('2.5.1.1')
 );
 
Index: branches/2.5/expressoMail1_2/inc/class.db_functions.inc.php
===================================================================
--- branches/2.5/expressoMail1_2/inc/class.db_functions.inc.php	(revision 7673)
+++ branches/2.5/expressoMail1_2/inc/class.db_functions.inc.php	(revision 8232)
@@ -147,14 +147,33 @@
 		return $stringDropDownContacts;
 	}
-	
-	function getContactsByGroupAlias($alias)
-	{
+function getContactsByGroupAlias($alias)
+	{
+		/*
 		list($alias,$uid) = explode("::",$alias);		
+		
 		$cc_related_ids = $_SESSION['phpgw_info']['expressomail']['user']['cc_related_ids'];		
 		// Explode personal group, If exists related ids (the user has permission to send email).
+		
 		if(is_array($cc_related_ids) && $uid){
-			$owner =  array_search($uid,$cc_related_ids);			
-		}
-		
+			$owner =  array_search($uid,$cc_related_ids);					
+		}*/
+		$groups = $this->get_cc_groups();
+		if ($groups){
+			$groups = explode(",", $groups);
+			for($ii=0; $ii < count($groups); ++$ii) {
+				$tmp = preg_split("/;|\::/",$groups[$ii]);
+				$relatedGroups[$ii] = array("name" => $tmp[0],"alias" => $tmp[1],"owner" => $tmp[2]);
+			}
+			foreach ($relatedGroups as $key => $value) {
+				if ($value["alias"] == $alias)
+				 	$owner = $value["owner"];
+			}
+			if ($owner){
+					include_once("class.ldap_functions.inc.php");
+					$ldap = new ldap_functions();			
+					$owner = $ldap->uid2uidnumber($owner);
+			}
+		}
+
 		$query = "select C.id_connection, A.names_ordered, C.connection_value from phpgw_cc_contact A, ".
 		"phpgw_cc_contact_conns B, phpgw_cc_connections C,phpgw_cc_contact_grps D,phpgw_cc_groups E where ".
Index: branches/2.5/expressoMail1_2/inc/class.imap_functions.inc.php
===================================================================
--- branches/2.5/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 8114)
+++ branches/2.5/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 8232)
@@ -42,5 +42,5 @@
 	var $useCache = false;
 	var $expirationCache = false;
-
+    var $msgIds = array();// Usado para guardar o messagesIds
         
 	function imap_functions (){
@@ -233,69 +233,74 @@
                                     ++$i;
                             }
-							
-							$filter = array('AND', array('=', 'folderName', $folder), array('IN','messageNumber', $sort_array_msg));
-							$followupflagged = Controller::find(
-								array('concept' => 'followupflagged'),
-								false, 
-								array('filter' => $filter, 'criteria' => array('deepness' => '2'))
-							);
-							$labeleds = Controller::find(
-								array('concept' => 'labeled'),
-								false, 
-								array('filter' => $filter, 'criteria' => array('deepness' => '2'))
-							);
-                            $sort_array_msg_count = count($sort_array_msg);
-							for($i=0; $i<$sort_array_msg_count; ++$i){
-								if(!isset($return[$i]['msg_number']))
-									continue;
-									
-								$numFlags = count($followupflagged);
-								for($ii=0; $ii<$numFlags; ++$ii){
-									if($return[$i]['msg_number'] == $followupflagged[$ii]['messageNumber']){
-										$followupflag = Controller::read( array( 'concept' => 'followupflag', 'id' => $followupflagged[$ii]['followupflagId'] ));
-										$return[$i]['followupflagged'] = $followupflagged[$ii];
-										$return[$i]['followupflagged']['followupflag'] = $followupflag;
-										break;
-									}
-								}
-								$numLabels = count($labeleds);
-								for($ii=0; $ii<$numLabels; ++$ii){
-									if($return[$i]['msg_number'] == $labeleds[$ii]['messageNumber']){
-										$labels = Controller::read( array( 'concept' => 'label', 'id' =>  $labeleds[$ii]['labelId'])); 
-										$return[$i]['labels'][$labeleds[$ii]['labelId']] = $labels;
-									}
-								}
-							}
+                            if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_followupflags_and_labels'] == "1")
+                            {
+                                $filter = array('AND', array('=', 'folderName', $folder), array('IN','messageNumber', $sort_array_msg));
+                                $followupflagged = Controller::find(
+                                    array('concept' => 'followupflagged'),
+                                    false,
+                                    array('filter' => $filter, 'criteria' => array('deepness' => '2'))
+                                );
+                                $labeleds = Controller::find(
+                                    array('concept' => 'labeled'),
+                                    false,
+                                    array('filter' => $filter, 'criteria' => array('deepness' => '2'))
+                                );
+                                $sort_array_msg_count = count($sort_array_msg);
+                                for($i=0; $i<$sort_array_msg_count; ++$i){
+                                    if(!isset($return[$i]['msg_number']))
+                                        continue;
+
+                                    $numFlags = count($followupflagged);
+                                    for($ii=0; $ii<$numFlags; ++$ii){
+                                        if($return[$i]['msg_number'] == $followupflagged[$ii]['messageNumber']){
+                                            $followupflag = Controller::read( array( 'concept' => 'followupflag', 'id' => $followupflagged[$ii]['followupflagId'] ));
+                                            $return[$i]['followupflagged'] = $followupflagged[$ii];
+                                            $return[$i]['followupflagged']['followupflag'] = $followupflag;
+                                            break;
+                                        }
+                                    }
+                                    $numLabels = count($labeleds);
+                                    for($ii=0; $ii<$numLabels; ++$ii){
+                                        if($return[$i]['msg_number'] == $labeleds[$ii]['messageNumber']){
+                                            $labels = Controller::read( array( 'concept' => 'label', 'id' =>  $labeleds[$ii]['labelId']));
+                                            $return[$i]['labels'][$labeleds[$ii]['labelId']] = $labels;
+                                        }
+                                    }
+                                }
+                            }
                     }
                     $return['num_msgs'] =  $num_msgs;   
-		} else {
+		}
+        else
+        {
 			$num_msgs = imap_num_msg($this->mbox);
 			$sort_array_msg = $this-> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$num_msgs);
 
-
 			$return['tot_unseen'] = 0;
 			$i = 0;
 
-                        if(is_array($sort_array_msg)){
-
-                            foreach($sort_array_msg as $msg_number => $value)
-                            {
-                                $temp = $this->get_info_head_msg($msg_number);
-                                if(!$temp)
-                                    return false;
-
-                                if($temp['Unseen'] == 'U' || $temp['Recent'] == 'N'){
-						$return['tot_unseen']++;
-					}
-
-                                if($i <= ($msg_range_end-$msg_range_begin))
-                                    $return[$i] = $temp;
-                                ++$i;
-                            }
-                        }
-      			$return['num_msgs'] = count($sort_array_msg)+($msg_range_begin-1);
+            if(is_array($sort_array_msg))
+            {
+                foreach($sort_array_msg as $msg_number => $value)
+                {
+                    $temp = $this->get_info_head_msg($msg_number);
+                    if(!$temp)
+                        return false;
+
+                    if($temp['Unseen'] == 'U' || $temp['Recent'] == 'N')
+                        $return['tot_unseen']++;
+
+                    if($i <= ($msg_range_end-$msg_range_begin))
+                        $return[$i] = $temp;
+
+                    ++$i;
                 }
-				          	
-                return $return; 
+            }
+
+            $return['num_msgs'] = count($sort_array_msg)+($msg_range_begin-1);
+        }
+
+        $return['messagesIds'] = $this->msgIds;
+        return $return;
     }
 	
@@ -458,7 +463,13 @@
             $return['attachment'] = ( preg_match('/((Content-Disposition:(.)*([\r\n\s]*filename))|(Content-Type:(.)*([\r\n\s]*name)))/i', $mimeBody) ) ? '1' : '0'; //Verifica se a anexos na mensagem
             $return['reply_toaddress'] = isset($header->reply_toaddress) ? self::decodeMimeString($header->reply_toaddress) : '';
-            $return['flag'] = $header->Unseen.$header->Recent.$header->Flagged.$header->Draft.$header->Answered.$header->Deleted.( $return['attachment'] === '1' ? 'T': '' );
-			
-			if (!empty($header->to)){
+            $return['flag'] = $header->Unseen.
+                $header->Recent.
+                ($header->Flagged == 'F' || !( preg_match('/importance *: *(.*)\r/i', $mimeHeader , $importance) === 0 )? 'F' : '').
+                $header->Draft.
+                $header->Answered.
+                $header->Deleted.
+                ( $return['attachment'] === '1' ? 'T': '' );
+
+        if (!empty($header->to)){
 				foreach ($header->to as $i => $v){
 					$return['to'][$i] = self::formatMailObject( $v );
@@ -592,10 +603,10 @@
 					if (zip_entry_open($zip, $zip_entry, "r")) {
 						$email = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
- 
-                                                /*Caso mensagens vierem com quebras de linha diferentes do esperado, como por exemplo, 
-                                                mensagens exportadas pelo MailArchiver, é preciso corrigir.*/ 
-                                                $email = str_replace("\r\n", "\n", $email); 
-                                                $email = str_replace("\n", "\r\n", $email); 
- 
+
+						/*Caso mensagens vierem com quebras de linha diferentes do esperado, como por exemplo,
+						mensagens exportadas pelo MailArchiver, é preciso corrigir.*/
+						$email = str_replace("\r\n", "\n", $email);
+						$email = str_replace("\n", "\r\n", $email);
+
 						$status = @imap_append($this->mbox,
 								"{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$params["folder"],
@@ -620,10 +631,10 @@
 		}else if(substr($filename,strlen($filename)-4)==".eml") {
 			$email = implode("",file($params['FILES'][0]['tmp_name']));
- 
-                        /*Caso mensagens vierem com quebras de linha diferentes do esperado, como por exemplo, 
-                        mensagens exportadas pelo MailArchiver, é preciso corrigir.*/ 
-                        $email = str_replace("\r\n", "\n", $email); 
-                        $email = str_replace("\n", "\r\n", $email); 
- 
+
+			/*Caso mensagens vierem com quebras de linha diferentes do esperado, como por exemplo,
+			mensagens exportadas pelo MailArchiver, é preciso corrigir.*/
+			$email = str_replace("\r\n", "\n", $email);
+			$email = str_replace("\n", "\r\n", $email);
+
 			$status = imap_append($this->mbox,"{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$params["folder"],$email);
 				
@@ -954,4 +965,5 @@
 
                                    $content .= $this->decodeMailPart($part->body,$part->ctype_parameters['charset']);
+                                   $i = -1;
                                 }
 
@@ -962,26 +974,26 @@
 
                                    $content .= '<pre>'. htmlentities($this->decodeMailPart($part->body,$part->ctype_parameters['charset'],false)).'</pre>';
+                                   $i = -1;
                                 }
-                                if(strtolower($part->ctype_secondary) == 'calendar')
-                                    $content.= $this->builderMsgCalendar($this->decodeMailPart($part->body, $part->ctype_parameters['charset']));
-
+                               // Comentado para tratamento de e-mail multipart alternative com html e ical. Parseava o ical e ignorava o html.
+                               //if(strtolower($part->ctype_secondary) == 'calendar')
+                               //     $content.= $this->builderMsgCalendar($this->decodeMailPart($part->body, $part->ctype_parameters['charset']));
                            }
 
-                            $i = -1;
                             break;
 
                        case 'multipart':
 
- 	                    if(strtolower($part->ctype_secondary) == 'alternative' ) //Unico formato multipart suportado, escapa os outros 
- 	                    { 
- 	                        if($printHeader) 
- 	                            $content .= $this->builderMsgHeader($part); 
-
- 	                        $this->builderMsgBody($part,$content); 
-
- 	                        $i = -1; 
- 	                    } 
- 
- 	                    break;
+                           if(strtolower($part->ctype_secondary) == 'alternative' ) //Unico formato multipart suportado, escapa os outros
+                           {
+                               if($printHeader)
+                                   $content .= $this->builderMsgHeader($part);
+
+                               $this->builderMsgBody($part,$content);
+
+                               $i = -1;
+                           }
+
+                           break;
 
                        case 'message':
@@ -1211,6 +1223,6 @@
 
 		$return['msg_number'] = $msg_number.$plus_id;
-                $return['msg_folder'] = mb_convert_encoding( $msg_folder, "ISO-8859-1", "UTF-8" ); 
-                //isset($params['decoded']) ? mb_convert_encoding( $msg_folder, "ISO-8859-1", "UTF-8" ) : $msg_folder; 
+		$return['msg_folder'] = mb_convert_encoding( $msg_folder, "ISO-8859-1", "UTF-8" );
+		//isset($params['decoded']) ? mb_convert_encoding( $msg_folder, "ISO-8859-1", "UTF-8" ) : $msg_folder;
 
 		
@@ -1460,5 +1472,5 @@
 		}  
 		$return['alarm'] = $alarm;
-		
+
 		return $return;
 	}
@@ -2186,8 +2198,8 @@
 	function delete_msgs($params)
 	{
-
 		$folder = $params['folder'];
 		$folder =  mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1");
 		$msgs_number = explode(",",$params['msgs_number']);
+
 		if(array_key_exists('border_ID' ,$params))
 		$border_ID = $params['border_ID'];
@@ -2205,5 +2217,5 @@
 	 	$mbox_stream = @imap_open("{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder, $this->username, $this->password) or die(serialize(array('imap_error' => $this->parse_error(imap_last_error()))));
 
-		foreach ($msgs_number as $msg_number)
+        foreach ($msgs_number as $msg_number)
 		{
 			if (imap_delete($mbox_stream, $msg_number, FT_UID));
@@ -2650,10 +2662,10 @@
 	function ren_mailbox($arr)
 	{
-                $namebox = $arr['current'];              
-                $path_delimiter = strrpos($namebox,$this->imap_delimiter)+1; 
-                $base_path = substr($namebox,0,$path_delimiter); 
-                $rename = preg_split("/\/|\./",substr($arr['rename'], $path_delimiter)); 
-                $new_box = array_shift($rename); 
-                $subfolders = $rename; 
+		$namebox = $arr['current'];		
+		$path_delimiter = strrpos($namebox,$this->imap_delimiter)+1;
+		$base_path = substr($namebox,0,$path_delimiter);
+		$rename = preg_split("/\/|\./",substr($arr['rename'], $path_delimiter));
+		$new_box = array_shift($rename);
+		$subfolders = $rename;
 		$imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
 		$mbox_stream = $this->open_mbox();
@@ -2666,20 +2678,20 @@
 			$result = imap_last_error();
 		}
-                /*Cria as subpastas*/ 
-                if (is_array($subfolders)){ 
-                        $child = $new_box.$this->imap_delimiter; 
-            $subfolders_count = count($subfolders); 
-                        for($i =0; $i < $subfolders_count; ++$i){ 
-                                $child .= ($subfolders[$i] ? $subfolders[$i] : $this->functions->getLang("New Folder")); 
-                                $namebox =  mb_convert_encoding($child, "UTF7-IMAP", "UTF-8"); 
-                                $result = "Ok"; 
-                                if(!imap_createmailbox($mbox_stream,"{".$imap_server."}$namebox")) 
-                                { 
-                                        $result = imap_last_error();                                             
-                                } 
-                                $child .=$this->imap_delimiter; 
-                        }                        
-                } 
- 
+		/*Cria as subpastas*/
+		if (is_array($subfolders)){
+			$child = $new_box.$this->imap_delimiter;
+            $subfolders_count = count($subfolders);
+			for($i =0; $i < $subfolders_count; ++$i){
+				$child .= ($subfolders[$i] ? $subfolders[$i] : $this->functions->getLang("New Folder"));
+				$namebox =  mb_convert_encoding($child, "UTF7-IMAP", "UTF-8");
+				$result = "Ok";
+				if(!imap_createmailbox($mbox_stream,"{".$imap_server."}$namebox"))
+				{
+					$result = imap_last_error();						
+				}
+				$child .=$this->imap_delimiter;
+			}			
+		}
+
 		if($mbox_stream)
 			imap_close($mbox_stream);
@@ -2711,5 +2723,23 @@
 		return $return;
 	}
-	
+
+	/*Método utilizado para retornar dados da mensagem local (desarquivada na pasta lixeira)
+	para poder ser anexada à mensagem.*/
+    function get_info_msg_archiver($params){
+        $folder = "INBOX".$this->imap_delimiter.$this->folders['trash'];
+        $mbox_stream = $this->open_mbox($folder);
+        $id = $params['idMsgs'];
+
+        $name = imap_headerinfo($mbox_stream, imap_msgno($mbox_stream, $id));
+        $return[] =  array(
+            'uid' => $id,
+            'folder' => "archiver",
+            'type' => "imapMSG",
+            'name' => base64_encode($name->subject.".eml")
+        );
+
+        return json_encode($return);
+    }
+
 	function send_mail($params) {
             require_once dirname(__FILE__) . '/../../services/class.servicelocator.php';
@@ -2934,5 +2964,5 @@
 					$arr_new_folder['base_path'] = $base_path;
 
-					$this->create_mailbox($arr_new_folder);					
+					$this->create_mailbox($arr_new_folder);	
 					$has_new_folder = true;
                     $folder = $newfolder;
@@ -2954,5 +2984,5 @@
 
 			$from = $fromaddress ?  ('"' . $fromaddress[0] . '" <' . $fromaddress[1] . '>') : ('"' . $_SESSION['phpgw_info']['expressomail']['user']['firstname'] . ' ' . $_SESSION['phpgw_info']['expressomail']['user']['lastname'] . '" <' . $_SESSION['phpgw_info']['expressomail']['user']['email'] . '>');
-			$mailService->setFrom($from);				
+			$mailService->setFrom( mb_convert_encoding($from, "ISO-8859-1","UTF-8, ISO-8859-1"));
         
 			$mailService->addHeaderField('Reply-To', !!$replytoaddress ? $replytoaddress : $from);
@@ -3004,6 +3034,5 @@
             $isHTML = ( isset($params['type']) && $params['type'] == 'html' )?  true : false;
 
-
-    //	TODO - tratar mensagem criptografada e remover o AND false abaixo
+    		//	TODO - tratar mensagem criptografada e remover o AND false abaixo
             if (($encrypt && $signed && $params['smime']) || ($encrypt && !$signed) AND false) { // a msg deve ser enviada cifrada...
                 $email = $this->add_recipients_cert($toaddress . ',' . $ccaddress . ',' . $ccoaddress);
@@ -3103,4 +3132,7 @@
                 {
                     $value = json_decode($value, true);
+                    if($value["folder"] == "archiver"){
+                        $value['folder'] = "INBOX/Trash";
+                    }
 
                     switch ($value['type']) {
@@ -3110,5 +3142,5 @@
                                 if(strstr($body,'src="./inc/get_archive.php?msgFolder='.$value['folder'].'&msgNumber='.$value['uid'].'&indexPart='.$value['part'].'"') !== false)//Embeded IMG
                                 {    
-                                    $body = str_ireplace('src="./inc/get_archive.php?msgFolder='.$value['folder'].'&msgNumber='.$value['uid'].'&indexPart='.$value['part'].'"' , 'src="'.$att['name'].'"', $body);
+                                    $body = str_ireplace('src="./inc/get_archive.php?msgFolder='.$value['folder'].  '&msgNumber='.$value['uid'].'&indexPart='.$value['part'].'"' , 'src="'.$att['name'].'"', $body);
                                     $mailService->addStringImage($att['source'], $att['type'],mb_convert_encoding($att['name'], 'ISO-8859-1' , 'UTF-8,ISO-8859-1') );
                                 }
@@ -3124,4 +3156,5 @@
                                 
                                 $mailService->addStringAttachment($rawmsg, mb_convert_encoding(base64_decode($value['name']), 'ISO-8859-1' , 'UTF-8,ISO-8859-1'), 'message/rfc822', '7bit', 'attachment' );
+                                /*envia o anexo para o email*/
                                 $message_size_total += mb_strlen($rawmsg); //Adiciona o tamanho do anexo a variavel que controlao tamanho da msg.
                                 unset($rawmsg);
@@ -3419,4 +3452,7 @@
 			$sort = array();
 		}
+
+        $this->msgIds = $sort;
+
 		if ($slice_array)
 			$sort = array_slice($sort,$offsetBegin-1,$offsetEnd-($offsetBegin-1),true);
@@ -3556,4 +3592,18 @@
 	}
 
+    function verifyShareFolder($params){
+        $folder = $params['folder'];
+
+         if (substr($folder,0,4) == 'user'){
+            $acl = $this->getacltouser($folder, isset($params['decoded']));
+
+            $acl_share_delete = (stripos($acl,'t') !== false && stripos($acl,'e') !== false);
+
+            if (!$acl_share_delete) {
+                $return['status'] = false;
+                return $return;
+            }
+        }
+    }
 	function move_messages($params)
 	{
@@ -3676,5 +3726,5 @@
 	}
 	
-	function set_messages_flag_from_search($params){		
+	function set_messages_flag_from_search($params){
 		$error = False;
 		$fileNames = "";
@@ -4404,29 +4454,31 @@
                                             $elem['uid'] = $new_search;
                                             /* compare dates in ordering */
-                                            $elem['udatecomp'] = substr ($elem['udate'], -4) ."-". substr ($elem['udate'], 3, 2) ."-". substr ($elem['udate'], 0, 2);  
-
-											$filter = array('AND', array('=', 'folderName', $name_box), array('=','messageNumber', $new_search));
-											$followupflagged = Controller::find(
-												array('concept' => 'followupflagged'),
-												false, 
-												array('filter' => $filter, 'criteria' => array('deepness' => '2'))
-											);
-
-											if(isset($followupflagged[0]['followupflagId']))
-											{
-												$followupflag = Controller::read( array( 'concept' => 'followupflag', 'id' => $followupflagged[0]['followupflagId'] ));     
-												$followupflagged[0]['followupflag'] = $followupflag;
-												$elem['followupflagged'] = $followupflagged[0];
-
-											}	
-											$labeleds = Controller::find(
-												array('concept' => 'labeled'),
-												false, 
-												array('filter' => $filter, 'criteria' => array('deepness' => '2'))
-											);
-											foreach ($labeleds as $e){
-												$labels = Controller::read( array( 'concept' => 'label', 'id' =>  $e['labelId']));     
-												$elem['labels'][$e['labelId']] = $labels;
-}											
+                                            $elem['udatecomp'] = substr ($elem['udate'], -4) ."-". substr ($elem['udate'], 3, 2) ."-". substr ($elem['udate'], 0, 2);
+                                            if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_followupflags_and_labels'] == "1")
+                                            {
+                                                $filter = array('AND', array('=', 'folderName', $name_box), array('=','messageNumber', $new_search));
+                                                $followupflagged = Controller::find(
+                                                    array('concept' => 'followupflagged'),
+                                                    false,
+                                                    array('filter' => $filter, 'criteria' => array('deepness' => '2'))
+                                                );
+
+                                                if(isset($followupflagged[0]['followupflagId']))
+                                                {
+                                                    $followupflag = Controller::read( array( 'concept' => 'followupflag', 'id' => $followupflagged[0]['followupflagId'] ));
+                                                    $followupflagged[0]['followupflag'] = $followupflag;
+                                                    $elem['followupflagged'] = $followupflagged[0];
+
+                                                }
+                                                $labeleds = Controller::find(
+                                                    array('concept' => 'labeled'),
+                                                    false,
+                                                    array('filter' => $filter, 'criteria' => array('deepness' => '2'))
+                                                );
+                                                foreach ($labeleds as $e){
+                                                    $labels = Controller::read( array( 'concept' => 'label', 'id' =>  $e['labelId']));
+                                                    $elem['labels'][$e['labelId']] = $labels;
+                                                }
+                                            }
                                             $retorno[] = $elem;
                                         }
@@ -4460,5 +4512,5 @@
 	    $arrayRetorno['data']		=  $pageret;
 	    $arrayRetorno['currentTab'] =  $params['current_tab'];
-            return ($pageret) ? $arrayRetorno : 'none';
+        return ($pageret) ? $arrayRetorno : 'none';
 	}
 
@@ -4546,9 +4598,9 @@
 	            {
 	                $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
-                        //$folder = str_replace("&-", "&", $folder);                     
-                        $trashFolder = explode($this->imap_delimiter,$folder); 
-                        $acls = ($trashFolder[count($trashFolder) - 1] == "Trash") ? $value['acls']."i" : $value['acls']; 
-                        $folder = imap_utf7_encode($folder);                     
-                        imap_setacl ($mbox_stream, $folder, "$user", $acls); 
+	                //$folder = str_replace("&-", "&", $folder);			
+	                $trashFolder = explode($this->imap_delimiter,$folder);
+	                $acls = ($trashFolder[count($trashFolder) - 1] == "Trash") ? $value['acls']."i" : $value['acls'];
+	                $folder = imap_utf7_encode($folder);	                
+	                imap_setacl ($mbox_stream, $folder, "$user", $acls);
 	            }
 	        }
@@ -4909,4 +4961,5 @@
 				$insert = $this->insert_email($source,$dest_folder,$timestamps[$index],$flags[$index]);
 
+                $return['idsMsg'] = $insert['msg_no'];
                 if($insert['error'])
                 {
@@ -5070,33 +5123,39 @@
 				foreach ($subject as $tmp)
 					$return['msgs'][$i]['subject'] .= mb_convert_encoding($tmp->text, 'UTF-8', 'UTF-8 , ISO-8859-1');
-				
-				$filter = array('AND', array('=', 'folderName', $folder), array('=','messageNumber', $v));
-				$followupflagged = Controller::find(
-					array('concept' => 'followupflagged' , 'folder' => $folder ),
-					false, 
-					array('filter' => $filter, 'criteria' => array('deepness' => '2'))
-				);
-
-				if(isset($followupflagged[0]['followupflagId']))
-				{
-					$followupflag = Controller::read( array( 'concept' => 'followupflag', 'id' => $followupflagged[0]['followupflagId'] ));     
-					$followupflagged[0]['followupflag'] = $followupflag;
-					$return['msgs'][$i]['followupflagged'] = $followupflagged[0];
-
-				}	
-				$labeleds = Controller::find(
-					array('concept' => 'labeled'),
-					false, 
-					array('filter' => $filter, 'criteria' => array('deepness' => '2'))
-				);
-				if(is_array($labeleds))
-				foreach ($labeleds as $e){
-					$labels = Controller::read( array( 'concept' => 'label', 'id' =>  $e['labelId']));     
-					$return['msgs'][$i]['labels'][$e['labelId']] = $labels;
-				}	
+
+
+                if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_followupflags_and_labels'] == "1")
+                {
+
+                    $filter = array('AND', array('=', 'folderName', $folder), array('=','messageNumber', $v));
+                    $followupflagged = Controller::find(
+                        array('concept' => 'followupflagged' , 'folder' => $folder ),
+                        false,
+                        array('filter' => $filter, 'criteria' => array('deepness' => '2'))
+                    );
+
+                    if(isset($followupflagged[0]['followupflagId']))
+                    {
+                        $followupflag = Controller::read( array( 'concept' => 'followupflag', 'id' => $followupflagged[0]['followupflagId'] ));
+                        $followupflagged[0]['followupflag'] = $followupflag;
+                        $return['msgs'][$i]['followupflagged'] = $followupflagged[0];
+
+                    }
+                    $labeleds = Controller::find(
+                        array('concept' => 'labeled'),
+                        false,
+                        array('filter' => $filter, 'criteria' => array('deepness' => '2'))
+                    );
+                    if(is_array($labeleds))
+                    foreach ($labeleds as $e){
+                        $labels = Controller::read( array( 'concept' => 'label', 'id' =>  $e['labelId']));
+                        $return['msgs'][$i]['labels'][$e['labelId']] = $labels;
+                    }
+                }
+
 				$mimeBody = imap_body( $this->mbox, $v  , FT_UID|FT_PEEK  );
 				$return['msgs'][$i]['flag'] = ' ';
 				$return['msgs'][$i]['flag'] .= $msg->Unseen ? $msg->Unseen : '';
-				$return['msgs'][$i]['flag'] .= $msg->Recent ? $msg->Recent : '';	
+				$return['msgs'][$i]['flag'] .= $msg->Recent ? $msg->Recent : '';
 				$return['msgs'][$i]['flag'] .= $msg->Draft ? $msg->Draft : '';	
 				$return['msgs'][$i]['flag'] .= $msg->Answered ? $msg->Answered : '';	
@@ -5159,9 +5218,9 @@
 			$nMsgs[] = $v;
 		}
-		$return['msgs'] = $nMsgs;	
-		
-		$return = json_encode($return);		
+		$return['msgs'] = $nMsgs;
+
+		$return = json_encode($return);
 		$return = base64_encode($return);
-	
+        
 		return $return;
 	}
@@ -5227,16 +5286,17 @@
 	function searchSieveRule( $params )
 	{
- 
-		$imap = $this->open_mbox( 'INBOX' );
+		$imap = $this->open_mbox( $params['folder']['criteria'] ? $params['folder']['criteria'] : 'INBOX' );
 		$msgs = imap_sort( $imap , SORTDATE , 0 , SE_UID);
-		
+	
 		$rr = array();
- 
+
         if(isset($params['from']))  $rr['from'] = array();
         if(isset($params['to']))  $rr['to'] = array();
         if(isset($params['subject'])) $rr['subject'] = array();
-        if(isset($params['body'])) $rr['body'] = array(); 
-        if(isset($params['size'])) $rr['size'] = array(); 
- 
+        if(isset($params['body'])) $rr['body'] = array();
+        if(isset($params['size'])) $rr['size'] = array();
+
+        //$params['search'] = mb_convert_encoding($params['search'], 'UTF-8',mb_detect_encoding($params['search'].'x', 'UTF-8, ISO-8859-1'));
+
 		foreach ($msgs as $i => $v)
 		{
@@ -5264,5 +5324,5 @@
 			
 			if(isset($params['to']))
-			{ 
+			{
 				$tos = $msg->to;
 				$val = '';
@@ -5284,5 +5344,5 @@
 					
 				}
-				
+
 				if($this->filterCheck( $val , $params['to']['criteria'] , $params['to']['filter'] ))
 					$rr['to'][] = $v;
@@ -5294,5 +5354,5 @@
 				$subject = imap_mime_header_decode($msg->subject);
 				foreach ($subject as $tmp)
-					$ss .= $tmp->text;
+					$ss .= ($tmp->charset == "default") ? $tmp->text : utf8_encode($tmp->text);
 				
 				if($this->filterCheck($ss , $params['subject']['criteria'] , $params['subject']['filter'] ))
@@ -5302,10 +5362,10 @@
 			if(isset($params['body']))
 			{			
-				$this->mbox = $this->open_mbox( 'INBOX' );
-				$b = $this->get_body_msg( $v , 'INBOX' );
-				
-				if( $this->filterCheck( $b['body'] , $params['body']['criteria'] , $params['body']['filter'] ))
+				$this->mbox = $this->open_mbox( $params['folder']['criteria'] ? $params['folder']['criteria'] : 'INBOX' );
+				$b = $this->get_body_msg( $v , $params['folder']['criteria'] ? $params['folder']['criteria'] : 'INBOX' );
+
+				if( $this->filterCheck( mb_convert_encoding(html_entity_decode($b['body']), 'UTF-8',mb_detect_encoding(html_entity_decode($b['body']).'x', 'UTF-8, ISO-8859-1')) , $params['body']['criteria'] , $params['body']['filter'] ))
 					$rr['body'][] = $v;
-				
+
 				unset($b);
 			}
@@ -5320,17 +5380,13 @@
 		$rrr = array();
 		$init = true;
-		
-		
 		foreach ($rr as $i => $v)
-		{			
+		{
 			if(count($rrr) == 0 && $init === true)
 				$rrr = $v;
 			else if($params['isExact'] == 'yes')
-                		$rrr = array_intersect($rrr , $v);
+                $rrr = array_intersect($rrr , $v);
 			else
 				$rrr =  array_unique(array_merge($rrr , $v));
-			
-		}
-		
+		}
 
 //		if($params['page'] && $params['rows'])
@@ -5403,7 +5459,10 @@
 						$ret[$msg][] = imap_mail_copy($imap,$msg,$proc['value'], CP_UID);
 					else
+					{
 						/* Está sempre copiando a mensagem para a pasta destino */
 					    //$ret[$msg][] = imap_mail_move($imap,$msg,$proc['parameter'], CP_UID);
 						$ret[$msg][] = imap_mail_move($imap,$msg,$proc['parameter'], CP_UID);						
+						imap_expunge($imap);
+					}
 					break;
 				case 'redirect':											
Index: branches/2.5/expressoMail1_2/inc/class.exporteml.inc.php
===================================================================
--- branches/2.5/expressoMail1_2/inc/class.exporteml.inc.php	(revision 7673)
+++ branches/2.5/expressoMail1_2/inc/class.exporteml.inc.php	(revision 8232)
@@ -150,55 +150,4 @@
 	}
 
-function export_all_byLocalFolder($params){
-        $error = false;
-
-        if(empty($params['messages'])){
-            $file["empty_folder"] = true;
-        } else {
-            foreach($params['messages'] as $eachMsg){
-               $header = "";
-               $body = "";
-               $tempDir = $this->tempDir;
-
-               $this->get_header_byLocalFolder($eachMsg, $header);
-               $this->get_body_byLocalFolder($eachMsg, $body);
-               $sEMLData    = $this->parseEml($header, $body);
-               $fileName   = $this->createFileEml_by_localFolder($sEMLData, $tempDir,$eachMsg['msg_number']);
-
-               if(!$fileName){
-                   $error = true;
-                   break;
-               } else 
-                   $fileNames .= "\"".$fileName."\" ";
-            }
-
-            $nameFileZip = 'False';         
-            if($fileNames && !$error) {         
-                $nameFileZip = $this->createFileZip($fileNames, $tempDir);
-                ($nameFileZip) ? ($file = $tempDir.'/'.$nameFileZip) : ($file = false);
-            } else 
-                $file = false;
-        }
-       
-       return $file;
-
-}
-
-function get_header_byLocalFolder($eachMsg, &$header){
-    $header = <<<header
-        MIME-Version: 1.0
-        Content-Type: text/html; charset=ISO-8859-1
-        Content-Transfer-Encoding: quoted-printable
-        From: "{$eachMsg['from']['name']}" <{$eachMsg['from']['email']}>
-        To: {$eachMsg['to']['email']}
-        Subject: {$eachMsg['subject']}
-        Message-Id: {$eachMsg['msg_number']}
-        Date: {$eachMsg['date']}
-header;
-}
-
-function get_body_byLocalFolder($eachMsg, &$body){
-    $body = $eachMsg['msg_sample']['body'];
-}
 
 function export_all($params){
Index: branches/2.5/expressoMail1_2/inc/class.ldap_functions.inc.php
===================================================================
--- branches/2.5/expressoMail1_2/inc/class.ldap_functions.inc.php	(revision 8172)
+++ branches/2.5/expressoMail1_2/inc/class.ldap_functions.inc.php	(revision 8232)
@@ -499,6 +499,6 @@
 			
 			foreach($info_return as &$value){
-				$value['type_contact'] = "G";
-
+				if (is_array($value))
+					$value['type_contact'] = "G";
 				//Converte a descrição dos filtros para ISO8859 corrigindo inconsitências com caractéres especiais
 				if(isset($value['vacationinfo']) && isset($value['vacationinfo'][0]) && $value['vacationinfo'][0] != '')
Index: branches/2.5/expressoMail1_2/inc/hook_settings.inc.php
===================================================================
--- branches/2.5/expressoMail1_2/inc/hook_settings.inc.php	(revision 8166)
+++ branches/2.5/expressoMail1_2/inc/hook_settings.inc.php	(revision 8232)
@@ -150,6 +150,6 @@
 								    signatures[default_signature].replace( /\\n/g, "<br>" );
     }
-    if (document.getElementById( "signature" ).value != "") 
-        document.getElementById( "signature" ).value = encode64(document.getElementById( "signature" ).value); 
+    if (document.getElementById( "signature" ).value != "")
+    	document.getElementById( "signature" ).value = encode64(document.getElementById( "signature" ).value);
     document.getElementById( "signatures" ).value = toJSON( signatures );
     document.getElementById( "signature_types" ).value = toJSON( types );
@@ -270,51 +270,56 @@
 	return output.toString();
 }
-function normalizerSignature(values){ 
-	var value = {}; 
-	for( key in values ){ 
-		value[isEncoded64(key) ? decode64(key) : key] = values[key]; 
-	} 
-	return value; 
-} 
-/*Verifica se a string input esta em Base 64*/ 
-function isEncoded64(input){ 
-        var baseStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; 
-        var encoded = true; 
-        if ( (input.length % 4) != 0) 
-                return false; 
-        for(var i=0; i<input.length; i++){ 
-                if ( baseStr.indexOf(input[i]) < 0 ){ 
-                        encoded = false; 
-                        break; 
-                } 
-        } 
-        return encoded; 
+function normalizerSignature(values){
+
+    var value = {};
+
+    for( key in values ){
+
+        value[isEncoded64(key) ? decode64(key) : key] = values[key];
+
+    }
+
+    return value;
+}
+/*Verifica se a string input esta em Base 64*/
+function isEncoded64(input){
+	var baseStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
+	var encoded = true;
+	if ( (input.length % 4) != 0)
+		return false;
+	for(var i=0; i<input.length; i++){
+		if ( baseStr.indexOf(input[i]) < 0 ){
+			encoded = false;
+			break;
+		}
+	}
+	return encoded;
 }
 function loadSignature()
 {
     var types = fromJSON( document.getElementById( "signature_types" ).value );
-    var signatures; 
-    if (document.getElementById( "signatures" ).value) 
-    { 
-        signatures = fromJSON(document.getElementById("signatures").value); 
-    } else if (document.getElementById( "signature" ).value) // Caso a assinatura esteja no formato da versão 2.2.10: 
-    { 
-        // TODO: Internazionalizar a string 
-        signatures = {}; 
-        signatures["Assinatura padrão"] = document.getElementById( "signature" ).value; 
-        if (!document.getElementById("signature_default").value) 
-        { 
-            document.getElementById("signature_default").value = "Assinatura padrão"; 
-	} 
-}    
-    
-    var old_signature = document.getElementById( "signature" ).value; 
-    var def = document.getElementById( "signature_default" ).value; 
-        def = isEncoded64(def) ? decode64(def) : def; 
+    var signatures;
+    if (document.getElementById( "signatures" ).value)
+    {
+        signatures = fromJSON(document.getElementById("signatures").value);
+    } else if (document.getElementById( "signature" ).value) // Caso a assinatura esteja no formato da versão 2.2.10:
+    {
+        // TODO: Internazionalizar a string
+        signatures = {};
+        signatures["Assinatura padrão"] = document.getElementById( "signature" ).value;
+        if (!document.getElementById("signature_default").value)
+        {
+            document.getElementById("signature_default").value = "Assinatura padrão";
+        }
+    }
+
+    signatures = normalizerSignature(signatures);
+    types = normalizerSignature(types);
+
+    var old_signature = document.getElementById( "signature" ).value;
+    var def = document.getElementById( "signature_default" ).value;
+	def = isEncoded64(def) ? decode64(def) : def;
 
     var counter = 0, ids = [], def_signature = "", noSig = true;
-
-	signatures = normalizerSignature(signatures); 
- 	types = normalizerSignature(types);
 
     for( key in signatures )
@@ -336,14 +341,14 @@
 
     if( def_signature !== "" )
-		document.getElementById( "default_signature" + def_signature ).checked = true;
+    	document.getElementById( "default_signature" + def_signature ).checked = true;
     else if( noSig && old_signature )
     {
-	    var type_signature = document.getElementById("type_signature"); 
-        if (type_signature) 
-        { 
-            addSignature( type_signature.value !== "html" ); 
-            document.getElementById( "user_signature" + counter ).value = old_signature; 
-        }
-	}
+        var type_signature = document.getElementById("type_signature");
+        if (type_signature)
+        {
+            addSignature( type_signature.value !== "html" );
+            document.getElementById( "user_signature" + counter ).value = old_signature;
+        }
+    }
 }
 ');
@@ -364,4 +369,7 @@
 
 create_check_box('View the user name in the header of the messages printed?', 'show_name_print_messages', 'Displays the user name in the header print email');
+
+create_check_box('Habilitar funcionalidade de notificar ao receber mensagens filtradas por remetente ?', 'use_alert_filter_criteria', '');
+create_check_box('Habilitar sinalizadores e marcadores em mensagens', 'use_followupflags_and_labels', '');
 
 //$default = 0;
Index: branches/2.5/expressoMail1_2/js/mail_archiver.js
===================================================================
--- branches/2.5/expressoMail1_2/js/mail_archiver.js	(revision 8126)
+++ branches/2.5/expressoMail1_2/js/mail_archiver.js	(revision 8232)
@@ -427,14 +427,15 @@
            
                 var fcaption = "";
-                
-                if(destination_folder.substr(0,5) == 'local'){
-                    expresso_mail_archive.folder_destination = destination_folder.replace("local_messages_","");
-                }
-                else{
-                    expresso_mail_archive.folder_destination = destination_folder;
-                }
+
+                if(destination_folder.substr(0,5) == 'local'){ 
+                    expresso_mail_archive.folder_destination = destination_folder.replace("local_messages_",""); 
+                } 
+                else{ 
+                    expresso_mail_archive.folder_destination = destination_folder; 
+                } 
+
                 
                 if(!expresso_mail_archive.archivefolder){
-                    expresso_mail_archive.getFolderInfo(expresso_mail_archive.folder_destination);
+                    expresso_mail_archive.getFolderInfo(expresso_mail_archive.folder_destination); 
                     if(typeof(expresso_mail_archive.folder) != "undefined"){
                         //window.alert('folder.path -> ' + expresso_mail_archive.folder.path);
@@ -575,19 +576,13 @@
 }
 
-
-
-
-/**
- *Unarchieve Message
- *
- *@author Cassiano Dal Pizzol [cassiano.dalpizzol@serpro.gov.br]
- *
- *@param folder Original Folder of the message
- *@param new_folder The new folder of the message
- *@param msgs_number id of the messages
- */
-MailArchiver.prototype.unarchieve = function (folder, new_folder, msgs_number){
-    try{ 
-        write_msg(get_lang("Starting to unarchive messages"));
+MailArchiver.prototype.unarchieveToAttach = function (folder, new_folder, msgs_number, callback){
+    try{
+
+        if(typeof callback !== 'function') callback = function(){};
+
+        if(typeof(expresso_mail_archive.idMsgsToAttach) == "undefined"){
+            expresso_mail_archive.idMsgsToAttach = new Array();
+        }
+        //write_msg(get_lang("Starting to unarchive messages"));
         expresso_mail_archive.isArchiveOperation = true;
         if(currentTab.toString().indexOf("_r") != -1){
@@ -599,14 +594,15 @@
                 
         if (parseInt(msgs_number) > 0 || msgs_number.length > 0){       
-            expresso_mail_archive.message_list = new Array();
-            expresso_mail_archive.CreateMessageList(msgs_number);
-            if((expresso_mail_archive.message_list.length > 0) && (expresso_mail_archive.message_list[0] != '')) {
+           
+            expresso_mail_archive.messageToAttach = msgs_number;
+            if(expresso_mail_archive.messageToAttach) {
+                
                 expresso_mail_archive.unarchivecounter = 0;
                 expresso_mail_archive.unarchive_error_counter=0;
-                expresso_mail_archive.getFolderInfo(folder.replace("local_messages_",""));
+                expresso_mail_archive.getFolderInfo(folder.replace("local_messages_","")); 
                 expresso_mail_archive.unarchievefolder = expresso_mail_archive.folder.name;
                 (new_folder != null)?expresso_mail_archive.unarchievenewfolder = new_folder:expresso_mail_archive.unarchievenewfolder='INBOX';
                 
-                expresso_mail_archive.unarchieveHandler();
+                expresso_mail_archive.unarchieveToAttachHandler(callback);
                 
                 if(currentTab.toString().indexOf("_r") != -1){
@@ -628,14 +624,7 @@
 }
 
-/**
- *
- *Unarchieve Message Handler
- *
- *@author Cassiano Dal Pizzol [cassiano.dalpizzol@serpro.gov.br]
- *
- **/
-MailArchiver.prototype.unarchieveHandler = function(){
-    try{
-        var email = mail_archive_protocol+'://'+mail_archive_host+':'+mail_archive_port+'/mail/' + expresso_mail_archive.session.id +'/'+ expresso_mail_archive.folder.path + '/'+ expresso_mail_archive.message_list[expresso_mail_archive.unarchivecounter] + '.eml';    
+MailArchiver.prototype.unarchieveToAttachHandler = function(uCallback){
+    try{
+         var email = mail_archive_protocol+'://'+mail_archive_host+':'+mail_archive_port+'/mail/' + expresso_mail_archive.session.id +'/'+ expresso_mail_archive.folder.path + '/'+ expresso_mail_archive.messageToAttach + '.eml';    
     
         //Creates a new object to unarchive messages. It's a CXF Add-on CORS component
@@ -647,5 +636,5 @@
             for (var w=0; w < expresso_mail_archive.allcompletemessagesbyfolder.length; w++){
                                 
-                if(expresso_mail_archive.allcompletemessagesbyfolder[w]["msg_number"] == expresso_mail_archive.message_list[expresso_mail_archive.unarchivecounter]){
+                if(expresso_mail_archive.allcompletemessagesbyfolder[w]["msg_number"] == expresso_mail_archive.messageToAttach){
                     var timestamp = expresso_mail_archive.allcompletemessagesbyfolder[w]["timestamp"];
                     
@@ -702,4 +691,204 @@
                 }
             }
+            var id = expresso_mail_archive.messageToAttach;
+            var source =  encodeURIComponent(UnarchiveReqHandler.handler.responseText) + "#@#@#@";
+            var params = 
+            "&folder="      + escape(expresso_mail_archive.unarchievenewfolder) +
+            "&source="      + source + 
+            "&timestamp="   + timestamp + 
+            "&madata=true"  + 
+            "&flags="       + flags +
+            "&id="          + id;
+
+
+            var handler_unarchive = function(data){
+                expresso_mail_archive.unarchieveToAttachController(data);
+            }
+            write_msg(get_lang("Please, Wait the messages from archieve be ready."));
+            
+             $.ajax({
+                url: "controller.php?action=$this.imap_functions.unarchive_mail",
+                success: function(data){
+                    data = connector.unserialize(data);
+                    expresso_mail_archive.idMsgsToAttach.push(data.idsMsg);
+                    handler_unarchive(data);
+                    uCallback(data);
+                },
+                async: false,
+                data:  params,
+                type: 'POST',
+                
+            });
+
+        }
+
+        
+        UnarchiveReqHandler.handler.open("GET", email, true);
+        if(UnarchiveReqHandler.handler.overrideMimeType){
+            UnarchiveReqHandler.handler.overrideMimeType("message/rfc822; charset=windows-1252"); 
+        }
+        UnarchiveReqHandler.handler.send();
+    }
+    catch(e){
+        write_msg(get_lang('Unarchive error: ' + e));
+    }
+}
+
+MailArchiver.prototype.unarchieveToAttachController = function(data){
+    
+    if (data){
+        if (data.error != "") {
+            expresso_mail_archive.unarchive_error_counter++;
+        }
+        
+    }
+}
+
+
+/**
+ *Unarchieve Message
+ *
+ *@author Cassiano Dal Pizzol [cassiano.dalpizzol@serpro.gov.br]
+ *
+ *@param folder Original Folder of the message
+ *@param new_folder The new folder of the message
+ *@param msgs_number id of the messages
+ */
+MailArchiver.prototype.unarchieve = function (folder, new_folder, msgs_number){
+    try{ 
+
+        var aclShare = false;
+        $.ajax({
+              url: 'controller.php?' + $.param( { action: '$this.imap_functions.verifyShareFolder', folder: new_folder } ),
+              success: function( data ){
+                 data = connector.unserialize( data );
+                 if(data != null){
+                     if(!data.status){
+                        aclShare = true;
+                     }
+                 }
+
+              },
+              async: false
+        });
+
+        if(aclShare){
+            write_msg(get_lang("You don't have permission for this operation in this shared folder!"));
+            return false;
+        } 
+
+        write_msg(get_lang("Starting to unarchive messages"));
+        expresso_mail_archive.isArchiveOperation = true;
+        if(currentTab.toString().indexOf("_r") != -1){
+            msgs_number = currentTab.toString().substr(0,currentTab.toString().indexOf("_r"));
+        }
+
+        if(!msgs_number)
+            msgs_number = get_selected_messages();        
+                
+        if (parseInt(msgs_number) > 0 || msgs_number.length > 0){       
+            expresso_mail_archive.message_list = new Array();
+            expresso_mail_archive.CreateMessageList(msgs_number);
+            if((expresso_mail_archive.message_list.length > 0) && (expresso_mail_archive.message_list[0] != '')) {
+                expresso_mail_archive.unarchivecounter = 0;
+                expresso_mail_archive.unarchive_error_counter=0;
+                expresso_mail_archive.getFolderInfo(folder.replace("local_messages_","")); 
+                expresso_mail_archive.unarchievefolder = expresso_mail_archive.folder.name;
+                (new_folder != null)?expresso_mail_archive.unarchievenewfolder = new_folder:expresso_mail_archive.unarchievenewfolder='INBOX';
+                
+                expresso_mail_archive.unarchieveHandler();
+                
+                if(currentTab.toString().indexOf("_r") != -1){
+                    delete_border(currentTab,'false');  
+                }
+            }
+            else{
+                write_msg(get_lang('No selected message.'));
+            }
+        }                               
+        else
+            write_msg(get_lang('No selected message.'));
+        
+        clear_selected_messages();
+    }
+    catch (e){
+        write_msg(get_lang('Unarchive error: ' + e));
+    }
+}
+
+/**
+ *
+ *Unarchieve Message Handler
+ *
+ *@author Cassiano Dal Pizzol [cassiano.dalpizzol@serpro.gov.br]
+ *
+ **/
+MailArchiver.prototype.unarchieveHandler = function(){
+    try{
+        var email = mail_archive_protocol+'://'+mail_archive_host+':'+mail_archive_port+'/mail/' + expresso_mail_archive.session.id +'/'+ expresso_mail_archive.folder.path + '/'+ expresso_mail_archive.message_list[expresso_mail_archive.unarchivecounter] + '.eml';    
+    
+        //Creates a new object to unarchive messages. It's a CXF Add-on CORS component
+        var UnarchiveReqHandler = new cxf_cors_request_object();
+        UnarchiveReqHandler.init();
+
+        //Both XDomainRequest and XMLHttpRequest L2 supports onload event
+        UnarchiveReqHandler.handler.onload = function(){            
+            for (var w=0; w < expresso_mail_archive.allcompletemessagesbyfolder.length; w++){
+                                
+                if(expresso_mail_archive.allcompletemessagesbyfolder[w]["msg_number"] == expresso_mail_archive.message_list[expresso_mail_archive.unarchivecounter]){
+                    var timestamp = expresso_mail_archive.allcompletemessagesbyfolder[w]["timestamp"];
+                    
+                    //Get local tagged message data
+                    var flags = new String("");
+                    
+                    //Forwarded is special one: marks as "answered" and "draft"
+                    if(expresso_mail_archive.allcompletemessagesbyfolder[w]["Forwarded"]){
+                        if(expresso_mail_archive.allcompletemessagesbyfolder[w]["Forwarded"] == 'F')
+                            flags += 'A:X'+':';                                  
+                    }
+                    else{
+                        //Answered tag
+                        if(expresso_mail_archive.allcompletemessagesbyfolder[w]["Answered"])
+                            if(expresso_mail_archive.allcompletemessagesbyfolder[w]["Answered"] == 'A')
+                                flags += 'A'+':';
+                            else
+                                flags += ':';
+                        else
+                            flags += ':';                    
+
+                        //Draft tag
+                        if(expresso_mail_archive.allcompletemessagesbyfolder[w]["Draft"])
+                            if(expresso_mail_archive.allcompletemessagesbyfolder[w]["Draft"] == 'X')
+                                flags += 'D'+':';                    
+                            else
+                                flags += ':';
+                        else
+                            flags += ':';
+                    }
+                    
+                    //Flagged tag
+                    if(expresso_mail_archive.allcompletemessagesbyfolder[w]["Flagged"])
+                        if(expresso_mail_archive.allcompletemessagesbyfolder[w]["Flagged"] == 'F')
+                            flags += 'F'+':';                                        
+                        else
+                            flags += ':';
+                    else
+                        flags += ':';
+                    
+                    //Unseen tag
+                    if(expresso_mail_archive.allcompletemessagesbyfolder[w]["Unseen"])
+                        if(expresso_mail_archive.allcompletemessagesbyfolder[w]["Unseen"] == 'U')
+                            flags += 'U';     
+                        else
+                            flags += '';
+                    else
+                        flags += '';
+                    
+                    //Imap tag hash id
+                    flags += "#@#@#@";                    
+                    
+                    break;
+                }
+            }
             var id = expresso_mail_archive.message_list[expresso_mail_archive.unarchivecounter];
             var source =  encodeURIComponent(UnarchiveReqHandler.handler.responseText) + "#@#@#@";
@@ -717,5 +906,18 @@
             write_msg(get_lang('Unarchiving message %1 of %2', (expresso_mail_archive.unarchivecounter + 1), expresso_mail_archive.message_list.length));
             
-            cExecute ("$this.imap_functions.unarchive_mail&", handler_unarchive, params);
+            //cExecute ("$this.imap_functions.unarchive_mail&", handler_unarchive, params);
+
+            $.ajax({
+                url: "controller.php?action=$this.imap_functions.unarchive_mail",
+                data:  params,
+                type: 'POST',
+                async: false,
+                success: function(data){
+                    handler_unarchive(connector.unserialize(data));
+                },
+            });
+
+
+
         }
         
@@ -846,7 +1048,7 @@
     expresso_mail_archive.message_list = new Array();
 
-    expresso_mail_archive.currentfolder = folder.replace("local_messages_","");
-
-    expresso_mail_archive.listMessages(expresso_mail_archive.currentfolder);
+    expresso_mail_archive.currentfolder = folder.replace("local_messages_",""); 
+
+    expresso_mail_archive.listMessages(expresso_mail_archive.currentfolder); 
 
     // This is necessary 'couse we can get a delete operation while an unarchive operation
@@ -956,7 +1158,7 @@
         expresso_mail_archive.message_list = new Array();  
 
-        expresso_mail_archive.getFolderInfo(expresso_mail_archive.currentfolder);
-        expresso_mail_archive.getFolderInfo(expresso_mail_archive.folder_destination);
-        expresso_mail_archive.listMessages(expresso_mail_archive.currentfolder); 
+        expresso_mail_archive.getFolderInfo(expresso_mail_archive.currentfolder); 
+        expresso_mail_archive.getFolderInfo(expresso_mail_archive.folder_destination); 
+        expresso_mail_archive.listMessages(expresso_mail_archive.currentfolder);  
               
         expresso_mail_archive.resetObject();
@@ -1258,7 +1460,7 @@
         if(folderId == 'local_root')
             folderId = "";
-        var exp_verifyId = RegExp("^messages\_[0-9|a-z]+\-[0-9|a-z|\-]+$"); 
-        if(exp_verifyId.test(folderId)) 
-            folderId = folderId.replace("messages_", ""); 
+        var exp_verifyId = RegExp("^messages\_[0-9|a-z]+\-[0-9|a-z|\-]+$");
+        if(exp_verifyId.test(folderId))
+            folderId = folderId.replace("messages_", "");
         ArchiveServices.getFolderInfo(expresso_mail_archive.getFolderInfoOperationOK, expresso_mail_archive.getFolderInfoOperationFailure, expresso_mail_archive.session.id, folderId);
     }
@@ -1296,7 +1498,7 @@
 
 MailArchiver.prototype.deleteAllMessages = function(folderId){
-    try{
+    try{    
         var objfolder = new Object();
-        objfolder.folder = folderId;
+        objfolder.folder = folderId; 
 
         var query_data = expresso_mail_archive.queryconfig.query(objfolder);
@@ -1337,12 +1539,13 @@
         }
         var objfolder = new Object();
-        var exp_verifyId = RegExp("^messages\_[0-9|a-z]+\-[0-9|a-z|\-]+$"); 
-        if(exp_verifyId.test(folderid)) 
-            folderid = folderid.replace("messages_", ""); 
-        objfolder.folder = folderid; 
+        var exp_verifyId = RegExp("^messages\_[0-9|a-z]+\-[0-9|a-z|\-]+$");
+        if(exp_verifyId.test(folderid))
+            folderid = folderid.replace("messages_", "");
+        objfolder.folder = folderid;
         //var testing_data_xml = '<?xml version="1.0" encoding="UTF-8"?><query lowerIndex="0" upperIndex="50"><folder id="'+folderid+'"/><order asc="date"/><order desc="subject"/></query>';
         //var testing_data_json_mapped = '{"query":{"@lowerIndex":"0", "@upperIndex":"50", "folder":[{"@id":"'+folderid+'"}], "order":[{"@asc":"date", "@desc":"subject"}]}}';
         var query_data = expresso_mail_archive.queryconfig.query(objfolder);
-        expresso_mail_archive.getFolderInfo(folderid);
+
+        expresso_mail_archive.getFolderInfo(folderid); 
         expresso_mail_archive.currentfolder = folderid;
         
@@ -1404,4 +1607,47 @@
 }
 
+
+MailArchiver.prototype.getMessagesByFolder = function(folderid, searchType){
+    try{
+        if(searchType == "ALL")
+            var query_messages = '{"query":{"folder":[{"@id":"'+folderid+'"}], "order":[{"@asc":"date"}]}}';
+        else
+            var query_messages = '{"query":{"folder":[{"@id":"'+folderid+'"}], "tags":[{"@contains":"'+searchType+'"}], "order":[{"@asc":"date"}]}}';
+        ArchiveServices.listMessages(expresso_mail_archive.getMessagesByFolderOperationOK, expresso_mail_archive.getMessagesByFolderOperationFailure, expresso_mail_archive.session.id, query_messages);
+    }
+    catch (e){
+        expresso_mail_archive.getFaultInfo();
+    }
+}
+
+MailArchiver.prototype.getMessagesByFolderOperationOK = function(returnService){
+    var msglist = new Array();
+    var msglistcomplete = new Array();
+    var msgAll = new Array();
+    for(var i=0; i< returnService.getReturn().length; i++){
+        //Array montado apenas com ids para tratamento de seleÃ§Ã£o de mensagens independente de paginaÃ§Ã£o
+        msglist.push(returnService.getReturn()[i]._id);
+
+        msgAll.push(returnService.getReturn()[i]);
+
+        //Incremento de contadores para atualizaÃ§Ã£o da aba de listagem
+        if(returnService.getReturn()[i]._tags.indexOf("unseen") != -1){
+            expresso_mail_archive.tot_unseen_msgs_tab++;
+        }
+        expresso_mail_archive.tot_msgs_tab++;
+        //Array montado para operaÃ§Ã£o de desarquivamento
+        var ExpSerialized = expresso_mail_archive.pattern.toExpressoHeader(returnService.getReturn()[i]);
+        msglistcomplete.push(connector.unserialize(ExpSerialized));
+    }
+    expresso_mail_archive.allmessagesbyfolder = msglist;
+    expresso_mail_archive.allcompletemessagesbyfolder = msglistcomplete;
+    expresso_mail_archive.msgAll = msgAll;
+}
+
+MailArchiver.prototype.getMessagesByFolderOperationFailure = function(ServiceFault){
+    window.alert('listAllmessagesByFolder FALHOU!\n' + ServiceFault.getReturn());
+}
+
+
 //List all messages by folder given and set a array with all messages ids
 MailArchiver.prototype.listAllMessagesByFolder = function(folderid, searchType){
@@ -1521,4 +1767,5 @@
     if(msgfound){
         expresso_mail_archive.currentheaders = headerMsg;
+        expresso_mail_archive.subjectPreview = headerMsg.subject;
         return(headerMsg);
     }
@@ -1543,4 +1790,5 @@
             bodies.push(temp);
         }
+        expresso_mail_archive.bodyPreview = temp.getReturn();
         return bodies;
     }
@@ -1548,4 +1796,10 @@
         expresso_mail_archive.getFaultInfo();
     }
+}
+
+
+MailArchiver.prototype.getPreviewToAttach = function(id){
+    expresso_mail_archive.getMessageInfo(id);
+    expresso_mail_archive.getMessageBodies([id]);
 }
 
@@ -1624,4 +1878,5 @@
         return;
     }    
+    expresso_mail_archive.te = returnService.getReturn();
     var msgBody = returnService.getReturn();
     //var msgHeaders = expresso_mail_archive.getMessageHeaders(expresso_mail_archive.currentmessage);
@@ -1918,4 +2173,6 @@
             var filters = eval('(' + expresso_mail_archive.queryconfig.pharseSearchFields(fields) + ')');
 
+
+
             if(folderlist.indexOf("#") != -1)
                 filters.folder = folderlist.substr(0, folderlist.indexOf("#"));
@@ -1928,5 +2185,7 @@
 
             expresso_mail_archive.querydata = expresso_mail_archive.search_queryconfig.query(filters);
-            
+
+
+
             //var query_data = '<?xml version="1.0" encoding="UTF-8"?><query subject="teste"><folder id="inbox"/><order asc="date"/></query>';
             ArchiveServices.listMessages(expresso_mail_archive.searchOperationOK, expresso_mail_archive.searchOperationFailure, expresso_mail_archive.session.id, expresso_mail_archive.querydata);        
@@ -1962,5 +2221,5 @@
             
         //expresso_mail_archive.queryresult = msglist;        
-        expresso_mail_archive.search_queryresult = msglist;    
+        expresso_mail_archive.search_queryresult = msglist; 
         //expresso_mail_archive.messageslisted = msglist2;
         expresso_mail_archive.search_message_list = msglist2;
@@ -2096,6 +2355,10 @@
         var ExpSerialized2 = expresso_mail_archive.pattern.toExpressoHeader(serviceReturn.getReturn());
         var msgitem2 = connector.unserialize(ExpSerialized2);
+        if(!expresso_mail_archive.messageslisted){
+            expresso_mail_archive.messageslisted = [];
+        }
         expresso_mail_archive.messageslisted.push(msgitem2);    
         expresso_mail_archive.getMessageHeaders(serviceReturn.getReturn().getId());
+
     }
     else{
Index: branches/2.5/expressoMail1_2/js/abas.js
===================================================================
--- branches/2.5/expressoMail1_2/js/abas.js	(revision 8125)
+++ branches/2.5/expressoMail1_2/js/abas.js	(revision 8232)
@@ -10,6 +10,6 @@
 function setBorderAttributes(ID)
 {
-	this.border_id = "border_id_"+ID;
-	this.sequence = ID; 
+    this.border_id = "border_id_"+ID;
+    this.sequence = ID; 
 }
 
@@ -17,26 +17,28 @@
 function alternate_border(ID)
 {
-	msg_selected = false;//Controle da seleÃ§Ã£o de mensagens
-	if(isNaN(ID))
-		if(preferences.use_shortcuts == "1")
-			select_msg((ID.split("_"))[0]);
-	if( document.getElementById("div_menu_c3") != null )
-	{
-		//div que contém divs de paginação de todas abas de listagem possíveis (listagem de pasta e listagem de pesquisa)
-		var node = document.getElementById("div_menu_c3").firstChild;
-		//Se for diferente da aba de listagem, remove a paginação
-		if(currentTab != 0){
-			//Enquanto node for true (retorna false se não houver mais elementos)
-			while ( node ) {
-				node.style.display = "none";
-				node = node.nextSibling;
-			}
-		}
-		
-		if( document.getElementById("span_paging"+ID) != null )
-			document.getElementById("span_paging"+ID).style.display = "block";
-	}
-	
-	if ( typeof win == 'object' && win.close && win.close.constructor == Function ){
+   
+
+    msg_selected = false;//Controle da seleÃ§Ã£o de mensagens
+    if(isNaN(ID))
+        if(preferences.use_shortcuts == "1")
+            select_msg((ID.split("_"))[0]);
+    if( document.getElementById("div_menu_c3") != null )
+    {
+        //div que contém divs de paginação de todas abas de listagem possíveis (listagem de pasta e listagem de pesquisa)
+        var node = document.getElementById("div_menu_c3").firstChild;
+        //Se for diferente da aba de listagem, remove a paginação
+        if(currentTab != 0){
+            //Enquanto node for true (retorna false se não houver mais elementos)
+            while ( node ) {
+                node.style.display = "none";
+                node = node.nextSibling;
+            }
+        }
+        
+        if( document.getElementById("span_paging"+ID) != null )
+            document.getElementById("span_paging"+ID).style.display = "block";
+    }
+    
+    if ( typeof win == 'object' && win.close && win.close.constructor == Function ){
             var search_win = document.getElementById( 'window_QuickCatalogSearch' );
             if(search_win){
@@ -45,88 +47,88 @@
             win.close( );
         }
-		
-	if (! Element('border_id_'+ID))
-		return false; // Not possible to alternate
-	show_hide_span_paging(ID);
-	spanD = Element("span_D");
-	if (spanD)
-		spanD.style.display = (openTab.type[ID] == 0 ? '' : 'none');
-
-	var footer_menu = Element("footer_menu");	
-	var aba = Element('border_id_'+ID);
-	if (footer_menu != null) {
-		footer_menu.style.display = (openTab.type[ID] != 4 ? '' : 'none');
-		var alternate_menu = document.getElementById('localOption');
-		
-		if(alternate_menu != null && alternate_menu != 'undefined'){ //Quando Carregado o expresso mail
-			if(openTab.imapBox[ID]!= null && openTab.imapBox[ID]!= 'undefined' ){ //Quando abrir uma Nova Mensagem
-				if((openTab.imapBox[ID].indexOf("local_") >= 0)){						
-						alternate_menu.title = get_lang("Unarchive");
-						alternate_menu.removeAttribute("onclick");
-						if(!is_ie)
-							alternate_menu.setAttribute("onclick",  'expresso_local_messages.unarchive_msgs(\''+openTab.imapBox[ID]+'\', null)');
-						else{
-							alternate_menu.onclick = function(){
-								expresso_local_messages.unarchive_msgs(openTab.imapBox[ID], null);
-							}
-						}
-						alternate_menu.innerHTML = get_lang("Unarchive");
-						
-					}else{
-						alternate_menu.title = get_lang("Archive");
-						alternate_menu.removeAttribute("onclick");
-						if(!is_ie)
-							alternate_menu.setAttribute("onclick", 'archive_msgs(\''+openTab.imapBox[ID]+'\', null)');		
-						else{
-							alternate_menu.onclick = function(){
-								archive_msgs(openTab.imapBox[ID], null);
-							}	
-						}
-						alternate_menu.innerHTML = get_lang("Archive");
-					}
-					
-			}
-		}
-		
-		if((aba.id.indexOf("_r") < 0) && (aba.id.indexOf("_0") < 0) && (aba.id.indexOf("id_search_") < 0) && (aba.id.indexOf("_s") < 0)){
-			spanD.style.display = 'none';
-			footer_menu.style.display = 'none';			
-		}
-	}
-
-
-	var len = BordersArray.length;
-	for (var i=0; i < len; i++)
-	{
-		m = document.getElementById(BordersArray[i].border_id);
-		if ((m)&&(m.className == 'menu-sel'))
-		{
-			m.className = 'menu';
-			c = document.getElementById("content_id_"+BordersArray[i].sequence);
-			c.style.display = 'none';
-			if(Element("font_border_id_"+BordersArray[i].sequence))
-				Element("font_border_id_"+BordersArray[i].sequence).className = 'font-menu';	
-
-		}
-	}
-
-	m = Element("border_id_"+ID);
-	if (m)
-		m.className = 'menu-sel';
-	if(Element("font_border_id_" + ID))
-		Element("font_border_id_" + ID).className = 'font-menu-sel';
-	var c = Element("content_id_"+ID)
-	if (c)
-		c.style.display = '';
-
-
-	// hide the DropDrowContact, if necessary
-	window_DropDownContacts = Element('tipDiv');
-	if ((window_DropDownContacts)&&(window_DropDownContacts.style.visibility != 'hidden')){
-		window_DropDownContacts.style.visibility = 'hidden';
-	}
-
-	numBox = getNumBoxFromTabId(ID);
-	if (typeof(ID)=='number') {
+        
+    if (! Element('border_id_'+ID))
+        return false; // Not possible to alternate
+    show_hide_span_paging(ID);
+    spanD = Element("span_D");
+    if (spanD)
+        spanD.style.display = (openTab.type[ID] == 0 ? '' : 'none');
+
+    var footer_menu = Element("footer_menu");   
+    var aba = Element('border_id_'+ID);
+    if (footer_menu != null) {
+        footer_menu.style.display = (openTab.type[ID] != 4 ? '' : 'none');
+        var alternate_menu = document.getElementById('localOption');
+        
+        if(alternate_menu != null && alternate_menu != 'undefined'){ //Quando Carregado o expresso mail
+            if(openTab.imapBox[ID]!= null && openTab.imapBox[ID]!= 'undefined' ){ //Quando abrir uma Nova Mensagem
+                if((openTab.imapBox[ID].indexOf("local_") >= 0)){                       
+                        alternate_menu.title = get_lang("Unarchive");
+                        alternate_menu.removeAttribute("onclick");
+                        if(!is_ie)
+                            alternate_menu.setAttribute("onclick",  'expresso_local_messages.unarchive_msgs(\''+openTab.imapBox[ID]+'\', null)');
+                        else{
+                            alternate_menu.onclick = function(){
+                                expresso_local_messages.unarchive_msgs(openTab.imapBox[ID], null);
+                            }
+                        }
+                        alternate_menu.innerHTML = get_lang("Unarchive");
+                        
+                    }else{
+                        alternate_menu.title = get_lang("Archive");
+                        alternate_menu.removeAttribute("onclick");
+                        if(!is_ie)
+                            alternate_menu.setAttribute("onclick", 'archive_msgs(\''+openTab.imapBox[ID]+'\', null)');      
+                        else{
+                            alternate_menu.onclick = function(){
+                                archive_msgs(openTab.imapBox[ID], null);
+                            }   
+                        }
+                        alternate_menu.innerHTML = get_lang("Archive");
+                    }
+                    
+            }
+        }
+        
+        if((aba.id.indexOf("_r") < 0) && (aba.id.indexOf("_0") < 0) && (aba.id.indexOf("id_search_") < 0) && (aba.id.indexOf("_s") < 0)){
+            spanD.style.display = 'none';
+            footer_menu.style.display = 'none';         
+        }
+    }
+
+
+    var len = BordersArray.length;
+    for (var i=0; i < len; i++)
+    {
+        m = document.getElementById(BordersArray[i].border_id);
+        if ((m)&&(m.className == 'menu-sel'))
+        {
+            m.className = 'menu';
+            c = document.getElementById("content_id_"+BordersArray[i].sequence);
+            c.style.display = 'none';
+            if(Element("font_border_id_"+BordersArray[i].sequence))
+                Element("font_border_id_"+BordersArray[i].sequence).className = 'font-menu';    
+
+        }
+    }
+
+    m = Element("border_id_"+ID);
+    if (m)
+        m.className = 'menu-sel';
+    if(Element("font_border_id_" + ID))
+        Element("font_border_id_" + ID).className = 'font-menu-sel';
+    var c = Element("content_id_"+ID)
+    if (c)
+        c.style.display = '';
+
+
+    // hide the DropDrowContact, if necessary
+    window_DropDownContacts = Element('tipDiv');
+    if ((window_DropDownContacts)&&(window_DropDownContacts.style.visibility != 'hidden')){
+        window_DropDownContacts.style.visibility = 'hidden';
+    }
+
+    numBox = getNumBoxFromTabId(ID);
+    if (typeof(ID)=='number') {
                  numBox = ID;
          }
@@ -145,26 +147,27 @@
              }
          }
-	currentTab=ID;
-	if( document.getElementById('to_'+ID) && document.getElementById('to_'+ID).type == "textarea"){ 
- 	    document.getElementById('to_'+ID).focus(); 
-	}
-	if (ID == 0){ 
-		updateSelectedMsgs();
-	}
-	RichTextEditor.setEditable(ID);
-	resizeWindow();
-	return ID;
+    currentTab=ID;
+    if( document.getElementById('to_'+ID) && document.getElementById('to_'+ID).type == "textarea"){ 
+        document.getElementById('to_'+ID).focus(); 
+    }
+    if (ID == 0){ 
+        updateSelectedMsgs();
+    }
+    RichTextEditor.setEditable(ID);
+    resizeWindow();
+
+    return ID;
 }
 
 function create_border(borderTitle, id_value, search)
 {
-	borderTitle = ( ( borderTitle && borderTitle.constructor == String && borderTitle.length > 0 ) ? borderTitle : ' ' );
+    borderTitle = ( ( borderTitle && borderTitle.constructor == String && borderTitle.length > 0 ) ? borderTitle : ' ' );
     borderTitle = html_entities(borderTitle);    
-	var resize = false;
+    var resize = false;
         resize = resize_borders();
         if (!resize){
             var str_continue = '';
             var bolContinue = true;
-			str_continue = '\n' + get_lang('You must manually close one of your tabs before opening a new one');
+            str_continue = '\n' + get_lang('You must manually close one of your tabs before opening a new one');
             if (preferences.auto_close_first_tab == 1){
                 var children = Element('border_tr').childNodes;
@@ -180,92 +183,92 @@
                         }
                         if (bolDelete || bolContinue){
-							str_fechar = '\n' + get_lang('Reached maximum tab limit. Want to close this tab');
-							var confirmacao = confirm(str_fechar);
+                            str_fechar = '\n' + get_lang('Reached maximum tab limit. Want to close this tab');
+                            var confirmacao = confirm(str_fechar);
                             if(confirmacao){
                             bolContinue = false;
                             delete_border(num_child, 'false');
                             break;
-							}else{
-								return 'maximo';
+                            }else{
+                                return 'maximo';
                         }
                     }
                 }
             }
-            }else{			
+            }else{          
                 alert(get_lang('Reached maximum tab limit') + str_continue );
                 return 'maximo';
             }
         }
-	
-	if (! id_value){ // Is new message?
-		var ID = parseInt(BordersArray[(BordersArray.length-1)].sequence) + 1;
-			if(isNaN(ID)){
-				var aux = BordersArray[(BordersArray.length-1)].sequence.split("_");
-				ID = parseInt(aux[1]) + 1;
-			}
+    
+    if (! id_value){ // Is new message?
+        var ID = parseInt(BordersArray[(BordersArray.length-1)].sequence) + 1;
+            if(isNaN(ID)){
+                var aux = BordersArray[(BordersArray.length-1)].sequence.split("_");
+                ID = parseInt(aux[1]) + 1;
+            }
         }else
-	{
-		if (Element("border_id_"+id_value)) // It's opened already!
-			return alternate_border(id_value);
-		
-		var ID = id_value;
-		if(isNaN(ID) && ID.indexOf("search_local") >= 0){
-			if(current_folder.indexOf("local") >= 0)
-				openTab.imapBox[ID] = current_folder;
-			else
-				openTab.imapBox[ID] = 'local_search';
-		}else if(isNaN(ID) && ID.indexOf("search_") >= 0){
-			if(current_folder.indexOf("local") < 0)
-				openTab.imapBox[ID] = current_folder;
-			else
-				openTab.imapBox[ID] = 'search';
-		}else if( (currentTab != 0) && isNaN(currentTab) && (currentTab.indexOf("search") >= 0) && (ID.indexOf("msg") < 0) ) {
-			var id_border = currentTab.replace(/[a-zA-Z_]+/, "");
-			ID_TR = ID.toString().substr(0,ID.toString().indexOf("_r"));
-			var tr = Element(ID_TR) ? Element(ID_TR) : Element(ID_TR+"_s"+id_border);
-			openTab.imapBox[ID] = (tr.getAttribute('name') == null?get_current_folder():tr.getAttribute('name'));
-		}else
-			openTab.imapBox[ID] = current_folder;
-	}
-	td = document.createElement("TD");
-	td.id="border_id_" + ID;
-	if(resize) 
-	{
-		td.setAttribute("width", parseInt(resize)+"px");
-		td.style.width = parseInt(resize)+"px";
-	}
-	else
-		td.setAttribute("width", "200px");
-
-	td.setAttribute("align", "right");
-	td.onclick = function(){alternate_border(ID);resizeWindow()};
-	td.setAttribute("noWrap","true");
-    	td.setAttribute("role",get_current_folder());
-    	td.title = borderTitle;
-	borderTitle = borderTitle ?  borderTitle : id_value ? get_lang("No Subject") : " "	;
-	td.value = borderTitle;
-	if (borderTitle.length > 21)
-		borderTitle = borderTitle.substring(0,21) + "...";
-
-	if ( resize )
-		borderTitle = borderTitle.substring(0, resize*0.08);
-	
-	var cc = search;
-	if(!cc){
-		if(isNaN(ID)){
-			var is_local = ID.match('.*_local_.*');
-			if(!is_local)
-				cc = document.getElementById("em_message_search").value;
-			else{
-				if (currentTab == 0)
-					cc = "";
-				else
-					cc = document.getElementsByName(currentTab)[0].value;
-			}
-		}else{
-			cc ="";
-		}
-	}
-	td.innerHTML = "<div><div id='font_border_id_" + ID+"' class='font-menu'>" +
+    {
+        if (Element("border_id_"+id_value)) // It's opened already!
+            return alternate_border(id_value);
+        
+        var ID = id_value;
+        if(isNaN(ID) && ID.indexOf("search_local") >= 0){
+            if(current_folder.indexOf("local") >= 0)
+                openTab.imapBox[ID] = current_folder;
+            else
+                openTab.imapBox[ID] = 'local_search';
+        }else if(isNaN(ID) && ID.indexOf("search_") >= 0){
+            if(current_folder.indexOf("local") < 0)
+                openTab.imapBox[ID] = current_folder;
+            else
+                openTab.imapBox[ID] = 'search';
+        }else if( (currentTab != 0) && isNaN(currentTab) && (currentTab.indexOf("search") >= 0) && (ID.indexOf("msg") < 0) ) {
+            var id_border = currentTab.replace(/[a-zA-Z_]+/, "");
+            ID_TR = ID.toString().substr(0,ID.toString().indexOf("_r"));
+            var tr = Element(ID_TR) ? Element(ID_TR) : Element(ID_TR+"_s"+id_border);
+            openTab.imapBox[ID] = (tr.getAttribute('name') == null?get_current_folder():tr.getAttribute('name'));
+        }else
+            openTab.imapBox[ID] = current_folder;
+    }
+    td = document.createElement("TD");
+    td.id="border_id_" + ID;
+    if(resize) 
+    {
+        td.setAttribute("width", parseInt(resize)+"px");
+        td.style.width = parseInt(resize)+"px";
+    }
+    else
+        td.setAttribute("width", "200px");
+
+    td.setAttribute("align", "right");
+    td.onclick = function(){alternate_border(ID);resizeWindow()};
+    td.setAttribute("noWrap","true");
+    td.setAttribute("role",get_current_folder());
+    td.title = borderTitle;
+    borderTitle = borderTitle ?  borderTitle : id_value ? get_lang("No Subject") : " "  ;
+    td.value = borderTitle;
+    if (borderTitle.length > 21)
+        borderTitle = borderTitle.substring(0,21) + "...";
+
+    if ( resize )
+        borderTitle = borderTitle.substring(0, resize*0.08);
+    
+    var cc = search;
+    if(!cc){
+        if(isNaN(ID)){
+            var is_local = ID.match('.*_local_.*');
+            if(!is_local)
+                cc = document.getElementById("em_message_search").value;
+            else{
+                if (currentTab == 0)
+                    cc = "";
+                else
+                    cc = document.getElementsByName(currentTab)[0].value;
+            }
+        }else{
+            cc ="";
+        }
+    }
+    td.innerHTML = "<div><div id='font_border_id_" + ID+"' class='font-menu'>" +
                                 borderTitle +
                             "</div>\n\
@@ -273,130 +276,165 @@
                                 <img onmousedown='javascript:return false' style='cursor:pointer' onclick=delete_border('" + ID + "','false') src='templates/"+template+"/images/close_button.gif'/>\n\ " +
                             "</div>\n\ " + 
-							"<input type=\"hidden\" name=\""+ ID+"\" value=\""+cc+"\"></div>";		
-	bb = document.getElementById("border_blank");
-	parent_bb = bb.parentNode; //Pego o tbody
-	parent_bb.insertBefore(td, bb);
-
-	if((typeof(id_value) == 'string') && id_value.match(/_r/)){
-		$(td).draggable({
-			start : function(){
-				$('.upper, .lower').show();
-        		$(".lower").css("top", ($("#content_folders").height()-18) + $("#content_folders").offset().top);
-				if($(".shared-folders").length){
-					$(".shared-folders").parent().find('.folder:not(".shared-folders")').droppable({
-						over : function(a, b){						
-							//SETA BORDA EM VOLTA DA PASTA
-							over = $(this);
-							$(this).addClass("folder-over");
-							if(($(this)[0] != $(this).parent().find(".head_folder")[0]))
-								if($(this).prev()[0])
-									if($(this).parent().find(".expandable-hitarea")[0] == $(this).prev()[0]){
-										setTimeout(function(){
-											if(over.hasClass("folder-over"))
-												over.prev().trigger("click");
-										}, 500);
-										
-									}
-							//$("#content_folders").stop().scrollTo($(this), {axis:'y', margin:true, offset:-50, duration:400});
-						},
-						out : function(){
-							//RETIRA BORDA EM VOLTA DA PASTA
-							$(this).removeClass("folder-over");
-						},
-						//accept: ".draggin_mail",
-						drop : function(event, ui){
-							$(this).css("border", "0");
-							if($(this).parent().attr('id') == undefined){
-								var folder_to = 'INBOX';
-								var to_folder_title = get_lang("Inbox");
-							}else{
-								var folder_to = $(this).parent().attr('id');
-								var to_folder_title = $(this).attr('title');
-							}		
-							var folder_to_move = ui.draggable.parent().attr('id');
-							var border_id = ui.draggable.find("input[type=hidden]").attr("name");
-							if(folder_to_move == "border_tr"){
-								var id_msg = border_id.split("_")[0];
-								folder = $("#input_folder_"+border_id+"_r")[0] ? $("#input_folder_"+border_id+"_r").val() : (openTab.imapBox[border_id] ? openTab.imapBox[border_id]:get_current_folder());
-								move_msgs2(folder, id_msg, border_id, folder_to, to_folder_title,true);
-								return refresh();
-							}
-						}
-					});
-				}
-			},
-			stop :function(){
-				$('.upper, .lower').hide();
-				$(".shared-folders").parent().find(".folder").droppable("destroy");
-			},
-			helper: function(event){
-				if(	borderTitle.length > 18 )
-					return $("<td>"+DataLayer.render('../prototype/modules/mail/templates/draggin_box.ejs', {texto : borderTitle.substring(0,18) + "...", type: "messages"})+"</td>");
-				else
-					return $("<td>"+DataLayer.render('../prototype/modules/mail/templates/draggin_box.ejs', {texto : borderTitle, type: "messages"})+"</td>");
-			},
-			delay: 150,
-			cursorAt: {top: 5, left: 56},
-			refreshPositions: true ,
-			containment: "#divAppbox"
-		});
-	}
-		//_dragArea.makeDragged(td, id_value,td.value);
-
-	BordersArray[BordersArray.length] = new setBorderAttributes(ID);
-
-	var div = document.createElement("DIV");
-	div.id = "content_id_" + ID;
-	div.className = "conteudo";
-	div.style.display='';
-
-	div.style.overflow = "hidden";
-
-	Element("exmail_main_body").insertBefore(div,Element("footer_menu"));       
-	if (!is_ie)
-		resizeWindow();
-	alternate_border(ID);
+                            "<input type=\"hidden\" name=\""+ ID+"\" value=\""+cc+"\"></div>";      
+    bb = document.getElementById("border_blank");
+    parent_bb = bb.parentNode; //Pego o tbody
+    parent_bb.insertBefore(td, bb);
+
+    if((typeof(id_value) == 'string') && id_value.match(/_r/)){
+        $(td).draggable({
+            start : function(){
+                $('.upper, .lower').show();
+                $(".lower").css("top", ($("#content_folders").height()-18) + $("#content_folders").offset().top);
+                /* Habilitar anexar mensagem por drag-and-drop, se a aba atual for editável,  
+                ou seja, nem de leitura (2), nem de lista de mensagens (0):*/ 
+                var current_tab_type = openTab.type[currentTab]; 
+                if (current_tab_type != 0 && current_tab_type != 2){ 
+                    var dropzone = $("#fileupload_msg" + currentTab + "_droopzone"); 
+                    dropzone.show(); 
+                    dropzone.prev().hide(); 
+                    dropzone.droppable({ 
+                        over: function (event, ui){ 
+                            dropzone.addClass('hover in'); 
+                            $(ui.helper).find(".draggin-folder,.draggin-mail").css("color", "green"); 
+                        }, 
+                        out: function (event, ui) { 
+                            dropzone.removeClass('hover in'); 
+                            $(ui.helper).find(".draggin-folder,.draggin-mail").css("color", ""); 
+                        }, 
+                        drop: function (event, ui) { 
+                            var border_id = ui.draggable.find("input[type=hidden]").attr("name"); 
+                            var id_msg = border_id.split("_")[0]; 
+                            var folder = $("#input_folder_"+border_id+"_r")[0] ? $("#input_folder_"+border_id+"_r").val() : (openTab.imapBox[border_id] ? openTab.imapBox[border_id]:get_current_folder()); 
+                            attach_message(folder, id_msg); /* Anexa a mensagem especificada (por folder e id_msg) 
+                                                               na mensagem sendo criada.*/ 
+                        } 
+                    }); 
+                } 
+                if($(".shared-folders").length){
+                    $(".shared-folders").parent().find('.folder:not(".shared-folders")').droppable({
+                        over : function(a, b){                      
+                            //SETA BORDA EM VOLTA DA PASTA
+                            $(b.helper).find(".draggin-folder,.draggin-mail").css("color", "green");
+                            over = $(this);
+                            $(this).addClass("folder-over");
+                            if(($(this)[0] != $(this).parent().find(".head_folder")[0]))
+                                if($(this).prev()[0])
+                                    if($(this).parent().find(".expandable-hitarea")[0] == $(this).prev()[0]){
+                                        setTimeout(function(){
+                                            if(over.hasClass("folder-over"))
+                                                over.prev().trigger("click");
+                                        }, 500);
+                                        
+                                    }
+                            //$("#content_folders").stop().scrollTo($(this), {axis:'y', margin:true, offset:-50, duration:400});
+                        },
+                        out : function(a,b){
+                            //RETIRA BORDA EM VOLTA DA PASTA
+                            $(b.helper).find(".draggin-folder,.draggin-mail").css("color", "");
+                            $(this).removeClass("folder-over");
+                        },
+                        //accept: ".draggin_mail",
+                        drop : function(event, ui){
+                            $(this).css("border", "0");
+                            if($(this).parent().attr('id') == undefined){
+                                var folder_to = 'INBOX';
+                                var to_folder_title = get_lang("Inbox");
+                            }else{
+                                var folder_to = $(this).parent().attr('id');
+                                var to_folder_title = $(this).attr('title');
+                            }       
+                            var folder_to_move = ui.draggable.parent().attr('id');
+                            var border_id = ui.draggable.find("input[type=hidden]").attr("name");
+                            if(folder_to_move == "border_tr"){
+                                var id_msg = border_id.split("_")[0];
+                                folder = $("#input_folder_"+border_id+"_r")[0] ? $("#input_folder_"+border_id+"_r").val() : (openTab.imapBox[border_id] ? openTab.imapBox[border_id]:get_current_folder());
+                                move_msgs2(folder, id_msg, border_id, folder_to, to_folder_title,true);
+                                return refresh();
+                            }
+                        }
+                    });
+                }
+            },
+            stop :function(){
+                $('.upper, .lower').hide();
+                $(".shared-folders").parent().find(".folder").droppable("destroy");
+                /* Habilitar anexar mensagem por drag-and-drop, se a aba atual for editável,  
+                ou seja, nem de leitura (2), nem de lista de mensagens (0):*/ 
+                var current_tab_type = openTab.type[currentTab]; 
+                if (current_tab_type != 0 && current_tab_type != 2){ 
+                    var dropzone = $("#fileupload_msg" + currentTab + "_droopzone"); 
+                    dropzone.hide(); 
+                    dropzone.prev().show(); 
+                } 
+            },
+            helper: function(event){
+                if( borderTitle.length > 18 )
+                    return $("<td>"+DataLayer.render('../prototype/modules/mail/templates/draggin_box.ejs', {texto : borderTitle.substring(0,18) + "...", type: "messages"})+"</td>");
+                else
+                    return $("<td>"+DataLayer.render('../prototype/modules/mail/templates/draggin_box.ejs', {texto : borderTitle, type: "messages"})+"</td>");
+            },
+            delay: 150,
+            cursorAt: {top: 5, left: 56},
+            refreshPositions: true ,
+            containment: "#divAppbox"
+        });
+    }
+        //_dragArea.makeDragged(td, id_value,td.value);
+
+    BordersArray[BordersArray.length] = new setBorderAttributes(ID);
+
+    var div = document.createElement("DIV");
+    div.id = "content_id_" + ID;
+    div.className = "conteudo";
+    div.style.display='';
+
+    div.style.overflow = "hidden";
+
+    Element("exmail_main_body").insertBefore(div,Element("footer_menu"));       
+    if (!is_ie)
+        resizeWindow();
+    alternate_border(ID);
     uidsSave[ID] = [];
     saveBorderError[ID] = false;
-	return ID;
+    return ID;
 }
 
 function resize_borders()
 {
-	var numBorders = count_borders();
-
-	if (numBorders > 8)
-		return false;
-
-	return redim_borders(numBorders+1);
+    var numBorders = count_borders();
+
+    if (numBorders > 8)
+        return false;
+
+    return redim_borders(numBorders+1);
 }
 
 function count_borders()
 {
-	var numBorders = 0;
-	var children = Element('border_tr').childNodes;
-	for (var i=0; i<children.length; i++) {
-	    if ((children[i].nodeName === 'TD') && (children[i].id!=='border_id_0') && (children[i].id!=='border_blank'))
-		numBorders++;
-	}
-
-	return numBorders;
+    var numBorders = 0;
+    var children = Element('border_tr').childNodes;
+    for (var i=0; i<children.length; i++) {
+        if ((children[i].nodeName === 'TD') && (children[i].id!=='border_id_0') && (children[i].id!=='border_blank'))
+        numBorders++;
+    }
+
+    return numBorders;
 }
 
 function redim_borders(numBorders)
 {
-	var children = Element('border_tr').childNodes;
-	var clientWidth = (window.document.body.clientWidth - findPosX(Element("exmail_main_body"))) - Element("border_id_0").clientWidth - 30;
-	var newWidthTD = (clientWidth/numBorders)-6;
-	newWidthTD = newWidthTD > 200 ? 200 : (newWidthTD < 50 ? 50 : newWidthTD);
-	children = Element('border_tr').childNodes;
-	for (var i=0; i<children.length; i++) {
-		if ((children[i].nodeName === 'TD') && (children[i].id!=='border_id_0') && (children[i].id!=='border_blank')){
-			$(children[i]).css("width", newWidthTD);
-			$(children[i]).find('div:first').css("width", newWidthTD);
-			set_border_caption(children[i].id, children[i].title, newWidthTD);
-		}
-	}
-	return newWidthTD;
+    var children = Element('border_tr').childNodes;
+    var clientWidth = (window.document.body.clientWidth - findPosX(Element("exmail_main_body"))) - Element("border_id_0").clientWidth - 30;
+    var newWidthTD = (clientWidth/numBorders)-6;
+    newWidthTD = newWidthTD > 200 ? 200 : (newWidthTD < 50 ? 50 : newWidthTD);
+    children = Element('border_tr').childNodes;
+    for (var i=0; i<children.length; i++) {
+        if ((children[i].nodeName === 'TD') && (children[i].id!=='border_id_0') && (children[i].id!=='border_blank')){
+            $(children[i]).css("width", newWidthTD);
+            $(children[i]).find('div:first').css("width", newWidthTD);
+            set_border_caption(children[i].id, children[i].title, newWidthTD);
+        }
+    }
+    return newWidthTD;
 }
 
@@ -411,10 +449,10 @@
             border_width = border.clientWidth;
         }
-	var caption = "";
+    var caption = "";
     if (border != null){
-		Element("font_"+border.id).style.width = (border_width - 35)+'px';
-		Element("font_"+border.id).innerHTML = title;
-	}
-	return(title);
+        Element("font_"+border.id).style.width = (border_width - 35)+'px';
+        Element("font_"+border.id).innerHTML = title;
+    }
+    return(title);
 }
 
@@ -442,14 +480,14 @@
                             'type':     'question',
                             'overlay_opacity': '0.5',
-							'custom_class': 'custom-zebra-filter',
+                            'custom_class': 'custom-zebra-filter',
                             'buttons':  buttons,
                             'width' : width,
                             'onClose':  function(clicked) {
-									if(clicked == 'Cancelar'){
-										if (RichTextEditor.plain[id] != true) 
-											setTimeout("RichTextEditor.focus("+ID+")",100);                  
-										else  
-											$('#body_'+ID).focus(); 
-									}
+                                    if(clicked == 'Cancelar'){
+                                        if (RichTextEditor.plain[id] != true) 
+                                            setTimeout("RichTextEditor.focus("+ID+")",100);                  
+                                        else  
+                                            $('#body_'+ID).focus(); 
+                                    }
                                     if(clicked == 'Descartar alterações' || clicked == 'Descartar alterações e anexos' ) {
                                         if (openTab.imapBox[ID] && !openTab.toPreserve[ID])
@@ -477,5 +515,5 @@
                                                                 $("#cc_"+ID).focus();
                                                         else if ($("#tr_cco_"+ID).css('display') != 'none' && $.trim($("#cco_"+ID).val()) == "")
-                                                                $("#cco_"+ID).focus();		
+                                                                $("#cco_"+ID).focus();      
                                                         else if ($.trim($("#subject_"+ID).val()) == "")
                                                                 $("#subject_"+ID).focus();
@@ -494,10 +532,10 @@
                             }})}, 300);    
         }
-	
+    
 }
 
 function editTest(ID){
     var body = document.getElementById('body_'+ ID);
-	var content = $('#content_id_'+ ID);
+    var content = $('#content_id_'+ ID);
     if (body)
     {
@@ -522,8 +560,8 @@
     }
 
-    if($("#content_id_"+currentTab+" textarea[name=input_to]").length ){
-        if($("#content_id_"+currentTab+" .save").is(':disabled') ) {
+    if($("#content_id_"+ID+" textarea[name=input_to]").length ){
+        if($("#content_id_"+ID+" .save").is(':disabled') ) {
              close_delete(ID, msg_sent);
-        } else if( $("#content_id_"+currentTab+" .save").is(':enabled') ) {
+        } else if( $("#content_id_"+ID+" .save").is(':enabled') ) {
              return(draftTests(ID, msg_sent));
         }
@@ -537,12 +575,12 @@
      
     /*var bolExecuteClose = true;
-	var borderElem = Element("border_id_" + ID);
-	if (borderElem){
+    var borderElem = Element("border_id_" + ID);
+    if (borderElem){
             borderElem.onclick = null; // It's avoid a FF3 bug
         }else{
             return false;
         }
-	if (msg_sent == 'false')
-	{
+    if (msg_sent == 'false')
+    {
             if (editTest(ID)){
                 bolExecuteClose = false;
@@ -550,5 +588,5 @@
                     return(draftTests(ID, msg_sent));
             }
-	}
+    }
     
         
@@ -556,6 +594,6 @@
         {
             close_delete(ID, msg_sent);
-		}
-		delete(openTab.type[ID]);
+        }
+        delete(openTab.type[ID]);
         return true;*/
          
@@ -564,5 +602,5 @@
 function close_delete(ID, msg_sent)
 {
-	openTab.toPreserve[ID] = false;
+    openTab.toPreserve[ID] = false;
         // Limpa o autosave
             if (preferences.auto_save_draft == 1 && autoSaveControl.timer[ID] !== null )
@@ -573,38 +611,38 @@
         ////////////////////////////////
         
-	hold_session = false;
-	if (exist_className(Element('border_id_'+ID),'menu-sel'))
-	{
-		if (BordersArray[BordersArray.length-2].sequence == ID)
-			this.alternate_border(0);
-		else
-			this.alternate_border(BordersArray[BordersArray.length-2].sequence);
-	}
-
-	// Remove TD, title
-	border = Element('border_id_' + ID);
-	border.parentNode.removeChild(border);
-	var j=0;
-	var new_BordersArray = new Array();
-	for (i=0;i<BordersArray.length;i++)
-		if (document.getElementById(BordersArray[i].border_id) != null){
-			new_BordersArray[j] = BordersArray[i];
-			j++;
-		}
-	if(j == 1)
-		Element("footer_menu").style.display = '';
-	BordersArray = new_BordersArray;
-
-	// Remove Div Content
-	content = Element('content_id_' + ID);
-	content.parentNode.removeChild(content);
-	if(is_webkit)
-		resizeWindow();
-	RichTextEditor.destroy( 'body_'+ID );
+    hold_session = false;
+    if (exist_className(Element('border_id_'+ID),'menu-sel'))
+    {
+        if (BordersArray[BordersArray.length-2].sequence == ID)
+            this.alternate_border(0);
+        else
+            this.alternate_border(BordersArray[BordersArray.length-2].sequence);
+    }
+
+    // Remove TD, title
+    border = Element('border_id_' + ID);
+    border.parentNode.removeChild(border);
+    var j=0;
+    var new_BordersArray = new Array();
+    for (i=0;i<BordersArray.length;i++)
+        if (document.getElementById(BordersArray[i].border_id) != null){
+            new_BordersArray[j] = BordersArray[i];
+            j++;
+        }
+    if(j == 1)
+        Element("footer_menu").style.display = '';
+    BordersArray = new_BordersArray;
+
+    // Remove Div Content
+    content = Element('content_id_' + ID);
+    content.parentNode.removeChild(content);
+    if(is_webkit)
+        resizeWindow();
+    RichTextEditor.destroy( 'body_'+ID );
         delete msgAttachments[ID];
         //Caso for uma mensagem anexada tem que deletar ela da lixeira apos fechar a aba
             var isPartMsg = false;
-			if(!parseInt(id2))
-				return;
+            if(!parseInt(id2))
+                return;
             var id2 = ID.replace('_r','');
             for(var ii = 0; ii < partMsgs.length; ii++)
@@ -620,30 +658,30 @@
         ///////////////////////////////////////////////////////////////////////////////////
         
-	return true;
+    return true;
 }
 
 function getTabPrefix() { // define o prefixo para os checkboxes das mensagens
-	if (typeof(currentTab)!='number')
-		return currentTab+"_";
-	else
-		return "";
+    if (typeof(currentTab)!='number')
+        return currentTab+"_";
+    else
+        return "";
 }
 
 function getMessageIdFromRowId(row_id) { // extrai o id da mensagem do id da linha
-	var p = row_id.search("_s");
-	if (p>0)
-		return row_id.substr(0,p);
-	else
-		return row_id;
+    var p = row_id.search("_s");
+    if (p>0)
+        return row_id.substr(0,p);
+    else
+        return row_id;
 }
 
 function getNumBoxFromTabId(tab_id) { // extrai o numBox do id da tab
-	if (typeof(tab_id)=='number') {
-		return tab_id;
-	}
-	else {
-		var p = tab_id.search(/[0-9]/);
-		return tab_id.substr(p);
-	}
+    if (typeof(tab_id)=='number') {
+        return tab_id;
+    }
+    else {
+        var p = tab_id.search(/[0-9]/);
+        return tab_id.substr(p);
+    }
 }
 
@@ -673,5 +711,4 @@
 function listAttachment(ID)
 {
-   return (typeof(msgAttachments[ID]) == 'undefined') ? '' : JSON.stringify(msgAttachments[ID]); 
-}
-
+    return (typeof(msgAttachments[ID]) == 'undefined') ? '' : JSON.stringify(msgAttachments[ID]);
+}
Index: branches/2.5/expressoMail1_2/js/InfoContact.js
===================================================================
--- branches/2.5/expressoMail1_2/js/InfoContact.js	(revision 8147)
+++ branches/2.5/expressoMail1_2/js/InfoContact.js	(revision 8232)
@@ -7,4 +7,5 @@
 	this.td;
 	this.createCard();
+	this.folder = get_current_folder();
 }
 
@@ -69,9 +70,13 @@
 
 emInfoContact.prototype.show = function (data){
+	if (this.folder != get_current_folder()){
+		this.folder = get_current_folder();
+		return false;
+	}	
 	var _this = this;
 	var card = Element("card_cc");
 	card.style.left = (findPosX(this.td) + 20)+"px";
-        var divScroll = Element("divScrollMain_"+numBox); 
-        var y = findPosY(this.td) + 20 - (divScroll ? divScroll.scrollTop : 0); 
+	var divScroll = Element("divScrollMain_"+numBox);
+	var y = findPosY(this.td) + 20 - (divScroll ? divScroll.scrollTop : 0);
 	var w_height = is_ie ? document.body.clientHeight + document.body.scrollTop : window.innerHeight + window.pageYOffset;
 	if(y + 160 > w_height)
Index: branches/2.5/expressoMail1_2/js/common_functions.js
===================================================================
--- branches/2.5/expressoMail1_2/js/common_functions.js	(revision 8080)
+++ branches/2.5/expressoMail1_2/js/common_functions.js	(revision 8232)
@@ -694,4 +694,15 @@
 }
 
+/* 
+	Abre o diálogo de edição de filtro na tela de criação de filtro,  
+	com os dados da mensagem (remetente e assunto) pré-carregados. 
+*/ 
+ function filter_from_msg (msg) { 
+	var html = DataLayer.render( BASE_PATH + 'modules/filters/init.ejs', {}); 
+	initialize_container(html); 
+	list_container = create_filter_dialog(); 
+	render_new_rule(msg.from.email, html_entities(msg.subject)); 
+	$('.expresso-window-container').dialog('open'); 
+} 
 
 function sharebox(){
@@ -771,5 +782,5 @@
 			var number = id.replace(/_[a-zA-Z0-9]+/,"");
 		}
-		messages.push(onceOpenedHeadersMessages[folder_name][number]);
+		messages.push(onceOpenedHeadersMessages[folder_name][number] || number);
 	}
 
@@ -997,12 +1008,12 @@
     abas_unseen = abas_unseen.match(/(<font.*?>){0,1} *([0-9]+) *(<\/font>){0,1}/)[2];
 
-        if (folder_unseen){ 
-                //folder_unseen.innerHTML = (parseInt(folder_unseen.innerHTML) + 1); 
-                /*Incrementa recursivamente o contador de mensagens*/
-                $('.selected').parents().find('> span.folder').not('.inbox').each(function(index,ui){
-                   var unseen = $(ui).find('.folder_unseen:last');
-                   unseen.html(parseInt(unseen.html(),10) + 1);
-                }); 
-        } 
+	if (folder_unseen){
+		//folder_unseen.innerHTML = (parseInt(folder_unseen.innerHTML) + 1);
+		/*Incrementa recursivamente o contador de mensagens*/
+		$('.selected').parents().find('> span.folder').not('.inbox').each(function(index,ui){
+		   var unseen = $(ui).find('.folder_unseen:last');
+		   unseen.html(parseInt(unseen.html(),10) + 1);
+		});
+	}
 	else
 	{
@@ -1046,10 +1057,10 @@
 	if ((folder_unseen) && (parseInt(folder_unseen.innerHTML) > 1))
 	{
-                //folder_unseen.innerHTML = (parseInt(folder_unseen.innerHTML) - 1); 
-                /*Decrementa recursivamente o contador de mensagens*/ 
-                $('.selected').parents().find('> span.folder').not('.inbox').each(function(index,ui){ 
-                   var unseen = $(ui).find('.folder_unseen:last'); 
-                   unseen.html(parseInt(unseen.html(),10) - 1); 
-                });      
+		//folder_unseen.innerHTML = (parseInt(folder_unseen.innerHTML) - 1);
+		/*Decrementa recursivamente o contador de mensagens*/
+		$('.selected').parents().find('> span.folder').not('.inbox').each(function(index,ui){
+		   var unseen = $(ui).find('.folder_unseen:last');
+		   unseen.html(parseInt(unseen.html(),10) - 1);
+		});	
 	}
 	else if (parseInt(folder_unseen.innerHTML) <= 1)
Index: branches/2.5/expressoMail1_2/js/main.js
===================================================================
--- branches/2.5/expressoMail1_2/js/main.js	(revision 8188)
+++ branches/2.5/expressoMail1_2/js/main.js	(revision 8232)
@@ -1,3 +1,2 @@
-// Tempo do auto refresh (em milisegundos)
 var time_refresh = 150000;
 
@@ -152,137 +151,110 @@
 
 		
-    if(preferences.show_name_print_messages == "1") { 
-        var getUserName = document.getElementById("user_info"); 
-        var userName = getUserName.innerHTML; 
-        var position = userName.indexOf("-"); 
-        var userName = userName.substring(3, position); 
-        cabecalho = '<h4>' + userName; 
-    } 
- 
-        current_folder="INBOX"; 
- 
-    //MAILARCHIVER-02 
-    //Try to get ArchiveServices object directly 
-    if(ArchiveServices) 
-        expresso_mail_archive.Startup(); 
-    //ArchiveServices not runnnig: catch the user preferences to set up message at header 
-    else{ 
-        if(preferences.use_local_messages=="1") 
-            write_msg(get_lang('Sorry, but Mail Archiver does not seems to be running or installed at this workstation. By now, we are turning off local messages!')); 
-    } 
- 
-    //cExecute ("$this.db_functions.get_dropdown_contacts", save_contacts); //Save contacts needs preferences. 
-    $.ajax({ 
-        async: false, 
-        url: "controller.php?" + $.param( {action: "$this.imap_functions.getMessagesIds", 
-            folder: get_current_folder(), 
-             msg_range_begin: "0", 
-             msg_range_end: "0", 
-            sort_box_type: "SORTARRIVAL", 
-            search_box_type: search_box_type, 
-            sort_box_reverse: "1" 
-            }), 
-        success: function(data){ 
-            data = connector.unserialize(data); 
-            if(data){ 
-                var _data = {}; 
-                $.each(data,function(index,value){ 
-                    if (data[index]){ 
-                        _data[data[index]] = data[index]; 
-                    } 
-                }); 
-                populateSelectedMsgs(_data); 
-            } 
-        }, 
-        beforeSend: function( jqXHR, settings ){ 
-            connector.showProgressBar(); 
-        }, 
-        complete: function( jqXHR, settings ){ 
-            connector.hideProgressBar(); 
+    if(preferences.show_name_print_messages == "1") {
+        var getUserName = document.getElementById("user_info");
+        var userName = getUserName.innerHTML;
+        var position = userName.indexOf("-");
+        var userName = userName.substring(3, position);
+        cabecalho = '<h4>' + userName;
+    }
+
+	current_folder="INBOX";
+
+    //MAILARCHIVER-02
+    //Try to get ArchiveServices object directly
+    if(ArchiveServices)
+        expresso_mail_archive.Startup();
+    //ArchiveServices not runnnig: catch the user preferences to set up message at header
+    else{
+        if(preferences.use_local_messages=="1")
+            write_msg(get_lang('Sorry, but Mail Archiver does not seems to be running or installed at this workstation. By now, we are turning off local messages!'));
+    }
+
+//  cExecute ("$this.db_functions.get_dropdown_contacts", save_contacts); //Save contacts needs preferences.
+
+    cExecute ("$this.imap_functions.get_range_msgs2&folder=INBOX&msg_range_begin=1&msg_range_end="+preferences.max_email_per_page+"&sort_box_type=SORTARRIVAL&search_box_type=ALL&sort_box_reverse=1", handler_draw_box);
+
+    if(preferences.hide_folders == "1")
+        Element('divAppboxHeader').innerHTML =  title_app_menu;
+
+    //Desbilitado limpeza de lixeira por request. Ticket #3253
+    //if (preferences.delete_trash_messages_after_n_days != 0)
+    ///	cExecute ("$this.imap_functions.automatic_trash_cleanness&before_date="+preferences.delete_trash_messages_after_n_days+"&cyrus_delimiter="+cyrus_delimiter, handler_automatic_trash_cleanness);
+
+    //if(preferences.outoffice == "1")
+    //
+
+    //Troca da forma de construção de menu para o plugin jquery.contextMenu
+    //ConstructMenuTools();
+    //MAILARCHIVER-00
+    //if ( (preferences.use_local_messages==1) && (expresso_local_messages.is_offline_installed()) )  //Precisa ser feito após a renderização da caixa de emails
+        //check_mail_in_queue();
+
+    // Insere a applet de criptografia
+    if (preferences.use_signature_digital_cripto == '1'){
+        loadApplet();
+    }
+    // Fim da inserção da applet
+    cExecute("$this.imap_functions.get_folders_list&onload=true", update_menu);
+    //update_menu(Folder.getList(false));
+
+    if($.cookie('collapse_folders') == "true"){
+        if(!is_ie)
+            $("#folderscol").addClass( "hidden");
+        else
+            $("#folderscol").hide();
+        $(".collapse_folders").addClass("ui-icon ui-icon-triangle-1-e").children().attr('title', "Expandir");
+        refresh();
+        resizeWindow();
+    }
+    else{
+        $(".collapse_folders").addClass("ui-icon ui-icon-triangle-1-w").children().attr('title', "Ocultar");
+        refresh();
+        resizeWindow();
+    }
+
+    $(".collapse_folders_td").attr('title', "Ocultar/Expandir").click(function(){
+        if($("#folderscol").css("display") != "none"){
+            if(!is_ie)
+                $("#folderscol").addClass( "hidden");
+            else
+                $("#folderscol").hide();
+
+            $(".collapse_folders").removeClass("ui-icon-triangle-1-w");
+            $(".collapse_folders").addClass("ui-icon-triangle-1-e");
+            $(".collapse_folders").parent().attr('title', "Expandir");
+            $.cookie('collapse_folders', "true");
+            refresh();
+            resizeWindow();
+        }else{
+            if(!is_ie)
+                $("#folderscol").removeClass( "hidden");
+            else
+                $("#folderscol").show();
+            $(".collapse_folders").removeClass("ui-icon-triangle-1-e");
+            $(".collapse_folders").addClass("ui-icon-triangle-1-w");
+            $(".collapse_folders").parent().attr('title', "Ocultar");
+            $.cookie('collapse_folders', "false");
+            refresh();
+            resizeWindow();
         }
-    }); 
-     cExecute ("$this.imap_functions.get_range_msgs2&folder=INBOX&msg_range_begin=1&msg_range_end="+preferences.max_email_per_page+"&sort_box_type=SORTARRIVAL&search_box_type=ALL&sort_box_reverse=1", handler_draw_box); 
- 
-    if(preferences.hide_folders == "1") 
-        Element('divAppboxHeader').innerHTML =  title_app_menu; 
- 
-    //Desbilitado limpeza de lixeira por request. Ticket #3253 
-    //if (preferences.delete_trash_messages_after_n_days != 0) 
-    /// cExecute ("$this.imap_functions.automatic_trash_cleanness&before_date="+preferences.delete_trash_messages_after_n_days+"&cyrus_delimiter="+cyrus_delimiter, handler_automatic_trash_cleanness); 
- 
-    //if(preferences.outoffice == "1") 
-    // 
- 
-    //Troca da forma de construção de menu para o plugin jquery.contextMenu 
-    //ConstructMenuTools(); 
-    //MAILARCHIVER-00 
-    //if ( (preferences.use_local_messages==1) && (expresso_local_messages.is_offline_installed()) )  //Precisa ser feito após a renderização da caixa de emails 
-        //check_mail_in_queue(); 
- 
-    // Insere a applet de criptografia 
-    if (preferences.use_signature_digital_cripto == '1'){ 
-        loadApplet(); 
-    } 
-    // Fim da inserção da applet 
-    cExecute("$this.imap_functions.get_folders_list&onload=true", update_menu); 
- 
-    if($.cookie('collapse_folders') == "true"){ 
-        if(!is_ie) 
-            $("#folderscol").addClass( "hidden"); 
-        else 
-            $("#folderscol").hide(); 
-        $(".collapse_folders").addClass("ui-icon ui-icon-triangle-1-e").children().attr('title', "Expandir"); 
-        refresh(); 
-        resizeWindow(); 
-    } 
-    else{ 
-        $(".collapse_folders").addClass("ui-icon ui-icon-triangle-1-w").children().attr('title', "Ocultar"); 
-        refresh(); 
-        resizeWindow(); 
-    } 
- 
-    $(".collapse_folders_td").attr('title', "Ocultar/Expandir").click(function(){ 
-        if($("#folderscol").css("display") != "none"){ 
-            if(!is_ie) 
-                $("#folderscol").addClass( "hidden"); 
-            else 
-                $("#folderscol").hide(); 
- 
-            $(".collapse_folders").removeClass("ui-icon-triangle-1-w"); 
-            $(".collapse_folders").addClass("ui-icon-triangle-1-e"); 
-            $(".collapse_folders").parent().attr('title', "Expandir"); 
-            $.cookie('collapse_folders', "true"); 
-            refresh(); 
-            resizeWindow(); 
-        }else{ 
-            if(!is_ie) 
-                $("#folderscol").removeClass( "hidden"); 
-            else 
-                $("#folderscol").show(); 
-            $(".collapse_folders").removeClass("ui-icon-triangle-1-e"); 
-            $(".collapse_folders").addClass("ui-icon-triangle-1-w"); 
-            $(".collapse_folders").parent().attr('title', "Ocultar"); 
-            $.cookie('collapse_folders', "false"); 
-            refresh(); 
-            resizeWindow(); 
-        } 
-        resizeWindow(); 
- 
-    }).hover( 
-        function(){ 
-            $(this).addClass("collapse_folders_td_over"); 
-        }, 
-        function(){ 
-            $(this).removeClass("collapse_folders_td_over"); 
-        } 
-    ); 
- 
-    if(parseInt(preferences.use_dynamic_contacts)){ 
-        updateDynamicContact(); 
-    } 
- 
- 
-    var handler_automatic_trash_cleanness = function(data) 
-    { 
+        resizeWindow();
+
+    }).hover(
+        function(){
+            $(this).addClass("collapse_folders_td_over");
+        },
+        function(){
+            $(this).removeClass("collapse_folders_td_over");
+        }
+    );
+
+    if(parseInt(preferences.use_dynamic_contacts)){
+        updateDynamicContact();
+    }
+
+
+    var handler_automatic_trash_cleanness = function(data)
+    {
 		if (data != false){
 			write_msg(data.length +' '+ Element('txt_clear_trash').value);
@@ -295,8 +267,4 @@
 	// Get cyrus delimiter
 	cyrus_delimiter = Element('cyrus_delimiter').value;
-
-    cExecute ("phpgwapi.browser.isMobile", function( data ){
-		mobile_device = ( ( data.constructor == Boolean ) ? data : ( data === 'true' ) );
-	});
 
 	cExecute("$this.imap_functions.get_folders_list&onload=true", update_menu);	
@@ -595,9 +563,9 @@
 		if(Element("border_id_" + id_msg_read)) {
 			alternate_border(id_msg_read);
-			resizeWindow(); 
+			resizeWindow();
 		}
 		else {
 			var border_id = create_border(msg_info.subject, id_msg_read);
-			if(border_id)
+			if(border_id && border_id != "maximo")
 			{
 				openTab.type[border_id] = 2;
@@ -661,9 +629,9 @@
 				
 		}
-                if (msg_info.showImg) 
-                { 
-                        $("#body_"+id_msg_read).html(msg_info.body); 
-                        $('#show_img_link_'+id_msg_read).remove(); 
-                } 
+		if (msg_info.showImg)
+		{
+			$("#body_"+id_msg_read).html(msg_info.body);
+			$('#show_img_link_'+id_msg_read).remove();
+		}
 		//Change msg class to read.
 		if (!msg_is_read(ID))
@@ -705,10 +673,10 @@
 		if(differenceOfNewCriteria > 0){
 			for(var i=data.length - differenceOfNewCriteria; i < data.length; i++){
-                var msg_folder = data[i].msg_folder; 
-                var msg_number = data[i].msg_number; 
+                var msg_folder = data[i].msg_folder;
+                var msg_number = data[i].msg_number;
 				desktopNotification.sentNotification("",get_lang("Filter criteria"),  truncate(new Date(data[i].udate).toString('dd/MM HH:mm') + ' - ' + data[i].from+' - '+data[i].subject, 75));
-                                desktopNotification.showNotification(function(){ 
-                    cExecute ("$this.imap_functions.removeFlagMessagesFilter&folder="+msg_folder+"&msg_number="+msg_number, function(){}); 
-                }, function(){ 
+				desktopNotification.showNotification(function(){
+                    cExecute ("$this.imap_functions.removeFlagMessagesFilter&folder="+msg_folder+"&msg_number="+msg_number, function(){});
+                }, function(){
 					window.focus();
 					this.cancel();
@@ -721,13 +689,22 @@
 function refresh(alert_new_msg, notifyPermission){
 
+    //Não deixa atualizar caso o usuario esteja em uma aba de nova mesnagem , reponder ou encaminhar;
+    //Evita o travamento da escrita no CKEDITOR.
+    if(typeof(currentTab) !== 'undefined' && currentTab.toString().indexOf("_r_") === -1 && currentTab !== 0 )
+        return;
+
 	getFromAlertRules();
 	var handler_refresh = function(data){
-		handlerMessageFilter = function (data) {			
-			notificationFilter(data, notifyPermission);
-			alarmFollowupflagged('filtersAlarms', data);
-			
-		}
-		/* Busca  nas pastas indexadas para ver se há novas mensagens com a flag $FilteredMessage */
-		cExecute ("$this.imap_functions.getFlaggedAlertMessages&folders="+fromRules, handlerMessageFilter);
+
+        if(preferences['use_alert_filter_criteria'] == "1")
+        {
+            var handlerMessageFilter = function (data) {
+                notificationFilter(data, notifyPermission);
+                alarmFollowupflagged('filtersAlarms', data);
+
+            }
+            /* Busca  nas pastas indexadas para ver se há novas mensagens com a flag $FilteredMessage */
+            cExecute ("$this.imap_functions.getFlaggedAlertMessages&folders="+fromRules, handlerMessageFilter);
+        }
 
 		if(data['msg_range_end'])
@@ -801,4 +778,5 @@
 									over : function(a, b){						
 										//SETA BORDA EM VOLTA DA PASTA
+										$(b.helper).find(".draggin-folder,.draggin-mail").css("color", "green");
 										over = $(this);
 										$(this).addClass("folder-over");
@@ -813,6 +791,8 @@
 												}
 									},
-									out : function(){
+									out : function(a,b){
+
 										//RETIRA BORDA EM VOLTA DA PASTA
+										$(b.helper).find(".draggin-folder,.draggin-mail").css("color", "");
 										$(this).removeClass("folder-over");
 									},
@@ -1005,6 +985,6 @@
 				
  		        var userTrashFolder = ''; 
- 		       
- 		        if (arguments.length <= 6) show_success_msg = true; 
+
+ 		        if (arguments.length <= 6 && typeof(show_success_msg) == "undefined") show_success_msg = true; 
  		        if (folder == 'null') folder = current_folder; 
  		 
@@ -1013,11 +993,11 @@
 					var arrayFolder = folder.split(cyrus_delimiter); 
 					userTrashFolder = 'user'+cyrus_delimiter+arrayFolder[1]+cyrus_delimiter+special_folders['Trash'];
-                                        var has_folder = false;//Folder.get( userTrashFolder, false ); 
-                                        var folders = DataLayer.get("folder"); 
-                                        $.each(folders,function(index,value){ 
-                                                if(value && value.id == userTrashFolder)  
-                                                        has_folder = true; 
-                                        }); 
- 
+					var has_folder = false;//Folder.get( userTrashFolder, false );
+					var folders = DataLayer.get("folder");
+					$.each(folders,function(index,value){
+						if(value && value.id == userTrashFolder) 
+							has_folder = true;
+					});
+
 					if(!has_folder){
 						create_new_folder(special_folders['Trash'], 'user'+cyrus_delimiter+arrayFolder[1]);
@@ -1097,6 +1077,8 @@
 								  data = connector.unserialize( data );
 								  
-								  if( data )
-								  show_msg( data );
+								  if( data ){
+								  	data.openSameBorder = true;
+								  	show_msg( data );
+								  }
 							  },
 							  beforeSend: function( jqXHR, settings ){
@@ -1147,4 +1129,5 @@
 		params_to_delete += "&search_box_type="+search_box_type;
 		params_to_delete += "&sort_box_reverse="+sort_box_reverse;
+
 		cExecute ("$this.imap_functions.delete_msgs", handler_delete_msgs, params_to_delete);
 	}
@@ -1359,5 +1342,24 @@
 			return false;
 		}
+
 		mail_msg = ( Element("divScrollMain_"+numBox) ) ? Element("divScrollMain_"+numBox).firstChild.firstChild : Element("divScrollMain_0").firstChild.firstChild;
+
+        var showMsg = function(){
+
+            //Se pref. usar mensagens locais ativada e não for operação de arquivamento exibe mensagem de remoção.
+            if(preferences.use_local_messages == 1){
+                if(!expresso_mail_archive.isArchiveOperation){
+                    if (data.msgs_number.length == 1 || typeof(data.msgs_number) == 'string' )
+                        write_msg(get_lang("The message was moved to folder ") + lang_folder(data.new_folder_name));
+                    else
+                        write_msg(get_lang("The messages were moved to folder ") + lang_folder(data.new_folder_name));
+                }
+            } else {
+                if (data.msgs_number.length == 1 || typeof(data.msgs_number) == 'string' )
+                    write_msg(get_lang("The message was moved to folder ") + lang_folder(data.new_folder_name));
+                else
+                    write_msg(get_lang("The messages were moved to folder ") + lang_folder(data.new_folder_name));
+            }
+        }
 
 		if (openTab.type[currentTab] > 1)
@@ -1394,5 +1396,5 @@
 							proxy_mensagens.get_msg(previous_msg,folder,null,show_msg);
 						}
-					}	
+					}
 				}
 				//se houver pagina anterior a paginação deve ser refeita
@@ -1453,5 +1455,9 @@
 				mail_msg.removeChild(msg_to_delete);
 			}
-
+			if (preferences.use_shortcuts == '1' && msg_to_delete && !msg_to_delete.previousSibling){
+				if( $("#tbody_box .current_selected_shortcut_msg").length == 0 ){
+					select_msg('null','reload_msg','null');
+				}
+			}
 			// Update Box BgColor
 			var box = Element("tbody_box");
@@ -1464,4 +1470,6 @@
 				Element('tot_m').innerHTML = parseInt(Element('tot_m').innerHTML) - 1;
 			}
+
+            showMsg();
 			return;
 		}
@@ -1508,18 +1516,5 @@
 		}
 
-		//Se pref. usar mensagens locais ativada e não for operação de arquivamento exibe mensagem de remoção.
-		if(preferences.use_local_messages == 1){
-			if(!expresso_mail_archive.isArchiveOperation){
-				if (data.msgs_number.length == 1)
-					write_msg(get_lang("The message was moved to folder ") + lang_folder(data.new_folder_name));
-				else
-					write_msg(get_lang("The messages were moved to folder ") + lang_folder(data.new_folder_name));
-			}
-		} else {
-			if (data.msgs_number.length == 1)
-				write_msg(get_lang("The message was moved to folder ") + lang_folder(data.new_folder_name));
-			else
-				write_msg(get_lang("The messages were moved to folder ") + lang_folder(data.new_folder_name));
-		}	
+        showMsg();
 
 		if (data.border_ID.indexOf('r') != -1){
@@ -1550,8 +1545,9 @@
 
 	try{
-		if (proxy_mensagens.is_local_folder(Element('input_folder_'+currentTab).getAttribute('value')) && !border_ID) {
-			alert(get_lang("You cant manipulate local messages on search"));
-			return;
-		}
+        if(Element('input_folder_'+currentTab))
+            if (proxy_mensagens.is_local_folder(Element('input_folder_'+currentTab).getAttribute('value')) && !border_ID) {
+                alert(get_lang("You cant manipulate local messages on search"));
+                return;
+            }
 	} catch (e) {} 
     //Validação para recuperar o id caso não seja aba de listagem
@@ -1599,6 +1595,6 @@
                 //expresso_mail_archive.moveMessages(new_folder.substr(6), msgs_number);
                 expresso_mail_archive.moveMessages(new_folder.replace('local_messages_', ''), msgs_number);
-                if(currentTab != 0) 
-                        delete_border(border_ID); 
+                if(currentTab != 0)
+                	delete_border(border_ID);
             }
             else{
@@ -1682,11 +1678,14 @@
 				}
 				var hasFolder = false;
-				$.each(fromRules, function(index, value) {
-					if(value == folder){
-						hasFolder = true;
-						cExecute ("$this.imap_functions.removeFlagMessagesFilter&folder="+folder+"&msg_number="+msgs_number, handler_removeFlag); 
-						return false;
-					}
-				});
+                if(preferences['use_alert_filter_criteria'] == "1")
+                {
+                    $.each(fromRules, function(index, value) {
+                        if(value == folder){
+                            hasFolder = true;
+                            cExecute ("$this.imap_functions.removeFlagMessagesFilter&folder="+folder+"&msg_number="+msgs_number, handler_removeFlag);
+                            return false;
+                        }
+                    });
+                }
 				if(!hasFolder){
 					handler_removeFlag();
@@ -2149,38 +2148,38 @@
 
 function new_message_to(email) {
-        var new_border_ID = new_message('new','null');           
-        if (!new_border_ID){ 
-                var msgId; 
-                setTimeout(function(){ 
-                        msgId = $('#border_tr td.menu-sel').attr('id').toString(); 
-                        content = $("#content_id_"+msgId.substr(msgId.lastIndexOf("_")+1,msgId.length)); 
-                        /*Envio de email para um grupo*/ 
-                        if (email.indexOf('@') == -1){ 
-                                var groups = REST.get('/groups'); 
-                                        $.each(normalizeContacts(groups.collection.itens),function(index,group){ 
-                                                if (group.name.toLocaleLowerCase() == email.toLocaleLowerCase()){ 
-                                                        email = group.id; 
-                                                } 
-                                        }); 
-                                draw_email_box(email, content.find('.to').filter('textarea:first'),"G");         
-                        } 
-                        else 
-                                draw_reply_boxes_by_field("to",email,content); 
-                },500); 
-        } 
-        else{ 
-                var content = $("#content_id_"+new_border_ID);  
-                if (email.indexOf('@') == -1){ 
-                        var groups = REST.get('/groups'); 
-                                $.each(normalizeContacts(groups.collection.itens),function(index,group){ 
-                                        if (group.name.toLocaleLowerCase() == email.toLocaleLowerCase()){ 
-                                                email = group.id; 
-                                        } 
-                                }); 
-                        draw_email_box(email, content.find('.to').filter('textarea:first'),"G");         
-                } 
-                else 
-                        draw_reply_boxes_by_field("to",email,content); 
-        }        
+	var new_border_ID = new_message('new','null');		
+	if (!new_border_ID){
+		var msgId;
+		setTimeout(function(){
+			msgId = $('#border_tr td.menu-sel').attr('id').toString();
+			content = $("#content_id_"+msgId.substr(msgId.lastIndexOf("_")+1,msgId.length));
+			/*Envio de email para um grupo*/
+			if (email.indexOf('@') == -1){
+				var groups = REST.get('/groups');
+					$.each(normalizeContacts(groups.collection.itens),function(index,group){
+						if (group.name.toLocaleLowerCase() == email.toLocaleLowerCase()){
+							email = group.id;
+						}
+					});
+				draw_email_box(email, content.find('.to').filter('textarea:first'),"G");	
+			}
+			else
+				draw_reply_boxes_by_field("to",email,content);
+		},500);
+	}
+	else{
+		var content = $("#content_id_"+new_border_ID); 
+		if (email.indexOf('@') == -1){
+			var groups = REST.get('/groups');
+				$.each(normalizeContacts(groups.collection.itens),function(index,group){
+					if (group.name.toLocaleLowerCase() == email.toLocaleLowerCase()){
+						email = group.id;
+					}
+				});
+			draw_email_box(email, content.find('.to').filter('textarea:first'),"G");	
+		}
+		else
+			draw_reply_boxes_by_field("to",email,content);
+	}	
 }
 
@@ -3397,9 +3396,9 @@
 	/* Lista de palavras que vão ser procuradas no corpo do email, referente às variantes da palavra anexo em português, inglês e espanhol. */
 	if(language == "pt-br") //Português brasileiro
-		var words = ['anexo', 'anexos', 'anexada', 'anexado', 'anexei', 'anexando', 'anexaste', 'anexastes', 'anexamos', 'anexaram'];
-	else if(language == "es-es") //Espanhol
+        var words = ['anexando', 'anexos', 'anexadas', 'anexados', 'anexei',  'anexaste', 'anexastes', 'anexamos', 'anexaram', 'anexas', 'anexado', 'anexada', 'anexo', 'anexa'];
+    else if(language == "es-es") //Espanhol
 		var words = ['anexo','adjunto', 'adjuntos', 'adjuntado','adjuntamos'];
 	else //Inglês ('en')
-		var words = ['attach', 'attachment', 'attached', 'annex', 'appending'];
+        var words = ['attach', 'attachment', 'attached', 'annex', 'appending', 'appendage', 'annexe', 'appendix'];
 
 	if($('#fileupload_msg'+ID).find('.att-box').length == 0 && preferences.alert_message_attachment == '1' ) {
@@ -3456,12 +3455,12 @@
 function send_valided_message(ID, folder, folder_name)
 { 
-	if (preferences.auto_save_draft == 1)
-	   autoSaveControl.status[ID] = true;
-
-	var content = $("#content_id_"+ID);
-	var save_link = $("#content_id_"+ID).find(".save");
-	var onClick = save_link.onclick;
-	save_link.onclick = '';
-	save_link.button({disabled: true});
+    if (preferences.auto_save_draft == 1)
+       autoSaveControl.status[ID] = true;
+
+    var content = $("#content_id_"+ID);
+    var save_link = $("#content_id_"+ID).find(".save");
+    var onClick = save_link.onclick;
+    save_link.onclick = '';
+    save_link.button({disabled: true});
 
     var _subject = trim(content.find(".subject").val());
@@ -3478,5 +3477,5 @@
     $.each(array, function(index, value){
         stringReply += $(value).find("input").val() + ",";
-    });	
+    }); 
     var stringToEmail = "";
     draw_email_box(content.find(".to-tr").find("textarea:first").val() || content.find(".to-tr").find("input:visible").val(), content.find(".to-tr").find("textarea:first"));
@@ -3513,5 +3512,5 @@
         });
     }
-    stringEmail += 	stringCCEmail;
+    stringEmail +=  stringCCEmail;
 
     var mailData = new Object();
@@ -3534,41 +3533,34 @@
     mailData.msg_forward_from = $(content).find('[name="msg_forward_from"]').val();
     mailData.msg_reply_from = $(content).find('[name="msg_reply_from"]').val();
-	
-	if ($(content).find('select[name="input_from"]').val())
-		mailData.input_from = $(content).find('select[name="input_from"]').val();
-
-
-	if(stringEmail != ""){
-		$.ajax({
-			url: "controller.php?action=$this.imap_functions.send_mail",
-            data:  mailData,
-            type: 'POST',
-
-            beforeSend: function(jqXHR, settings){
-
-                write_msg( get_lang( 'Sending the message...' ) );
-                $(content).find('button.send').button('option', 'disabled', true);
-
-
-            },
-            success: function(data){
-                send_message_return(connector.unserialize(data),ID);
-			},
-			error: function(){
-				write_msg(get_lang( 'Error trying to send the message. Retry in a few seconds...' ) );
-                $(content).find('button.send').button('option', 'disabled', false);
-                var interval = setInterval(function(){
-						send_valided_message(ID,folder,folder_name);
-						clearInterval(interval);
-				},15000);
-				return;
-			}
-		});
+    
+    if ($(content).find('select[name="input_from"]').val())
+        mailData.input_from = $(content).find('select[name="input_from"]').val();
+    
+    if(stringEmail != ""){
+    $.ajax({
+        url: "controller.php?action=$this.imap_functions.send_mail",
+        data:  mailData,
+        type: 'POST',
+        async: false,
+        beforeSend: function(jqXHR, settings){
+            write_msg( get_lang( 'Sending the message...' ) );
+            $(content).find('button.send').button('option', 'disabled', true);
+        },
+        success: function(data){
+            send_message_return(connector.unserialize(data),ID);
+        },
+        error: function(){
+            write_msg(get_lang( 'Error trying to send the message. Retry in a few seconds...' ) );
+            $(content).find('button.send').button('option', 'disabled', false);
+            var interval = setInterval(function(){
+                send_valided_message(ID,folder,folder_name);
+                clearInterval(interval);
+            },15000);
+            return;
+        }
+    });
 	}else{
-		write_msg(get_lang("message without receiver"));
-		return;
-	}
-
-
+		write_msg(get_lang("message without receiver")); 
+	}
 }
 
@@ -3765,8 +3757,10 @@
 						case "unseen":
 							set_msg_as_unread(msgs[j]+'_s'+id_border, true);
+							set_msg_as_unread(msgs[j], true); // Atualiza msg na aba principal.
 							Element("search_"+id_border+"_check_box_message_"+msgs[j]).checked = false;
 							break;
 						case "seen":
 							set_msg_as_read(msgs[j]+'_s'+id_border, true);
+							set_msg_as_read(msgs[j], true); //Atualiza msg na aba principal.
 							Element("search_"+id_border+"_check_box_message_"+msgs[j]).checked = false;
 							break;
@@ -3787,5 +3781,5 @@
 		}
 		
-		draw_tree_folders();
+		draw_tree_folders(folders);
 		Element('chk_box_select_all_messages_search').checked = false;
 		refresh();
@@ -3878,12 +3872,14 @@
 						Element("check_box_message_" + msgs_to_set[i]).checked = false;
 
-						// remove a flag $FilteredMessage da mensagem ao ser marcada como lida	
-						$.each(fromRules, function(index, value) {
-							if(value == folder){
-								cExecute ("$this.imap_functions.removeFlagMessagesFilter&folder="+folder+"&msg_number="+msgs_to_set, function(){}); 
-								return false;
-							}
-						});	
-						
+                        if(preferences['use_alert_filter_criteria'] == "1")
+                        {
+                            // remove a flag $FilteredMessage da mensagem ao ser marcada como lida
+                            $.each(fromRules, function(index, value) {
+                                if(value == folder){
+                                    cExecute ("$this.imap_functions.removeFlagMessagesFilter&folder="+folder+"&msg_number="+msgs_to_set, function(){});
+                                    return false;
+                                }
+                            });
+                        }
 						break;
 					case "flagged":
@@ -4455,5 +4451,6 @@
 		update_quota(get_current_folder());
 		draw_new_tree_folder();
-		draw_tree_labels();
+        if( preferences['use_followupflags_and_labels'] == "1" )
+		    draw_tree_labels();
 		if (data){
 			if(typeof(data) == "object"){
@@ -4514,5 +4511,6 @@
 		//tree_folders.getNodeById(mount_url_folder(["INBOX",special_folders["Spam"]]))._refresh();
 		draw_new_tree_folder();
-		draw_tree_labels();
+        if( preferences['use_followupflags_and_labels'] == "1" )
+		    draw_tree_labels();
 		update_quota(get_current_folder());
 		if (data){
@@ -4552,40 +4550,4 @@
 }
 
-function buildExportArchiver(msgsArchive, name_box){
-
-    var hand_export = function(data){
-        if(!data){
-            write_msg(get_lang('Error compressing messages (ZIP). Contact the administrator.'))
-        }else if(data["empty_folder"] || data == "empty_folder"){
-            write_msg(get_lang("The selected folder is empty."));
-        }else
-          download_attachments(null, null, data, null,null, get_current_folder().split("_")[2] +'.zip');
-    }
-
-    var array = new Array();
-
-    for(var i =0; i < msgsArchive.length; i++){
-        eachMsg = {
-                'ContentType' : msgsArchive[i].ContentType,
-                'from' : { 'email' : msgsArchive[i].from.email, 'full' : msgsArchive[i].from.full, 'name' : msgsArchive[i].from.name},
-                'msg_sample' : msgsArchive[i].msg_sample,
-                'subject' : msgsArchive[i].subject,
-                'to' : { 'email' : msgsArchive[i].to.email, 'full' : msgsArchive[i].to.full, 'name' : msgsArchive[i].to.name},
-                'toaddress2' : msgsArchive[i].toaddress2,
-                'msg_number' : msgsArchive[i].msg_number,
-                'date' : new Date(msgsArchive[i].timestamp).toString()  
-        };
-        array.push(eachMsg);
-    }
-
-    $.ajax({
-        type: "POST",
-        url: "controller.php?action=$this.exporteml.export_all_byLocalFolder",
-        data: { folder: name_box, type: "msg_local", messages : array}
-    }).done(function(msg) {
-        hand_export(msg.split('"')[1]);
-    });
-}
-
 function export_all_selected_msgs(){
 	if(get_current_folder().split("_")[0] == "local"){
@@ -4596,9 +4558,7 @@
             expresso_mail_archive.getSomeMsgs([get_selected_messages()]);
         }
+
+    } else {
         
-        buildExportArchiver(expresso_mail_archive.getSomeMsg, get_current_folder().split("_")[2]);
-
-    } else {
-
     if (openTab.type[currentTab] > 1){	    
 		source_msg(currentTab,openTab.imapBox[currentTab]);
@@ -4635,9 +4595,9 @@
                 filename = data[1]+'.eml'; 
 			} 
- 
-            if(typeof data == "object") 
-                             download_attachments(null, null, data[0], null,null,filename); 
-            else  
-                 download_attachments(null, null, data, null,null,filename); 
+
+            if(typeof data == "object")
+			     download_attachments(null, null, data[0], null,null,filename);
+            else 
+                 download_attachments(null, null, data, null,null,filename);
 		}
 	}
@@ -4879,56 +4839,55 @@
 								 			write_msg(get_lang('You must wait while the messages will be imported...'));
 											
-                                                                                        var local_folder = input_hidden.attr("value"); //recupera a pasta selecionada 
-                                                                                        if(local_folder.indexOf("local_") == 0){ //verifica se a pasta selecionada é uma pasta local 
- 
-                                                                                                var fdata = local_folder.substr(15, local_folder.length); //recupera somente a estrutura da pasta ou o id 
-                                                                                                expresso_mail_archive.getFolderInfo(fdata); //recuperar a estrutura da pasta,  
-                                                                                                                                                                                        //para realizar a importação de mensagens 
-                                                                                                fdata = expresso_mail_archive.folder.path; 
- 
-                                                                                                //o mailarchiver não provê um serviço para a importação de mensagens nas pastas locais, 
-                                                                                                //mas sim uma modal, da qual são extraídas as informações e as urls para submitar os dados 
-                                                                                                //para o arquivamento de mensagens em pastas locais. 
-                                                                                                var url_src = mail_archive_protocol + '://' + mail_archive_host + ':' + mail_archive_port + '/arcserv/import?prt=' + mail_archive_protocol + '&por=' + mail_archive_port+ '&fid='+ encodeURIComponent(fdata) + '&sid=' + expresso_mail_archive.session.id; 
-                                                                                                var _html = DataLayer.render(url_src); 
-                                                                                                var regex_url = RegExp('\<iframe(.)*src=\"([^\"]*)"(.)*\>'); 
-                                                                                                var obj_params = $.parseQuery( regex_url.exec(_html)[2].split('?')[1] || '' ); 
-                                                                                                $(formSend).append('<input id="ma_import_flat" type="checkbox" value="false" name="flat" style="display:none"> ' + 
-                                                                                                        '<input id="sessionId" type="hidden" value="'+obj_params['sessvalue']+'" name="sessionId">' + 
-                                                                                                        '<input id="base" type="hidden" value="'+obj_params['basevalue']+'" name="base">' + 
-                                                                                                        '<input id="lang" type="hidden" value="'+obj_params['langvalue']+'" name="lang">'); 
- 
-                                                                                                var importEmailsLocalDialog = $('#importEmailsLocal'); 
-                                                                                                importEmailsLocalDialog.css("overflow","hidden"); 
-                                                                                                importEmailsLocalDialog.dialog( 
-                                                                                                { 
-                                                                                                        autoOpen    : false, 
-                                                                                                        height          : 200, 
-                                                                                                        width           : 350, 
-                                                                                                        resizable       : false, 
-                                                                                                        title           : get_lang('Local Archive'), 
-                                                                                                        modal           : true, 
-                                                                                                        buttons         : [ 
-                                                                                                                                         { 
-                                                                                                                                                text    : get_lang("Close"),  
-                                                                                                                                                click   : function() 
-                                                                                                                                                { 
-                                                                                                                                                        importEmailsLocalDialog.dialog("close").dialog("destroy"); 
-                                                                                                                                                } 
-                                                                                                                                         } 
-                                                                                                                                ] 
-                                                                                                }); 
- 
-                                                                                                importEmailsLocalDialog.html('<iframe frameborder="0" scrolling="no" id="frameResult" name="frameResult" ></iframe>') 
-                                                                                                $(formSend).attr("action", mail_archive_protocol + '://' + mail_archive_host + ':' + mail_archive_port + '/arcserv/import'); 
-                                                                                                $(formSend).attr("target", "frameResult"); 
-                                                                                                $(formSend).submit(); 
-                                                                                                importEmailsLocalDialog.dialog( "open" );
- 												if(typeof(shortcut) != 'undefined')
+											var local_folder = input_hidden.attr("value"); //recupera a pasta selecionada
+											if(local_folder.indexOf("local_") == 0){ //verifica se a pasta selecionada é uma pasta local
+												var fdata = local_folder.substr(15, local_folder.length); //recupera somente a estrutura da pasta ou o id
+												expresso_mail_archive.getFolderInfo(fdata); //recuperar a estrutura da pasta, 
+																							//para realizar a importação de mensagens
+												fdata = expresso_mail_archive.folder.path;
+
+												//o mailarchiver não provê um serviço para a importação de mensagens nas pastas locais,
+												//mas sim uma modal, da qual são extraídas as informações e as urls para submitar os dados
+												//para o arquivamento de mensagens em pastas locais.
+												var url_src = mail_archive_protocol + '://' + mail_archive_host + ':' + mail_archive_port + '/arcserv/import?prt=' + mail_archive_protocol + '&por=' + mail_archive_port+ '&fid='+ encodeURIComponent(fdata) + '&sid=' + expresso_mail_archive.session.id;
+												var _html = DataLayer.render(url_src);
+												var regex_url = RegExp('\<iframe(.)*src=\"([^\"]*)"(.)*\>');
+												var obj_params = $.parseQuery( regex_url.exec(_html)[2].split('?')[1] || '' );
+												$(formSend).append('<input id="ma_import_flat" type="checkbox" value="false" name="flat" style="display:none"> ' +
+													'<input id="sessionId" type="hidden" value="'+obj_params['sessvalue']+'" name="sessionId">' +
+													'<input id="base" type="hidden" value="'+obj_params['basevalue']+'" name="base">' +
+													'<input id="lang" type="hidden" value="'+obj_params['langvalue']+'" name="lang">');
+
+												var importEmailsLocalDialog = $('#importEmailsLocal');
+												importEmailsLocalDialog.css("overflow","hidden");
+												importEmailsLocalDialog.dialog(
+												{
+													autoOpen    : false,
+													height		: 200,
+													width		: 350,
+													resizable	: false,
+													title		: get_lang('Local Archive'),
+													modal		: true,
+													buttons		: [
+																	 {
+																	 	text	: get_lang("Close"), 
+																	 	click	: function()
+																	 	{
+																	 		importEmailsLocalDialog.dialog("close").dialog("destroy");
+																	 	}
+																	 }
+																]
+												});
+
+												importEmailsLocalDialog.html('<iframe frameborder="0" scrolling="no" id="frameResult" name="frameResult" ></iframe>')
+												$(formSend).attr("action", mail_archive_protocol + '://' + mail_archive_host + ':' + mail_archive_port + '/arcserv/import');
+												$(formSend).attr("target", "frameResult");
+												$(formSend).submit();
+												importEmailsLocalDialog.dialog( "open" );
+												if(typeof(shortcut) != 'undefined') 
 													shortcut.disabled = false;
-                                                                                        } else { 
-                                                                                                cExecuteForm('$this.imap_functions.import_msgs', formSend , handler_return ); 
-                                                                                        } 
- 
+											} else {
+												cExecuteForm('$this.imap_functions.import_msgs', formSend , handler_return );
+											}
+
 								 		}
 							 		}
@@ -5439,5 +5398,12 @@
             if(data.append == 1)
             {
-                proxy_mensagens.get_msg(data.msg_number,data.msg_folder,false,show_msg,false);
+                proxy_mensagens.get_msg(data.msg_number,data.msg_folder,false,function (data) {
+                    if (onceOpenedHeadersMessages[data.msg_folder] == undefined) 
+                    {
+                        onceOpenedHeadersMessages[data.msg_folder] = [];
+                    };
+                    onceOpenedHeadersMessages[data.msg_folder][data.msg_number] = data;
+                    show_msg(data);
+                },false);
                 partMsgs.push(data.msg_number);
 	}
Index: branches/2.5/expressoMail1_2/js/connector.js
===================================================================
--- branches/2.5/expressoMail1_2/js/connector.js	(revision 8103)
+++ branches/2.5/expressoMail1_2/js/connector.js	(revision 8232)
@@ -171,108 +171,108 @@
 	}
 
-    cConnector.prototype.unserializeArchiver = function(str) 
-    {    
-        _thisObject = this; 
-        var matchB = function (str, iniPos) 
-        { 
-            var nOpen, nClose = iniPos; 
-            do 
-            { 
-                nOpen = str.substr(nClose+1).search(/[0-9]\:\{/ ); 
- 
-                if (nOpen > 0) 
-                    nOpen = nOpen + nClose+3; 
- 
-                nClose = str.indexOf('}', nClose+1); 
- 
-                if (nOpen < 0) 
-                { 
-                    return nClose; 
-                } 
-                if (nOpen < nClose ) 
-                { 
-                    nClose = matchB(str, nOpen); 
-                } 
-            } while (nOpen < nClose); 
- 
-            return nClose; 
-        } 
-         
-        var f = function (str) 
-        { 
-            switch (str.charAt(0)) 
-            { 
-                case 'a': 
-                     
-                    var data = new Array(); 
-                    var n = parseInt( str.substring( str.indexOf(':')+1, str.indexOf(':',2) ) ); 
-                    var arrayContent = str.substring(str.indexOf('{')+1, str.lastIndexOf('}')); 
-                 
-                    for (var i = 0; i < n; i++) 
-                    { 
-                        var pos = 0; 
-     
-                        /* Process Index */ 
-                        var indexStr = arrayContent.substr(pos, arrayContent.indexOf(';')+1); 
-                        var index = f(indexStr); 
-                        pos = arrayContent.indexOf(';', pos)+1; 
-                         
-                        /* Process Content */ 
-                        var part = null; 
-                        switch (arrayContent.charAt(pos)) 
-                        { 
-                            case 'a': 
-                                var pos_ = matchB(arrayContent, arrayContent.indexOf('{', pos))+1; 
-                                part = arrayContent.substring(pos, pos_); 
-                                pos = pos_; 
-                                data[index] = f(part); 
-                                break; 
-                         
-                            case 's': 
-                                var pval = arrayContent.indexOf(':', pos+2); 
-                                var val  = parseInt(arrayContent.substring(pos+2, pval)); 
-                                pos = pval + val + 4; 
-                                data[index] = arrayContent.substr(pval+2, val); 
-                                break; 
-     
-                            default: 
-                                part = arrayContent.substring(pos, arrayContent.indexOf(';', pos)+1); 
-                                pos = arrayContent.indexOf(';', pos)+1; 
-                                data[index] = f(part); 
-                                break; 
-                        } 
-                        arrayContent = arrayContent.substr(pos); 
-                    } 
-                    break; 
-                     
-                case 's': 
-                    var pos = str.indexOf(':', 2); 
-                    var val = parseInt(str.substring(2,pos)); 
-                    var data = str.substr(pos+2, val); 
-                    str = str.substr(pos + 4 + val); 
-                    break; 
-     
-                case 'i': 
-                case 'd': 
-                    var pos = str.indexOf(';'); 
-                    var data = parseInt(str.substring(2,pos)); 
-                    str = str.substr(pos + 1); 
-                    break; 
-                 
-                case 'N': 
-                    var data = null; 
-                    str = str.substr(str.indexOf(';') + 1); 
-                    break; 
-     
-                case 'b': 
-                    var data = str.charAt(2) == '1' ? true : false; 
-                    break; 
-            } 
-            return data; 
-        } 
-     
-        return f(str); 
-    } 
- 
+    cConnector.prototype.unserializeArchiver = function(str)
+    {   
+        _thisObject = this;
+        var matchB = function (str, iniPos)
+        {
+            var nOpen, nClose = iniPos;
+            do
+            {
+                nOpen = str.substr(nClose+1).search(/[0-9]\:\{/ );
+
+                if (nOpen > 0)
+                    nOpen = nOpen + nClose+3;
+
+                nClose = str.indexOf('}', nClose+1);
+
+                if (nOpen < 0)
+                {
+                    return nClose;
+                }
+                if (nOpen < nClose )
+                {
+                    nClose = matchB(str, nOpen);
+                }
+            } while (nOpen < nClose);
+
+            return nClose;
+        }
+        
+        var f = function (str)
+        {
+            switch (str.charAt(0))
+            {
+                case 'a':
+                    
+                    var data = new Array();
+                    var n = parseInt( str.substring( str.indexOf(':')+1, str.indexOf(':',2) ) );
+                    var arrayContent = str.substring(str.indexOf('{')+1, str.lastIndexOf('}'));
+                
+                    for (var i = 0; i < n; i++)
+                    {
+                        var pos = 0;
+    
+                        /* Process Index */
+                        var indexStr = arrayContent.substr(pos, arrayContent.indexOf(';')+1);
+                        var index = f(indexStr);
+                        pos = arrayContent.indexOf(';', pos)+1;
+                        
+                        /* Process Content */
+                        var part = null;
+                        switch (arrayContent.charAt(pos))
+                        {
+                            case 'a':
+                                var pos_ = matchB(arrayContent, arrayContent.indexOf('{', pos))+1;
+                                part = arrayContent.substring(pos, pos_);
+                                pos = pos_;
+                                data[index] = f(part);
+                                break;
+                        
+                            case 's':
+                                var pval = arrayContent.indexOf(':', pos+2);
+                                var val  = parseInt(arrayContent.substring(pos+2, pval));
+                                pos = pval + val + 4;
+                                data[index] = arrayContent.substr(pval+2, val);
+                                break;
+    
+                            default:
+                                part = arrayContent.substring(pos, arrayContent.indexOf(';', pos)+1);
+                                pos = arrayContent.indexOf(';', pos)+1;
+                                data[index] = f(part);
+                                break;
+                        }
+                        arrayContent = arrayContent.substr(pos);
+                    }
+                    break;
+                    
+                case 's':
+                    var pos = str.indexOf(':', 2);
+                    var val = parseInt(str.substring(2,pos));
+                    var data = str.substr(pos+2, val);
+                    str = str.substr(pos + 4 + val);
+                    break;
+    
+                case 'i':
+                case 'd':
+                    var pos = str.indexOf(';');
+                    var data = parseInt(str.substring(2,pos));
+                    str = str.substr(pos + 1);
+                    break;
+                
+                case 'N':
+                    var data = null;
+                    str = str.substr(str.indexOf(';') + 1);
+                    break;
+    
+                case 'b':
+                    var data = str.charAt(2) == '1' ? true : false;
+                    break;
+            }
+            return data;
+        }
+    
+        return f(str);
+    }
+
 	//Unserialize Data Method
 	cConnector.prototype.unserialize = function(str)
@@ -290,5 +290,5 @@
 
                 nClose = (str.substr(nClose+1) == '}' || str.substr(nClose+1,1) == '}') ? nClose +1 : str.substr(nClose+1).search(/[0-9\"]\;\}/ ) + nClose + 3;
-                 
+                
                 if (nOpen < 0)
                 {
@@ -554,20 +554,20 @@
 	{
 		var div = document.getElementById('divProgressBar');
- 
-        if(div) 
-        { 
-            div.style.visibility = 'hidden'; 
-            this.isVisibleBar = false; 
-        } 
+
+        if(div)
+        {
+            div.style.visibility = 'hidden';
+            this.isVisibleBar = false;
+        }
 	}
 	
 	cConnector.prototype.showProgressBar = function(){
- 
+
 		var div = document.getElementById('divProgressBar');
-                if(div) 
-        { 
-            div.style.visibility = 'visible'; 
-            this.isVisibleBar = true; 
-        } 
+		if(div)
+        {
+            div.style.visibility = 'visible';
+            this.isVisibleBar = true;
+        }
 	}
 
Index: branches/2.5/expressoMail1_2/js/search.js
===================================================================
--- branches/2.5/expressoMail1_2/js/search.js	(revision 7760)
+++ branches/2.5/expressoMail1_2/js/search.js	(revision 8232)
@@ -568,4 +568,16 @@
 					$(td).click(function(event, ui){	
 						var messageClickedId = $(this).attr('id').match(/td_message_followup_search_([\d]+)/)[1];
+
+						var loading = $('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited")
+                    		.find('img[alt=Carregando]');
+
+                    	//Verificar se está carregando a bandeira.
+                    	//Caso esteja ele sai da função até que seja carregado. 
+            			if( loading.length ) {
+                			return false;
+            			}
+
+ 						var followupColor = $('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited").css('backgroundColor');
+
 						
 						var followupColor = $('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited").css('backgroundColor');
@@ -607,5 +619,6 @@
 								
 								$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited")
-								.css({"background-image":"url(../prototype/modules/mail/img/flagEditor.png)"});
+								.css({"background-image":"url(../prototype/modules/mail/img/flagEditor.png)"})
+								.find('img').remove();;
 								
 								if (fail) {
@@ -613,4 +626,8 @@
 								    var isCurrentFolder = current_folder == mailbox ? '#td_message_followup_' + messageClickedId + ', ' : ''; 	
 								    $(isCurrentFolder + 'tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited").css("background", "#CCCCCC");
+								    
+								    $('#td_message_followup_search_' + messageClickedId).find(".flag-edited")
+								    .append("<img src='../prototype/modules/mail/img/flagEditor.png'/>");
+
 								    MsgsCallbackFollowupflag[fail]();
 								    return false;
@@ -619,7 +636,11 @@
 								if(current_folder == mailbox){
 									$('#td_message_followup_' + messageClickedId + ', ' + 
-									'tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).attr('title', get_lang('Follow up')).find(".flag-edited").css("background", aux.followupflagged.backgroundColor);	
+									'tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).attr('title', get_lang('Follow up')).find(".flag-edited").css("background", aux.followupflagged.backgroundColor);
+
+									$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).attr('title', get_lang('Follow up')).find(".flag-edited").css("background", aux.followupflagged.backgroundColor)
+									.append("<img src='../prototype/modules/mail/img/flagEditor.png'/>");	
 								}else{								
-									$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).attr('title', get_lang('Follow up')).find(".flag-edited").css("background", aux.followupflagged.backgroundColor);		
+									$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).attr('title', get_lang('Follow up')).find(".flag-edited").css("background", aux.followupflagged.backgroundColor)
+									.append("<img src='../prototype/modules/mail/img/flagEditor.png'/>");			
 								}								
 								updateCacheFollowupflag(messageClickedId, mailbox, true);
@@ -634,6 +655,6 @@
 							DataLayer.remove('followupflagged', flagged[0].id );
 							DataLayer.commit(false, false, function(){
-								$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited")
-								.css({"background-image":"url(../prototype/modules/mail/img/flagEditor.png)"});
+								$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited").html('<img src="../prototype/modules/mail/img/flagEditor.png">')
+								.css({"width":"8px","height":"6px"/*,"background-image":"url(../prototype/modules/mail/img/flagEditor.png)"*/});
 								if(current_folder == mailbox){
 									updateCacheFollowupflag(messageClickedId, mailbox, false);
@@ -651,5 +672,6 @@
 									
 									$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited")
-										.css({"background-image":"url(../prototype/modules/mail/img/flagEditor.png)"});
+										.css({"background-image":"url(../prototype/modules/mail/img/flagEditor.png)"})
+										.append("<img src='../prototype/modules/mail/img/flagEditor.png'/>");
 								}
 							});
@@ -657,7 +679,17 @@
 						} else {
 							$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited")
-							.css({"background-image":"url(../prototype/modules/mail/img/flagEditor.png)"});
-							$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited").css("background", followupColor);
-							$(this).parents('[role="'+messageClickedId+'_'+mailbox+'"]').attr('class', 'selected_msg').find(':checkbox').trigger('click');
+							.css({"background-image":"url(../prototype/modules/mail/img/flagEditor.png)"}).find('img').remove();
+							
+							$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited").css("background", followupColor)
+							.append("<img src='../prototype/modules/mail/img/flagEditor.png'/>");
+
+							//Pega id do checkbox
+							var id = $(this).parents('[role="'+messageClickedId+'_'+mailbox+'"]').attr('class', 'selected_msg').find(':checkbox').attr('id');
+							
+							//verifica se o checkbox já está selecionada
+							if($('#' + id).attr('checked') != 'checked')
+								$(this).parents('[role="'+messageClickedId+'_'+mailbox+'"]').attr('class', 'selected_msg').find(':checkbox').trigger('click');
+							
+							updateSelectedMsgs(true,messageClickedId);
 							configureFollowupflag();
 						}
@@ -676,5 +708,5 @@
 					if (aux.labels) {
 						//td1 = '<img src="../prototype/modules/mail/img/tag.png">';
-						$(td1).css({'background-image':'url(../prototype/modules/mail/img/mail-sprites.png)','background-position': '0 -1711px',"margin-left":"0",'margin-top':'3px','background-repeat':'no-repeat'});
+						$(td).css({'background-image':'url(../prototype/modules/mail/img/mail-sprites.png)','margin-left': '0px', 'margin-top':'3px', 'background-position': '0px -1706px', 'background-repeat':'no-repeat no-repeat'});
 						updateLabelsColumn(aux)		
 					} else {
@@ -829,4 +861,5 @@
 						over : function(a, b){						
 							//SETA BORDA EM VOLTA DA PASTA
+							$(b.helper).find(".draggin-folder,.draggin-mail").css("color", "green");
 							over = $(this);
 							$(this).addClass("folder-over");
@@ -841,6 +874,7 @@
 									}
 						},
-						out : function(){
+						out : function(a,b){
 							//RETIRA BORDA EM VOLTA DA PASTA
+							$(b.helper).find(".draggin-folder,.draggin-mail").css("color", "");
 							$(this).removeClass("folder-over");
 						},
@@ -882,5 +916,5 @@
 					return $(DataLayer.render('../prototype/modules/mail/templates/draggin_box.ejs', {texto : $(this).find(".td_msg_search_subject").text(), type: "messages"}));
 			},
-			cursorAt: {cursor: "crosshair", top: -5, left: -5},
+			cursorAt: {top: 5, left: 56},
 			refreshPositions: true ,
 			scroll: true, 
Index: branches/2.5/expressoMail1_2/js/messages_controller.js
===================================================================
--- branches/2.5/expressoMail1_2/js/messages_controller.js	(revision 8128)
+++ branches/2.5/expressoMail1_2/js/messages_controller.js	(revision 8232)
@@ -12,5 +12,5 @@
         if(this.is_local_folder(folder)) {
             //MAILARCHIVER-01
-            var baseFolder = folder.replace('local_messages_', '');
+            var baseFolder = folder.replace('local_messages_', ''); 
             var tree_name;
             var drawinginfo = {};
Index: branches/2.5/expressoMail1_2/js/shortcut.js
===================================================================
--- branches/2.5/expressoMail1_2/js/shortcut.js	(revision 8087)
+++ branches/2.5/expressoMail1_2/js/shortcut.js	(revision 8232)
@@ -209,8 +209,12 @@
 				
 			}
-                        if (currentTab && currentTab == 0 && code == 13){ 
-                                e.stopPropagation(); 
-                                e.preventDefault(); 
-                        } 
+			if (currentTab && currentTab == 0 && code == 13){
+				e.stopPropagation();
+				e.preventDefault();
+			}
+			if ((openTab.type[currentTab] == 2) && code == 13){
+				e.preventDefault();
+				e.stopPropagation();
+			}		
 		}
 		this.all_shortcuts[shortcut_combination] = {
@@ -279,6 +283,6 @@
 		proxy_mensagens.delete_msgs(current_folder, get_selected_messages(), 'null');
 	}else{
-                if (e.target.className.indexOf("box") == -1) 
-                        proxy_mensagens.delete_msgs(openTab.imapBox[currentTab], currentTab.substring(0, selMessageShortcut.indexOf("_r")), 'null'); 
+		if (e.target.className.indexOf("box") == -1)
+			proxy_mensagens.delete_msgs(openTab.imapBox[currentTab], currentTab.substring(0, selMessageShortcut.indexOf("_r")), 'null');
 	}
 }
Index: branches/2.5/expressoMail1_2/js/folder.js
===================================================================
--- branches/2.5/expressoMail1_2/js/folder.js	(revision 8102)
+++ branches/2.5/expressoMail1_2/js/folder.js	(revision 8232)
Index: branches/2.5/expressoMail1_2/js/MAExpressoPattern.js
===================================================================
--- branches/2.5/expressoMail1_2/js/MAExpressoPattern.js	(revision 8103)
+++ branches/2.5/expressoMail1_2/js/MAExpressoPattern.js	(revision 8232)
Index: branches/2.5/expressoMail1_2/js/wfolders.js
===================================================================
--- branches/2.5/expressoMail1_2/js/wfolders.js	(revision 7426)
+++ branches/2.5/expressoMail1_2/js/wfolders.js	(revision 8232)
@@ -48,5 +48,6 @@
 										 	click	: function()
 										 	{
-												winSaveFile.dialog("close"),dialog("destroy");
+												winSaveFile.dialog("close");
+                                                winSaveFile.dialog("destroy");
 										 	}
 										 },
@@ -134,10 +135,29 @@
 	cWFolders.prototype.makeWindow = function(border_id, type)
 	{
-        if(typeof (currentTab) == "string" && currentTab.indexOf("local") != -1){  
-            alert("Impossível manipular mensagens locais a partir de uma busca. Isso é permitido apenas para mensagens não locais.");
-            return true;
+        if(type == "move_to"){
+            if( (currentTab == 0) || (currentTab.toString().indexOf("search") >= 0)){
+                
+            	//Verifica em qual aba o usuário está
+                var selected_msg = (currentTab == 0) ? get_selected_messages() : get_selected_messages_search();
+
+                if ((parseInt(selected_msg) > 0 || selected_msg.length > 0)||(type != "move_to")){
+                    this.load( border_id, type, false);
+                }else
+                    write_msg(get_lang('No selected message.'));
+            } else{
+                if(typeof (currentTab) == "string" && currentTab.indexOf("local") != -1){
+                    alert("Impossível manipular mensagens locais a partir de uma busca. Isso é permitido apenas para mensagens não locais.");
+                    return true;
+                }
+                this.load( border_id, type, false);
+            }
+        }else {
+            if(typeof (currentTab) == "string" && currentTab.indexOf("local") != -1){
+                alert("Impossível manipular mensagens locais a partir de uma busca. Isso é permitido apenas para mensagens não locais.");
+                return true;
+            }
+            this.load( border_id, type, false);
         }
-		this.load( border_id, type, false);
-	}
+    }
 	
 /* Build the Object */
Index: branches/2.5/expressoMail1_2/js/draw_api.js
===================================================================
--- branches/2.5/expressoMail1_2/js/draw_api.js	(revision 8188)
+++ branches/2.5/expressoMail1_2/js/draw_api.js	(revision 8232)
@@ -106,4 +106,5 @@
 			}
 			cExecute ("$this.imap_functions.get_folders_list&folder="+current_folder, update_tree_folders);
+            
 		}
 
@@ -239,6 +240,7 @@
 					var nn = new dNode({id:folders[i].folder_id, caption:lang_folder(folders[i].folder_name) + '<font style=color:red>&nbsp(</font><span id="dftree_'+folders[i].folder_id+'_unseen" style=color:red>'+folders[i].folder_unseen+'</span><font style=color:red>)</font>', onClick:"change_folder('"+folders[i].folder_id+"','"+folders[i].folder_name+"')", plusSign:folders[i].folder_hasChildren});
 
-					if( folders[i].folder_name.toLowerCase() == 'inbox' )
-						Element('new_m').innerHTML = '<font style="color:red">' + folders[i].folder_unseen + '</font>';
+
+					// if( folders[i].folder_name.toLowerCase() == 'inbox' )
+					// 	Element('new_m').innerHTML = '<font style="color:black">' + folders[i].folder_unseen + '</font>';
 				}
 				else
@@ -471,6 +473,4 @@
 		}
 	}
-	
-	outOfficeVerify();
 }
 
@@ -646,5 +646,8 @@
 		}
 		draw_new_tree_folder(false, forceLoadFolders);
-		draw_tree_labels();
+
+        if( preferences['use_followupflags_and_labels'] == "1" )
+            draw_tree_labels();
+
 		if(Element("table_quota"))
 			connector.loadScript("InfoQuota");
@@ -655,4 +658,5 @@
 
 var handler_draw_box = function(data){
+    populateSelectedMsgs(data.messagesIds);
 	draw_box(data, 'INBOX', true);
 	//alternate_border(0);
@@ -661,5 +665,8 @@
 // Action on change folders.
 function change_folder(folder, folder_name){
-	if (openTab.imapBox[0] != folder)
+	if (parseInt(preferences.use_dynamic_contacts) && $(".to").length && $(".to").data( "autocomplete" ).menu.active){
+        $(".to").data( "autocomplete" ).close();
+    }
+    if (openTab.imapBox[0] != folder)
 	{
 		selectAllFolderMsgs(false);
@@ -667,5 +674,5 @@
 		var handler_draw_box = function(data)
 		{
-
+            populateSelectedMsgs(data.messagesIds);
 			if(!verify_session(data))
 				return;
@@ -683,39 +690,9 @@
 			return true;
 		}
+
 		//MAILARCHIVE
         //se for pasta local
         if (/^local_messages/.test(current_folder)) {
             $(".folders-loading").removeClass("folders-loading"); //remove o icone de loading ao clicar nas pastas locais
-        }
-        else { //se não, processamento normal da pasta
-    		$.ajax({
-                async: false,
-    			url: "controller.php?" + $.param( {action: "$this.imap_functions.getMessagesIds", 
-    				folder: folder,
-    				 msg_range_begin: "0",
-    				 msg_range_end: "0", 					
-    				sort_box_type: "SORTARRIVAL", 
-    				search_box_type: search_box_type,
-    				sort_box_reverse: "1"
-    				}),
-    			success: function(data){
-    				data = connector.unserialize(data);
-    				if(data){
-    					var _data = {};
-    					$.each(data,function(index,value){
-    						if (data[index]){
-    							_data[data[index]] = data[index];
-    						}
-    					});
-    					populateSelectedMsgs(_data);
-    				}
-    			},
-    			beforeSend: function( jqXHR, settings ){
-    				connector.showProgressBar();
-    			},
-    			complete: function( jqXHR, settings ){
-    				connector.hideProgressBar();
-    			}
-    		});
         }
 		proxy_mensagens.messages_list(current_folder,1,preferences.max_email_per_page,sort_box_type,search_box_type,sort_box_reverse,preferences.preview_msg_subject,preferences.preview_msg_tip,handler_draw_box);
@@ -917,7 +894,7 @@
 	if (document.getElementById("table_message_header_box_"+numBox).emptyBody)
 		return;
-    objCell.style.cursor = "col-resize"; 
-    $(objCell).next().css('cursor','col-resize'); 
- 
+    objCell.style.cursor = "col-resize";
+    $(objCell).next().css('cursor','col-resize');
+
 	if (objCell.style.cursor == "col-resize" && detectLeftButton(ev)) {
 		var cellIndex = objCell.cellIndex;
@@ -942,5 +919,5 @@
 
 		document.getElementById("table_message_ruler").style.left = cellOffset+cellWidth;
-        syncColumns(); 
+        syncColumns();
 	}
 	ev.returnValue = false;
@@ -1649,7 +1626,8 @@
                     $(".lower").css("top", ($("#content_folders").height()-18) + $("#content_folders").offset().top);
 					if($(".shared-folders").length){
-						$(".shared-folders").parent().find('.folder:not(".shared-folders")').droppable({
+						$(".shared-folders,.head_folder").parent().find('.folder:not(".shared-folders")').droppable({
 							over : function(a, b){						
 								//SETA BORDA EM VOLTA DA PASTA
+                                $(b.helper).find(".draggin-folder,.draggin-mail").css("color", "green");
 								over = $(this);
 								$(this).addClass("folder-over");
@@ -1664,6 +1642,7 @@
 										}
 							},
-							out : function(){
+							out : function(a,b){
 								//RETIRA BORDA EM VOLTA DA PASTA
+                                $(b.helper).find(".draggin-folder,.draggin-mail").css("color", "");
 								$(this).removeClass("folder-over");
 							},
@@ -1723,7 +1702,16 @@
 			
                         $(this).addClass("selected_msg");
-					}
-					updateSelectedMsgs($(this).find("input:checkbox").is(':checked'),$(this).attr("id"));
-				}
+                }
+                updateSelectedMsgs($(this).find("input:checkbox").is(':checked'),$(this).attr("id"));
+                } else if ( typeof $(event.target).attr("style") == "undefined" || $(event.target).attr("style").match(/background/g) == null ) {
+                    if($(this).find("input:checkbox").attr("checked") != "checked"){
+
+                        $(this).find("input:checkbox").trigger('click');
+            
+                        $(this).addClass("selected_msg");
+                    }
+                    updateSelectedMsgs($(this).find("input:checkbox").is(':checked'),$(this).attr("id"));
+                }
+
 			});
 	}
@@ -1739,8 +1727,5 @@
 	draw_footer_box(headers_msgs.num_msgs);
 	Element('main_table').style.display = '';
-	if(is_ie6)	  // Stupid Fixing on IE6.
-		setTimeout("resizeWindow()",1);
-	else
-		resizeWindow();
+	resizeWindow();
 	if(debug) {
 		var _eTime = new Date();
@@ -1752,9 +1737,9 @@
 	var msg_number = Element('msg_number').value;
 	if(!msg_folder && msg_number) {
-        if ((msg_number.toString().indexOf('@') != -1) || !msg_number.toString().match(/[0-9]/)){ 
-            new_message_to(msg_number); 
-        }     
-        else 
-            new_message('new','null'); 
+        if ((msg_number.toString().indexOf('@') != -1) || !msg_number.toString().match(/[0-9]/)){
+            new_message_to(msg_number);
+        }    
+        else
+            new_message('new','null');
 	}
 	else if(msg_folder && msg_number){
@@ -1871,16 +1856,16 @@
                     //if (headers_msgs.msg_sample.body.length > 0)
 				    tr_element.msg_sample = Base64.decode(headers_msgs.msg_sample.body).substr(0,180) + "..."; //trecho do body que sera exibido com o assunto; //blabla
-			     } else {
+			        tr_element.msg_sample = html_entities(tr_element.msg_sample); 
+                 } else {
 				    //if (headers_msgs.msg_sample.body.length > 0)
 					tr_element.msg_sample = Base64.decode(headers_msgs.msg_sample.body).substr(0,120) + "..."; //trecho do body que sera exibido com o assunto;
-		          }
-
-                // preferencia dos tooltips
-                if(headers_msgs.msg_sample && preferences.preview_msg_tip == "1" && headers_msgs.msg_sample.body !== "") {
-                    tr_element.tip = Base64.decode(headers_msgs.msg_sample.body).substr(3,300) + "..."; //trecho do body que sera exibido no tool-tip;
-                }
+		            tr_element.msg_sample = html_entities(tr_element.msg_sample);  
+                  }
             }
         }
-
+        // preferencia dos tooltips
+        if(headers_msgs.msg_sample && preferences.preview_msg_tip == "1" && headers_msgs.msg_sample.body !== "") {
+            tr_element.tip = Base64.decode(headers_msgs.msg_sample.body).substr(3,300) + "..."; //trecho do body que sera exibido no tool-tip;
+        }
 		
 		if ((headers_msgs.Unseen == 'U') || (headers_msgs.Recent == 'N')){
@@ -1925,5 +1910,5 @@
 
 		if ((headers_msgs.Forwarded == 'F')  || (headers_msgs.Draft == 'X' && headers_msgs.Answered == 'A')){
-			td_element21.onclick=function(){search_emails(headers_msgs.subject.replace(/^(re: ?|fw: ?|enc: ?|res: ?|fwd: ?)*/gi,''),true);};
+			$(td_element21).on('click',function(){search_emails(headers_msgs.subject.replace(/^(re: ?|fw: ?|enc: ?|res: ?|fwd: ?)*/gi,''),true);});
                         td_element21.innerHTML = "<img src ='templates/"+template+"/images/forwarded.png' title='"+get_lang('Forwarded')+"'>";
 			headers_msgs.Draft = ''
@@ -1934,5 +1919,5 @@
 			td_element21.innerHTML = "<img src ='templates/"+template+"/images/draft.png' title='"+get_lang('Draft')+"'>";
 		else if (headers_msgs.Answered == 'A'){
-                        td_element21.onclick=function(){search_emails(headers_msgs.subject.replace(/^(re: ?|fw: ?|enc: ?|res: ?|fwd: ?)*/gi,''),true);};
+                        $(td_element21).on('click',function(){search_emails(headers_msgs.subject.replace(/^(re: ?|fw: ?|enc: ?|res: ?|fwd: ?)*/gi,''),true);});
 			td_element21.innerHTML = "<img src ='templates/"+template+"/images/answered.png' title='"+get_lang('Answered')+"'>";
                     }else
@@ -2048,10 +2033,12 @@
 						this.title = title_to; 
 					};
-					if (headers_msgs.to && headers_msgs.to[0]) {
+					if (headers_msgs.to && headers_msgs.to[0] != null) {
 						if (headers_msgs.to[0].name != null){
 							spanSender.innerHTML += headers_msgs.to[0].name;
 						}else if(headers_msgs.to[0].email != null) {
 							spanSender.innerHTML += headers_msgs.to[0].email;
-						}
+						}else {
+                            spanSender.innerHTML += get_lang("without destination");
+                        }
 					}
 				}else if(headers_msgs.from !== undefined){
@@ -2139,5 +2126,16 @@
 		$(td_element26).click(function() {	
 			var messageClickedId = $(this).attr('id').match(/td_message_followup_([\d]+)/)[1];
-			
+
+            var loading = $('#td_message_followup_' + messageClickedId + ', ' + 
+            'tr[role="'+messageClickedId+'_'+msg_folder+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited")
+            .find('img[alt=Carregando]');
+
+
+            //Verificar se está carregando a bandeira.
+            //Caso esteja ele sai da função até que seja carregado. 
+            if( loading.length ) {
+                return false;
+            }
+
 			var followupColor = $('#td_message_followup_' + messageClickedId).find(".flag-edited").css('backgroundColor');
 			
@@ -2192,12 +2190,17 @@
 					
 					if(fail != 'success'){
-					    $('#td_message_followup_' + messageClickedId + ', ' + 
-					    'tr[role="'+messageClickedId+'_'+msg_folder+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited").css("background", "#CCCCCC")
-						.find('img').remove();
-					    MsgsCallbackFollowupflag[fail]();
+					    var msgFlag =  $('#td_message_followup_' + messageClickedId + ', ' + 
+                        'tr[role="'+messageClickedId+'_'+msg_folder+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited").css("background", "#CCCCCC");
+
+                        msgFlag.find('img').remove();
+                        
+                        //Insere a imagem da flag quando ocorre erro ao marcar a msg
+                        msgFlag.append("<img src='../prototype/modules/mail/img/flagEditor.png'/>");
+
+                        MsgsCallbackFollowupflag[fail]();
 					}else{
 					    $('#td_message_followup_' + messageClickedId + ', ' + 
 					    'tr[role="'+messageClickedId+'_'+msg_folder+'"] #td_message_followup_search_' + messageClickedId).attr('title', get_lang('Follow up')).find(".flag-edited").css("background", headers_msgs.followupflagged.backgroundColor)
-						.find('img').remove();
+						.append("<img src='../prototype/modules/mail/img/flagEditor.png'/>");
 					    updateCacheFollowupflag(messageClickedId, msg_folder, true);
 					}				
@@ -2215,5 +2218,4 @@
 					$('#td_message_followup_' + messageClickedId + ', ' + 
 					'tr[role="'+messageClickedId+'_'+msg_folder+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited")
-					.css({"background-image":"url(../prototype/modules/mail/img/flagEditor.png)"})
 					.find('img').remove();
 					
@@ -2222,6 +2224,6 @@
 				
 					$('#td_message_followup_' + messageClickedId + ', ' + 
-						'tr[role="'+messageClickedId+'_'+msg_folder+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited")
-                        .css({"background-image":"url(../prototype/modules/mail/img/flagEditor.png)"});
+						'tr[role="'+messageClickedId+'_'+msg_folder+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited").html('<img src="../prototype/modules/mail/img/flagEditor.png">')
+                        .css({"width":"8px","height":"6px"/*"background-image":"url(../prototype/modules/mail/img/flagEditor.png)"*/});
 				});	
 
@@ -2229,7 +2231,16 @@
 				$('#td_message_followup_' + messageClickedId + ', ' + 
 				'tr[role="'+messageClickedId+'_'+msg_folder+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited")
-				.css({"background-image":"url(../prototype/modules/mail/img/flagEditor.png)"}).css("background", followupColor);
+				.css("backgroundColor", followupColor)
+                .find('img').remove(); //remove imagem carregando da bandeira
+
+                $('#td_message_followup_' + messageClickedId).find('.flag-edited').append("<img src='../prototype/modules/mail/img/flagEditor.png'/>");
+
 				
-				$(tr_element).addClass('selected_msg').find(':checkbox').trigger('click');
+			   //Pega id do checkbox
+               var id = $(tr_element).addClass('selected_msg').find(':checkbox').attr('id');
+                
+                //Verifica se o checkbox está selecionado
+                if($('#' + id).attr('checked') != 'checked')
+                    $(tr_element).addClass('selected_msg').find(':checkbox').trigger('click');
 				
 				/**
@@ -2320,5 +2331,9 @@
 	var message_header = Element("message_header_"+search);
 	var handler_draw_box = function(data){
-		draw_box(data, current_folder,true);
+
+        if (typeof(clean_selected) == "undefined")
+            populateSelectedMsgs(data.messagesIds);
+
+        draw_box(data, current_folder,true);
 		//Mostrar as msgs nao lidas de acordo com o filtro de relevancia
         var msgs_unseen = 0;
@@ -2341,27 +2356,4 @@
 	sort_box_type = sort;
 	search_box_type = search;
-
-	if (typeof(clean_selected) == "undefined"){	
-        $.ajax({			
-			url: "controller.php?" + $.param( {action: "$this.imap_functions.getMessagesIds", 
-				folder: get_current_folder(),					
-				sort_box_type: "SORTARRIVAL", 
-				search_box_type: search_box_type,
-				sort_box_reverse: "1"
-				}),
-			success: function(data){
-				data = connector.unserialize(data);
-				if(data){
-					var _data = {};
-					$.each(data,function(index,value){
-						if (value){
-							_data[index] = value;
-						}
-					});
-					populateSelectedMsgs(_data);				
-				}
-			}
-		});
-	}	
 
 	proxy_mensagens.messages_list(current_folder,1,preferences.max_email_per_page,sort,search,sort_box_reverse,preferences.preview_msg_subject,preferences.preview_msg_tip,handler_draw_box);
@@ -2432,5 +2424,5 @@
 function draw_message(info_msg, ID){
 	// remove a flag $FilteredMessage da mensagem ao ser lida
-	if(info_msg.Unseen == "U"){
+	if(info_msg.Unseen == "U" && preferences['use_alert_filter_criteria'] == "1"){
 		$.each(fromRules, function(index, value) {
 			if(value == info_msg.msg_folder){
@@ -2479,8 +2471,8 @@
 			{
                 if(info_msg.msg_number.match("s[0-9]+")){
-                    var new_info = info_msg.msg_number;
-                    new_info = new_info.split("_")[1];
-                    info_msg.next_message = info_msg.next_message+"_"+new_info;
-                    info_msg.nextMsgBox = info_msg.nextMsgBox+"_"+new_info;
+                    var msg_next = $('#'+info_msg.msg_number).next();
+                    info_msg.next_message = msg_next.attr("id");
+                    info_msg.nextMsgBox = msg_next.attr("name");
+                    nextMsgBox = msg_next.attr("name");
                 }
 				currentTab = ID;
@@ -2489,5 +2481,6 @@
 				//select_msg('null', 'down', true);
 				if (!msg_selected){
-					select_msg('null', 'down', true);
+					if(!!parseInt(preferences.use_shortcuts))
+                        select_msg('null', 'down', true);
 					msg_selected = true;
 				}
@@ -2495,5 +2488,5 @@
 		}
 		/*Ultima mensagem de cada página, exceto a ultima*/
-        else if( (current_page < total_pages) ){
+        else if( (current_page < total_pages) && !info_msg.msg_number.match("s[0-9]+") ){
 		   
 		   img_next_msg.onclick = function()
@@ -2559,8 +2552,8 @@
 			{
                 if(info_msg.msg_number.match("s[0-9]+")){
-                    var new_info = info_msg.msg_number;
-                    new_info = new_info.split("_")[1];
-                    info_msg.prev_message = info_msg.prev_message+"_"+new_info;
-                    info_msg.previousMsgBox = info_msg.previousMsgBox+"_"+new_info;
+                    var msg_prev = $('#'+info_msg.msg_number).prev();
+                    info_msg.prev_message = msg_prev.attr("id");
+                    info_msg.previousMsgBox = msg_prev.attr("name");
+                    previousMsgBox = msg_prev.attr("name");
                 }
 				currentTab = ID;
@@ -2569,5 +2562,6 @@
 				//select_msg('null', 'up', false);
 				if (!msg_selected){
-					select_msg('null', 'up', true);
+                    if(!!parseInt(preferences.use_shortcuts))
+					    select_msg('null', 'up', true);
 					msg_selected = true;
 				}
@@ -3010,5 +3004,7 @@
 		var option_export = '<span onclick="proxy_mensagens.export_all_messages()" onmouseover="this.className=\'reply_options_active\'" onmouseout="this.className=\'reply_options\'" class="reply_options">'+get_lang("Export")+'</span> | ';
 		var report_error = '<span onmouseover="this.className=\'reply_options_active\'" onmouseout="this.className=\'reply_options\'" class="reply_options" onclick=reports_window("'+currentTab+'");>'+get_lang("Report error")+'</span> | '; 
-		div_other_more_options.innerHTML += option_move + option_print + option_export + block_user +  report_error;
+		// Opção do menu 'Mais Ações' para criar filtro a partir da mensagem aberta:  
+		var option_create_filter = '<span onmouseover="this.className=\'reply_options_active\'" onmouseout="this.className=\'reply_options\'" class="reply_options" onclick=filter_from_msg(onceOpenedHeadersMessages[\'' + html_entities(info_msg.msg_folder) + '\'][' + info_msg.msg_number + ']);>' + get_lang("Create filter from message") + '</span> | '; 
+		div_other_more_options.innerHTML += option_create_filter + option_move + option_print + option_export + block_user +  report_error;
 		
 		
@@ -3509,5 +3505,5 @@
 	subject.innerHTML = html_entities(info_msg.subject); 
 	subject.className = "header_message_field";
-	if(defaultCalendar == "expressoCalendar" && $("#expressoCalendarid")[0]){
+	if($("#expressoCalendarid")[0]){
 		var new_task_logo = document.createElement("IMG");
 		new_task_logo.title = "Criar uma nova tarefa a partir deste email.";
@@ -4644,24 +4640,17 @@
             delay : 300,
             minLength: 0
-        }).bind('catcompleteopen', function(event, ui) {
+        }).bind('autocompleteopen', function(event, ui) {
 
             $(this).data('is_open',true);
 
-        }).bind('catcompleteclose', function(event, ui) {
+        }).bind('autocompleteclose', function(event, ui) {
 
             canMakeBox = true;
             $(this).data('is_open',false);
-
+            $(this).blur().focus();
         }).data( "autocomplete" )._renderItem = function( ul, item ) {
             var autocomplete = $(this)[0].element;
 
-            //cálculo dinâmico da largura da lista
-            var minwidth = 450;
-            var width = (item.label ? item.label.length : (item.value ? item.value.length : (item.mail ? item.mail.length : 30 )));
-            width = (is_ie ? width*2 : (is_webkit && !is_mozilla ? width*4 : width*5)) + 30;
-            if (width < minwidth)
-                width = minwidth;
-
-            ul.css({"min-width":width, "max-height" : "180px", "overflow-y" : "auto", "min-height": "30px"});
+            ul.css({"width":'50%',"min-width":'600px', "max-height" : "180px", "overflow-y" : "auto", "min-height": "30px"});
 
             item.raty = ((item.number_of_messages*10)/topContact) > 1 ? ((item.number_of_messages*10)/topContact) : 1;
@@ -4753,4 +4742,132 @@
 			emQuickSearch(($(this).parents("tr:first").find("textarea").val() ? $(this).parents("tr:first").find("textarea").val() : input_search), "."+$(this).parents("tr:first").attr('class').split("-")[0], ID, undefined, true);
 	});
+}
+
+/* 
+	Anexa uma mensagem a mensagem sendo enviada. 
+	Parâmetros: 
+		folder_name: nome da pasta na qual a mensagem sendo anexada se encontra. 
+		message_number: id da mensagem sendo anexada. 
+*/ 
+function attach_message (folder_name, message_number) { 
+    var ID = currentTab; 
+    var fileUploadMSG = $('#fileupload_msg'+ID); 
+    fileUploadMSG.find(' .attachments-list').show(); 
+    var att = new Object(); 
+
+   
+
+    var attach = {}; 
+    attach.fileName = onceOpenedHeadersMessages[folder_name][message_number].subject + '.eml'; 
+    attach.fullFileName = onceOpenedHeadersMessages[folder_name][message_number].subject + '.eml'; 
+    if(attach.fileName.length > 20){ 
+        attach.fileName = attach.fileName.substr(0, 17) + "... " + attach.fileName.substr(attach.fileName.length - 9, attach.fileName.length); 
+    } 
+    attach.error = false; 
+    attach.OK = true;
+    if (folder_name.indexOf('local_messages_') == 0){
+        attach.fileSize = formatBytes(onceOpenedHeadersMessages[folder_name][message_number].size);
+    } else {
+        attach.fileSize = formatBytes(onceOpenedHeadersMessages[folder_name][message_number].Size); 
+    }
+    var upload = $(DataLayer.render("../prototype/modules/mail/templates/attachment_add_itemlist.ejs", { 
+        file: attach 
+    })); 
+    $("#content_id_" + currentTab + " .save").button("enable"); 
+    upload.find('.att-box-loading').remove(); 
+    upload.append('<input type="hidden" name="fileId[]" value=\'' + idATT + '\'/>'); 
+ 
+    upload.find('.att-box-delete').click(function() 
+    { 
+        $("#content_id_" + currentTab + " .save").button("enable"); 
+        var idAttach = $(this).parent().find('input[name="fileId[]"]').val(); 
+        fileUploadMSG.find(' .attachments-list').find('input[value="' + idAttach + '"]').remove(); 
+        delAttachment(ID, idAttach); 
+        $(this).parent().qtip("destroy"); 
+        $(this).parent().remove(); 
+        if(!fileUploadMSG.find(' .attachments-list').find(".att-box").length) 
+        { 
+            fileUploadMSG.find(' .attachments-list').hide(); 
+        } 
+    }); 
+ 
+    var addtip = function(attach){
+        fileUploadMSG.find('.attachments-list .att-box:last').qtip( 
+        { 
+            content: DataLayer.render("../prototype/modules/mail/templates/attachment_add_itemlist_tooltip.ejs", { 
+                attach: attach 
+            }), 
+            position: { 
+                corner: { 
+                    tooltip: 'bottomMiddle', 
+                    target: 'topMiddle' 
+                }, 
+                adjust: { 
+                    resize: true, 
+                    scroll: true 
+                } 
+            }, 
+            show: { 
+                when: 'mouseover', 
+                // Don't specify a show event 
+                ready: false // Show the tooltip when ready 
+            }, 
+            hide: 'mouseout', 
+            // Don't specify a hide event 
+            style: { 
+                border: { 
+                    width: 1, 
+                    radius: 5 
+                }, 
+                width: { 
+                    min: 75, 
+                    max: 1000 
+                }, 
+                padding: 5, 
+                textAlign: 'center', 
+                tip: true, 
+                // Give it a speech bubble tip with automatic corner detection 
+                name: 'blue' // Style it according to the preset 'cream' style 
+            } 
+        }); 
+    } 
+
+    if(folder_name.indexOf("local_messages_") != 0)
+    {
+        att.folder = folder_name; 
+        att.uid = message_number; 
+        att.type = 'imapMSG'; 
+        att.name = Base64.encode(onceOpenedHeadersMessages[folder_name][message_number].subject + '.eml'); 
+        var idATT = JSON.stringify(att); 
+        addAttachment(ID, idATT); 
+
+        fileUploadMSG.find('.attachments-list').append(upload);
+        addtip(attach);
+    }
+    else
+    {
+        var folder_trash = "INBOX"+cyrus_delimiter+special_folders["Trash"];
+        expresso_mail_archive.unarchieveToAttach(folder_name, folder_trash, message_number, function(data){
+            $.ajax({
+                url: "controller.php?action=$this.imap_functions.get_info_msg_archiver",
+                data:  {"idMsgs":data.idsMsg},
+                type: 'POST',
+                async: false,
+                success: function(data){
+                    data = JSON.parse(connector.unserialize(data));
+                    data = data[0];
+                    att.folder = folder_trash;
+                    att.uid = data.uid; 
+                    att.type = 'imapMSG'; 
+                    att.name = Base64.encode(onceOpenedHeadersMessages[folder_name][message_number].subject + '.eml'); 
+                    var idATT = JSON.stringify(att); 
+                    addAttachment(ID, idATT);
+                    fileUploadMSG.find('.attachments-list').append(upload);
+                    addtip(attach);
+                },
+            });
+        }); 
+    }
+    upload.find('.att-box-loading').remove();     
 }
 		
@@ -4933,9 +5050,7 @@
     	$(this).prev().show();
 	});
-	fileUploadMSG.find(".fileUploadButton, .message-attach-link").button().filter(".fileUploadButton").click(function(){
-            fileUploadMSG.find("input:file").trigger("click");
-    });
-
-    fileUploadMSG.find("input:file").fileupload({
+
+
+    fileUploadMSG.find(".button").button().filter(".fileinput-button").find(".ui-button-text").css("margin-top","2px").find("input:file").fileupload({
 		//singleFileUploads : true,fileUploadMSG
 		sequentialUploads: true, 
@@ -5113,11 +5228,15 @@
             });
         }*/
-	});/*.css({
-		"height" : "20px", 
-		"width": (is_webkit ? "205px" : "100px"), 
-		"border-width": "0 0 0px 0px", 
-        "-moz-transform" : "rotate(-180deg) translate(5px, -0.5px) scale(1.1)",  
-        "-webkit-transform" : "rotate(-180deg) translate(0px, 0px)"
-	}).end().end().end().*/
+	}).css({
+        "height" : ($.browser.mozilla ? "15px" : "20px"), 
+        // "width": (is_webkit ? "205px" : "100px"),
+        "width" : "205px",
+        "margin-top" : ($.browser.mozilla ? "10px" : "0"),
+        "margin-right" : (is_mozilla ? "30px" : "0"),
+        "border-width": "0 0 0px 0px", 
+        "transform" : "rotate(-360deg) translate(5px, -0.5px) scale(1.1)",  
+        "-webkit-transform" : "rotate(-360deg) translate(0px, 0px)"
+	});/*.end().end().end().*/
+
     fileUploadMSG.find(".message-attach-link").click(function(){
 		jQuery('#message-attach-dialog').html(DataLayer.render("../prototype/modules/attach_message/attach_message.ejs", {}));
@@ -5149,74 +5268,7 @@
 				jQuery.each(selectedMessages[folder_name], function(message_number, message) { 
 					if (message) {
-						fileUploadMSG.find(' .attachments-list').show();	
-						var att = new Object();
-						att.folder = folder_name;
-						att.uid = message_number;
-						att.type = 'imapMSG';
-						att.name = Base64.encode(onceOpenedMessages[folder_name][message_number].subject + '.eml');
-						var idATT = JSON.stringify(att);
-						addAttachment( ID , idATT);                        
-						var attach = {};
-						attach.fileName = onceOpenedMessages[folder_name][message_number].subject + '.eml';
-						attach.fullFileName = onceOpenedMessages[folder_name][message_number].subject + '.eml';
-						if(attach.fileName.length > 20)
-							attach.fileName = attach.fileName.substr(0, 17) + "... " + attach.fileName.substr(attach.fileName.length-9, attach.fileName.length);
-
-						attach.error = false;
-                        attach.OK = true;
-						attach.fileSize = formatBytes(onceOpenedMessages[folder_name][message_number].size);
-						var upload = $(DataLayer.render("../prototype/modules/mail/templates/attachment_add_itemlist.ejs", {file : attach}));
-						$("#content_id_"+currentTab+" .save").button("enable");
-                        upload.find('.att-box-loading').remove();
-						upload.append('<input type="hidden" name="fileId[]" value=\''+idATT+'\'/>');
-						
-						upload.find('.att-box-delete').click(function(){
-                            $("#content_id_"+currentTab+" .save").button("enable");
-							var idAttach = $(this).parent().find('input[name="fileId[]"]').val();
-							fileUploadMSG.find(' .attachments-list').find('input[value="'+idAttach+'"]').remove();
-							delAttachment(ID,idAttach); 
-							$(this).parent().qtip("destroy");
-							$(this).parent().remove();
-							if(!fileUploadMSG.find(' .attachments-list').find(".att-box").length){
-								fileUploadMSG.find(' .attachments-list').hide();
-							}
-						});	
-							
-						fileUploadMSG.find('.attachments-list').append(upload);
-
-						upload.find('.att-box-loading').remove();
-
-						fileUploadMSG.find('.attachments-list .att-box:last').qtip({
-		                	content: DataLayer.render("../prototype/modules/mail/templates/attachment_add_itemlist_tooltip.ejs", {attach : attach}),
-							position: {
-								corner: {
-									tooltip: 'bottomMiddle',
-									target: 'topMiddle'
-								},
-								adjust: {
-					               resize: true,
-					               scroll: true
-					            }
-							},
-							show: {
-								when: 'mouseover', // Don't specify a show event
-								ready: false // Show the tooltip when ready
-							},
-							hide: 'mouseout', // Don't specify a hide event
-							style: {
-								border: {
-									width: 1,
-									radius: 5
-								},
-								width: {
-									 min: 75,
-									 max : 1000
-								},
-								padding: 5, 
-								textAlign: 'center',
-								tip: true, // Give it a speech bubble tip with automatic corner detection
-								name: 'blue' // Style it according to the preset 'cream' style
-							}
-		                });
+						/* Anexa a mensagem especificada (por folder e id_msg) 
+						   na mensagem sendo criada.*/
+						attach_message(folder_name, message_number);
 					}
 				});
@@ -5781,13 +5833,13 @@
 }
 
-function verifyContext(type) { 
-    var folderN = $(".menu-sel").attr("role") ? $(".menu-sel").attr("role") : get_current_folder(); 
-    if(type == "unarchive"){ 
-        expresso_mail_archive.unarchieve(folderN, null, null); 
-    } else { 
-        archive_msgs(folderN,null,null) 
-    } 
-} 
- 
+function verifyContext(type) {
+    var folderN = $(".menu-sel").attr("role") ? $(".menu-sel").attr("role") : get_current_folder();
+    if(type == "unarchive"){
+        expresso_mail_archive.unarchieve(folderN, null, null);
+    } else {
+        archive_msgs(folderN,null,null)
+    }
+}
+
 function draw_footer_box(num_msgs){
 	folder = get_current_folder();
@@ -5815,5 +5867,5 @@
 		((expresso_offline)?" ":'<span class="message_options_import"><span ' + change_font_color + ' title="'+get_lang("Import")+'" class="message_options" onclick="import_window()">'+get_lang("Import")+'</span></span>');
 
-     
+    
     //Link arquivar e desarquivar com ação
     //MAILARCHIVER
Index: branches/2.5/expressoMail1_2/js/doiMenuData.js
===================================================================
--- branches/2.5/expressoMail1_2/js/doiMenuData.js	(revision 8127)
+++ branches/2.5/expressoMail1_2/js/doiMenuData.js	(revision 8232)
@@ -142,10 +142,11 @@
     function loadMenu(){
         var archive = "";
-        if(use_local_messages != 0){
-            archive = {"name": get_lang("Archive"), "icon": "archive", callback: function(key, opt){ proxy_mensagens.archive_message('inbox', 'get_selected_messages'); }}
-        }else{
-            archive = "";
+
+        if( preferences['use_followupflags_and_labels'] == "1" )
+            var labelItems = getLabels();
+
+        var revertSortBox = function(){
+            if (search_box_type == "UNSEEN") sort_box_reverse = sort_box_reverse ? 0 : 1; 
         }
-    	var labelItems = getLabels();
 
     	$.contextMenu({
@@ -156,28 +157,51 @@
                     return true;
                 }
-                if( current.indexOf("local") == -1){ 
-                    archive = {"name": get_lang("Archive"), "icon": "archive", callback: function(key, opt){ proxy_mensagens.archive_message(get_current_folder(), 'get_selected_messages'); }} 
-                    
-                } else { 
-                    archive = {"name": get_lang("Unarchive"), "icon": "archive", callback: function(key, opt){ proxy_mensagens.unarchive_message(get_current_folder(), 'get_selected_messages'); }} 
-                }
-                var itensNotLocal = {
-                    "label": { "name": get_lang("Labels"), "items": labelItems},
-                    "follouwpflag":{"name": get_lang("Follow up"), callback: function(key, opt){ configureFollowupflag(); } },
-                    "sep2": "---------"
-                }
+                if(use_local_messages != 0){
+                    if( current.indexOf("local") != -1){
+                       archive = {"name": get_lang("Unarchive"), "icon": "archive", callback: function(key, opt){ proxy_mensagens.unarchive_message('inbox', 'get_selected_messages'); }}
+                    } else {
+                        archive = {"name": get_lang("Archive"), "icon": "archive", callback: function(key, opt){ proxy_mensagens.unarchive_message('inbox', 'get_selected_messages'); }}
+                    }
+                }
+
+                if( preferences['use_followupflags_and_labels'] == "1" )
+                    var itensNotLocal = {
+                        "label": { "name": get_lang("Labels"), "items": labelItems},
+                        "follouwpflag":{"name": get_lang("Follow up"), callback: function(key, opt){ configureFollowupflag(); } },
+                        "sep2": "---------"
+                    }
 
                 var items= {
-                    "flagSeen":      {"name": get_lang("Mark as") + " " + get_lang('seen'), "icon": "seen", callback: function(key, opt){ proxy_mensagens.proxy_set_messages_flag('seen','get_selected_messages'); }},
-                    "flagUnseen":    {"name": get_lang("Mark as") + " " + get_lang('unseen'), "icon": "unseen", callback: function(key, opt){ proxy_mensagens.proxy_set_messages_flag('unseen','get_selected_messages'); }},
-                    "flagFlagged":   {"name": get_lang("Mark as") + " " + get_lang('important'), "icon": "important", callback: function(key, opt){ proxy_mensagens.proxy_set_messages_flag('flagged','get_selected_messages'); }},
-                    "flagUnflagged": {"name": get_lang("Mark as") + " " + get_lang('normal'), callback: function(key, opt){ proxy_mensagens.proxy_set_messages_flag('unflagged','get_selected_messages'); }},
+                    "flagSeen":      {"name": get_lang("Mark as") + " " + get_lang('seen'), "icon": "seen", callback: function(key, opt){ revertSortBox(); proxy_mensagens.proxy_set_messages_flag('seen','get_selected_messages'); }},
+                    "flagUnseen":    {"name": get_lang("Mark as") + " " + get_lang('unseen'), "icon": "unseen", callback: function(key, opt){ revertSortBox(); proxy_mensagens.proxy_set_messages_flag('unseen','get_selected_messages'); }},
+                    "flagFlagged":   {"name": get_lang("Mark as") + " " + get_lang('important'), "icon": "important", callback: function(key, opt){ revertSortBox(); proxy_mensagens.proxy_set_messages_flag('flagged','get_selected_messages'); }},
+                    "flagUnflagged": {"name": get_lang("Mark as") + " " + get_lang('normal'), callback: function(key, opt){ revertSortBox(); proxy_mensagens.proxy_set_messages_flag('unflagged','get_selected_messages'); }},
                     "sep1": "---------"
                 }
-
+				
+				// Desabilita a opção de criar filtro a partir da mensagem, caso mais de uma mensagem esteja selecionada: 
+				var is_filterFromMsg_disabled = function () { 
+					var base_selector = ".table_box tbody tr.selected_msg"; 
+					return ($(base_selector).length > 1) || ($(base_selector + " td span").text().indexOf(get_lang("Draft")) > -1); 
+				} 
+				
                 var lastItens = {
                     "move": {"name": get_lang("Move to")+"...", "icon": "move", callback: function(key, opt){ wfolders.makeWindow('', 'move_to'); }},
                     "remove": {"name": get_lang("Delete"),      "icon": "delete", callback: function(key, opt){ proxy_mensagens.delete_msgs('null','selected','null'); }},
                     "export": {"name": get_lang("Export"),      "icon": "export", callback: function(key, opt){ proxy_mensagens.export_all_messages(); }},
+					/*Abre o diálogo de criação de filtro a partir da mensagem:*/ 
+					"filterFromMsg": { 
+						"name": get_lang("Create filter from message"),  
+						"icon": "filter",  
+						callback: function (key, opt) { 
+							var msg_number = get_selected_messages(); 
+							var msg = onceOpenedHeadersMessages[current_folder][msg_number]; 
+							if (msg !== undefined) 
+							{ 
+								filter_from_msg(msg); 
+							} 
+						}, 
+						disabled: is_filterFromMsg_disabled() 
+					}, 
                     "archive": archive
                 }
@@ -318,6 +342,6 @@
     	} else {
             var labeleds =  (messageInfo.forceIcon ? messageInfo.labels : DataLayer.get('labeled', {
-    			criteria: {deepness: '2'},
-    			filter: [
+    			criteria: {deepness: 2},
+                filter: [
     				'AND',
     				['=', 'folderName', msg_folder], 
@@ -337,5 +361,5 @@
 
                 for (var i=0; i < labeleds.length; i++){
-                    menuItems[ labeleds[i].id ? labeleds[i].id : labeleds[i].label.id] = labeleds[i].id ? labeleds[i] : labeleds[i].label;
+                    menuItems[ (labeleds[i].id ? labeleds[i].id : labeleds[i].label.id) ] = labeleds[i].label ? labeleds[i].label : labeleds[i];
                 }
     		} else {
@@ -351,4 +375,6 @@
     		menuItensLabel[index] = {type: "label", customName: menuItems[index].name, id: msg_folder+"/"+msg_number+"#"+index};		
     	}
+
+
     	$.contextMenu.types.label = function(item, opt, root) {
             $('<span>'+item.customName+'</span><span class="removeLabeled" title="'+get_lang("Remove Label")+'">x</span>')
Index: branches/2.5/expressoMail1_2/js/rich_text_editor.js
===================================================================
--- branches/2.5/expressoMail1_2/js/rich_text_editor.js	(revision 8166)
+++ branches/2.5/expressoMail1_2/js/rich_text_editor.js	(revision 8232)
@@ -130,6 +130,6 @@
 cRichTextEditor.prototype.getSignaturesOptions = function() {
 	
-        if(RichTextEditor.signatures !== false)
-            return RichTextEditor.signatures;
+    if(RichTextEditor.signatures !== false)
+        return RichTextEditor.signatures;
                 
    	var signatures = RichTextEditor.normalizerSignature(this.fromJSON( preferences.signatures ));
@@ -138,52 +138,55 @@
 	for( key in signatures )
 	    if( !signature_types[key] )
-		signatures[key] = signatures[key].replace( /\n/g, "<br>" );
-                 
-        RichTextEditor.signatures = signatures;
-        return signatures;
-
-}
-cRichTextEditor.prototype.normalizerSignature = function(values) { 
-	var value = {};  
-	for (key in values){ 
-		value[RichTextEditor.isEncoded64(key) ? RichTextEditor.decode64(key) : key] = values[key]; 
-  	} 
- 	return value;
-
-} 
- 
-/*Verifica se a string input esta em Base64*/ 
-cRichTextEditor.prototype.isEncoded64 = function(input){ 
-var baseStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; 
-var encoded = true; 
-        if ( (input.length % 4) != 0) 
-                return false; 
-        for(var i=0; i<input.length; i++){ 
-                if ( baseStr.indexOf(input[i]) < 0 ){ 
-                        encoded = false; 
-                        break; 
-                } 
-        } 
-        return encoded; 
+		    signatures[key] = signatures[key].replace( /\n/g, "<br>" );
+
+    RichTextEditor.signatures = signatures;
+    return signatures;
+
+}
+cRichTextEditor.prototype.normalizerSignature = function(values) {
+
+    var value = {};
+
+    for (key in values){
+
+        value[RichTextEditor.isEncoded64(key) ? RichTextEditor.decode64(key) : key] = values[key];
+    }
+
+    return value;
+
+}
+
+/*Verifica se a string input esta em Base64*/
+cRichTextEditor.prototype.isEncoded64 = function(input){
+var baseStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
+var encoded = true;
+	if ( (input.length % 4) != 0)
+		return false;
+	for(var i=0; i<input.length; i++){
+		if ( baseStr.indexOf(input[i]) < 0 ){
+			encoded = false;
+			break;
+		}
+	}
+	return encoded;
 }
 
 cRichTextEditor.prototype.getSignatureDefault = function() {
-	 
-        if(RichTextEditor.signatures === false){
-            RichTextEditor.signatures = RichTextEditor.getSignaturesOptions();
-            preferences.signature_default = preferences.signature;
-        }     
+
+    if(RichTextEditor.signatures === false){
+        RichTextEditor.signatures = RichTextEditor.getSignaturesOptions();
+        preferences.signature_default = preferences.signature;
+    }
          
-        if(!RichTextEditor.signatures || !preferences.signature_default) 
-	{
-          preferences.use_signature = "0"; //Desabilita o uso da assinatura
-          return '';
-        } 
-        if (RichTextEditor.isEncoded64(preferences.signature_default)) 
-                preferences.signature_default = RichTextEditor.decode64(preferences.signature_default); 
-        return unescape(preferences.signature_default);
-
-}
-
+    if(!RichTextEditor.signatures || !preferences.signature_default)
+    {
+      preferences.use_signature = "0"; //Desabilita o uso da assinatura
+      return '';
+    }
+	if (RichTextEditor.isEncoded64(preferences.signature_default))
+		preferences.signature_default = RichTextEditor.decode64(preferences.signature_default);
+    return unescape(preferences.signature_default);
+
+}
 
 
@@ -216,5 +219,5 @@
 	{
             autoSaveControl.status[id] = true;
-            autoSaveControl.timer[id] = window.setInterval( "autoSave("+id+")" ,autosave_time);  
+            autoSaveControl.timer[id] = window.setInterval( "autoSave(\""+id+"\")" ,autosave_time);  
 
             CKEDITOR.instances[inst].document.on('keydown', function(event){   
