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)
