Index: branches/2.4/expressoMail1_2/js/main.js
===================================================================
--- branches/2.4/expressoMail1_2/js/main.js	(revision 7214)
+++ branches/2.4/expressoMail1_2/js/main.js	(revision 7228)
@@ -1,4 +1,5 @@
 // Tempo do auto refresh (em milisegundos)
 var time_refresh = 300000;
+
 // tempo do auto save (em milisegundos)
 // 20000 = 20 segundos
@@ -6,8 +7,13 @@
 var results_search_messages = ""; 
 var cabecalho = '<h4>ExpressoLivre - ExpressoMail</h4>'; 
-// Variavel para controle de atualização das mensagens listadas na modal de alerta de filtro por remetente
-var checkAlarmsFilter = false;
+
+var auxNotificationCriteriaVetor = [];
+var auxNotification;
+
+var countNewMessage = 0;
+var notifyNewMessageFilter = [];
 
 var dynamicPersonalContacts = new Array();
+var dynamicPersonalGroups = new Array();
 var dynamicContacts = new Array();
 var topContact = 0;
@@ -20,7 +26,5 @@
 	} 
 }
-	
-
-	
+
 function mount_url_folder(folders){
 	return folders.join(cyrus_delimiter);
@@ -51,12 +55,12 @@
 function updateDynamicPersonalContacts(){
 	dynamicPersonalContacts = new Array();
-	var contactsData = REST.get("/contacts").collection.itens;
+	var contactsData = normalizeContacts(REST.get("/personalContact").collection.itens);
 	if(contactsData){
 		$.each(contactsData, function(index, value){
 			var contact = {
-				id : parseInt(value.data[0].value),
-				name : value.data[1].value,
-				email : value.data[2].value,
-				value: value.data[1].value + " - " + value.data[2].value,
+                id : parseInt(value.id),
+                name : value.name,
+                email: value.email,
+				value: value.name+ " - " + value.email,
 				type: "P"
 			};
@@ -66,4 +70,23 @@
 }
 
+
+function updateDynamicPersonalGroups(){
+	dynamicPersonalGroups = new Array();
+	var contactsData = normalizeContacts(REST.get("/groups").collection.itens);
+	if(contactsData){
+		$.each(contactsData, function(index, value){
+			var contact = {
+				id : parseInt(value.id),
+				owner : value.owner,
+				name : value.name,
+				email: value.email,
+				type: "G"
+			};
+			dynamicPersonalGroups.push(contact);
+		});
+	}
+}
+
+
 function init(){
 	if (!is_ie)
@@ -77,5 +100,5 @@
 		
  	                if(preferences.show_name_print_messages == "1") { 
-							var getUserName = document.getElementById("user_info"); 
+				var getUserName = document.getElementById("user_info"); 
  	                        var userName = getUserName.innerHTML; 
  	                        var position = userName.indexOf("-"); 
@@ -102,9 +125,37 @@
 		if (preferences.use_local_messages==1) { //O I.E 7 estava se atrapalhando caso esses loads fossem feitos após as chamadas ajax. Antes não apresentou problemas...
 			connector.loadScript('mail_sync');
-			if (is_ie)
-				connector.loadScript('TreeShow');
 			setTimeout('auto_archiving()', 30000);
 			
 		}
+		$.ajax({			
+			url: "controller.php?" + $.param( {action: "$this.imap_functions.get_range_msgs3", 
+				folder: "INBOX",
+				 msg_range_begin: "0",
+				 msg_range_end: "0", 					
+				sort_box_type: "SORTARRIVAL", 
+				search_box_type: "ALL",
+				sort_box_reverse: "1"
+				}),
+			success: function(data){
+				data = connector.unserialize(data);
+				if(data){
+					var _data = {};
+					$.each(data,function(index,value){
+						if (data[index] && data[index].msg_number){
+							_data[data[index].msg_number] = data[index].msg_number;
+						}
+					});
+					populateSelectedMsgs(_data);
+					_data = {};
+				
+				}
+			},
+			beforeSend: function( jqXHR, settings ){
+				connector.showProgressBar();
+			},
+			complete: function( jqXHR, settings ){
+				connector.hideProgressBar();
+			}
+		});
 		//Substituido por padrão Jquery
 		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);
@@ -188,4 +239,5 @@
 				updateDynamicContact();
 				updateDynamicPersonalContacts();
+				updateDynamicPersonalGroups();
 			};
 			load_dynamics();
@@ -507,5 +559,7 @@
 					var sort_type = sort_box_type;
 					sort_box_type = null;
-					sort_box('UNSEEN', sort_type);
+					sort_box('UNSEEN', sort_type,false); 
+					delete selectedPagingMsgs[msg_info.msg_number];
+					totalFolderMsgs--;
 				}
 			}
@@ -534,6 +588,24 @@
 					var confNotification = confirm(get_lang("The sender:\n%1\nwaits your notification of reading. Do you want to confirm this?",Base64.decode(msg_info.DispositionNotificationTo)), "");
 
-			if (confNotification)
-				cExecute ("$this.imap_functions.send_notification&notificationto="+msg_info.DispositionNotificationTo+"&date="+msg_info.udate+"&subject="+url_encode(msg_info.subject), handler_sendNotification);
+			if (confNotification) {
+			/* Adequação a nova funcionalidade. Agora, a confirmação de leitura é uma preferência do usuário. */
+				if(preferences.confirm_read_message) {
+					$.Zebra_Dialog(get_lang("Would you like to send the read receipt?"), {
+						'type':     'question',
+						'title':    get_lang('Read receipt'),
+						'buttons':  [get_lang("Yes"), get_lang("No")],
+						'overlay_opacity' : 0.5,
+						'onClose':  function(caption) {
+							if(caption == get_lang("Yes"))
+								cExecute ("$this.imap_functions.send_notification&notificationto="+msg_info.DispositionNotificationTo+"&date="+msg_info.udate+"&subject="+url_encode(msg_info.subject), handler_sendNotification);								
+							else 
+								write_msg(get_lang("Confirmation message is not sent"));
+						}
+					});
+				}
+				else
+					cExecute ("$this.imap_functions.send_notification&notificationto="+msg_info.DispositionNotificationTo+"&date="+msg_info.udate+"&subject="+url_encode(msg_info.subject), handler_sendNotification);								
+			}
+				
 		}
 		//Change msg class to read.
@@ -551,5 +623,5 @@
 
 function auto_refresh(){
-	refresh(preferences.alert_new_msg);
+	refresh(preferences.alert_new_msg, preferences.notifications);
 	setTimeout('auto_refresh()', time_refresh);
 }
@@ -560,15 +632,36 @@
 }
 
-function refresh(alert_new_msg){
+function notificationFilter(data, notifyCriteria){
+	
+	if(parseInt(notifyCriteria)  && data.length > 0 && !activePage ){
+	
+		var howManyCriteria = $('div.gray.filtersDeadline .message-list li').length;
+		var differenceOfNewCriteria = data.length - howManyCriteria;
+		
+		if(differenceOfNewCriteria > 0){
+			for(var i=data.length - differenceOfNewCriteria; i < data.length; i++){
+	
+				desktopNotification.sentNotification("",get_lang("Filter criteria"),  truncate(new Date(data[i].udate).toString('dd/MM HH:mm') + ' - ' + data[i].from+' - '+data[i].subject, 75));
+				desktopNotification.showNotification(false, function(){
+					window.focus();
+					this.cancel();
+				});
+			}
+		}
+	}
+}
+
+function refresh(alert_new_msg, notifyPermission){
+
 	getFromAlertRules();
 	var handler_refresh = function(data){
-		if(checkAlarmsFilter){
-			handlerMessageFilter = function (data) {
-				alarmFollowupflagged('filtersAlarms', data);
-			}
-			/* Busca  nas pastas indexadas para ver se há novas mensagens com a flag $FilteredMessage */
-			cExecute ("$this.imap_functions.getFlaggedAlertMessages&folders="+fromRules, handlerMessageFilter);
-		}
-		checkAlarmsFilter = true;
+		handlerMessageFilter = function (data) {			
+			notificationFilter(data, notifyPermission);
+			alarmFollowupflagged('filtersAlarms', data);
+			
+		}
+		/* Busca  nas pastas indexadas para ver se há novas mensagens com a flag $FilteredMessage */
+		cExecute ("$this.imap_functions.getFlaggedAlertMessages&folders="+fromRules, handlerMessageFilter);
+
 		if(data['msg_range_end'])
 			if(data['msg_range_end'] > 0)
@@ -582,5 +675,5 @@
 			showEmptyBoxMsg(box);
 
-		if (data.length > 0){
+		if (data.length > 0 || countNewMessage > 0){
 			for(var i=0;i< data.length;i++){
 				if (!onceOpenedHeadersMessages[current_folder])
@@ -588,5 +681,5 @@
 				onceOpenedHeadersMessages[current_folder][data[i].msg_number] = data[i];
 			}
-			Element("table_message_header_box_"+numBox).emptyBody = false;
+			Element("table_message_header_box_0").emptyBody = false;
 			table_element = Element("table_box");
 			var msg_info = document.getElementById('msg_info');
@@ -617,8 +710,13 @@
 			if (data[0].msg_folder != current_folder) // Bad request
 				return false;
+				
+			totalFolderMsgs += data.new_msgs; 
+				
 			for (var i=0; i<data.length; i++){
 				var existent = document.getElementById(data[i].msg_number);
 				if (!existent)
 				{
+					selectedPagingMsgs[data[i].msg_number] = false;
+					updateSelectedMsgs(false,data[i].msg_number);
 					var new_msg = this.make_tr_message(data[i], current_folder, data.offsetToGMT);
 					$(new_msg).draggable({
@@ -669,14 +767,18 @@
 						},
 						helper: function(event){
-								if($(this).find("input:checkbox").attr("checked") != "checked"){
-									$(this).find("input:checkbox").trigger('click');
-									$(this).addClass("selected_msg");
-								}
-								if($("#table_box").find("tr input:checked").length > 1)
-									return $("<tr><td>"+DataLayer.render('../prototype/modules/mail/templates/draggin_box.ejs', {texto : (($("#table_box").find("tr input:checked")).length+" mensagens selecionadas"), type: "messages"})+"</td></tr>");
-								if(	$(this).find(".td_msg_subject").text().length > 18 )
-									return $("<tr><td>"+DataLayer.render('../prototype/modules/mail/templates/draggin_box.ejs', {texto : $(this).find(".td_msg_subject").text().substring(0,18) + "...", type: "messages"})+"</td></tr>");
-								else
-									return $("<tr><td>"+DataLayer.render('../prototype/modules/mail/templates/draggin_box.ejs', {texto : $(this).find(".td_msg_subject").text(), type: "messages"})+"</td></tr>");
+							$(this).addClass("selected_msg").find("input:checkbox").attr("checked", true);
+							updateSelectedMsgs($(this).find("input:checkbox").is(':checked'),$(this).attr("id"));
+							if ( $("#tbody_box .selected_shortcut_msg").length > 1) {
+								$("#tbody_box .selected_shortcut_msg").addClass("selected_msg").find('.checkbox').attr('checked',true);
+								$.each( $(".selected_shortcut_msg"), function(index, value){
+					            	updateSelectedMsgs($(value).find(":checkbox").is(':checked'),$(value).attr("id"));
+						        });
+							}
+							if(totalSelected() > 1)
+								return $("<tr><td>"+DataLayer.render('../prototype/modules/mail/templates/draggin_box.ejs', {texto : (totalSelected()+" mensagens selecionadas"), type: "messages"})+"</td></tr>");
+							if(	$(this).find(".td_msg_subject").text().length > 18 )
+								return $("<tr><td>"+DataLayer.render('../prototype/modules/mail/templates/draggin_box.ejs', {texto : $(this).find(".td_msg_subject").text().substring(0,18) + "...", type: "messages"})+"</td></tr>");
+							else
+								return $("<tr><td>"+DataLayer.render('../prototype/modules/mail/templates/draggin_box.ejs', {texto : $(this).find(".td_msg_subject").text(), type: "messages"})+"</td></tr>");
 						},
 						iframeFix: true,
@@ -686,7 +788,10 @@
 						containment: "#divAppbox"
 					}).bind("contextmenu", function(){
-						if($(this).find("input:checkbox").attr("checked") != "checked"){
-							$(this).find("input:checkbox").trigger('click');
-							$(this).addClass("selected_msg");
+						if (!(($(event.target).find('img').length > 0) && ($(event.target).hasClass('td-label')))){
+							if($(this).find("input:checkbox").attr("checked") != "checked"){
+								$(this).find("input:checkbox").trigger('click');
+								$(this).addClass("selected_msg");
+							}
+							updateSelectedMsgs($(this).find("input:checkbox").is(':checked'),$(this).attr("id"));
 						}
 					});
@@ -711,7 +816,28 @@
 			if(parseInt(preferences.use_shortcuts))
 				select_msg("null","reload_msg","null");
-
-			if(parseInt(alert_new_msg) && data.new_msgs > 0)
+		
+			if(parseInt(alert_new_msg) && data.new_msgs > 0 && activePage)
 				alert(data['new_msgs'] > 1 ? get_lang("You have %1 new messages", data['new_msgs']) + "!" : get_lang("You have 1 new message") +"!");
+			
+			
+			if(parseInt(notifyPermission)  && (data.new_msgs > 0 || !!countNewMessage) && !activePage ){
+			
+				countNewMessage += data.length;
+				
+				desktopNotificationAux = desktopNotification.sentNotification("",get_lang("Notification"), countNewMessage > 1 ? get_lang("You have %1 new messages", countNewMessage) + "!" : get_lang("You have 1 new message") + "!");
+				
+				if(auxNotification !== 'undefined')
+					desktopNotification.cancelByReference(auxNotification);
+				
+				desktopNotification.showNotification(function(){
+					countNewMessage = 0;
+				}, function(){
+					window.focus();
+					this.cancel();
+					countNewMessage = 0;
+				});
+				
+				auxNotification = desktopNotificationAux;
+			}
 			build_quota(data['quota']);
 		}
@@ -811,5 +937,7 @@
  		         
  		        if (!archive && (parseInt(preferences.save_deleted_msg)) && (folder != userTrashFolder)){ 
- 		                move_msgs2(folder, msgs_number, border_ID, userTrashFolder,special_folders['Trash'],show_success_msg ); 
+                    if(currentTab == 0)
+						msgs_number = get_selected_messages();
+ 		            move_msgs2(folder, ""+msgs_number, border_ID, userTrashFolder,special_folders['Trash'],show_success_msg ); 
 				return;
 	}
@@ -835,16 +963,16 @@
 			}
 
-			if(data.status == false){ 
-                    write_msg(get_lang("You don't have permission for this operation in this shared folder!")); 
-                    return false; 
- 		    } 
-
-		if (show_success_msg){ 
-                if (data.msgs_number.length == 1) 
-                        write_msg(get_lang("The message was deleted.")); 
-                else 
-                        write_msg(get_lang("The messages were deleted.")); 
-        } 
-        
+		if(data.status == false){
+			write_msg(get_lang("You don't have permission for this operation in this shared folder!"));
+			return false;
+		}
+
+		if (show_success_msg){
+			if (data.msgs_number.length == 1)
+				write_msg(get_lang("The message was deleted."));
+			else
+				write_msg(get_lang("The messages were deleted."));
+		}
+
 		if (openTab.type[currentTab] > 1){
 			var msg_to_delete = Element(msgs_number);
@@ -882,13 +1010,15 @@
 				if (msg_to_delete){
 						removeAll(msg_to_delete.id);
+						 delete selectedPagingMsgs[data.msgs_number[i]]; 
 				}
-				totalFolderMsgs = totalFolderMsgs - data.msgs_number.length;
+				 totalFolderMsgs = totalFolderMsgs - data.msgs_number.length; 
 		}
 		Element('tot_m').innerHTML = parseInt(Element('tot_m').innerHTML) - data.msgs_number.length;
 		refresh();
 	}
-
-	if (msgs_number == 'selected')
+	
+	if(currentTab == 0 )
 		msgs_number = get_selected_messages();
+
 	if (msgs_number.length > 0 || parseInt(msgs_number) > 0)
 		cExecute ("$this.imap_functions.delete_msgs&folder="+folder+"&msgs_number="+msgs_number+"&border_ID="+border_ID+"&sort_box_type="+sort_box_type+"&search_box_type="+search_box_type+"&sort_box_reverse="+sort_box_reverse, handler_delete_msgs);
@@ -1053,6 +1183,6 @@
 			params += "&new_folder="+url_encode(new_folder);
 			params += "&new_folder_name="+url_encode(new_folder_name);
-		cExecute ("$this.imap_functions.move_search_messages", handler_move_search_msgs, params);
-	}
+			cExecute ("$this.imap_functions.move_search_messages", handler_move_search_msgs, params);
+		}
 	}
 	else
@@ -1079,11 +1209,10 @@
 				var move_to_folder = data.match(/^(.*)Spam(.*)$/) ? "Spam" : special_folders['Trash'];
 				alert(get_lang('There is not %1 folder, Expresso is creating it for you... Please, repeat your request later.', folder_error));
-				connector.loadScript('TreeShow');
 				ttree.FOLDER = 'root';
-				ttreeBox.new_past(move_to_folder);
+				create_new_folder(move_to_folder,"INBOX");
 				return false;
 			}else{
-				data = data.split("/").reverse(); //Recupera o nome da pasta do array 
-                write_msg(get_lang('Error moving message.')+" "+get_lang('Permission denied to folder "%1".', data[0])); 
+				data = data.split("/").reverse(); //Recupera o nome da pasta do array
+				write_msg(get_lang('Error moving message.')+" "+get_lang('Permission denied to folder "%1".', data[0]));
 				return false;
 			}
@@ -1227,7 +1356,6 @@
 	} catch (e) {} 
 
-	if (msgs_number == 'selected'){
+	if(currentTab == 0)
 		msgs_number = get_selected_messages();
-		}
 
 	if(openTab.type[currentTab] == 1){
@@ -1251,5 +1379,5 @@
 				url: 'controller.php?' + $.param( {action: '$this.imap_functions.move_messages',
 								    folder: folder,
-								    msgs_number: msgs_number,
+								    msgs_number: ""+msgs_number,
 								    border_ID: border_ID,
 								    sort_box_type: sort_box_type,
@@ -1264,5 +1392,13 @@
 				success: function( data ){
 				    data = connector.unserialize( data );
-				    
+				    $.each(msgs_number, function(index, value){
+				    	delete selectedPagingMsgs[value];
+				    });
+				    totalFolderMsgs -= msgs_number.split(",").length;
+
+				    //TESTE
+				    selectAllFolderMsgs();
+           			$('.select-link').unbind('click');
+
 				    if( data )
 					handler_move_msgs( data );
@@ -1606,5 +1742,5 @@
 }
 
-function get_selected_messages(){
+/*function get_selected_messages(){
 	var main;
 	try{
@@ -1650,9 +1786,9 @@
 
  		         
- 		        /* Verifica se está na tela de pesquisa. */ 
+ 		        /* Verifica se está na tela de pesquisa. */ /*
  		        if(selected_messages.indexOf("_") != -1) 
  		        { 
  		                results_search_messages = selected_messages; 
- 		                /* Retira a informação da aba */ 
+ 		                /* Retira a informação da aba */ /*
  		                selected_messages = selected_messages.substring(0,selected_messages.indexOf("_"));
 	}
@@ -1670,5 +1806,5 @@
 			return selected_messages_by_shortcuts;
 		}*/
-		/*Se houver mais de uma mensagem selecionada por atalho*/
+		/*Se houver mais de uma mensagem selecionada por atalho*//*
 		if (array_selected_messages_by_shortcuts.length > 1){
 			if (selected_messages == "")
@@ -1682,4 +1818,12 @@
 	else
 		return selected_messages;
+}*/
+function get_selected_messages(){
+	var selected = new Array();
+	$.each(selectedPagingMsgs, function(index, value){
+		if(value)
+			selected.push(index);
+	});
+	return ""+selected;
 }
 
@@ -1696,5 +1840,5 @@
 }
 
-function new_message(type, border_ID, flagged){ 
+function new_message(type, border_ID, flagged){
 		if(RichTextEditor.editorReady === false) return false; 
  		             
@@ -1739,5 +1883,5 @@
 	{
 		RichTextEditor.editorReady = true; 
- 	    setTimeout('new_message(\''+type+'\',\''+border_ID+'\',\''+flagged+'\');',500); 
+ 	    setTimeout('new_message(\''+type+'\',\''+border_ID+'\',\''+flagged+'\');',500);
 		return false;
 	}
@@ -1804,4 +1948,6 @@
 	if (document.getElementById("body_" + border_ID))
 		data.body = document.getElementById("body_" + border_ID).innerHTML;
+	if (document.getElementById("from_values_" + border_ID))
+		data.from = document.getElementById("from_values_"+border_ID).value;
 	if (Element('date_' + border_ID)){
 		data.date = Element('date_' + border_ID).innerHTML;
@@ -1827,5 +1973,4 @@
 	var content = $("#content_id_"+new_border_ID);
 
-	
 switch(type){
 		case "reply_without_history":
@@ -1846,5 +1991,4 @@
 			break;
 		case "reply_with_history":
-
 			RichTextEditor.replyController = true; //Seta o editor como modo reply 
 			title = "Re: " + html_entities(data.subject);
@@ -1853,8 +1997,6 @@
 			
 			draw_reply_boxes_by_field("to", data.to, content);
-			
 			content.find('[name="msg_reply_from"]').val($("#msg_number_" + border_ID).val());	
-
-			block_quoted_body = make_body_reply(data.body, data.to, data.date_day, data.date_hour);
+			block_quoted_body = make_body_reply(data.body, data.from, data.date_day, data.date_hour);
 			
 			useOriginalAttachments(new_border_ID,border_ID);
@@ -1956,5 +2098,5 @@
 			content.find(".subject").val("Re: " + data.subject);
 			
-			block_quoted_body = make_body_reply(data.body, data.to, data.date_day, data.date_hour);
+			block_quoted_body = make_body_reply(data.body, data.from, data.date_day, data.date_hour);
 			
 			useOriginalAttachments(new_border_ID,border_ID);
@@ -2020,8 +2162,9 @@
 			break;
 		case "edit":
+		
+			if(flagged == 'F')
+				$(".important").addClass("expressomail-button-icon-ative");
 			
-			if(flagged == 'F') 
- 	                $(".important").addClass("expressomail-button-icon-ative"); 
- 	            
+			openTab.imapBox[new_border_ID] = folder_message.value;
 			document.getElementById('font_border_id_'+new_border_ID).innerHTML = data.subject;
 			title = "Edição: "+ html_entities(data.subject);
@@ -2099,5 +2242,5 @@
 //DESENHA OS RETANGULOS PARA OS E-MAIL NA OPÇÃO REPLY
 function draw_reply_boxes_by_field(field, value, context){
-	array = value.split(",");
+	array = break_comma(value);
 	$.each(array, function(index, value){
 		draw_email_box(value, context.find("."+field).filter("textarea:first"));
@@ -2166,21 +2309,16 @@
 				    var attach = {};
 				    attach.fileName =  attachments[i].text.substring(0, attachments[i].text.lastIndexOf('('));
-
-				    if(attach.fileName.length > 45)
-					attach.fileName = attach.fileName.substr(0, 32) + " ... " + attach.fileName.substr(attach.fileName.length-9, attach.fileName.length);
+                    attach.fullFileName = attach.fileName;
+				    if(attach.fileName.length > 20)
+					attach.fileName = attach.fileName.substr(0, 17) + " ... " + attach.fileName.substr(attach.fileName.length-9, attach.fileName.length);
 
 				    attach.fileSize =  attachments[i].text.substring(( attachments[i].text.lastIndexOf('(')+1), attachments[i].text.lastIndexOf(')'));
 
+                    attach.error = false;
+                    fileUploadMSG.find(' .attachments-list').show();
 				    var upload = $(DataLayer.render("../prototype/modules/mail/templates/attachment_add_itemlist.ejs", {file : attach}));
-				    upload.find('.status-upload').remove();
-				    upload.find('.in-progress').remove(); 
 				    upload.append('<input type="hidden" name="fileId[]" value=\''+idATT+'\'/>');
-				    upload.find('.button.close').button({
-					    icons: {
-						    primary: "ui-icon-close"
-					    },
-					    text: false
-
-				    }).click(function(){
+                    upload.find(".att-box-loading").remove();
+				    upload.find('.att-box-delete').click(function(){
 					    var idAttach = $(this).parent().find('input[name="fileId[]"]').val();
 					    var content_body = RichTextEditor.getData('body_'+new_border_ID);
@@ -2198,8 +2336,45 @@
 					    fileUploadMSG.find('.attachments-list').find('input[value="'+idAttach+'"]');
 					    delAttachment(new_border_ID,idAttach); 
-					    $(this).parent().remove();
+					    $(this).parent().qtip("destroy");
+                        $(this).parent().remove();
+                        if(!fileUploadMSG.find(' .attachments-list').find(".att-box").length){
+                            fileUploadMSG.find(' .attachments-list').hide();
+                        }
 				    });
 
 				    fileUploadMSG.find('.attachments-list').append(upload);
+                    fileUploadMSG.find('.attachments-list .att-box:last').qtip({
+                        content: DataLayer.render("../prototype/modules/mail/templates/attachment_add_itemlist_tooltip.ejs", {attach : attach}),
+                        position: {
+                            corner: {
+                                tooltip: 'bottomMiddle',
+                                target: 'topMiddle'
+                            },
+                            adjust: {
+                               resize: true,
+                               scroll: true,
+                               screen: true
+                            }
+                        },
+                        show: {
+                            when: 'mouseover', // Don't specify a show event
+                            ready: false // Show the tooltip when ready
+                        },
+                        hide: 'mouseout', // Don't specify a hide event
+                        style: {
+                            border: {
+                                width: 1,
+                                radius: 5
+                            },
+                            width: {
+								 min: 75,
+								 max : 1000
+							},
+                            padding: 3, 
+                            textAlign: 'left',
+                            tip: true, // Give it a speech bubble tip with automatic corner detection
+                            name: 'blue' // Style it according to the preset 'cream' style
+                        }
+                    });
 				}
 				else
@@ -2224,22 +2399,16 @@
 				    var attach = {};
 				    attach.fileName =  arrayAttachmentsA[i].text.substring(0, arrayAttachmentsA[i].text.lastIndexOf('('));
-
-				    if(attach.fileName.length > 45)
-					attach.fileName = attach.fileName.substr(0, 32) + " ... " + attach.fileName.substr(attach.fileName.length-9, attach.fileName.length);
+                    attach.fullFileName = attach.fileName;
+				    if(attach.fileName.length > 20)
+					attach.fileName = attach.fileName.substr(0, 17) + " ... " + attach.fileName.substr(attach.fileName.length-9, attach.fileName.length);
 
 				    attach.fileSize =  arrayAttachmentsA[i].text.substring(( arrayAttachmentsA[i].text.lastIndexOf('(')+1), arrayAttachmentsA[i].text.lastIndexOf(')'));
-
+                    attach.error = false;
+                    fileUploadMSG.find(' .attachments-list').show();
 				    var upload = $(DataLayer.render("../prototype/modules/mail/templates/attachment_add_itemlist.ejs", {file : attach}));
-				    upload.find('.status-upload').remove();
-				    upload.find('.in-progress').remove(); 
+				    upload.find('.att-box-loading').remove(); 
 				    upload.append('<input type="hidden" name="fileId[]" value=\''+arrayAttachments[i]+'\'/>');
-				    upload.find('.button.close').button({
-					    icons: {
-						    primary: "ui-icon-close"
-					    },
-					    text: false
-
-				    }).click(function(){
-					    var idAttach = $(this).parent().parent().find('input[name="fileId[]"]').val();
+				    upload.find('.att-box-delete').click(function(){
+					    var idAttach = $(this).parent().find('input[name="fileId[]"]').val();
 					    var content_body = RichTextEditor.getData('body_'+new_border_ID);
 					    var imagens = content_body.match(/<img[^>]*>/g);
@@ -2256,9 +2425,45 @@
 					    fileUploadMSG.find('.attachments-list').find('input[value="'+idAttach+'"]');
 					    delAttachment(new_border_ID,idAttach); 
-					    $(this).parent().remove();
+					    $(this).parent().qtip("destroy");
+                        $(this).parent().remove();
+                        if(!fileUploadMSG.find(' .attachments-list').find(".att-box").length){
+                            fileUploadMSG.find(' .attachments-list').hide();
+                        }
 				    });
 
 				    fileUploadMSG.find('.attachments-list').append(upload);
-
+                    fileUploadMSG.find('.attachments-list .att-box:last').qtip({
+                        content: DataLayer.render("../prototype/modules/mail/templates/attachment_add_itemlist_tooltip.ejs", {attach : attach}),
+                        position: {
+                            corner: {
+                                tooltip: 'bottomMiddle',
+                                target: 'topMiddle'
+                            },
+                            adjust: {
+                               resize: true,
+                               scroll: true,
+                               screen: true
+                            }
+                        },
+                        show: {
+                            when: 'mouseover', // Don't specify a show event
+                            ready: false // Show the tooltip when ready
+                        },
+                        hide: 'mouseout', // Don't specify a hide event
+                        style: {
+                            border: {
+                                width: 1,
+                                radius: 5
+                            },
+                            width: {
+								 min: 75,
+								 max : 1000
+							},
+                            padding: 3, 
+                            textAlign: 'left',
+                            tip: true, // Give it a speech bubble tip with automatic corner detection
+                            name: 'blue' // Style it according to the preset 'cream' style
+                        }
+                    });
 			}
 
@@ -2278,5 +2483,5 @@
             if((attachments[i].tagName=="SPAN") || (attachments[i].tagName=="IMG") || ((attachments[i].href.indexOf("javascript:download_local_attachment")==-1)&&(attachments[i].href.indexOf("javascript:download_attachments")==-1)))
                     continue;
-
+                fileUploadMSG.find(' .attachments-list').show();
                 var arrayAtt = attachments[i].href.replace("javascript:download_attachments(", "").replace(")", "").split(',');                                 
                 var att = new Object();
@@ -2290,41 +2495,75 @@
 
                 var attach = {};
+
                 attach.fileName =  attachments[i].text.substring(0, attachments[i].text.lastIndexOf('('));
-
-                if(attach.fileName.length > 45)
-                    attach.fileName = attach.fileName.substr(0, 32) + " ... " + attach.fileName.substr(attach.fileName.length-9, attach.fileName.length);
+                attach.fullFileName = attach.fileName;
+
+                if(attach.fileName.length > 20)
+                    attach.fileName = attach.fileName.substr(0, 17) + " ... " + attach.fileName.substr(attach.fileName.length-9, attach.fileName.length);
 
                 attach.fileSize =  attachments[i].text.substring(( attachments[i].text.lastIndexOf('(')+1), attachments[i].text.lastIndexOf(')'));
+                attach.error = false;
 
                 var upload = $(DataLayer.render("../prototype/modules/mail/templates/attachment_add_itemlist.ejs", {file : attach}));
-                upload.find('.status-upload').remove();
-                upload.find('.in-progress').remove(); 
-                upload.find('.button.close').button({
-                        icons: {
-                                primary: "ui-icon-close"
+                upload.find('.att-box-loading').remove(); 
+                upload.find('.att-box-delete').click(function(){
+                    var idAttach = $(this).parent().find('input[name="fileId[]"]').val();
+                    var content_body = RichTextEditor.getData('body_'+new_border_ID);
+                    var imagens = content_body.match(/<img[^>]*>/g);
+                    var att = JSON.parse(idAttach);
+                    if(imagens != null)
+                    {   
+                        for (var x = 0; x < imagens.length; x++)
+                            if(imagens[x].indexOf('src="./inc/get_archive.php?msgFolder='+att.folder+'&amp;msgNumber='+att.uid+'&amp;indexPart='+att.part) !== -1)
+                                content_body = content_body.replace(imagens[x],'');
+
+                         RichTextEditor.setData('body_'+new_border_ID,content_body);    
+                    }       
+
+                    fileUploadMSG.find(' .attachments-list').find('input[value="'+idAttach+'"]');
+                    delAttachment(new_border_ID,idAttach); 
+                    $(this).parent().qtip("destroy");
+                    $(this).parent().remove();
+                    if(!fileUploadMSG.find(' .attachments-list').find(".att-box").length){
+                        fileUploadMSG.find(' .attachments-list').hide();
+                    }
+                });	
+
+
+                upload.append('<input type="hidden" name="fileId[]" value=\''+idATT+'\'/>');
+                fileUploadMSG.find('.attachments-list').append(upload);
+                fileUploadMSG.find('.attachments-list .att-box:last').qtip({
+                    content: DataLayer.render("../prototype/modules/mail/templates/attachment_add_itemlist_tooltip.ejs", {attach : attach}),
+                    position: {
+                        corner: {
+                            tooltip: 'bottomMiddle',
+                            target: 'topMiddle'
                         },
-                        text: false
-                }).click(function(){
-                        var idAttach = $(this).parent().find('input[name="fileId[]"]').val();
-                        var content_body = RichTextEditor.getData('body_'+new_border_ID);
-                        var imagens = content_body.match(/<img[^>]*>/g);
-                        var att = JSON.parse(idAttach);
-                        if(imagens != null)
-                        {   
-                            for (var x = 0; x < imagens.length; x++)
-                                if(imagens[x].indexOf('src="./inc/get_archive.php?msgFolder='+att.folder+'&amp;msgNumber='+att.uid+'&amp;indexPart='+att.part) !== -1)
-                                    content_body = content_body.replace(imagens[x],'');
-
-                             RichTextEditor.setData('body_'+new_border_ID,content_body);    
-                        }       
-
-                        fileUploadMSG.find(' .attachments-list').find('input[value="'+idAttach+'"]');
-                        delAttachment(new_border_ID,idAttach); 
-                        $(this).parent().remove();
-                });	
-
-
-                upload.find("p").append('<input type="hidden" name="fileId[]" value=\''+idATT+'\'/>');
-                fileUploadMSG.find('.attachments-list').append(upload);
+                        adjust: {
+                           resize: true,
+                           scroll: true,
+                           screen: true
+                        }
+                    },
+                    show: {
+                        when: 'mouseover', // Don't specify a show event
+                        ready: false // Show the tooltip when ready
+                    },
+                    hide: 'mouseout', // Don't specify a hide event
+                    style: {
+                        border: {
+                            width: 1,
+                            radius: 5
+                        },
+                        width: {
+							 min: 75,
+							 max : 1000
+						},
+                        padding: 3, 
+                        textAlign: 'left',
+                        tip: true, // Give it a speech bubble tip with automatic corner detection
+                        name: 'blue' // Style it according to the preset 'cream' style
+                    }
+                });
 
     }	                
@@ -2482,4 +2721,10 @@
 				}
 			});
+			$.each(dynamicPersonalGroups, function(x, valuex){
+				if(valuex.email == $(value).find("input").val().match(reComplexEmail)[1]){
+					stop = true;
+					return false;
+				}
+			});
 			if(!stop){
 				var exist = 0;
@@ -2572,27 +2817,29 @@
 
 function send_message(ID, folder, folder_name){
-     if(!zebraDiscardEventDialog && $('#fileupload_msg'+ID).find('.in-progress').length )
-     {
-         zebraDiscardEventDialog = true;
-         window.setTimeout(function() {
-         $.Zebra_Dialog('Existem anexos sendo enviados para o servidor. Caso envie sua mensagem agora estes arquivos serão perdidos.', {
-                    'type':     'question',
-                    'overlay_opacity': '0.5',
-                    'buttons':  ['Descartar anexos e enviar', 'Continuar editando e esperar anexos'],
-                    'width' : 500,
-                    'onClose':  function(clicked) {
-                            if(clicked == 'Descartar anexos e enviar' ) 
-                              send_valided_message(ID, folder, folder_name);
-
-                            window.setTimeout(function() {
-                                    zebraDiscardEventDialog = false;
-                            }, 500);
+    if(!zebraDiscardEventDialog && $('#fileupload_msg'+ID).find('.att-box-loading').length )
+    {
+        zebraDiscardEventDialog = true;
+        window.setTimeout(function() {
+            $.Zebra_Dialog('Existem anexos sendo enviados para o servidor. Caso envie sua mensagem agora estes arquivos serão perdidos.', {
+                'type':     'question',
+                'overlay_opacity': '0.5',
+                'buttons':  ['Descartar anexos e enviar', 'Continuar editando e esperar anexos'],
+                'width' : 500,
+                'onClose':  function(clicked) {
+                    if(clicked == 'Descartar anexos e enviar' ){ 
+                        $.each($('#fileupload_msg'+ID).find('.att-box'), function(index, value){
+                            if($(value).find(".att-box-loading").length)
+                                $(value).find('.att-box-delete').trigger("click");
+                        });
+                        send_valided_message(ID, folder, folder_name);
                     }
-             })
-          }, 300); 
-
-     }
-     else
-       send_valided_message(ID, folder, folder_name);     
+                    window.setTimeout(function() {
+                        zebraDiscardEventDialog = false;
+                    }, 500);
+                }
+            })
+        }, 300); 
+    }else
+        send_valided_message(ID, folder, folder_name);     
 }
 
@@ -2695,43 +2942,52 @@
 	}
 	//stringEmail = content.find('[name="input_to"]').val();
+
+    var stringReply = "";
+    draw_email_box(content.find(".reply-to-tr").find("textarea:first").val(), content.find(".reply-to-tr").find("textarea:first"));
+    content.find(".reply-to-tr").find("textarea:first").val("");
+    var array = content.find(".reply-to-tr").find(".box");
+    $.each(array, function(index, value){
+        stringReply += $(value).find("input").val() + ",";
+    });
+    content.find('[name="input_reply_to"]').val(stringReply);
+
 	var stringEmail = "";
 	var stringToEmail = "";
-	draw_email_box(content.find(".to-tr").find("textarea:first").val(), content.find(".to-tr").find("textarea:first")); 
+	draw_email_box(content.find(".to-tr").find("textarea:first").val(), content.find(".to-tr").find("textarea:first"));
 	content.find(".to-tr").find("textarea:first").val("");
 	var array = content.find(".to-tr").find(".box");
 	$.each(array, function(index, value){
-		//stringEmail += $(value).find("input").val() + ","; 
- 	    stringToEmail += $(value).find("input").val() + ",";
+		//stringEmail += $(value).find("input").val() + ",";
+		stringToEmail += $(value).find("input").val() + ",";
 	});
-	content.find('[name="input_to"]').val(stringToEmail); 
- 	stringEmail = stringToEmail; 
- 	var stringCCoEmail = "";
+	content.find('[name="input_to"]').val(stringToEmail);
+	stringEmail = stringToEmail;
+	var stringCCoEmail = "";
 	if ( content.find('[name="input_cco"]').length){
 		if(content.find(".cco-tr").css("display") != "none"){
-			draw_email_box(content.find(".cco-tr").find("textarea:first").val(), content.find(".cco-tr").find("textarea:first")); 
+			draw_email_box(content.find(".cco-tr").find("textarea:first").val(), content.find(".cco-tr").find("textarea:first"));
 			content.find(".cco-tr").find("textarea:first").val("");
 			var array = content.find(".cco-tr").find(".box");
 			$.each(array, function(index, value){
-				//stringEmail += $(value).find("input").val() + ","; 
- 	            stringCCoEmail += $(value).find("input").val() + ","; 
+				//stringEmail += $(value).find("input").val() + ",";
+				stringCCoEmail += $(value).find("input").val() + ",";
 			});
-			content.find('[name="input_cco"]').val(stringCCoEmail); 
-	        } 
-	} 
-	stringEmail += stringCCoEmail; 
+			content.find('[name="input_cco"]').val(stringCCoEmail);
+		}
+	}
+	stringEmail += stringCCoEmail;
 	var stringCCEmail = "";		
 	if(content.find(".cc-tr").css("display") != "none")
 	{
-		draw_email_box(content.find(".cc-tr").find("textarea:first").val(), content.find(".cc-tr").find("textarea:first")); 
+		draw_email_box(content.find(".cc-tr").find("textarea:first").val(), content.find(".cc-tr").find("textarea:first"));
 		content.find(".cc-tr").find("textarea:first").val("");
 		var array = content.find(".cc-tr").find(".box");
 		$.each(array, function(index, value){
-			//stringEmail += $(value).find("input").val() + ","; 
- 	        stringCCEmail += $(value).find("input").val() + ",";
+			//stringEmail += $(value).find("input").val() + ",";
+			stringCCEmail += $(value).find("input").val() + ",";
 		});
-		content.find('[name="input_cc"]').val(stringCCEmail); 
- 	} 
- 	stringEmail +=  stringCCEmail;
-		
+		content.find('[name="input_cc"]').val(stringCCEmail);
+	}
+	stringEmail += 	stringCCEmail;
 	if (expresso_offline) {
 		
@@ -2752,18 +3008,18 @@
 	else{
 		if(stringEmail != ""){
-			$.ajax({                         
-                    url: "controller.php?", 
-                    success: function(data){ 
-                            cExecuteForm("$this.imap_functions.send_mail", form, handler_send_message, ID); 
-                    }, 
-                    error: function(){ 
-                            write_msg("Erro ao tentar enviar a mensagem. Nova tentativa em alguns segundos..."); 
-                            var interval = setInterval(function(){ 
-                                            send_valided_message(ID,folder,folder_name); 
-                                            clearInterval(interval); 
-                            },15000); 
-                            return; 
-                    } 
-            });
+			$.ajax({			
+				url: "controller.php?",
+				success: function(data){
+					cExecuteForm("$this.imap_functions.send_mail", form, handler_send_message, ID);
+				},
+				error: function(){
+					write_msg("Erro ao tentar enviar a mensagem. Nova tentativa em alguns segundos...");
+					var interval = setInterval(function(){
+							send_valided_message(ID,folder,folder_name);
+							clearInterval(interval);
+					},15000);
+					return;
+				}
+			});			
 		}else{
 			write_msg(get_lang("message without receiver"));
@@ -2853,4 +3109,12 @@
     var content = $("#content_id_"+border_id);
 	
+
+    var array = content.find(".reply-to-tr").find(".box");
+    var stringReplyToEmail = "";
+    $.each(array, function(index, value){
+        stringReplyToEmail += $(value).find("input").val() + ",";
+    });
+    content.find('[name="input_reply_to"]').val(stringReplyToEmail);
+
    	var stringEmail = "";
    	draw_email_box(content.find(".to-tr").find("textarea:first").val(), content.find(".to-tr").find("textarea:first")); 
@@ -3106,5 +3370,8 @@
 			  success: function( data ){
 			      data = connector.unserialize( data );
-			      
+
+			      selectAllFolderMsgs();
+			      $('.select-link').unbind('click');
+
 			      if( data )
 				  handler_set_messages_flag( data );
@@ -3206,5 +3473,4 @@
 		}
 	}
-
 	
 	var print_width = screen.width - 200; 
@@ -3422,5 +3688,10 @@
 }
 
-function empty_trash_imap(){
+function empty_trash_imap(shared, button){
+	if(shared){
+		var folder_part = $(button).parents("li:first").attr("id").split(cyrus_delimiter);
+		var folder = folder_part[0]+cyrus_delimiter+folder_part[1];
+	}
+
 	var handler_empty_trash = function(data){
 		Element('chk_box_select_all_messages').checked = false;
@@ -3433,4 +3704,10 @@
 		draw_tree_labels();
 		if (data){
+			if(typeof(data) == "object"){
+				if(data[1] == "Permission denied"){
+					cExecute("$this.imap_functions.get_folders_list&onload=true", update_menu);
+					return write_msg(get_lang("Permission denied"));
+				}
+			}
 			write_msg(get_lang('Your Trash folder was empty.'));
 			if (get_current_folder() == mount_url_folder(["INBOX",special_folders["Trash"]])){
@@ -3452,5 +3729,5 @@
 		'onClose':  function(caption) {
 			if(caption == get_lang("Yes")){
-				cExecute ("$this.imap_functions.empty_folder&clean_folder="+"imapDefaultTrashFolder", handler_empty_trash);
+				cExecute ("$this.imap_functions.empty_folder&clean_folder="+"imapDefaultTrashFolder"+(shared ? "&shared="+folder : ""), handler_empty_trash);
 			}
 		}
@@ -3458,5 +3735,9 @@
 }
 
-function empty_spam_imap(){
+function empty_spam_imap(shared, button){
+	if(shared){
+		var folder_part = $(button).parents("li:first").attr("id").split(cyrus_delimiter);
+		var folder = folder_part[0]+cyrus_delimiter+folder_part[1];
+	}
 	var handler_empty_spam = function(data){
 		Element('chk_box_select_all_messages').checked = false;
@@ -3472,6 +3753,16 @@
 		draw_tree_labels();
 		update_quota(get_current_folder());
-		if (data)
-			write_msg(get_lang('Your Spam folder was empty.'));
+		if (data){
+			if(typeof(data) == "object"){
+				if(data[1] == "Permission denied"){
+					cExecute("$this.imap_functions.get_folders_list&onload=true", update_menu);
+					return write_msg(get_lang("Permission denied"));
+				}else{
+					write_msg(get_lang('Your Spam folder was empty.'));		
+				}
+			}else{
+				write_msg(get_lang('Your Spam folder was empty.'));	
+			}
+		}
 		else
 			write_msg(get_lang('ERROR emptying your Spam folder.'));
@@ -3485,5 +3776,5 @@
 		'onClose':  function(caption) {
 			if(caption == get_lang("Yes")){
-				cExecute ("$this.imap_functions.empty_folder&clean_folder="+"imapDefaultSpamFolder", handler_empty_spam);
+				cExecute ("$this.imap_functions.empty_folder&clean_folder="+"imapDefaultSpamFolder"+(shared ? "&shared="+folder : ""), handler_empty_spam);
 			}
 		}
@@ -3524,8 +3815,8 @@
 		else{
 			var filename = 'mensagens.zip'; 
-			if (data.match(/\.eml$/gi)) { 
-	                        filename = 'fonte_da_mensagem.eml'; 
+			if (data[0].match(/\.eml$/gi)) { 
+                filename = data[1]+'.eml'; 
 			} 
-			download_attachments(null, null, data, null,null,filename);
+			download_attachments(null, null, data[0], null,null,filename); 
 		}
 	}
@@ -3621,4 +3912,8 @@
 		msgs_number = get_selected_messages();
 
+	//TODO: REFATORAR O CÓDIGO PARA EVITAR recodificação
+	if(currentTab == 0)
+		msgs_number = get_selected_messages();
+
 	if (parseInt(msgs_number) > 0 || msgs_number.length > 0)
 		cExecute ("$this.imap_functions.spam&folder="+folder+"&spam=false"+"&msgs_number="+msgs_number+"&border_ID="+border_ID+"&sort_box_type="+sort_box_type+"&sort_box_reverse="+sort_box_reverse+"&reuse_border="+border_ID+"&new_folder="+new_folder+"&new_folder_name="+new_folder_name+"&get_previous_msg="+0+"&cyrus_delimiter="+cyrus_delimiter, handler_move_msgs);
@@ -3658,4 +3953,8 @@
 		return;
 	}else if(msgs_number == 'selected')
+		msgs_number = get_selected_messages();
+
+	//TODO: REFATORAR O CÓDIGO PARA EVITAR recodificação
+	if(currentTab == 0)
 		msgs_number = get_selected_messages();
 
@@ -3733,13 +4032,13 @@
 							 	}
 							 }
-						], 
-	    open: function(event, ui)  
-	    { 
-	        if(typeof(shortcut) != 'undefined') shortcut.disabled = true;  
-	    }, 
-	    close: function(event, ui)  
-	    { 
-	        if(typeof(shortcut) != 'undefined') shortcut.disabled = false;  
-	    } 
+						],
+                open: function(event, ui) 
+                {
+                    if(typeof(shortcut) != 'undefined') shortcut.disabled = true; 
+                },
+                close: function(event, ui) 
+                {
+                    if(typeof(shortcut) != 'undefined') shortcut.disabled = false; 
+                }
 		});
 
@@ -3855,4 +4154,116 @@
 }
 
+//Normalização dos dados evita ter que reemplementar toda as funcionalidades do calendar
+function decodeCreateSchedulable(type, ID){
+	var startEvent = new Date();  
+	if(startEvent.toString('mm') < 30) 
+		startEvent.add({minutes: (30 - parseInt(startEvent.toString('mm')))}); 
+	else 
+		startEvent.add({hours: 1, minutes: '-'+startEvent.toString('mm')}); 
+	var endEvent = function(date){ 
+	if(!!User.preferences.defaultCalendar){ 
+		return  new Date(parseInt(date.getTime()) + 
+			(!!Calendar.signatureOf[User.preferences.defaultCalendar].calendar.defaultDuration ?  
+			(Calendar.signatureOf[User.preferences.defaultCalendar].calendar.defaultDuration * 60000) :
+			(User.preferences.defaultDuration * 60000)
+		));
+	}else 
+		return new Date(parseInt(date.getTime()) + (User.preferences.defaultDuration * 60000)); 
+	};       
+
+	var emails = $("#to_values_"+ID).val().split(',');
+	
+	var schedulable = {};
+	
+	schedulable = { 
+		acl: {inviteGuests: true, organization: true ,participationRequired: false, read: true, write: true},
+		alarms: [],
+		allDay: false,
+		attachments: [],
+		isAttendee: true,
+		attendee: '',//TODOOOOOO,
+		category: '',
+		'class': '1',
+		delegatedFrom: {},
+		endDate: startEvent.toString(User.preferences.dateFormat),
+		startDate: endEvent(startEvent).toString(User.preferences.dateFormat),
+		startHour: startEvent.toString(User.preferences.hourFormat),
+		endHour: endEvent(startEvent).toString(User.preferences.hourFormat),
+		timezone: User.preferences.defaultCalendar ? Calendar.signatureOf[User.preferences.defaultCalendar].calendar.timezone : User.preferences.timezone,
+		summary : $("#subject_"+ID).text(),
+		description : $("#body_" + ID).text(),
+		startTime: startEvent.getTime(),
+		endTime: endEvent(startEvent),
+		timezones: Timezone.timezones,
+		me: {name: User.me.name, mail: User.me.mail, acl: 'rowi', status: '1', delegatedFrom: '0', id: User.me.id},
+		organizer: {name: User.me.name, mail: User.me.mail, acl: 'rowi', status: '1', delegatedFrom: '0' , id: User.me.id},
+		statusParticipants: {accepted: 0, cancelled: 0, tentative: 0, unanswered:emails.length},
+		location: '',
+		attendee: $.map(emails, function( mail ){			
+			var contact = false;
+			var decoded =  Encoder.htmlDecode(mail);
+			var newAttendeeName = "";
+
+			var name = decoded.match(/"([^"]*)"/) ? decoded.match(/"([^"]*)"/)[1] : '';
+			var mail = decoded.match(/<([^<]*)>[\s]*$/) ? decoded.match(/<([^<]*)>[\s]*$/)[1].toLowerCase() : decoded; 
+
+
+			var user = DataLayer.get('user', ["=", "mail", mail], true);
+			
+			if( $.type(user) == "array" )
+				user = user[0];
+
+			if(user != ''){
+				//user = {name : name , mail : mail};
+				if(User.me.mail == user.mail)
+					return(null);
+				user.isExternal = (!!user && !(!!user.isExternal)) ? 0 : 1;
+
+				return  DataLayer.merge({
+					name: user.name,
+					mail: user.mail,
+					acl:  'r',
+					delegatedFrom: '0',
+					status: '4',
+					isExternal: user.isExternal
+				}, !!user.id ? {id : DataLayer.put('participant', {user: user.id, isExternal: user.isExternal})} : {id: DataLayer.put('participant', {user: user})}); 
+			}else if(mail.match(/[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])/)){
+				
+				var userId = DataLayer.put('user', {
+				name: name, 
+				mail: mail, 
+				isExternal: '1'
+				});
+				var newAttendeeId = DataLayer.put('participant', {
+				user: userId, 
+				isExternal: '1'
+				});
+
+				return  {
+					id: newAttendeeId,
+					name: name,
+					mail: mail,
+					acl:  'r',
+					delegatedFrom: '0',
+					status: '4',
+					isExternal: '1'
+				};
+				
+			}else
+				return (null);
+		})
+	};
+
+	schedulable  = DataLayer.merge(schedulable, 
+		type == 'event' ? 
+		{calendar: User.preferences.defaultCalendar ? User.preferences.defaultCalendar : Calendar.calendars[0], calendars: Calendar.calendars}
+		: {group: Calendar.groups[0].id, groups: Calendar.groups, percentage: 0, isOrganizer: true}
+	);
+	
+	return schedulable;
+	    
+
+}
+
 function import_implements_calendar(){
 
@@ -3868,7 +4279,9 @@
 		$.ajax({url: "../prototype/modules/calendar/js/map.disponibility.js", async: false, beforeSend: function( xhr ) {xhr.overrideMimeType('text/javascript; charset=ISO-8859-1')}});
 		$.ajax({url: "../prototype/modules/calendar/js/helpers.js", async: false, beforeSend: function( xhr ) {xhr.overrideMimeType('text/javascript; charset=ISO-8859-1')}});
+		$.ajax({url: "../prototype/modules/calendar/js/task.helpers.js", async: false, beforeSend: function( xhr ) {xhr.overrideMimeType('text/javascript; charset=ISO-8859-1')}});
 		//$.ajax({ url: "../prototype/modules/calendar/js/timezone.js", async: false});
 		//$.ajax({ url: "../prototype/modules/calendar/js/calendar.codecs.js", async: false});
 		$.ajax({url: "../prototype/plugins/encoder/encoder.js", async: false, beforeSend: function( xhr ) {xhr.overrideMimeType('text/javascript; charset=ISO-8859-1')}});
+		$.ajax({url: "../prototype/plugins/jquery.spinner/jquery.spinner.min.js", async: false, beforeSend: function( xhr ) {xhr.overrideMimeType('text/javascript; charset=ISO-8859-1')}});
 		//$.ajax({url: "../prototype/plugins/dateFormat/dateFormat.js", async: false, beforeSend: function( xhr ) { xhr.overrideMimeType('text/javascript; charset=ISO-8859-1')}});
 
@@ -3910,13 +4323,6 @@
 		wfolders.makeWindow('null','import');
 }
-function import_calendar(data){
-    var import_url = '$this.db_functions.import_vcard&msg_folder='+data;
-    var logUser;
-    var up;
-    var owner;
-    
     //Verifica o contexto de importação
-    var decodeOwner = function(){
-	
+    function decodeOwner(){
 	owner = User.me.id;
 	var imapBox = openTab.imapBox[currentTab].split(cyrus_delimiter);
@@ -3924,194 +4330,191 @@
 	    var user = DataLayer.get('user', {filter: ['=','uid',imapBox[1]]});		    
 	    owner = $.isArray(user) ? user[0].id : user.id;
-	}
-	
+	}	
 	return owner;
     }
+
+   function import_calendar(data){
+        var import_url = '$this.db_functions.import_vcard&msg_folder='+data;
+        var logUser;
+        var up;
+        var owner;
+
+        function handler_import_calendar(data){
+	    if(data === true){
+		write_msg(get_lang("The event was imported successfully."));
+	    }
+	    else if( data['url'] )
+	    {
+		var form = document.createElement( "form" );
+
+		form.setAttribute( "action", DEFAULT_URL + data['url'] + '&isPost=true' );
+		form.setAttribute( "method", "POST" );
+
+		document.body.appendChild( form );
+
+		form.submit();
+	    }
+	    else
+		write_msg(get_lang(data));
+        }   
+	if(defaultCalendar == "expressoCalendar" && $("#expressoCalendarid")[0]){
+	    import_implements_calendar();
+		$( "#import-dialog" ).dialog({
+		    autoOpen: false,
+		    height: 220,
+		    modal: true,
+		    resizable : false,
+		    open: function(event, ui) {
+			if(typeof(shortcut) != 'undefined') shortcut.disabled = true; 
+		    },
+		    close: function(event, ui){
+			event.stopPropagation();
+			if(typeof(shortcut) != 'undefined') shortcut.disabled = false; 
+		    },
+		    closeOnEscape: true
+		});
+                   
+		$.ajax({
+		    url: "controller.php?action="+import_url+'&from_ajax=true&id_user='+User.me.id+'&readable=true&cirus_delimiter='+cyrus_delimiter+'&analize=true&uidAccount='+decodeOwner(),
+		    async: false,
+		    success: function(data){
+			data = connector.unserialize(data);
+			var createDialog = function(typeImport, propaget){
+                                               
+			    if(typeof(typeImport) == "object"){
+				var calendarIds = !!typeImport.calendar ? typeImport.calendar : Calendar[typeImport.type];
+				typeImport = typeImport.action;
+			    }
+                                                   
+			    switch(parseInt(typeImport)){
+				case 1:
+				case 7:
+				case 10:
+				    $("#select-agenda").html('');
+
+				    var options = '';
+
+				    if(calendarIds){
+					for(var i = 0; i < calendarIds.length; i++)
+					    options += '<option value="'+calendarIds[i]+'">'+Calendar.signatureOf[calendarIds[i]].calendar.name+'</option>'
+				    }
+
+				    $("#select-agenda").append(options);
+				    $("#select-agenda").css("display", "block");
+
+				    $("#import-dialog" ).dialog({
+					buttons: {
+					    Cancel: function() {
+						$( this ).dialog( "close" );
+					    },
+					    "Importar" : function(){
+						    $.ajax({
+							url: "controller.php?action="+import_url+'&from_ajax=true&selected='+$("#select-agenda option:selected").val()+'&status='+$("#select-status option:selected").val()+'&uidAccount='+decodeOwner()+'&cirus_delimiter='+cyrus_delimiter,
+							success: function(msg){
+							    var alt = ( (msg = connector.unserialize(msg)) == "ok") ? "Importado com sucesso para " : "Ocorreu um erro ao importar o evento/tarefa para a agenda ";
+							    alert( alt + $("#select-agenda option:selected").text() );
+							}
+						    });
+						    $( this ).dialog( "close" );
+					    }
+					}
+				    });
     
-    function handler_import_calendar(data){
-            if(data === true){
-                    write_msg(get_lang("The event was imported successfully."));
-            }
-            else if( data['url'] )
-            {
-                var form = document.createElement( "form" );
-
-                form.setAttribute( "action", DEFAULT_URL + data['url'] + '&isPost=true' );
-                form.setAttribute( "method", "POST" );
-
-                document.body.appendChild( form );
-
-                form.submit();
-            }
-            else
-                write_msg(get_lang(data));
-    }	
-	if(defaultCalendar == "expressoCalendar" && $("#expressoCalendarid")[0]){
-		import_implements_calendar();
-		$( "#import-dialog" ).dialog({
-			autoOpen: false,
-			height: 220,
-			modal: true,
-			resizable : false,
-			open: function(event, ui)  
-            { 
-                if(typeof(shortcut) != 'undefined') shortcut.disabled = true;  
-            }, 
-            close: function(event, ui)  
-            { 
-                event.stopPropagation(); 
-                if(typeof(shortcut) != 'undefined') shortcut.disabled = false;  
-            },
-			closeOnEscape: true
-		});
-		
-		$.ajax({
-			url: "controller.php?action="+import_url+'&from_ajax=true&id_user='+User.me.id+'&readable=true&cirus_delimiter='+cyrus_delimiter+'&analize=true&uidAccount='+decodeOwner(),
-			async: false,
-			success: function(data){
-					data = connector.unserialize(data);
-
-
-					var createDialog = function(typeImport, propaget){
-					    
-						if(typeof(typeImport) == "object"){
-						    var calendarPermission = typeImport.calendar;
-						    typeImport = typeImport.action;
+				    if(typeImport == 7){
+					$("#import-dialog").find('#select-status option[value=1]').attr('selected','selected').trigger('change');
+					$("#import-dialog").find('#select-status').attr('disabled','disabled');
+				    }
+				    break;
+				case 3:
+				    $.ajax({
+					url: "controller.php?action="+import_url+'&from_ajax=true&selected=true',
+					success: function(msg){
+					    alert( ( ( connector.unserialize(msg)) == "ok") ? "Seu evento/tarefa foi removido " : "Ocorreu um erro ao remover o evento/tarefa" );
+					}
+				    });
+				    return;
+				    break; 
+				case 5:
+				    $.ajax({
+					url: 'controller.php?action='+import_url+'&from_ajax=true&selected=true&cirus_delimiter='+cyrus_delimiter,
+					success: function(msg){
+					    alert( ( ( connector.unserialize(msg)) == "ok") ? "Seu evento/tarefa foi Atualizado com sucesso" : "Ocorreu um erro ao atualizar evento/tarefa" );
+					}
+				    });
+				    return;
+				    break; 
+				case 6:
+					var acceptedSuggestion = confirm("Deseja atualizar o evento/tarefa de acordo com a sugestão ?");
+					$.ajax({
+					    url: "controller.php?action="+import_url+'&from_ajax=true&id_user='+User.me.id+'&selected=true&cirus_delimiter='+cyrus_delimiter+'&acceptedSuggestion='+acceptedSuggestion+"&from="+document.getElementById('from_values_'+currentTab).value+'&uidAccount='+decodeOwner(),
+					    success: function(msg){
+						if(acceptedSuggestion)
+						    alert( ( ( connector.unserialize(msg)) == "ok") ? "Evento/tarefa atualizado com sucesso " : "Ocorreu um erro ao atualizar o evento" );
 						}
-						
-						switch(parseInt(typeImport)){
-						case 1:
-						case 7:
-						case 10:
-						    $("#select-agenda").html('');
-
-						    var options = '';
-
-						    if(typeImport == 10){
-							for(var i = 0; i < calendarPermission.length; i++)
-							    options += '<option value="'+calendarPermission[i]+'">'+Calendar.signatureOf[calendarPermission[i]].calendar.name+'</option>'
-						    }else{
-							for(var id in Calendar.signatures)
-							   options += parseInt(Calendar.signatures[id].isOwner) ? '<option value="'+Calendar.signatures[id].calendar.id+'">'+Calendar.signatures[id].calendar.name+'</option>' : '';							
+					});
+					return;
+					break;
+					case 9:
+					    alert('Seu evento/tarefa não possui alterações!');
+					    return;
+					    break;
+					case 11:
+					    alert('Este evento/tarefa já fora importando por algum dos particpantes e já se encontra disponível em sua agenda compartilhada!');
+					    return;
+					    break;
+					default:
+					    up = true;
+					    $("#select-agenda").css("display", "none");
+					    $("#import-dialog" ).children("p:first-child").css("display", "none");
+					    $("#import-dialog" ).dialog({
+						height: 160,
+						title: 'Atualizar Evento/Tarefa',
+						buttons: {
+						    Cancel: function() {
+							$( this ).dialog( "close" );
+						    },
+						    "Atualizar": function() {
+							$.ajax({
+							    url: "controller.php?action="+import_url+'&from_ajax=true&cirus_delimiter='+cyrus_delimiter+'&selected='+ (parseInt(typeImport) == 2 || parseInt(typeImport) == 4 ? 'true' : $("#select-agenda option:selected").val()) +'&status='+$("#select-status option:selected").val()+'&uidAccount='+decodeOwner(),
+							    success: function(msg){
+								alert( ( (msg = connector.unserialize(msg)) == "ok") ? "Atualizado com sucesso" : "Ocorreu um erro ao atualizar o evento" );
+							    }
+							});
+							$( this ).dialog( "close" );
 						    }
-						    
-						    $("#select-agenda").append(options);
-						    $("#select-agenda").css("display", "block");
-						    
-						    $("#import-dialog" ).dialog({
-							buttons: {
-							    Cancel: function() {
-								$( this ).dialog( "close" );
-							    },
-							    "Importar" : function(){
-								    $.ajax({
-									url: "controller.php?action="+import_url+'&from_ajax=true&selected='+$("#select-agenda option:selected").val()+'&status='+$("#select-status option:selected").val()+'&uidAccount='+decodeOwner(),
-									success: function(msg){
-									    var alt = ( (msg = connector.unserialize(msg)) == "ok") ? "Importado com sucesso para " : "Ocorreu um erro ao importar o evento para a agenda ";
-									    alert( alt + $("#select-agenda option:selected").text() );
-									}
-								    });
-								    $( this ).dialog( "close" );
-							    }
-							}
-							});
-
-							if(typeImport == 7){
-							    $("#import-dialog").find('#select-status option[value=1]').attr('selected','selected').trigger('change');
-							    $("#import-dialog").find('#select-status').attr('disabled','disabled');
-							}
-						    break;
-						case 3:
-							$.ajax({
-								url: "controller.php?action="+import_url+'&from_ajax=true&selected=true',
-								success: function(msg){
-									alert( ( ( connector.unserialize(msg)) == "ok") ? "Seu evento foi removido " : "Ocorreu um erro ao remover o evento" );
-								}
-							});
-							return;
-							break;	
-						case 5:
-							$.ajax({
-								url: "controller.php?action="+import_url+'&from_ajax=true&selected=true',
-								success: function(msg){
-									alert( ( ( connector.unserialize(msg)) == "ok") ? "Seu evento foi Atualizado com sucesso" : "Ocorreu um erro ao atualizar evento" );
-								}
-							});
-							return;
-							break;	
-						case 6:
-							var acceptedSuggestion = confirm("Deseja atualizar o evento de acordo com a sugestão ?");
-							$.ajax({
-								url: "controller.php?action="+import_url+'&from_ajax=true&id_user='+User.me.id+'&selected=true&cirus_delimiter='+cyrus_delimiter+'&acceptedSuggestion='+acceptedSuggestion+"&from="+document.getElementById('from_values_'+currentTab).value+'&uidAccount='+decodeOwner(),
-								success: function(msg){
-									if(acceptedSuggestion)
-										alert( ( ( connector.unserialize(msg)) == "ok") ? "Evento atualizado com sucesso " : "Ocorreu um erro ao atualizar o evento" );
-								}
-							});
-							return;
-							break;
-						case 9:
-							alert('Seu evento não possui alterações!');
-							return;
-							break;
-						case 11:
-							alert('Este evento já fora importando por algum dos particpantes e já se encontra disponível em sua agenda compartilhada!');
-							return;
-							break;
-						default:
-							up = true;
-							$("#select-agenda").css("display", "none");
-							$("#import-dialog" ).children("p:first-child").css("display", "none");
-							$("#import-dialog" ).dialog({
-								height: 160,
-								title: 'Atualizar Evento',
-								buttons: {
-									Cancel: function() {
-										$( this ).dialog( "close" );
-									},
-								   "Atualizar": function() {
-										
-										$.ajax({
-											 url: "controller.php?action="+import_url+'&from_ajax=true&cirus_delimiter='+cyrus_delimiter+'&selected='+ (parseInt(typeImport) == 2 || parseInt(typeImport) == 4 ? 'true' : $("#select-agenda option:selected").val()) +'&status='+$("#select-status option:selected").val()+'&uidAccount='+decodeOwner(),
-											 success: function(msg){
-													alert( ( (msg = connector.unserialize(msg)) == "ok") ? "Atualizado com sucesso para " : "Ocorreu um erro ao atualizar o evento" );
-											}
-										});
-										$( this ).dialog( "close" );
-									}
-								}, 
-						    close:function(event, ui)  
-						    { 
-						        if(typeof(shortcut) != 'undefined') shortcut.disabled = false;  
-						    }, 
-						    open: function(event, ui)  
-						    { 
-						        if(typeof(shortcut) != 'undefined') shortcut.disabled = true;  
-						    } 
-							});
-							$(".ui-dialog-buttonpane").find(".ui-button:last").children().html("Atualizar");
+						},
+						close:function(event, ui) 
+						{
+						    if(typeof(shortcut) != 'undefined') shortcut.disabled = false; 
+						},
+						open: function(event, ui) 
+						{
+						    if(typeof(shortcut) != 'undefined') shortcut.disabled = true; 
 						}
-						$( "#import-dialog" ).dialog( "open" );	
-																
-					};
-					createDialog(data, true);
-                                
-                },
-                beforeSend: function( jqXHR, settings ){
-				  	connector.showProgressBar();
-				},
-				complete: function( jqXHR, settings ){
-				  	connector.hideProgressBar();
-				}
-            });
-			
-		}
-		else
-		{
-		    if(confirm(get_lang("Do you confirm this import to your Calendar?"))){
-			cExecute( import_url + "&from_ajax=true", handler_import_calendar);
-		    }
-		}
-}
+					    });
+					    $(".ui-dialog-buttonpane").find(".ui-button:last").children().html("Atualizar");
+				    }
+				    $( "#import-dialog" ).dialog( "open" );
+                                                                                                                                   
+				};
+				createDialog(data, true);
+                                   
+			    },
+			    beforeSend: function( jqXHR, settings ){
+				connector.showProgressBar();
+			    },
+			    complete: function( jqXHR, settings ){
+				connector.hideProgressBar();
+			    }
+			});    
+                    }
+                    else
+                    {
+                        if(confirm(get_lang("Do you confirm this import to your Calendar?"))){
+                            cExecute( import_url + "&from_ajax=true", handler_import_calendar);
+                        }
+                    }
+    }
+    
 function open_msg_part(data){
 	var handler_open_msg_part = function (data)
@@ -4193,4 +4596,13 @@
 
 function create_new_folder(name_folder, base_path){
+	//Limit reached folders
+	if(preferences.imap_max_folders){
+		if(cp_tree1.length == parseInt(preferences.imap_max_folders)){
+			$(".folders-loading").removeClass("folders-loading");
+			cExecute("$this.imap_functions.get_folders_list&onload=true", update_menu);
+			return write_msg(get_lang("Limit reached folders"));
+		}
+	}
+	
 	$.ajax({
 		url : "controller.php?action=$this.imap_functions.create_mailbox",
@@ -4202,4 +4614,8 @@
 			if(data == "Mailbox already exists"){
 				write_msg(get_lang("Mailbox already exists"));
+			}else if(data.substring(data.indexOf("Permission"), data.length) == "Permission denied"){
+				$(".folders-loading").removeClass("folders-loading");
+				cExecute("$this.imap_functions.get_folders_list&onload=true", update_menu);
+				return write_msg(get_lang("Permission denied"));
 			}
 			cExecute("$this.imap_functions.get_folders_list&onload=true", update_menu);
@@ -4336,4 +4752,33 @@
 }
 
+/*
+* @author Marcos Luiz Wilhelm (marcoswilhelm@gmail.com)
+* @date 2012/07/17
+* @brief Break out emails only with comma out of quote marks
+*/
+function break_comma (originalText){
+	var quotesMarks = false;
+	var completeString = "";
+	var brokenEmails = new Array();
+	originalText+=",";
+	for(i=0; i<originalText.length; i++){
+		var character = originalText.substr(i,1);
+		if(character == "\""){
+			quotesMarks = !quotesMarks;
+		}
+		if(!quotesMarks){
+			if(character == ","){
+				brokenEmails.push(completeString);
+				completeString = "";
+			}
+			else
+				completeString+=character;	
+		}
+		else
+			completeString+=character;
+	}
+	return brokenEmails;
+}
+
 DataLayer.links('message');
 DataLayer.poll('message',30);
