Index: branches/2.4/expressoMail1_2/js/draw_api.js
===================================================================
--- branches/2.4/expressoMail1_2/js/draw_api.js	(revision 6732)
+++ branches/2.4/expressoMail1_2/js/draw_api.js	(revision 6754)
@@ -8,6 +8,11 @@
  * formatação, etc.) 
  */
+ 
+focusIn = "";
+canMakeBox = true;
+fastSearch = false;
+
 onceOpenedHeadersMessages = {};
-
+var cache = new Array();
 var openTab = {
 	'type' : [], // 8 types of tabs, further info. see expressolivre.org/dev/wiki/mail/Documentacao
@@ -891,6 +896,6 @@
 	var _mouse_out;
 	var _cell;
-	var colGroupMain = document.getElementById("colgroup_main_"+numBox); 
- 	var colGroupHead = document.getElementById("colgroup_head_"+numBox);
+	var colGroupMain = document.getElementById("colgroup_main_"+numBox);
+	var colGroupHead = document.getElementById("colgroup_head_"+numBox);
 	for (var r=0;r<trM.length;r++) {
 		for (var c=0;c<trM[r].cells.length;c++) {
@@ -899,7 +904,7 @@
 			if (is_mozilla && !is_webkit) {
 				if (!emptyBody) {
-					colGroupMain.childNodes[c].setAttribute("width",colSizes[tbl][c]); 
+					colGroupMain.childNodes[c].setAttribute("width",colSizes[tbl][c]);
 				}
-				colGroupHead.childNodes[c].setAttribute("width",colSizes[tbl][c]); 
+				colGroupHead.childNodes[c].setAttribute("width",colSizes[tbl][c]);
 				if (tbH.rows[0].cells[c].className=="th_resizable") {
 					// lots of stupid fixes for FF to redraw cell content
@@ -929,12 +934,12 @@
 		document.getElementById("colgroup_main_"+numBox).childNodes[c].setAttribute("width",colSizes[tbl][c]);
 
-} 
- 	if (is_webkit || is_ie){ 
- 	                var arrHeader = $('.message_header td'); 
- 	                var arrBody = $('#tbody_box :first td'); 
- 	                for(i=0;i<arrHeader.length;i++){ 
+	}
+	if (is_webkit || is_ie){
+			var arrHeader = $('.message_header td');
+			var arrBody = $('#tbody_box :first td');
+			for(i=0;i<arrHeader.length;i++){
 					if(arrBody[i] !== undefined && arrBody[i].width !== undefined)
- 	                                arrHeader[i].width = arrBody[i].width; 
- 	                } 
+					arrHeader[i].width = arrBody[i].width;
+			}			
 	}
 }
@@ -1506,5 +1511,5 @@
 		if ((headers_msgs.Forwarded == 'F')  || (headers_msgs.Draft == 'X' && headers_msgs.Answered == 'A')){
 			td_element21.onclick=function(){search_emails(headers_msgs.subject.replace(/^(re: ?|fw: ?|enc: ?|res: ?|fwd: ?)*/gi,''),true);};
-                        td_element21.innerHTML = "<img src ='templates/"+template+"/images/forwarded.gif' title='"+get_lang('Forwarded')+"'>";
+                        td_element21.innerHTML = "<img src ='templates/"+template+"/images/forwarded.png' title='"+get_lang('Forwarded')+"'>";
 			headers_msgs.Draft = ''
 			headers_msgs.Answered = '';
@@ -1512,8 +1517,8 @@
 		}
 		else if (headers_msgs.Draft == 'X')
-			td_element21.innerHTML = "<img src ='templates/"+template+"/images/draft.gif' title='"+get_lang('Draft')+"'>";
+			td_element21.innerHTML = "<img src ='templates/"+template+"/images/draft.png' title='"+get_lang('Draft')+"'>";
 		else if (headers_msgs.Answered == 'A'){
                         td_element21.onclick=function(){search_emails(headers_msgs.subject.replace(/^(re: ?|fw: ?|enc: ?|res: ?|fwd: ?)*/gi,''),true);};
-			td_element21.innerHTML = "<img src ='templates/"+template+"/images/answered.gif' title='"+get_lang('Answered')+"'>";
+			td_element21.innerHTML = "<img src ='templates/"+template+"/images/answered.png' title='"+get_lang('Answered')+"'>";
                     }else
 			td_element21.innerHTML = "&nbsp;&nbsp;&nbsp;";
@@ -1764,13 +1769,14 @@
 					.html('<img src="../prototype/modules/mail/img/flagEditor.png">');
 					
-					if(fail != 'success'){ 
-                                            $('#td_message_followup_' + messageClickedId + ', ' +  
-                                            'tr[role="'+messageClickedId+'_'+msg_folder+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited").css("background", "#CCCCCC"); 
-                                            MsgsCallbackFollowupflag[fail](); 
-                                        }else{ 
-                                            $('#td_message_followup_' + messageClickedId + ', ' +  
-                                            'tr[role="'+messageClickedId+'_'+msg_folder+'"] #td_message_followup_search_' + messageClickedId).attr('title', get_lang('Follow up')).find(".flag-edited").css("background", headers_msgs.followupflagged.backgroundColor); 
-                                            updateCacheFollowupflag(messageClickedId, msg_folder, true); 
-                                        } 
+					
+					if(fail != 'success'){
+					    $('#td_message_followup_' + messageClickedId + ', ' + 
+					    'tr[role="'+messageClickedId+'_'+msg_folder+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited").css("background", "#CCCCCC");
+					    MsgsCallbackFollowupflag[fail]();
+					}else{
+					    $('#td_message_followup_' + messageClickedId + ', ' + 
+					    'tr[role="'+messageClickedId+'_'+msg_folder+'"] #td_message_followup_search_' + messageClickedId).attr('title', get_lang('Follow up')).find(".flag-edited").css("background", headers_msgs.followupflagged.backgroundColor);
+					    updateCacheFollowupflag(messageClickedId, msg_folder, true);
+					}				
 				});
 				
@@ -1982,4 +1988,13 @@
 var msg_selected;
 function draw_message(info_msg, ID){
+	// remove a flag $FilteredMessage da mensagem ao ser lida
+	if(info_msg.Unseen == "U"){
+		$.each(fromRules, function(index, value) {
+			if(value == info_msg.msg_folder){
+				cExecute ("$this.imap_functions.removeFlagMessagesFilter&folder="+info_msg.msg_folder+"&msg_number="+info_msg.msg_number, function(){}); 
+				return false;
+			}
+		});
+	}
 	var content = document.getElementById('content_id_' + ID);
 
@@ -3033,51 +3048,51 @@
 						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);
+						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);
+						    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);
 					})	
 					
@@ -3508,5 +3523,5 @@
 	resizeWindow(); 
 	
-	$("#div_message_scroll_"+ID).scrollTo( 0, 400, {queue:true} ); 
+	$("#div_message_scroll_"+ID).scrollTo( 0, 400, {queue:true} );
 }
  
@@ -3559,54 +3574,603 @@
 }
 
-function input_binds(input, ID){
-	var mySource = new Array();
-	var myArray = contacts.split(",");
-	for(var i in myArray){
-		var teste = myArray[i].split(";");
-		if(teste.length > 1)
-			mySource.push({name : teste[0], email: teste[1], value : (teste[0] +" - "+teste[1])});
-		else
-			mySource.push({name : "", email: teste[0], value :teste[0]});
-	}
-	input.bind( "keydown", function( event ) {
-		if ( event.keyCode === $.ui.keyCode.TAB && $( this ).data( "autocomplete" ).menu.active ) {
-			event.preventDefault();
-		}
-		if((event.keyCode) == 120){
+//DESENHO DAS CAIXA DE EMAIL
+function draw_email_box(input_data, location, personal, shared){
+	if($.trim(input_data) != ""){
+		var box_data = valid_emails(input_data);
+		DataLayer.render("../prototype/modules/mail/templates/emailBox.ejs", box_data, function(html){
+			var newBox = location.before(html).prev();
+			box_actions(newBox);
+			if((preferences.expressoMail_ldap_identifier_recipient || personal)&& $(newBox).hasClass("invalid-email-box")){
+				//$(newBox).find(".loading").css("background-image", "../prototype/modules/mail/img/ajax-loader.gif");
+				show_detais(newBox, input_data, personal, shared);
+			}else{
+				$(newBox).find(".box-loading").remove();
+			}
+		});
+	}
+}
+
+function valid_emails(email){
+	var ContactBox = {name:"", email:"", valid : false};
+	var reSimpleEmail = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[_a-z0-9-]+(\.[_a-z0-9-]+)+$/;
+	var reComplexEmail = /<([^<]*)>[\s]*$/;
+	var validation = email.split('"');
+	
+	//FUNÇÃO QUE VALIDA OS DADOS QUANDO O EMAIL É DIGITADO COM ("NOME SOBRENOME" <Email@dominio.com>)
+	var complexValidation = function(complexMail){
+		var Objct = {};
+		if($.trim(complexMail[1]).match(reComplexEmail)){
+			if($.trim(complexMail[1]).match(reComplexEmail).length){
+				Objct['email'] = $.trim(complexMail[1]).match(reComplexEmail)[1];
+			}
+		}else{
+			Objct['email'] = $.trim(complexMail[1]);
+		}
+		Objct['name'] = complexMail[0];
+		Objct['valid'] = reSimpleEmail.test(Objct['email'].toLowerCase());
+		return Objct;
+	}
+	switch (validation.length) {
+		//PEGA TODO O CONTEUDO E SETA COMO SE FOSSE O EMAIL
+		case 1:
+			validation.unshift("");
+			ContactBox = complexValidation(validation);
+			break;
+		//CORRIGI ERRO DE DIGITAÇÃO COMO ( huahua"<huhau@hauhau.com>) ou (hahahaha"huahua@email.com) ou ainda (hahahaha"huahua@ema  il.com)
+		case 2: 
+			ContactBox = complexValidation(validation);
+			break;
+		//RECEBE O EMAIL CORRETAMENTE SÓ VALIDA POSSIVEIS ERROS COMO O DE CIMA E OS CORRIGI CASO ACONTEÇAM
+		case 3:
+			//RETIRA O PRIMEIRO INDICE QUE FICOU "INUTIL"
+			validation.shift();
+			ContactBox = complexValidation(validation);
+			break;
+		//SE EXISTIREM MAIS DO QUE 2 (")
+		default:
+			if($.trim(validation[validation.length-1]).match(reComplexEmail)){
+				if($.trim(validation[validation.length-1]).match(reComplexEmail).length){
+					ContactBox.mail = $.trim(validation[validation.length-1]).match(reComplexEmail)[1];
+				}
+			}else{
+				ContactBox.mail = $.trim(complexMail[1]);
+			}
+			ContactBox.valid = reSimpleEmail.test(ContactBox.mail.toLowerCase());	
+	}
+	return ContactBox;
+}
+
+//EVENTO DOS INPUTS PARA - CC - CCO
+function input_keydowns(input, ID){
+	var f9 = false;
+	input.keydown(function(e){
+		f9 = false;
+		focusIn = input;
+		var focusing = input.parent().find(".email-text");
+		//SE OS CONTATOS DINAMICOS ESTAO ATIVOS
+		if(parseInt(preferences.use_dynamic_contacts) && !input.hasClass("box-input")){
+			//SELECIONA O CONTATO E EVITA OUTROS COMANDOS
+			if ( e.keyCode === $.ui.keyCode.TAB && $( this ).data( "catcomplete" ).menu.active ) {
+				e.preventDefault();
+				return false;
+			}		
+			
+			//FECHA OS CONTATOS DINÂMICOS
+			if( (e.keyCode == 27) && $( this ).data( "catcomplete" ).menu.active ){
+				   e.stopPropagation();
+				   e.preventDefault();
+			}
+			
+			//SELECIONA O CONTATO E EVITA OUTROS COMANDOS
+			if(e.keyCode == $.ui.keyCode.ENTER && $( this ).data( "catcomplete" ).menu.active){
+				e.preventDefault();
+				return false;
+			}
+			
+			if(e.keyCode == $.ui.keyCode.DELETE && $( this ).data( "catcomplete" ).menu.active){
+				if($($( this ).data( "catcomplete" ).menu.element).find(".ui-state-hover").parents("li:first").hasClass("dynamic-recent"))
+					$($( this ).data( "catcomplete" ).menu.element).find(".ui-state-hover").next().trigger("click");
+				return false;
+			}
+		}
+		//BUSCA COM A TECLA F9
+		if((e.keyCode) == 120){
+			f9 = true;
 			emQuickSearch($(this).val(), "."+$(this).parents("tr:first").attr('class').split("-")[0], ID, undefined, true);
-		}else if( (event.keyCode == 27) && $( this ).data( "autocomplete" ).menu.active ){
-			   event.stopPropagation();
-               event.preventDefault();
-		}
-	}).autocomplete({
-		minLength: 0,			
-		source: function( request, response ) {
-			response( $.ui.autocomplete.filter(
-				mySource, extractLast( request.term ) ) );
+			e.preventDefault();
+			return false;
+		}
+
+		//AO DIGITAR ENTER, ";", "," "	"
+		if(e.keyCode == 13 || e.keyCode == 9 || (e.keyCode == 188 && !e.shiftKey) || (e.keyCode == 191 && !e.shiftKey) ){
+			if(e.keyCode == 13){
+				e.preventDefault();
+			}
+			if(input.val() != ""){
+				if(e.keyCode != 9)
+					e.preventDefault();
+				draw_email_box(input.val(), input);
+				if(input.hasClass("box-input")){
+					input.remove();
+					focusing.focus();
+					return;
+				}
+			}
+			if(input.length)
+				input.val("");
+		}
+		if((e.keyCode == 8 || e.keyCode == 37) && input.val() == "" && input.prev().hasClass("box")){
+			e.preventDefault();
+			input.prev().focus();
+			return;
+		}
+		//AO DIGITAR " "
+		if(e.keyCode == 32){
+			if(!input.val().length){
+				e.preventDefault();
+				return;
+			}else{
+				var texto = input.val();
+				texto = texto.substring(0, getPosition(input[0]));
+				if(texto.split('"').length-1 == 0){
+					if(input.val().split('"').length-1 == 0){
+						e.preventDefault();
+						e.stopPropagation();
+						draw_email_box(input.val(), input);
+						input.val("");
+						if(input.hasClass("box-input")){
+							input.remove();
+							focusing.focus();
+							return;
+						}
+						return;
+					}
+				}
+			}
+		}
+		//AO DIGITAR ">"
+		if(e.keyCode == 190 && e.shiftKey && input.val().length == getPosition(input[0])){
+			input.val(input.val()+">");
+			draw_email_box(input.val(), input);
+			e.preventDefault();
+			input.val("");
+			if(input.hasClass("box-input")){
+				input.remove();
+				focusing.focus();
+				return;
+			}
+		}
+		setTimeout(function(){
+			if(input.val()[input.val().length-1] == ";"){
+				draw_email_box(input.val().substring(0, input.val().length-1), input);
+				input.val("");
+			}
+		}, 100);
+		//INPUT AUTO RESIZE	
+		setTimeout(function(){
+			input_search = $(input).val();
+			var char = input.val().charAt(input.val().length-1);
+			var maiusculas = RegExp("[A-Z]");
+			/*Se o ultimo caracter for ">" é porque o campo está sendo editado (a partir de duplo clique)*/
+			var tamanho = 0;
+			if(char == ">"){
+				/*Faz um calculo prévio do tamanho do campo de acordo com o tamanho de cada caracter da string*/
+				for(i=0; i<input.val().length; i++){
+					/*Se o caracter for maiúsculo, o valor de pixel é maior*/
+					if(maiusculas.test(input.val().substr(i, 1)) == true){
+						tamanho += 9;
+					}
+					else{
+						tamanho += 7.1;
+					}
+				}
+				input.css("width", tamanho);
+			}
+			/*Ao inserir novo contato, não existe a necessidade de calcular tamanho do campo*/
+			else{
+				input.css("width", 15+(input.val().length * 9));
+			}
+			input.parent().scrollTo(":last");	
+		}, 100);
+	})
+	//AO SAIR DO FOCO MONTAGEM DA CAIXA DE EMAIL
+	.focusout(function(e){
+		var these = $(this);
+		
+		// Função para monstar a caixinha de e-mail.
+		function makeBoxMail(){
+			if(canMakeBox && !fastSearch){
+				if(!(	f9	||	click	||	$(this).parents("tr:first").find("button").hasClass("ui-state-active")	)){
+					if($(input).val() != "")
+						draw_email_box(input.val(), input);
+					if(input.hasClass("box-input"))
+						input.remove();
+					$(input).val("");
+					input_search = "";
+				}
+				f9 = false;
+				click = false;
+			}
+			canMakeBox = true;
+			fastSearch = false;
+		}
+		
+		/*
+		 ** Verifica se o dynamic contact esta aberto ou fechado, caso esteja aberto, 
+		 ** demora 250 millisegundos para executar a função makeBoxMail.
+		 */
+		these.data('is_open') ? setTimeout(makeBoxMail,250) : makeBoxMail();
+	})
+	//AO COLAR UM TEXTO NO CAMPO
+	.bind("paste", function(e){
+		$(this).trigger("keydown");
+		var pthis = $(this);
+		setTimeout(function() {
+			var str = pthis.val().replace(/[,;\t\n]/gi, ",");
+			str = str.split(",");
+			$.each(str, function(index, value){
+				draw_email_box(value, pthis);
+			});
+			pthis.val("");
+		}, 50);
+	});
+	//SE FOR EDIÇÃO DE EMAILS RECALCULA O INPUT E SETA O FOCO
+	if(input.hasClass("box-input")){
+		input.trigger("keydown");
+		input.focus();
+	}
+}
+var input_search = "";
+var click = false;
+//EVENTOS DA CAIXA
+function box_actions(box){
+	//AO PRESSIONAR UMA TECLA COM A CAIXA SELECIONADA	
+	box.keydown(function(e){
+		switch (e.keyCode) {
+			case $.ui.keyCode.LEFT:
+				//VERIFICA SE EXISTE ALGUMA CAIXA A ESQUERDA
+				if($(this).prev().hasClass("box"))
+					$(this).removeClass("box-selected").prev().focus();
+				break;
+			case $.ui.keyCode.RIGHT:
+				//VERIFICA SE EXISTE ALGUMA CAIXA A DIREITA 
+				if($(this).next().hasClass("box"))
+					$(this).removeClass("box-selected").next().focus();
+				//SENAO FOCO O INPUT DO EMAIL
+				else
+					$(this).removeClass("box-selected").next().focus();
+				break;
+			case $.ui.keyCode.HOME:
+				//SELECIONO A PRIMEIRA CAIXA
+				e.preventDefault();
+				$(this).parents(".email-area").find("div:first").focus();
+				break;
+			case $.ui.keyCode.END:
+				//SELECIONO A ULTIMA CAIXA
+				e.preventDefault();
+				$(this).parents(".email-area").find("div:last").focus();
+				break;
+			case $.ui.keyCode.DELETE:
+				//VERIFICA SE EXISTE ALGUMA CAIXA A DIREITA
+				if($(this).next().hasClass("box"))
+					$(this).next().focus();
+				//SENAO FOCO O INPUT DO EMAIL
+				else
+					$(this).next().focus();
+				//REMOVO ESTA CAIXA
+				$(this).remove();
+				break;
+			case $.ui.keyCode.BACKSPACE:
+				//VERIFICA SE EXISTE ALGUMA CAIXA A ESQUERDA
+				if($(this).prev().hasClass("box"))
+					$(this).removeClass("box-selected").prev().focus();
+				//SENAO HOUVER VERIFICA SE EXISTE ALGUMA CAIXA A DIREITA
+				else if($(this).next().hasClass("box"))
+					$(this).next().focus();
+				//SENAO HOUVER NEM A DIREITA NEM A ESQUERDA SETO O FOCO NO INPUT DO EMAIL
+				else
+					$(this).next().focus();
+				//REMOVO ESTA CAIXA	
+				$(this).remove();
+				e.preventDefault();
+				break;
+			case $.ui.keyCode.ENTER:
+				e.preventDefault();
+				$(this).trigger("dblclick");
+				break;
+		}
+	})
+	//AO FAZER UM DUPLO CLICK NA CAIXA
+	.dblclick(function(e){
+		var input = $(this).find("input").clone();
+		input.css("display" , "inline-block");
+		$(this).before(input);
+		input_keydowns(input, currentTab);
+		$(this).remove();
+	//CLICK SIMPLES NA CAIXA
+	}).click(function(){
+		$(this).focus();
+	//AO DAR O FOCO NA CAIXA
+	}).focus(function(){
+		$(this).parent().find("div").removeClass("box-selected");
+		$(this).addClass("box-selected");
+	}).focusout(function(){
+		$(this).removeClass("box-selected");
+	}).draggable({
+		revert: 'invalid',
+		helper : 'clone',
+		stack: "body",
+		containment : ".new-msg-head-data",
+		start: function(e, ui){
+			$(this).parent().droppable( "disable" );
 		},
-		focus: function() {
-			return false;
-		},
-		select: function( event, ui ) {
-			var terms = mySplit( this.value );
-			terms.pop();
-			terms.push( (ui.item.name != "" ? "\""+ui.item.name+"\" " : "") + (ui.item.email ? "<"+ui.item.email+">" : ""));
-			terms.push( "" );
-			this.value = terms.join( ", " );
-			return false;
-		},
-		autoFocus: true
-	}).data( "autocomplete" )._renderItem = function( ul, item ) {
-		ul.css({"max-height" : "115px", "overflow-y" : "auto"});
-		if( $(ul).find("li").length > 10 ){
+		stop : function(e, ui){
+			$(this).parent().droppable( "enable" );
+		}
+	});
+}
+
+//MOSTRA OS DETALHES DAS CAIXA DE EMAIL NOS CAMPOS PARA - CC - CCO
+function show_detais(box, value, personal, shared){
+	var ldap_id = preferences.expressoMail_ldap_identifier_recipient;
+	var group = (personal != undefined ? (personal == "G" ? true : false) : false);
+	shared = shared ? shared : false;
+	if(group){
+		REST.get("/"+ (shared ? "shared" : "") +"group/"+value, {}, function(data){
+			if(!data.error){
+				if(data.collection.error)
+					box.find(".box-loading").remove();
+				else{
+					box.find(".box-loading").removeClass("box-loading").addClass("box-info");
+					box.addClass("box-"+value).removeClass("invalid-email-box");
+					loadGroupBox(data.collection, ".box-"+value);
+					box.unbind("dblclick").bind("dblclick", function(e){
+						new $.Zebra_Dialog(get_lang("Impossible editing this contact, but it's possible to remove it"), {
+							'buttons':  false,
+							'modal': false,
+							'position': ['right - 20', 'top + 20'],
+							'auto_close': 3000
+						});
+					}).find(".box-input").val("\""+data.collection.data[1].value+"\" <"+data.collection.data[1].value+">");
+					box.find(".email-box-value").html( (data.collection.data[1].value.length > 18 ? data.collection.data[1].value.substring(0, 15)+"...": data.collection.data[1].value))
+				}
+			}else{
+				box.find(".box-loading").remove();
+			}
+		});
+		return;
+	}
+	
+	if(personal){
+		REST.get("/"+ (shared ? "shared" : "") +"contact/"+value, {}, function(data){
+			if(!data.error){
+				if(data.collection.error)
+					box.find(".box-loading").remove();
+				else{
+					box.find(".box-loading").removeClass("box-loading").addClass("box-info");
+					box.addClass("box-"+value).removeClass("invalid-email-box");
+					loadExtraLDAPBox(data.collection.data, ".box-"+value);
+					box.unbind("dblclick").bind("dblclick", function(e){
+						new $.Zebra_Dialog(get_lang("Impossible editing this contact, but it's possible to remove it"), {
+							'buttons':  false,
+							'modal': false,
+							'position': ['right - 20', 'top + 20'],
+							'auto_close': 3000
+						});
+					}).find(".box-input").val("\""+data.collection.data[0].value+"\" <"+data.collection.data[1].value+">");
+					box.find(".email-box-value").html( (data.collection.data[0].value.length > 18 ? data.collection.data[0].value.substring(0, 15)+"...": data.collection.data[0].value))
+				}
+			}else{
+				box.find(".box-loading").remove();
+			}
+		});
+		return;
+	}
+	
+	REST.get("/usersldap", {field : ldap_id,value: value}, function(data){
+		if(!data.error){
+			if(data.collection.error)
+				box.find(".box-loading").remove();
+			else{
+				box.find(".box-loading").removeClass("box-loading").addClass("box-info");
+				box.addClass("box-"+value).removeClass("invalid-email-box");
+				loadExtraLDAPBox(data.collection.itens[0].data, ".box-"+value);
+				box.unbind("dblclick").bind("dblclick", function(e){
+					new $.Zebra_Dialog(get_lang("Impossible editing this contact, but it's possible to remove it"), {
+						'buttons':  false,
+						'modal': false,
+						'position': ['right - 20', 'top + 20'],
+						'auto_close': 3000
+					});
+				}).find(".box-input").val("\""+data.collection.itens[0].data[0].value+"\" <"+data.collection.itens[0].data[1].value+">");
+				box.find(".email-box-value").html( (data.collection.itens[0].data[0].value.length > 18 ? data.collection.itens[0].data[0].value.substring(0, 15)+"...": data.collection.itens[0].data[0].value))
+				if(data.collection.itens[0].data[3].value == "TRUE"){
+					box.removeClass("invalid-email-box").addClass("out-office-box");
+				}
+			}
+		}else{
+			box.find(".box-loading").remove();
+		}
+	});
+}
+
+//FUNÇÃO QUE "SETA" OS BINDS DOS CAMPOS PARA - CC - CCO
+function input_binds(div, ID){
+
+	//AO CLICAR NA DIV SETA O FOCO NO INPUT
+	div.click(function(e){
+		if(e.target == $(this)[0]){
+			$(this).find("input:last").focus();
+			$(this).find("div").removeClass("box-selected");
+		}
+	})
+	
+	//AO SAIR DO FOCO DA DIV ELE RETIRA TODAS AS CLASSES DE CAIXAS SELECIONADAS
+	.focusout(function(e){
+		if(!$(e.target).parents(".email-area:first").length)
+			$(this).find("div").removeClass("box-selected");
+	}).droppable({
+		hoverClass: "box-draggable-hover",
+		accept : ".box",
+		drop : function(e, ui){
+			ui.draggable.parent().droppable( "enable" );
+			var box = ui.draggable.clone();
+			box_actions(box);
+			if(box.find(".box-info").length){
+				box.unbind("dblclick").bind("dblclick", function(e){
+					new $.Zebra_Dialog('<strong>Impossivel editar</strong> um contato do ldap\n' +
+						'<strong>Porém</strong>é possivel remove-lo', {
+						'buttons':  false,
+						'modal': false,
+						'position': ['right - 20', 'top + 20'],
+						'auto_close': 3000
+					});
+				});
+			}
+			$(this).prepend(box);
+			ui.draggable.remove();
+		}
+	});
+	
+	//MAKE KEYDOWN
+	input_keydowns(div.find("input"), ID);
+	
+	
+	//VERIFICA PREFERENCIA DE CONTATOS DINÂMICOS ESTA ATIVA
+	if(parseInt(preferences.use_dynamic_contacts)){
+		//PREPARAÇÃO DA ARRAY DOS CONTATOS DINÂMICOS
+
+		$.widget( "custom.catcomplete", $.ui.autocomplete, {
+			_renderMenu: function( ul, items ) {
+				var self = this,
+				currentType = "";
+				$.each( items, function( index, item ) {
+					if ( item.typel != currentType) {
+						if(item.typel == "/groups" && $(ul).find(".dynamic-recent").length)
+							self._renderItem( ul, {name:"", value:"", type:"linha"} );
+						if(item.typel == "/contacts" && ($(ul).find(".dynamic-group").length || $(ul).find(".dynamic-recent").length))
+							self._renderItem( ul, {name:"", value:"", type:"linha"} );	
+						currentType = item.typel;
+					}
+					self._renderItem( ul, item );
+					$(ul).find("li:last").find(".dynamic-stars").raty({
+						readOnly : true,
+						half : true,
+						hints : ['','','','',''],
+						score    : ((item.number_of_messages*5)/topContact) > 0.5 ? ((item.number_of_messages*5)/topContact) : 0.5,
+						starOn  : '../../prototype/plugins/jq-raty/img/star-on.png',
+						starOff : '../../prototype/plugins/jq-raty/img/star-off.png',
+						starHalf : '../../prototype/plugins/jq-raty/img/star-half.png'
+					});
+				});
+				if($(ul).find("li:last").hasClass("dynamic-separator")){
+					$(ul).find("li:last").remove();
+				}
+			}
+		});
+		//INSERÇÃO DO AUTO COMPLETE AO INPUT
+		div.find("input").catcomplete({
+			minLength: 1,			
+			source: function(request, response){
+				if ( request.term in cache ) {
+					response( cache[ request.term ] );
+					return;
+				}
+				dynamicContactsList = new Array();
+				REST.get("/usercontacts", false, function(data){
+					dynamicData = data.collection.itens;
+					if(dynamicData){
+						$.each(dynamicData, function(index, value){
+							dynamic = {};
+							$.each(value.data, function(index, value){
+								dynamic[value.name] = value.value;
+							});
+							dynamic['value'] = (dynamic.name ? dynamic.name +' - ': '') + dynamic.mail;
+							dynamic['type'] = value.dataType;
+							dynamic['typel'] = (value.dataType.substring(0,7) == "/shared" ? "/"+value.dataType.substring(7,value.dataType.length)+"s" : value.dataType) ;
+							dynamicContactsList.push(dynamic);
+						});
+					}
+					var data = $.ui.autocomplete.filter(dynamicContactsList, request.term );
+					cache[ request.term ] = data;
+					response( data );
+				});
+			},
+			focus: function() {
+				return false;
+			},
+			
+			//EVENTO AO SELECIONAR UM CONTATO DINÂMICO
+			select: function( event, ui ) {
+				canMakeBox = false;
+				event.preventDefault();
+				$(this).val("");
+				if(ui.item.typel == "/contacts")
+					draw_email_box(""+ui.item.id, $(this), true, (ui.item.type.substring(0,7) == "/shared" ? true : false));
+				else if(ui.item.typel == "/groups")
+					draw_email_box(""+ui.item.id, $(this), "G", (ui.item.type.substring(0,7) == "/shared" ? true : false));
+				else
+					draw_email_box(ui.item.name ? "\""+ui.item.name+"\" <"+ui.item.mail+">" : ui.item.mail, $(this));
+				return false;
+			},
+			autoFocus: true,
+			position : { my: "left top", at: "left bottom", collision: "fit" }
+		}).bind('catcompleteopen', function(event, ui) {
+			$(this).data('is_open',true);
+		}).bind('catcompleteclose', function(event, ui) {
+			canMakeBox = true;
+			$(this).data('is_open',false);
+		})
+		
+		//MONTAGEM DA LISTA DE CONTATOS DINÂMICOS DO AUTO COMPLETE
+		.data( "catcomplete" )._renderItem = function( ul, item ) {
+			if($(ul).find("li").length < 50){
+				var autocomplete = $(this)[0].element;
+				//cálculo dinâmico da largura da lista
+				var width = (item.label ? item.label.length : (item.value ? item.value.length : (item.email ? item.email.length : 20 )));
+				width = width*5 + (is_ie ? 170 : 200) + 16;
+				if (width < $(ul).width())
+					width = $(ul).width();
+				ul.css({"min-width":width,"max-height" : "180px", "overflow-y" : "auto", "min-height": "30px"});
+				var listContacts = DataLayer.render("../prototype/modules/mail/templates/listContacts.ejs", item);
+				return $(listContacts).data( "item.autocomplete", item ).appendTo( ul ).find("span:last").button({
+						icons : {
+						primary : "ui-icon-close"
+					},
+					text: false
+				}).click(function(event){
+					var removeLi = $(this).parents("li:first");
+					if(!event.keyCode)
+						autocomplete.catcomplete( "close" );
+					canMakeBox = false;
+					$.Zebra_Dialog('Deseja remover <b>'+(item.name ? item.name+" - " : "")+ item.mail+'</b>?', {
+							'type':     'question',
+							'custom_class': (is_ie ? 'configure-zebra-dialog' : ''),
+							'title':    'Atenção',
+							'buttons': ['Sim','Não'],		
+							'overlay_opacity': '0.5',
+							'onClose':  function(caption) {
+								if(caption == 'Sim'){
+									$(removeLi).remove();
+									REST.delete("/dynamiccontact/"+item.id);
+									updateDynamicContact();
+									cache = new Array();
+								}else if(caption == 'Não'){
+									$(focusIn).focus();
+								}
+							}
+					});
+				});
+			}
 			return;
-		}
-		return $( "<li></li>" )
-			.data( "item.autocomplete", item )
-			.append( "<a>" + item.name + " - " + item.email + "</a>" )
-			.appendTo( ul );
-	};
-	input.parents("tr:first").find("button").button().click(function(){
-		emQuickSearch($(this).parents("tr:first").find("textarea").val(), "."+$(this).parents("tr:first").attr('class').split("-")[0], ID, undefined, true);
+		};
+	}
+	
+	//FUNÇÃO DOS BOTÕES PARA - CC - CCO
+	div.parents("tr:first").find("button").button().click(function(){
+		click = true;
+		fastSearch = true;
+		if(!$(":focus").hasClass("new-message-input"))
+			emQuickSearch(($(this).parents("tr:first").find("input").val() ? $(this).parents("tr:first").find("input").val() : input_search), "."+$(this).parents("tr:first").attr('class').split("-")[0], ID, undefined, true);
 	});
 }
@@ -3615,4 +4179,5 @@
 	connector.loadScript("color_palette");
 	connector.loadScript('wfolders');
+	connector.loadScript("ccQuickAdd"); 
 	
 	if(typeof(RichTextEditor) == 'undefined' || typeof(ColorPalette) == 'undefined' || typeof(wfolders) == 'undefined')
@@ -3662,35 +4227,36 @@
 		button.toggleClass("expressomail-button-icon-ative");
 		field.toggle();
-		field.find("textarea").val("").focus();
-		if(!field.find("textarea").hasClass("elastic")){
-			field.find("textarea").css({"max-height" : "115px", "overflow-y" : "auto"}).addClass("elastic").elastic().unbind('blur');	
-			input_binds(field.find("textarea"), ID);
+		field.find("textarea").val("").parent().find("input").focus();
+		field.find(".email-area div").remove();
+		if(!field.find("textarea").hasClass("track")){
+			field.find("textarea").css({"max-height" : "115px", "overflow-y" : "auto"}).addClass("track");	
+			input_binds(field.find(".email-area"), ID);
 		}
 	} 
 	
-	input_binds(content.find('[name="input_to"]').css({"max-height" : "115px", "overflow-y" : "auto"}).addClass("elastic").elastic().unbind('blur').focus(), ID);	
+	input_binds(content.find('[name="input_aux_to"]').css("max-width" , parseInt(content.find(".email-area").css("width"))-5).focus().parent().css({"max-height" : "115px", "overflow-y" : "auto"}), ID);	
 	
 	//Botão TextoRico/TextoSimples
 	content.find(".new-msg-head-right-buttons").find(".button").button().filter(".rich-button").click(function(){
-		/*Se o texto do botão for "Texto simples" exibirá a mensagem antes de alterar para texto simples*/ 
-        if($(".rich-button").find("span").text() == get_lang("Simple Text")){ 
-                $.Zebra_Dialog(get_lang("Convert this message into plain text can make parts of it are removed. Continue?"), { 
-            'type':     'warning', 
-            'overlay_opacity': '0.5', 
-            'buttons':  ['OK','Cancelar'], 
-            'width' : 380, 
-            'onClose':  function(clicked) { 
-                if(clicked == 'OK'){ 
-                        RichTextEditor.setPlain(check_input(content.find('[name="textplain_rt_checkbox"]')), ID); 
-                        $(".rich-button").find("span").text(get_lang("Rich Text")); 
-                }  
-            } 
-                }) 
-        } 
-        /*Se o texto do botão for "Texto rico" simplesmente altera para texto rico*/ 
-        else{ 
-                RichTextEditor.setPlain(check_input(content.find('[name="textplain_rt_checkbox"]')), ID); 
-                $(".rich-button").find("span").text(get_lang("Simple Text")); 
-        }
+		/*Se o texto do botão for "Texto simples" exibirá a mensagem antes de alterar para texto simples*/
+		if($(".rich-button").find("span").text() == get_lang("Simple Text")){
+			$.Zebra_Dialog(get_lang("Convert this message into plain text can make parts of it are removed. Continue?"), {
+	            'type':     'warning',
+	            'overlay_opacity': '0.5',
+	            'buttons':  ['OK','Cancelar'],
+	            'width' : 380,
+	            'onClose':  function(clicked) {
+	                if(clicked == 'OK'){
+	            		RichTextEditor.setPlain(check_input(content.find('[name="textplain_rt_checkbox"]')), ID);
+		            	$(".rich-button").find("span").text(get_lang("Rich Text"));
+	                } 
+	            }
+			})
+		}
+		/*Se o texto do botão for "Texto rico" simplesmente altera para texto rico*/
+		else{
+			RichTextEditor.setPlain(check_input(content.find('[name="textplain_rt_checkbox"]')), ID);
+			$(".rich-button").find("span").text(get_lang("Simple Text"));
+		}
 	})
 	
@@ -3934,4 +4500,12 @@
 
 	var el_shared_users = Element("el_shared_users");
+	/* Recupera a pasta atual do usuário (selecionada) */
+	var user_shared = folder.split(cyrus_delimiter);
+	/* Verifica se está nas próprias pastas */
+	if(user_shared[0] == "INBOX"){
+		user_shared = User.me.uid;
+	}else{
+		user_shared = user_shared[1];
+	}	
 	// The element was loaded and populated...so return.
 	if(el_shared_users){
@@ -3944,4 +4518,12 @@
 			_option.text = el_shared_users.options[x].text;
 			_option.value = el_shared_users.options[x].value;
+			/* Faz o tratamento do nome da pasta para fazer a verificação e selecionar o valor no select */
+			var str_begin_name = _option.text.indexOf('<') + 1;
+			var str_end_name = _option.text.indexOf('@');
+			var user_selected_name = _option.text.substring(str_begin_name, str_end_name);
+			/* Verifica se é o usuário da pasta selecionada */			
+			if(user_selected_name == user_shared){
+				_option.selected = 'selected';
+			}
 			sel_from.options[sel_from.options.length] = _option	;
 		}
@@ -3969,13 +4551,15 @@
 		if(data.length > 0) {
 			tr1_1.style.display = '';
-                        var mycn = typeof(data.myname != 'undefined') ? data.myname : '';
+            var mycn = typeof(data.myname != 'undefined') ? data.myname : '';
 			var _option = document.createElement("OPTION");
 			_option.text =  '"'+mycn+'" <'+Element("user_email").value+'>';
 			_option.value  = mycn+";"+Element("user_email").value;
+			/* Verifica se é o usuário logado */
+			if(user_shared == User.me.uid)
+				_option.selected = 'selected';
 			sel_from.options[sel_from.options.length] = _option;
 
 			var options = '';
-                        var cn = '';
-								
+            var cn = '';
 			for (var x = 0; x < data.length; x++)	{
                                 cn = typeof(data[x].cn[0] != 'undefined') ? data[x].cn[0] : '';
@@ -3983,4 +4567,12 @@
 				_option.text = '"'+cn+'" <'+data[x].mail[0]+'>';
 				_option.value = cn+';'+data[x].mail[0]+';'+data[x].save_shared[0]+';'+data[x].uid[0];
+				/* Faz o tratamento do nome da pasta para fazer a verificação e selecionar o valor no select */
+				var str_begin_name = _option.text.indexOf('<') + 1;
+				var str_end_name = _option.text.indexOf('@');
+				var user_selected_name = _option.text.substring(str_begin_name, str_end_name); 
+				/* Verifica se é o usuário da pasta selecionada */
+				if(user_selected_name == user_shared){
+					_option.selected = 'selected';
+				}
 				sel_from.options[sel_from.options.length] = _option	;
 			}
@@ -4335,6 +4927,11 @@
 		cc_data[3] = array_addrs[0];
 
+	var onclick = '';		
+	$.each(cc_data, function(index, value){
+		onclick += "'"+value+"',";
+	});
+	onclick = onclick.substr(0, onclick.length-1);
 	var sm_envelope_img1 = '<img style="cursor:'+ (is_ie ? 'hand' : 'pointer') +'" title="' + get_lang("Add Contact") +
-	'" onclick="ccQuickAddOne.showList(\''+cc_data+'\')" src="./templates/'+template+'/images/user_card.png">';
+	'" onclick="ccQuickAddOne.showList(['+onclick+'])" src="./templates/'+template+'/images/user_card.png">';
 	var to_addybook_add = "<SPAN id='insert_plugin_"+idx_cc+"_"+ID+"'>";
 	to_addybook_add += addrs;
