Index: tags/expressoMail1_2/1.2211/setup/phpgw_es-es.lang
===================================================================
--- tags/expressoMail1_2/1.2211/setup/phpgw_es-es.lang	(revision 231)
+++ tags/expressoMail1_2/1.2211/setup/phpgw_es-es.lang	(revision 231)
@@ -0,0 +1,365 @@
+1 Day	expressoMail1_2	es-es	1 Día
+2 Days	expressoMail1_2	es-es	2 Días
+3 Days	expressoMail1_2	es-es	3 Días
+4 Days	expressoMail1_2	es-es	4 Días
+5 Day	expressoMail1_2	es-es	5 Días
+5 Days	expressoMail1_2	es-es	5 Días
+Access right	expressoMail1_2	es-es	Derechos de Acceso
+Action	expressoMail1_2	es-es	Acción
+Add BCC	expressoMail1_2	es-es	Añadir Cco
+Add CC	expressoMail1_2	es-es	Añadir CC
+Add Contact	expressoMail1_2	es-es	Añadir Contacto
+Add user into my IM	expressoMail1_2	es-es	Añadir a mí IM
+all	expressoMail1_2	es-es	Todas
+Also check message against next rule	expressoMail1_2	es-es	Verificar mensaje contra próxima regla también
+Answered	expressoMail1_2	es-es	Respondidas
+A read confirmation was sent.	expressoMail1_2	es-es	Una confirmación de lectura fue enviada.
+At %1, %2 hours, %3 wrote:	expressoMail1_2	pt-br	En %1 las %2 horas, %3 escribió:
+attachment	expressoMail1_2	es-es	anexo
+Attachments: add+	expressoMail1_2	es-es	Anexos: añadir+
+Attachments: 	expressoMail1_2	es-es	Datos adjuntos
+Attachments	expressoMail1_2	es-es	Datos adjuntos
+Back	expressoMail1_2	es-es	Volver
+<b>Answer messages from:</b> %1 - <b>Status:</b><font color='red'> %2</font> - <b>message:</b> %3</a>	expressoMail1_2	es-es	<b>Responder mensajes de:</b> %1 - <b>Estado:</b><font color='red'> %2</font> - <b>mensaje:</b> %3</a>
+BCC	expressoMail1_2	es-es	CCO
+Big	expressoMail1_2	es-es	grande
+Block Sender	expressoMail1_2	es-es	Boquear remitente
+Bold	expressoMail1_2	es-es	Negrita
+<b>Tip:</b> For faster save, click over the image with <u>right button</u>.	expressoMail1_2	es-es	<b>Tip:</b> Para guardar rápidamente, haga clic sobre la imagen con el <u>botón derecho</u> del mouse.
+Call to Comercial Number	expressoMail1_2	es-es	Discar para teléfono comercial
+Call to Mobile Number	expressoMail1_2	es-es	Discar para teléfono móvil
+cancel	expressoMail1_2	es-es	Cancelar
+CC	expressoMail1_2	es-es	Con Copia
+CCo	expressoMail1_2	es-es	CCo
+Change folder	expressoMail1_2	es-es	Cambiar carpeta
+Choose a name	expressoMail1_2	es-es	Elija un nombre
+Chose the text you want transform in link before.	expressoMail1_2	es-es	Seleccione el texto que desea transformar en enlace
+Clean	expressoMail1_2	es-es	Limpiar
+Click here do view (+)	expressoMail1_2	es-es	Haga clic en la imagen para ampliar (+).
+Click here to add into the fields	expressoMail1_2	es-es	Haga clic aquí para añadir en los espacios
+Close	expressoMail1_2	es-es	Cerrar
+Coincident	expressoMail1_2	es-es	Coincidente
+Command for spam	admin	es-es	Comando que será ejecutado al marcar como spam
+Command for unmark spam	admin	es-es	Comando que será ejecutado al marcar como no siendo spam
+Config for ExpressoMail	expressoMail1_2	es-es	Configuraciones para el ExpressoMail
+Cyrus IMAP Server	expressoMail1_2	es-es	Servidor de IMAP Cyrus
+Date: 	expressoMail1_2	es-es	Fecha:
+Date	expressoMail1_2	es-es	Fecha
+day(s)	expressoMail1_2	es-es	Día(s)
+Define some criterion to the fields From, To and Subject with more than 3 characters!	expressoMail1_2	es-es	Defina algún critério para los campos De, Para, Asunto com más de 3 caracteres!
+Define some search parameters!	expressoMail1_2	es-es	Defina algunos parámetros para la búsqueda
+Delete	expressoMail1_2	es-es	Eliminar
+Delete folder	expressoMail1_2	es-es	Borrar carpeta
+Delete trash messages after how many days?	expressoMail1_2	es-es	Eliminar mensajes después de cuantos días en la papelera?
+Delete your sub-folders first	expressoMail1_2	es-es	Primero elimine sus subcarpetas
+DISABLED	expressoMail1_2	es-es	Deshabilitada
+Disable	expressoMail1_2	es-es	Deshabilitar
+Download all atachments	expressoMail1_2	es-es	Descargar todos de una vez
+Download manual	expressoMail1_2	es-es	Descargar manual
+Do you really want to empty your trash folder?	expressoMail1_2	es-es	¿Esta seguro de que desea eliminar su papelera?
+Do you wanna receive an alert for new messages?	expressoMail1_2	es-es	¿Desea recibir una alerta de nuevos mensajes?
+Do you want to block this e-mail?	expressoMail1_2	es-es	¿Quieres bloquear este e-mail?
+Do you want to log the sent messages?	admin	es-es	¿Quieres registrar los mensajes enviados?
+Do you want to use the spam filter?	admin	es-es	¿A usted le gustaría utilizar el filtro anti-spam
+Do you wish to exclude the folder 	expressoMail1_2	es-es	¿Usted quiere eliminar la carpeta?
+Draft	expressoMail1_2	es-es	Borrador
+Drafts	expressoMail1_2	es-es	Borradores
+Drafts Folder name	admin	es-es	Nombre de la carpeta de borradores
+During (days off the office)	expressoMail1_2	es-es	Durante (días fuera de la oficina)
+During	expressoMail1_2	es-es	Durante
+Edit	expressoMail1_2	es-es	Editar
+Edit filters	expressoMail1_2	es-es	Editar filtros
+Edit folders	expressoMail1_2	es-es	Editar carpetas
+E-mail rule	expressoMail1_2	es-es	reglar del e-mail
+Emails of the account	expressoMail1_2	es-es	E-mails de la cuenta
+Empty Trash	expressoMail1_2	es-es	Limpiar papelera
+ENABLED	expressoMail1_2	es-es	Habilitada
+Enable	expressoMail1_2	es-es	Habilitar
+Enable Quick Reply	expressoMail1_2	es-es	Responder rápidamente (con detalles y al remitente)
+Enter a name for the box	expressoMail1_2	es-es	Entre con un nombre para la Bandeja
+Enter the name of the new folder:	expressoMail1_2	es-es	Entre con un nombre para la nueva carpeta: 
+Enter with link URL:", "http://"	expressoMail1_2	es-es	Entre con la URL del enlace: ",http://"
+Erase the message	expressoMail1_2	es-es	Elimine el mensaje
+Error compressing messages (ZIP). Contact the administrator.	expressoMail1_2	es-es	¡Error al comprimir los mensajes (ZIP)! Contacte al administrador
+Error in SMTP sending read confirmation.	expressoMail1_2	es-es	Error en el SMTP al enviar una confirmación de lectura
+Error moving message.	expressoMail1_2	es-es	Error al mover el mensaje
+Exclusion	expressoMail1_2	es-es	Exclusión
+Export	expressoMail1_2	es-es	Exportar
+Export messages	expressoMail1_2	es-es	Exportar mensajes
+ExpressoMail 1.2 Configuration	expressoMail1_2	es-es	Configuraciones del expressoMail 1.2
+expressoMail1_2	expressoMail1_2	es-es	ExpressoMail 1.2
+ExpressoMail settings	admin	es-es	Configuraciones del expresso Mail 1.2
+File extension forbidden	expressoMail1_2	es-es	Extensión de archivo prohibido
+files	expressoMail1_2	es-es	archivos
+Filters	expressoMail1_2	es-es	Filtros
+Filters maintenance	expressoMail1_2	es-es	Manutención de Filtros
+Filters management	expressoMail1_2	es-es	Gerenciar Filtros
+First	expressoMail1_2	es-es	Primera
+First Name	expressoMail1_2	pt-br	Primero nombre
+Folder	expressoMail1_2	es-es	Carpeta
+Folder Management	expressoMail1_2	es-es	Gerenciar Carpetas
+Folders	expressoMail1_2	es-es	Carpetas
+Font	expressoMail1_2	es-es	Fuente
+forecolor	expressoMail1_2	es-es	Color del texto
+Forwarded	expressoMail1_2	es-es	Reenviada
+Forwarded message	expressoMail1_2	es-es	Mensaje reenviada
+Forward	expressoMail1_2	es-es	Reenviar
+Forward to the address	expressoMail1_2	es-es	Reenvíe para la dirección
+From: 	expressoMail1_2	es-es	De:
+From	expressoMail1_2	es-es	Remitente
+Global Catalog	expressoMail1_2	es-es	Catálogo General
+Go back	expressoMail1_2	es-es	Volver
+greater than	expressoMail1_2	es-es	mayor que
+Groups	expressoMail1_2	es-es	Grupos
+Hide Menu Folders	expressoMail1_2	es-es	Ocultar Menú Carpetas
+Hide menu folders?	expressoMail1_2	es-es	Ocultar menú de las carpetas?
+Hide options	expressoMail1_2	es-es	Ocultar opciones
+Hide Search	expressoMail1_2	es-es	Ocultar busca
+hlp_msg_addcreate_acl	expressoMail1_2	es-es	Otros usuarios podrán CREAR/AÑADIR nuevos mensajes
+hlp_msg_delmov_acl	expressoMail1_2	es-es	Otros usuarios podrán ELIMINAR/MOVER sus mensajes
+hlp_msg_read_acl	expressoMail1_2	es-es	Otros usarios podrán LEER sus mensajes
+hlp_msg_sendlike_acl	expressoMail1_2	es-es	Otros usuarios podrán ENVIAR mensajes como siendo usted
+hours ago	expressoMail1_2	es-es	horas atrás
+Imap Folders Properties	admin	es-es	Características de las Carpetas del Imap
+Important	expressoMail1_2	es-es	Importantes
+In all the folders	expressoMail1_2	es-es	En todas las carpetas
+Inbox	expressoMail1_2	es-es	Bandeja de Entrada
+indent	expressoMail1_2	es-es	Tabulación a la izquierda
+Inform a forwarding e-mail	expressoMail1_2	es-es	¡Informe un e-mail de reenvío!
+Inform a message	expressoMail1_2	es-es	¡Informe um mensaje!
+Inform a text for rejection!	expressoMail1_2	es-es	¡Informe un texto para rechazar!
+Inform a valid e-mail!	expressoMail1_2	es-es	¡Informe um e-mail válido!
+Inform between 1 and 31!	expressoMail1_2	es-es	¡Informe entre  y 31!
+Inform the days!	expressoMail1_2	es-es	¡Informe los días!
+Inform the forwarding e-mail(s)	expressoMail1_2	es-es	¡Informe e-mail(s) para reenvío!
+Inform your search in the text fields	expressoMail1_2	es-es	Informe las búsqyedas en las cajas de texto
+insertorderedlist	expressoMail1_2	es-es	Insertar en lista ordenada
+Insert signature	expressoMail1_2	es-es	Insertar firma
+insertunorderedlist	expressoMail1_2	es-es	Insertar en lista no odenada
+in this message	expressoMail1_2	es-es	En el mensaje
+italic	expressoMail1_2	es-es	Cursiva
+Its %1 folder is not created. It is necessary to create so that it functions correctly.	expressoMail1_2	es-es	Su carpeta \"%1\" no esta creada. Es necesario crearla para que funcione correctamente
+It's not possible create inside: 	expressoMail1_2	es-es	No es posible crear dentro de: 
+It's not possible delete the folder: 	expressoMail1_2	es-es	No es posible remover la carpeta: 
+It's not possible	expressoMail1_2	es-es	No es posible
+It's not possible rename the folder: 	expressoMail1_2	es-es	No es posible cambiar el nombre de la carpeta: 
+It's not possible rename this folder, because it is being used in the moment!	expressoMail1_2	es-es	No es posible cambiar el nombre de esta carpeta, pues la misma está siendo usada en este momento!
+It's not possible rename this folder!	expressoMail1_2	es-es	No es posible cambiar el nombre de esta carpeta!
+justifycenter	expressoMail1_2	es-es	Centrar
+justifyfull	expressoMail1_2	es-es	Justificar
+justifyleft	expressoMail1_2	es-es	A la izquierda
+justifyright	expressoMail1_2	es-es	A la derecha
+Keep a copy of the message at your Inbox	expressoMail1_2	es-es	Guardar una copia del mensaje en su  Bandeja de Entrada
+Last	expressoMail1_2	es-es	última
+Last Name	expressoMail1_2	es-es	Apellido
+Less	expressoMail1_2	es-es	Menos
+Less than	expressoMail1_2	es-es	Menos que
+Link	expressoMail1_2	es-es	Enlace
+List All	expressoMail1_2	es-es	Listar Todo
+List Catalog	expressoMail1_2	es-es	Listar Catálogo
+List	expressoMail1_2	es-es	Listar
+list of the filters	expressoMail1_2	es-es	Lista de filtros
+Loading	expressoMail1_2	es-es	Cargando
+Mailbox Sharing	expressoMail1_2	es-es	Comparta Carpeta
+Manager your folders and export messages	expressoMail1_2	es-es	Administre sus carpetas y exporte mensajes
+Mark as	expressoMail1_2	es-es	Marcar como
+Mark as Spam	expressoMail1_2	es-es	Marcar como spam
+Max number of e-mails for page	expressoMail1_2	es-es	Número máximo de e-mails por página
+Max size	expressoMail1_2	es-es	Tamaño máximo
+Medium	expressoMail1_2	es-es	Medio
+Message body	expressoMail1_2	es-es	Cuerpo del mensaje
+message	expressoMail1_2	es-es	Mensaje
+Message Font	expressoMail1_2	es-es	Fuente del Mensaje
+Message Header	expressoMail1_2	es-es	Cabezal del Mensaje
+Message marked as 	expressoMail1_2	es-es	Mensaje marcado como 
+message(s) deleted from your trash folder.	expressoMail1_2	es-es	Mensaje(s) eliminado(s) de su papelera
+messages	expressoMail1_2	es-es	mensajes
+messages found in folder:	expressoMail1_2	es-es	mensajes encontrados en la carpeta
+Messages saved in %1 folder.	expressoMail1_2	es-es	Mensajes guardadas en la carpeta %1
+minute ago	expressoMail1_2	es-es	minuto atrás
+minutes ago	expressoMail1_2	es-es	minutos atrás
+More actions	expressoMail1_2	es-es	Más acciones
+More	expressoMail1_2	es-es	Más
+More options	expressoMail1_2	es-es	Más opciones
+More than %1 results. Please, try to refine your search.	expressoMail1_2	es-es	Más que %1 resultados fueron encontrados. Trate de refinar su búsqueda
+More than 200 results were found	expressoMail1_2	es-es	Más de 200 resultados fueron encontrados
+Move	expressoMail1_2	es-es	Mover
+Move to	expressoMail1_2	es-es	Mover para
+My Folders	expressoMail1_2	es-es	Mis Carpetas
+New	expressoMail1_2	es-es	Nuevo
+New folder	expressoMail1_2	es-es	Nueva carpeta
+New Message	expressoMail1_2	es-es	Nuevo Mensaje
+New rule	expressoMail1_2	es-es	Nueva Regla
+Next	expressoMail1_2	es-es	Próximo
+Nickname	expressoMail1_2	es-es	Apodo
+No data to search	expressoMail1_2	es-es	Ningún dato digitado para búsqueda
+None	expressoMail1_2	es-es	Ninguno
+None result was found.	expressoMail1_2	es-es	Ningún resultado fue encontrado
+No option marked!	expressoMail1_2	es-es	¡No fue marcada ninguna opción!
+normal	expressoMail1_2	es-es	normal
+No selected message.	expressoMail1_2	es-es	Ningún mensaje fue seleccionado
+No Subject	expressoMail1_2	es-es	Sin Asunto
+Note: This sharing will take action on all of your folders and messages.	expressoMail1_2	es-es	Atención: Esta acción de compartir tendrá acción en TODAS sus carpetas y mensajes
+Not Spam	expressoMail1_2	es-es	No es spam
+now	expressoMail1_2	es-es	ahora
+Open chat window	expressoMail1_2	es-es	Abrir ventana de conversación
+Open in New Window	expressoMail1_2	es-es	Abrir en Nueva Ventana
+Open search window...	expressoMail1_2	es-es	Abrir ventana de buca...
+Options	expressoMail1_2	es-es	Opciones
+Organization	expressoMail1_2	es-es	Organización
+outdent	expressoMail1_2	es-es	Tabulación a la derecha
+out office	expressoMail1_2	es-es	Fuera de la oficina
+Over quota	expressoMail1_2	es-es	Cuota de espacio excedida
+Page Not Found!	expressoMail1_2	es-es	Página no encontrada!
+People	expressoMail1_2	es-es	Personas
+Padding Email List	expressoMail1_2	es-es	Altura de las líneas de la lista de mensajes
+Personal Catalog	expressoMail1_2	es-es	Catálogo Personal
+Postfix with LDAP	expressoMail1_2	es-es	Postfix con LDAP
+Preferences	expressoMail1_2	es-es	Preferencias
+Previous	expressoMail1_2	es-es	Anterior
+Print	expressoMail1_2	es-es	Imprimir
+Public Lists	expressoMail1_2	es-es	Listas Públicas
+Reached maximum tab limit	expressoMail1_2	es-es	Límite máximo de abas alcanzado
+Read	expressoMail1_2	es-es	Lectura
+Redo	expressoMail1_2	es-es	Rehacer
+Refresh	expressoMail1_2	es-es	Actualizar
+Remove	expressoMail1_2	es-es	Eliminar
+Rename folder	expressoMail1_2	es-es	Cambiar nombre
+Reply	expressoMail1_2	es-es	Responder
+Reply sent messages to	expressoMail1_2	es-es	Responder mensajes enviados para
+Reply to all	expressoMail1_2	es-es	Responder a todos
+Reply to all with history	expressoMail1_2	es-es	Responder a todos con detalles
+Reply to all without history	expressoMail1_2	es-es	Responder a todos sin detalles
+Reply to	expressoMail1_2	es-es	Responder a
+Reply to sender	expressoMail1_2	es-es	Responder al Remitente
+Reply with history	expressoMail1_2	es-es	Responder con detalles
+Reply without history	expressoMail1_2	es-es	Responder sin detalles
+Result of the search	expressoMail1_2	es-es	Resultado de la búsqueda
+results found	expressoMail1_2	es-es	resultados encontrados
+Return receipt	expressoMail1_2	es-es	Conf. De Lectura
+Rule	expressoMail1_2	es-es	Regla
+Save as Draft	expressoMail1_2	es-es	Guardar como Borrador
+Save deleted messages in trash folder?	expressoMail1_2	es-es	¿Guardar mensajes eliminadas en la carpeta papelera?
+Save Draft	expressoMail1_2	es-es	Guardar Borrador
+Save	expressoMail1_2	es-es	Guardar
+Save in folder	expressoMail1_2	es-es	Guardar en la carpeta
+Save sent messages in folder	expressoMail1_2	es-es	Guardar las mensajes enviados en la carpeta
+Search	expressoMail1_2	es-es	Buscar
+Search for Organization	expressoMail1_2	es-es	Buscar por Organización
+Search in Catalog	expressoMail1_2	es-es	Buscando en el Catálogo
+Search in the Global Catalog	expressoMail1_2	es-es	Búsqueda en el catálogo general
+Search Results	expressoMail1_2	es-es	Resultado de la búsqueda
+ search results	expressoMail1_2	es-es	resultados encontrados
+Search the messages in these folders	expressoMail1_2	es-es	Busque mensajes en estas carpetas
+Search user...	expressoMail1_2	es-es	Búsqueda usuario...
+Search user	expressoMail1_2	es-es	Buscar usuarios
+Sector	expressoMail1_2	es-es	Sector
+Seen	expressoMail1_2	es-es	Leídas
+Select a folder:	expressoMail1_2	es-es	Seleccione una carpeta:
+Select a folder!	expressoMail1_2	es-es	Seleccione una carpeta!
+Select all messages.	expressoMail1_2	es-es	Seleccionar todos los mensajes
+Select a name	expressoMail1_2	es-es	Elija un nombre
+Select an organization and click on button <b>Search</b>	expressoMail1_2	es-es	Seleccione una Organización y haga clic en el Botón <b>Buscar</b>
+Select on send	expressoMail1_2	es-es	Seleccionar al enviar el mensaje
+Select the type of contact that you want to view	expressoMail1_2	es-es	Seleccione el tipo de contacto que desea ver
+Select the user	expressoMail1_2	es-es	Seleccionar al enviar el mensaje
+Send and file	expressoMail1_2	es-es	Enviar y Archivar
+Send a rejection message	expressoMail1_2	es-es	Envíe un mensaje de rechazo
+Sender's Information	expressoMail1_2	es-es	Datos del Remitente
+Send	expressoMail1_2	es-es	Enviar
+Send this message without a subject?	expressoMail1_2	es-es	¿Enviar este mensaje sin asunto?
+Send (without save)	expressoMail1_2	es-es	Enviar (sin archivar)
+Sent by	expressoMail1_2	es-es	Enviado por
+Sent	expressoMail1_2	es-es	Enviado
+Sent Folder name	admin	es-es	Nombre enviado de la carpeta
+Service unavailable	expressoMail1_2	es-es	Servicio no disponible
+Shared folders	expressoMail1_2	es-es	Carpetas compartidas
+Shared options saved with sucess	expressoMail1_2	es-es	Opciones de división guardadas con suceso
+Share mailbox	expressoMail1_2	es-es	Compartir carpetas
+Show default view on main screen?	expressoMail1_2	es-es	¿Mostrar resumen del ExpressoMail en la pantalla inicial?
+Showing only the results found in your organization	expressoMail1_2	es-es	Demostrando solamente los resultados encontró en su organización
+Show previous message, after delete actual message?	expressoMail1_2	es-es	Mostrar mensaje anterior, desoués de borrar mensaje actual?
+Signature	expressoMail1_2	es-es	Firma
+Signed message	expressoMail1_2	es-es	Mensaje firmado
+Size	expressoMail1_2	es-es	Tamaño
+Small	expressoMail1_2	es-es	pequeña
+Spam	expressoMail1_2	es-es	Espam
+Spam Folder name	admin	es-es	Nombre de la carpeta Spam
+standard IMAP server	expressoMail1_2	es-es	Servidor standar de IMAP
+standard POP3 server	expressoMail1_2	es-es	Servidor standar de POP3
+standard SMTP-Server	expressoMail1_2	es-es	standard SMTP-Server
+Status	expressoMail1_2	es-es	Estado
+Store at	expressoMail1_2	es-es	Archivar en 
+Subject: 	expressoMail1_2	es-es	Asunto: 
+Subject	expressoMail1_2	es-es	Asunto
+The Anti Pop-Up is enabled. Allow this site (%1) for print.	expressoMail1_2	es-es	El anti Pop-Up está habilitado. Desative-o para este sitio (%1) para permitir la impresión.
+The field \"%1\" of the message it contains	expressoMail1_2	es-es	El campo \"%1\" del mensaje contenga
+The field \"From:\" of the message it contains	expressoMail1_2	es-es	El campo "De:" del mensaje que contenga
+The field \"Subject: \" of the message it contains	expressoMail1_2	es-es	El campo "Asunto:" del mensaje que contenga
+The field \"To: \" of the message it contains	expressoMail1_2	es-es	El campo "Para:" del mensaje que contenga
+The folder %1 was successfully removed	expressoMail1_2	es-es	La carpeta %1 fue eliminada con éxito!
+The folder was not deleted!	expressoMail1_2	es-es	¡La carpeta no fue eliminada!
+The list has no participant.	expressoMail1_2	es-es	Esta lista no posee ningún participante
+The messages were deleted.	expressoMail1_2	es-es	Mesajes removidos
+The messages were moved to %1 folder 	expressoMail1_2	es-es	Mensajes movidos a la carpeta
+The message was deleted.	expressoMail1_2	es-es	Mensaje removido
+The message was moved to %1 folder 	expressoMail1_2	es-es	Mensaje fue movido a la carpeta 
+The origin folder and the destination folder are the same.	expressoMail1_2	es-es	La carpeta de origen y de destino son las mismas
+There's an action processing. Do you want abort it?	expressoMail1_2	es-es	Existe una acción que todavia está siendo procesada. ¿Cancelar la acción?
+The results were found in the Global Catalog	expressoMail1_2	es-es	Eventos enontrados en el Catálogo General
+The sender was blocked	expressoMail1_2	es-es	El remitente fue bloqueada
+The size of the message is	expressoMail1_2	es-es	El tamaño del mensaje sea
+The size of this message has exceeded  the limit (%1B).	expressoMail1_2	es-es	El tamaño del mensaje sea há excedido el límite (mayor que %1B)
+This list has no participants	expressoMail1_2	es-es	Esta lista no tiene participantes
+This mail box is empty	expressoMail1_2	es-es	Esta carpeta está vacía
+This message is already opened!	expressoMail1_2	es-es	¡Este mensaje ya está abierto!
+This message is already selected!	expressoMail1_2	es-es	Esta caja ya está en la selección!
+This message is signed, and you can trust.	expressoMail1_2	es-es	Se firma este mensaje, y usted puede confiar en.
+This message is signed, but it is invalid. You should not trust on it.	expressoMail1_2	es-es	Se firma este mensaje, pero es inválido. Usted no debe confiar en él.
+To: 	expressoMail1_2	es-es	Para:
+TO	expressoMail1_2	es-es	Para
+Tools	expressoMail1_2	es-es	Herramientas
+Trash	expressoMail1_2	es-es	Papelera
+Trash Folder name	admin	es-es	Nombre de la carpeta basura
+Type without spaces, dots or special characters!	expressoMail1_2	es-es	¡Escriba sin espacios, puntos o caracteres especiales! 
+underlined	expressoMail1_2	es-es	Subrayado
+underline	expressoMail1_2	es-es	Subrayado
+Undo	expressoMail1_2	es-es	Deshacer
+Unseen	expressoMail1_2	es-es	No leídas
+Use F9 Key as shortcut.	expressoMail1_2	es-es	Use la tecla F9 como atajo.
+User connected	instant_messenger	es-es	Esta conectado
+User didn't accepted you yet	instant_messenger	es-es	Todavia no te há aceptado
+User not connected	instant_messenger	es-es	Esta desconectado
+User not registered	instant_messenger	es-es	No está registrado
+Users	expressoMail1_2	es-es	Usuarios
+Use shortcuts?	expressoMail1_2	es-es	Usar teclas de atajo?
+View HTML source	expressoMail1_2	es-es	Ver código html
+View tips	expressoMail1_2	es-es	Ver tips
+Voided message	expressoMail1_2	es-es	Mensaje anulado
+Warning: Your Mailbox is almost full!	expressoMail1_2	es-es	Aviso: ¡Su Caja de Correo está casi llena!
+ was succefully removed	expressoMail1_2	es-es	fue eliminado con suceso
+What is the height of the lines in the list of messages?	expressoMail1_2	es-es	¿Cuál es la altura de las líneas en la lista de mensajes?
+What is the maximum number of messages per page?	expressoMail1_2	pt-br	¿Cuál es el número máximo de mensajes por página?
+What the font size in the list of messages?	expressoMail1_2	es-es	¿Cuál el tamaño de la fuente en la lista de mensajes?
+Who	expressoMail1_2	es-es	Quién
+With all	expressoMail1_2	es-es	Con todos
+Without Quota	expressoMail1_2	es-es	Sin espacio
+without save	expressoMail1_2	es-es	sin archivar
+with some	expressoMail1_2	es-es	con algunos
+With the following message	expressoMail1_2	es-es	Con el siguiente mensaje
+Write	expressoMail1_2	es-es	Escribir
+Write message	expressoMail1_2	es-es	Escribir mensaje
+wrote	expressoMail1_2	es-es	escribió
+You didn't accepted yet	instant_messenger	es-es	Usted todavía no há aceptó
+You have %1 new	expressoMail1_2	es-es	Usted tiene%1 nuevo(s)
+You must wait while the messages will be exported...	expressoMail1_2	es-es	Espere mientras los mensajes son exportados...
+Your Mailbox is 100% full! You must free more space or will not receive messages.	expressoMail1_2	es-es	¡Su caja de correo esta 100% llena! Libere espacio o no irá a recibir mensajes
+Your mailbox is shared with	expressoMail1_2	es-es	Su caja de correo esta compartida con 
+Your message has not been sent and will be discarted.	expressoMail1_2	es-es	Su mensaje no fue enviado y será perdido
+Your message has not been sent. Discard your message?	expressoMail1_2	es-es	Su mensaje no fue enviado. ¿Eliminar el mensaje?
+Your message was save as draft in folder %1.	expressoMail1_2	es-es	Su mensaje fue guardado como borrador en la carpeta %1
+Your message was sent and save.	expressoMail1_2	es-es	Su mensaje fue enviado y guardado
+Your message was sent.	expressoMail1_2	es-es	Su mensaje fue enviado
+Your search argument must be longer than 4 characters.	expressoMail1_2	es-es	Sus palavras para la búsqueda deben tener más que 4 dígitos
+your session could not be verified.	expressoMail1_2	es-es	Su sesión expiró. Entre nuevamente a su Expresso
+Your Trash folder was empty.	expressoMail1_2	es-es	Su carpeta Papelera fue vaciada
Index: tags/expressoMail1_2/1.2211/setup/phpgw_en.lang
===================================================================
--- tags/expressoMail1_2/1.2211/setup/phpgw_en.lang	(revision 252)
+++ tags/expressoMail1_2/1.2211/setup/phpgw_en.lang	(revision 252)
@@ -0,0 +1,357 @@
+1 Day	expressoMail1_2	en	1 Day
+2 Days	expressoMail1_2	en	2 Days
+3 Days	expressoMail1_2	en	3 Days
+4 Days	expressoMail1_2	en	4 Days
+5 Day	expressoMail1_2	en	5 Day
+5 Days	expressoMail1_2	en	5 Days
+Access right	expressoMail1_2	en	Access right
+Action	expressoMail1_2	en	Action
+Add BCC	expressoMail1_2	en	Add BCC
+Add CC	expressoMail1_2	en	Add CC
+Add Contact	expressoMail1_2	en	Add Contact
+Add user into my IM	expressoMail1_2	en	Add user into my IM
+Note: This sharing will take action on all of your folders and messages.	expressoMail1_2	en	Note: This sharing will take action on all of your folders and messages.
+all	expressoMail1_2	en	all
+Also check message against next rule	expressoMail1_2	en	Also check message against next rule
+Answered	expressoMail1_2	en	Answered
+l_answered	expressoMail1_2	en	Answered
+<b>Answer messages from:</b> %1 - <b>Status:</b><font color='red'> %2</font> - <b>message:</b> %3</a>	expressoMail1_2	en	<b>Answer messages from:</b> %1 - <b>Status:</b><font color='red'> %2</font> - <b>message:</b> %3</a>
+A read confirmation was sent.	expressoMail1_2	en	A read confirmation was sent.
+At %1, %2 hours, %3 wrote:	expressoMail1_2	en	At %1, %2 hours, %3 wrote:
+Back	expressoMail1_2	en	Back
+BCC	expressoMail1_2	en	BCC
+Big	expressoMail1_2	en	Big
+Bold	expressoMail1_2	en	Bold
+Block Sender	expressoMail1_2	en	Block Sender
+<b>Tip:</b> For faster save, click over the image with <u>right button</u>.	expressoMail1_2	en	<b>Tip:</b> For faster save, click over the image with <u>right button</u>.
+Call to Comercial Number	expressoMail1_2	en	Call to Comercial Number
+Call to Mobile Number	expressoMail1_2	en	Call to Mobile Number
+cancel	expressoMail1_2	en	cancel
+CC	expressoMail1_2	en	CC
+CCo	expressoMail1_2	en	CCo
+Change folder	expressoMail1_2	en	Change folder
+Choose a name	expressoMail1_2	en	Choose a name
+Chose the text you want transform in link before.	expressoMail1_2	en	Chose the text you want transform in link before.
+Clean	expressoMail1_2	en	Clean
+Click here do view (+)	expressoMail1_2	en	Click here do view (+)
+Click here to add into the fields	expressoMail1_2	en	Click here to add into the fields
+Close	expressoMail1_2	en	Close
+Coincident	expressoMail1_2	en	Coincident
+Command for spam	admin	en	Command for spam
+Command for unmark spam	admin	en	Command for unmark spam
+Config for ExpressoMail	expressoMail1_2	en	Config for ExpressoMail
+Cyrus IMAP Server	expressoMail1_2	en	Cyrus IMAP Server
+attachment	expressoMail1_2	en	attachment
+Attachments: add+	expressoMail1_2	en	Attachments: add+
+Attachments: 	expressoMail1_2	en	Attachments: 
+Attachments	expressoMail1_2	en	Attachments
+Date: 	expressoMail1_2	en	Date: 
+Date	expressoMail1_2	en	Date
+day(s)	expressoMail1_2	en	day(s)
+Define some criterion to the fields From, To and Subject with more than 3 characters!	expressoMail1_2	en	Define some criterion to the fields From, To and Subject with more than 3 characters!
+Define some search parameters!	expressoMail1_2	en	Define some search parameters!
+Delete	expressoMail1_2	en	Delete
+Delete trash messages after how many days?	expressoMail1_2	en	Delete trash messages after how many days?
+Delete your sub-folders first	expressoMail1_2	en	Delete your sub-folders first
+DISABLED	expressoMail1_2	en	DISABLED
+Disable	expressoMail1_2	en	Disable
+Download all atachments	expressoMail1_2	en	Download all atachments
+Download manual	expressoMail1_2	en	Download manual
+Do you really want to empty your trash folder?	expressoMail1_2	en	Do you really want to empty your trash folder?
+Do you wanna receive an alert for new messages?	expressoMail1_2	en	Do you wanna receive an alert for new messages?
+Do you want to block this e-mail?	expressoMail1_2	en	Do you want to block this e-mail?
+Do you want to log the sent messages?	admin	en	Do you want to log the sent messages?
+Do you want to use the spam filter?	admin	en	Do you want to use the spam filter?
+Do you wish to exclude the folder 	expressoMail1_2	en	Do you wish to exclude the folder 
+Draft	expressoMail1_2	en	Draft
+Drafts	expressoMail1_2	en	Drafts
+During	expressoMail1_2	en	During
+Drafts Folder name	admin	en	Drafts Folder name
+Edit	expressoMail1_2	en	Edit
+Edit filters	expressoMail1_2	en	Edit filters
+Edit folders	expressoMail1_2	en	Edit folders
+E-mail rule	expressoMail1_2	en	E-mail rule
+Emails of the account	expressoMail1_2	en	Emails of the account
+Empty Trash	expressoMail1_2	en	Empty Trash
+ENABLED	expressoMail1_2	en	ENABLED
+Enable	expressoMail1_2	en	Enable
+Enable Quick Reply	expressoMail1_2	en	Enable Quick Reply
+Enter a name for the box	expressoMail1_2	en	Enter a name for the box
+Enter the name of the new folder:	expressoMail1_2	en	Enter the name of the new folder:
+Enter with link URL:", "http://"	expressoMail1_2	en	Enter with link URL:", "http://"
+Delete folder	expressoMail1_2	en	Delete folder
+Erase the message	expressoMail1_2	en	Erase the message
+Error compressing messages (ZIP). Contact the administrator.	expressoMail1_2	en	Error compressing messages (ZIP). Contact the administrator.
+Error in SMTP sending read confirmation.	expressoMail1_2	en	Error in SMTP sending read confirmation.
+Error moving message.	expressoMail1_2	en	Error moving message.
+Exclusion	expressoMail1_2	en	Exclusion
+Export	expressoMail1_2	en	Export
+Export messages	expressoMail1_2	en	Export messages
+ExpressoMail 1.2 Configuration	expressoMail1_2	en	ExpressoMail 1.2 Configuration
+expressoMail1_2	expressoMail1_2	en	expressoMail1_2
+ExpressoMail settings	admin	en	ExpressoMail settings
+File extension forbidden	expressoMail1_2	en	File extension forbidden
+files	expressoMail1_2	en	files
+Filters	expressoMail1_2	en	Filters
+Filters maintenance	expressoMail1_2	en	Filters maintenance
+Filters management	expressoMail1_2	en	Filters management
+First	expressoMail1_2	en	First
+First Name	expressoMail1_2	en	First Name
+Folder	expressoMail1_2	en	Folder
+Folder Management	expressoMail1_2	en	Folder Management
+Folders	expressoMail1_2	en	Folders
+Font	expressoMail1_2	en	Font
+What the font size in the list of messages?	expressoMail1_2	en	What the font size in the list of messages?
+forecolor	expressoMail1_2	en	forecolor
+Forwarded	expressoMail1_2	en	Forwarded
+Forwarded message	expressoMail1_2	en	Forwarded message
+Forward	expressoMail1_2	en	Forward
+Forward to the address	expressoMail1_2	en	Forward to the address
+From: 	expressoMail1_2	en	From: 
+From	expressoMail1_2	en	From
+Global Catalog	expressoMail1_2	en	Global Catalog
+Go back	expressoMail1_2	en	Go back
+greater than	expressoMail1_2	en	greater than
+Groups	expressoMail1_2	en	Groups
+Hide menu folders?	expressoMail1_2	en	Hide menu folders?
+Hide options	expressoMail1_2	en	Hide options
+Hide Search	expressoMail1_2	en	Hide Search
+hlp_msg_addcreate_acl	expressoMail1_2	en	hlp_msg_addcreate_acl
+hlp_msg_delmov_acl	expressoMail1_2	en	hlp_msg_delmov_acl
+hlp_msg_read_acl	expressoMail1_2	en	hlp_msg_read_acl
+hlp_msg_sendlike_acl	expressoMail1_2	en	hlp_msg_sendlike_acl
+Imap Folders Properties	admin	en	Imap Folders Properties
+Important	expressoMail1_2	en	Important
+l_important	expressoMail1_2	en	Important
+In all the folders	expressoMail1_2	en	In all the folders
+Inbox	expressoMail1_2	en	Inbox
+indent	expressoMail1_2	en	indent
+Inform a forwarding e-mail!	expressoMail1_2	en	Inform a forwarding e-mail!
+Inform a message	expressoMail1_2	en	Inform a message
+Inform a text for rejection!	expressoMail1_2	en	Inform a text for rejection!
+Inform a valid e-mail!	expressoMail1_2	en	Inform a valid e-mail!
+Inform between 1 and 31!	expressoMail1_2	en	Inform between 1 and 31!
+Inform the days!	expressoMail1_2	en	Inform the days!
+Inform the forwarding e-mail(s)	expressoMail1_2	en	Inform the forwarding e-mail(s)
+Inform your search in the text fields	expressoMail1_2	en	Inform your search in the text fields
+insertorderedlist	expressoMail1_2	en	insertorderedlist
+Insert signature	expressoMail1_2	en	Insert signature
+insertunorderedlist	expressoMail1_2	en	insertunorderedlist
+in this message	expressoMail1_2	en	in this message
+italic	expressoMail1_2	en	italic
+Its %1 folder is not created. It is necessary to create so that it functions correctly.	expressoMail1_2	en	Its %1 folder is not created. It is necessary to create so that it functions correctly.
+It's not possible create inside: 	expressoMail1_2	en	It's not possible create inside: 
+It's not possible delete the folder: 	expressoMail1_2	en	It's not possible delete the folder: 
+It's not possible rename the folder: 	expressoMail1_2	en	It's not possible rename the folder: 
+It's not possible rename this folder!	expressoMail1_2	en	It's not possible rename this folder!
+It's not possible rename this folder, because it is being used in the moment!	expressoMail1_2	en	It's not possible rename this folder, because it is being used in the moment!
+justifycenter	expressoMail1_2	en	justifycenter
+justifyfull	expressoMail1_2	en	justifyfull
+justifyleft	expressoMail1_2	en	justifyleft
+justifyright	expressoMail1_2	en	justifyright
+Keep a copy of the message at your Inbox	expressoMail1_2	en	Keep a copy of the message at your Inbox
+Last	expressoMail1_2	en	Last
+Last Name	expressoMail1_2	en	Last Name
+Less	expressoMail1_2	en	Less
+Less than	expressoMail1_2	en	Less than
+Link	expressoMail1_2	en	Link
+List All	expressoMail1_2	en	List All
+List Catalog	expressoMail1_2	en	List Catalog
+List	expressoMail1_2	en	List
+list of the filters	expressoMail1_2	en	list of the filters
+Loading	expressoMail1_2	en	Loading
+Mailbox Sharing	expressoMail1_2	en	Mailbox Sharing
+Manager your folders and export messages	expressoMail1_2	en	Manager your folders and export messages
+Mark as	expressoMail1_2	en	Mark as
+Mark as Spam	expressoMail1_2	en	Mark as Spam
+What is the maximum number of messages per page?	expressoMail1_2	en	What is the maximum number of messages per page?
+Max size	expressoMail1_2	en	Max size
+Medium	expressoMail1_2	en	Medium
+Message body	expressoMail1_2	en	Message body
+message	expressoMail1_2	en	message
+minute ago	expressoMail1_2	en	minute ago
+minutes ago	expressoMail1_2	en	minutes ago
+hours ago	expressoMail1_2	en	hours ago
+Message Font	expressoMail1_2	en	Message Font
+Message Header	expressoMail1_2	en	Message Header
+Message marked as 	expressoMail1_2	en	Message marked as 
+message(s) deleted from your trash folder.	expressoMail1_2	en	message(s) deleted from your trash folder.
+messages	expressoMail1_2	en	messages
+messages found in folder:	expressoMail1_2	en	messages found in folder:
+Messages saved in %1 folder.	expressoMail1_2	en	Messages saved in %1 folder.
+More actions	expressoMail1_2	en	More actions
+More	expressoMail1_2	en	More
+More options	expressoMail1_2	en	More options
+More than %1 results. Please, try to refine your search.	expressoMail1_2	en	More than %1 results. Please, try to refine your search.
+More than 200 results were found	expressoMail1_2	en	More than 200 results were found
+Move	expressoMail1_2	en	Move
+Move to	expressoMail1_2	en	Move to
+My Folders	expressoMail1_2	en	My Folders
+New	expressoMail1_2	en	New
+New folder	expressoMail1_2	en	New folder
+New Message	expressoMail1_2	en	New Message
+New rule	expressoMail1_2	en	New rule
+Next	expressoMail1_2	en	Next
+Nickname	expressoMail1_2	en	Nickname
+No data to search	expressoMail1_2	en	No data to search
+None	expressoMail1_2	en	None
+None result was found.	expressoMail1_2	en	None result was found.
+No option marked!	expressoMail1_2	en	No option marked!
+normal	expressoMail1_2	en	normal
+now	expressoMail1_2	en	now
+No selected message.	expressoMail1_2	en	No selected message.
+No Subject	expressoMail1_2	en	No Subject
+Not Spam	expressoMail1_2	en	Not Spam
+Open chat window	expressoMail1_2	en	Open chat window
+Open in New Window	expressoMail1_2	en	Open in New Window
+Open search window...	expressoMail1_2	en	Open search window...
+Options	expressoMail1_2	en	Options
+Organization	expressoMail1_2	en	Organization
+outdent	expressoMail1_2	en	outdent
+out office	expressoMail1_2	en	out office
+Over quota	expressoMail1_2	en	Over quota
+Personal Catalog	expressoMail1_2	en	Personal Catalog
+Postfix with LDAP	expressoMail1_2	en	Postfix with LDAP
+People	expressoMail1_2	en	People
+Preferences	expressoMail1_2	en	Preferences
+Previous	expressoMail1_2	en	Previous
+Print	expressoMail1_2	en	Print
+Public Lists	expressoMail1_2	en	Public Lists
+Read	expressoMail1_2	en	Read
+Redo	expressoMail1_2	en	Redo
+Refresh	expressoMail1_2	en	Refresh
+Remove	expressoMail1_2	en	Remove
+Rename folder	expressoMail1_2	en	Rename folder
+Reply	expressoMail1_2	en	Reply
+Reply sent messages to	expressoMail1_2	en	Reply sent messages to
+Reply to all	expressoMail1_2	en	Reply to all
+Reply to all with history	expressoMail1_2	en	Reply to all with history
+Reply to all without history	expressoMail1_2	en	Reply to all without history
+Reply to	expressoMail1_2	en	Reply to
+Reply to sender	expressoMail1_2	en	Reply to sender
+Reply with history	expressoMail1_2	en	Reply with history
+Reply without history	expressoMail1_2	en	Reply without history
+Result of the search	expressoMail1_2	en	Result of the search
+Return receipt	expressoMail1_2	en	Return receipt
+Rule	expressoMail1_2	en	Rule
+Save as Draft	expressoMail1_2	en	Save as Draft
+Save deleted messages in trash folder?	expressoMail1_2	en	Save deleted messages in trash folder?
+Save Draft	expressoMail1_2	en	Save Draft
+Save	expressoMail1_2	en	Save
+Save in folder	expressoMail1_2	en	Save in folder
+Save sent messages in folder?	expressoMail1_2	en	Save sent messages in folder?
+Search	expressoMail1_2	en	Search
+Search for Organization	expressoMail1_2	en	Search for Organization
+Search in Catalog	expressoMail1_2	en	Search in Catalog
+Search in the Global Catalog	expressoMail1_2	en	Search in the Global Catalog
+Search Results	expressoMail1_2	en	Search Results
+ search results	expressoMail1_2	en	 search results
+Search the messages in these folders	expressoMail1_2	en	Search the messages in these folders
+Search user...	expressoMail1_2	en	Search user...
+Search user	expressoMail1_2	en	Search user
+Sector	expressoMail1_2	en	Sector
+Seen	expressoMail1_2	en	Seen
+l_seen	expressoMail1_2	en	Seen
+Select a folder:	expressoMail1_2	en	Select a folder:
+Select a folder!	expressoMail1_2	en	Select a folder!
+Select all messages.	expressoMail1_2	en	Select all messages.
+Select a name	expressoMail1_2	en	Select a name
+Select an organization and click on button <b>Search</b>	expressoMail1_2	en	Select an organization and click on button <b>Search</b>
+Select on send	expressoMail1_2	en	Select on send
+Select the type of contact that you want to view	expressoMail1_2	en	Select the type of contact that you want to view
+Select the user	expressoMail1_2	en	Select the user
+Send and file	expressoMail1_2	en	Send and file
+Send a rejection message	expressoMail1_2	en	Send a rejection message
+Sender's Information	expressoMail1_2	en	Sender's Information
+Send	expressoMail1_2	en	Send
+Send this message without a subject?	expressoMail1_2	en	Send this message without a subject?
+Send (without save)	expressoMail1_2	en	Send (without save)
+Sent by	expressoMail1_2	en	Sent by
+Sent	expressoMail1_2	en	Sent
+Sent Folder name	admin	en	Sent Folder name
+Service unavailable	expressoMail1_2	en	Service unavailable
+Shared folders	expressoMail1_2	en	Shared folders
+Shared options saved with success	expressoMail1_2	en	Shared options saved with success
+Share mailbox	expressoMail1_2	en	Share mailbox
+Show default view on main screen?	expressoMail1_2	en	Show default view on main screen?
+Showing only the results found in your organization	expressoMail1_2	en	Showing only the results found in your organization
+Show previous message, after delete actual message?	expressoMail1_2	en	Show previous message, after delete actual message?
+Signature	expressoMail1_2	en	Signature
+Signed message	expressoMail1_2	en	Signed message
+Size	expressoMail1_2	en	Size
+Small	expressoMail1_2	en	Small
+Spam	expressoMail1_2	en	Spam
+Spam Folder name	admin	en	Spam Folder name
+standard IMAP server	expressoMail1_2	en	standard IMAP server
+standard POP3 server	expressoMail1_2	en	standard POP3 server
+standard SMTP-Server	expressoMail1_2	en	standard SMTP-Server
+Status	expressoMail1_2	en	Status
+Store at	expressoMail1_2	en	Store at
+Subject	expressoMail1_2	en	Subject
+The Anti Pop-Up is enabled. Allow this site (%1) for print.	expressoMail1_2	en	The Anti Pop-Up is enabled. Allow this site (%1) for print.
+The field \"%1\" of the message it contains	expressoMail1_2	en	The field \"%1\" of the message it contains
+The folder %1 was successfully removed	expressoMail1_2	en	The folder %1 was successfully removed
+The folder was not deleted!	expressoMail1_2	en	The folder was not deleted!
+The list has no participant.	expressoMail1_2	en	The list has no participant.
+The messages were deleted.	expressoMail1_2	en	The messages were deleted.
+The messages were moved to folder 	expressoMail1_2	en	The messages were moved to folder 
+The message was deleted.	expressoMail1_2	en	The message was deleted.
+The message was moved to folder 	expressoMail1_2	en	The message was moved to folder 
+The origin folder and the destination folder are the same.	expressoMail1_2	en	The origin folder and the destination folder are the same.
+There's an action processing. Do you want abort it?	expressoMail1_2	en	There's an action processing. Do you want abort it?
+The results were found in the Global Catalog	expressoMail1_2	en	The results were found in the Global Catalog
+The size of the message is	expressoMail1_2	en	The size of the message is
+The size of this message has exceeded  the limit (%1B).	expressoMail1_2	en	The size of this message has exceeded  the limit (%1B).
+This message is already opened!	expressoMail1_2	en	This message is already opened!
+This message is already selected!	expressoMail1_2	en	This message is already selected!
+This message is signed, and you can trust.	expressoMail1_2	en	This message is signed, and you can trust.
+This message is signed, but it is invalid. You should not trust on it.	expressoMail1_2	en	This message is signed, but it is invalid. You should not trust on it.
+To: 	expressoMail1_2	en	To: 
+TO	expressoMail1_2	en	TO
+Tools	expressoMail1_2	en	Tools
+Trash	expressoMail1_2	en	Trash
+Trash Folder name	admin	en	Trash Folder name
+Type without spaces, dots or special characters!	expressoMail1_2	en	Type without spaces, dots or special characters!
+underlined	expressoMail1_2	en	underlined
+underline	expressoMail1_2	en	underline
+Undo	expressoMail1_2	en	Undo
+Unseen	expressoMail1_2	en	Unseen
+l_unseen	expressoMail1_2	en	Unseen
+Use F9 Key as shortcut.	expressoMail1_2	en	Use F9 Key as shortcut.
+Use shortcuts?	expressoMail1_2	en	Use shortcuts?
+User connected	instant_messenger	en	User connected
+User didn't accepted you yet	instant_messenger	en	User didn't accepted you yet
+User not connected	instant_messenger	en	User not connected
+User not registered	instant_messenger	en	User not registered
+Users	expressoMail1_2	en	Users
+View HTML source	expressoMail1_2	en	View HTML source
+View tips	expressoMail1_2	en	View tips
+Voided message	expressoMail1_2	en	Voided message
+Warning: Your Mailbox is almost full!	expressoMail1_2	en	Warning: Your Mailbox is almost full!
+ was succefully removed	expressoMail1_2	en	 was succefully removed
+What is the height of the lines in the list of messages?	expressoMail1_2	en	What is the height of the lines in the list of messages?
+Who	expressoMail1_2	en	Who
+With all	expressoMail1_2	en	With all
+Without Quota	expressoMail1_2	en	Without Quota
+without save	expressoMail1_2	en	without save
+with some	expressoMail1_2	en	with some
+With the following message	expressoMail1_2	en	With the following message
+Write	expressoMail1_2	en	Write
+Write message	expressoMail1_2	en	Write message
+wrote	expressoMail1_2	en	wrote
+You didn't accepted yet	instant_messenger	en	You didn't accepted yet
+You have %1 new	expressoMail1_2	en	You have %1 new
+You must wait while the messages will be exported...	expressoMail1_2	en	You must wait while the messages will be exported...
+Your Mailbox is 100% full! You must free more space or will not receive messages.	expressoMail1_2	en	Your Mailbox is 100% full! You must free more space or will not receive messages.
+Your mailbox is shared with	expressoMail1_2	en	Your mailbox is shared with
+Your message has not been sent and will be discarted.	expressoMail1_2	en	Your message has not been sent and will be discarted.
+Your message has not been sent. Discard your message?	expressoMail1_2	en	Your message has not been sent. Discard your message?
+Your message was save as draft in folder %1.	expressoMail1_2	en	Your message was save as draft in folder %1.
+Your message was sent and save.	expressoMail1_2	en	Your message was sent and save.
+Your message was sent.	expressoMail1_2	en	Your message was sent.
+Your search argument must be longer than 4 characters.	expressoMail1_2	en	Your search argument must be longer than 4 characters.
+your session could not be verified.	expressoMail1_2	en	your session could not be verified.
+Your Trash folder was empty.	expressoMail1_2	en	Your Trash folder was empty.
+Reached maximum tab limit	expressoMail1_2	en	Reached maximum tab limit
+Page Not Found!	expressoMail1_2	en	Page Not Found!
+This list has no participants	expressoMail1_2	en	This list has no participants
Index: tags/expressoMail1_2/1.2211/setup/phpmailer.lang-br.php
===================================================================
--- tags/expressoMail1_2/1.2211/setup/phpmailer.lang-br.php	(revision 16)
+++ tags/expressoMail1_2/1.2211/setup/phpmailer.lang-br.php	(revision 16)
@@ -0,0 +1,23 @@
+<?php
+	/**
+	* PHPMailer language file.
+	* Portuguese Version
+	* By Paulo Henrique Garcia - paulo@controllerweb.com.br
+	*/
+	  
+	$PHPMAILER_LANG = array();
+	$PHPMAILER_LANG["provide_address"] = 'Voc&ecirc; deve fornecer pelo menos um endere&ccedil;o de destinat&aacute;rio de email.';
+	$PHPMAILER_LANG["mailer_not_supported"] = 'Mailer n&atilde;o suportado.';
+	$PHPMAILER_LANG["execute"] = 'N&atilde;o foi poss&iacute;vel executar: ';
+	$PHPMAILER_LANG["instantiate"] = 'N&atilde;o foi poss&iacute;vel instanciar a fun&ccedil;&atilde;o mail.';
+	$PHPMAILER_LANG["authenticate"] = 'Erro de SMTP: N&atilde;o foi poss&iacute;vel autenticar.';
+	$PHPMAILER_LANG["from_failed"] = 'Os endere&ccedil;os de remetente a seguir falharam: ';
+	$PHPMAILER_LANG["recipients_failed"] = 'Erro de SMTP: Os endere&ccedil;os de destinat&aacute;rio a seguir falharam: ';
+	$PHPMAILER_LANG["data_not_accepted"] = 'Erro de SMTP: Dados n&atilde;o aceitos.';
+	$PHPMAILER_LANG["connect_host"] = 'Erro de SMTP: N&atilde;o foi poss&iacute;vel conectar com o servidor SMTP.';
+	$PHPMAILER_LANG["file_access"] = 'N&atilde;o foi poss&iacute;vel acessar o arquivo: ';
+	$PHPMAILER_LANG["file_open"] = 'Erro de Arquivo: N&atilde;o foi poss&iacute;vel abrir o arquivo: ';
+	$PHPMAILER_LANG["encoding"] = 'Codifica&ccedil;&atilde;o desconhecida: ';
+	$PHPMAILER_LANG["not_allowed"] = 'Voc&ecirc; n&atilde;o tem permiss&atilde;o para enviar emails para: ';
+?>
+
Index: tags/expressoMail1_2/1.2211/setup/tables_current.inc.php
===================================================================
--- tags/expressoMail1_2/1.2211/setup/tables_current.inc.php	(revision 2)
+++ tags/expressoMail1_2/1.2211/setup/tables_current.inc.php	(revision 2)
@@ -0,0 +1,36 @@
+<?php
+	/**************************************************************************\
+	* Expresso Administração                 										                                 *
+	* by Joao Alfredo Knopik Junior (joao.alfredo@gmail.com, jakjr@celepar.pr.gov.br)  	 *
+	* -----------------------------------------------------------------------------------------------------*
+	*  This program is free software; you can redistribute it and/or modify it					 *
+	*  under the terms of the GNU General Public License as published by the				 *
+	*  Free Software Foundation; either version 2 of the License, or (at your					 *
+	*  option) any later version.																						 *
+	\**************************************************************************/
+
+	$phpgw_baseline = array(
+		'phpgw_expressoMail_serverconfig' => array(
+			'fd' => array(
+				'id'		=> array('type' => 'varchar','precision' => 50,'nullable' => false),
+				'ip_smtp'	=> array('type' => 'varchar','precision' => 255,'nullable' => false),
+				'port_smtp'	=> array('type' => 'varchar','precision' => 100,'nullable' => false)
+			),
+			'pk' => array(),
+			'fk' => array(),
+			'ix' => array(),
+			'uc' => array()
+		),
+
+		'phpgw_expressoMail_preferences' => array(
+			'fd' => array(
+				'user_id'	=> array('type' => 'varchar','precision' => 50,'nullable' => false),
+				'signtur'	=> array('type' => 'varchar','precision' => 255,'nullable' => false)
+			),
+			'pk' => array(),
+			'fk' => array(),
+			'ix' => array(),
+			'uc' => array()
+		)
+	);
+?>
Index: tags/expressoMail1_2/1.2211/setup/setup.inc.php
===================================================================
--- tags/expressoMail1_2/1.2211/setup/setup.inc.php	(revision 271)
+++ tags/expressoMail1_2/1.2211/setup/setup.inc.php	(revision 271)
@@ -0,0 +1,41 @@
+<?php
+	/**********************************************************************************\
+	* Expresso Administração                 										   *
+	* by Joao Alfredo Knopik Junior (joao.alfredo@gmail.com, jakjr@celepar.pr.gov.br)  *
+	* ---------------------------------------------------------------------------------*
+	*  This program is free software; you can redistribute it and/or modify it         *
+	*  under the terms of the GNU General Public License as published by the           *
+	*  Free Software Foundation; either version 2 of the License, or (at your          *
+	*  option) any later version.											           *
+	\**********************************************************************************/
+
+	$setup_info['expressoMail1_2']['name']      	= 'expressoMail1_2';
+	$setup_info['expressoMail1_2']['title']     	= 'ExpressoMail 1.2';
+	$setup_info['expressoMail1_2']['version']   	= '1.2211';
+	$setup_info['expressoMail1_2']['app_order'] 	= 2;
+//	$setup_info['expressoMail1_2']['tables'][]    	= 'phpgw_expressoMail1_2';
+//	$setup_info['expressoMail1_2']['tables'][]    	= 'phpgw_expressoMail1_2_apps';
+//	$setup_info['expressoMail1_2']['tables'][]		= 'phpgw_expressoMail1_2_log';
+	$setup_info['expressoMail1_2']['enable']    	= 1;
+
+	$setup_info['expressoMail1_2']['author'] = 	'João Alfredo Knopik Junior'.
+												' (joao.alfredo@gmail.com / jakjr@celepar.pr.gov.br)<br>'.
+												'Nilton Emílio Bührer Neto'.
+												' (nilton.neto@gmail.com / niltonneto@celepar.pr.gov.br)';
+	$setup_info['expressoMail1_2']['maintainer'] =  'Empresa ou Instituição onde o seu Expresso está instalado.';
+	$setup_info['expressoMail1_2']['maintainer_email'] = '';
+
+	$setup_info['expressoMail1_2']['license']  = 'GPL';
+	$setup_info['expressoMail1_2']['description'] = 'Módulo de Email, usando metodologia AJAX';
+
+	/* The hooks this app includes, needed for hooks registration */
+	$setup_info['expressoMail1_2']['hooks'][] = 'preferences';
+	$setup_info['expressoMail1_2']['hooks'][] = 'admin';
+	$setup_info['expressoMail1_2']['hooks'][] = 'home';	
+	
+	/* Dependencies for this app to work */
+	$setup_info['expressoMail1_2']['depends'][] = array(
+		'appname' => 'phpgwapi',
+		'versions' => Array('0.9.14','0.9.15','1.0.0')
+	);
+?>
Index: tags/expressoMail1_2/1.2211/preferences.php
===================================================================
--- tags/expressoMail1_2/1.2211/preferences.php	(revision 271)
+++ tags/expressoMail1_2/1.2211/preferences.php	(revision 271)
@@ -0,0 +1,218 @@
+<?php
+	/**************************************************************************/
+	
+	$GLOBALS['phpgw_info']['flags'] = array(
+		'currentapp' => 'expressoMail1_2',
+		'noheader'   => True, 
+		'nonavbar'   => True,
+		'enable_nextmatchs_class' => True
+	);
+
+	include('../header.inc.php');
+	include('inc/class.imap_functions.inc.php');
+	
+	if (!$_POST['try_saved'])
+	{
+		// Read Config and get default values;
+		
+		$GLOBALS['phpgw']->preferences->read_repository();
+		
+		if($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['max_email_per_page'])
+			$GLOBALS['phpgw']->template->set_var('option_'.$GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['max_email_per_page'].'_selected','selected');
+		else
+		$GLOBALS['phpgw']->template->set_var('option_50_selected','selected');		
+
+		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['save_deleted_msg'])		
+			$GLOBALS['phpgw']->template->set_var('checked_save_deleted_msg','checked');
+		else
+			$GLOBALS['phpgw']->template->set_var('checked_save_deleted_msg','');
+
+		if($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['delete_trash_messages_after_n_days'])
+			$GLOBALS['phpgw']->template->set_var('delete_trash_messages_option_'.$GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['delete_trash_messages_after_n_days'].'_selected','selected');
+		else
+			$GLOBALS['phpgw']->template->set_var('delete_trash_messages_option_0_selected','selected');		
+		
+		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['delete_and_show_previous_message'])		
+			$GLOBALS['phpgw']->template->set_var('checked_delete_and_show_previous_message','checked');
+		else
+			$GLOBALS['phpgw']->template->set_var('checked_delete_and_show_previous_message','');
+
+		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['alert_new_msg'])		
+			$GLOBALS['phpgw']->template->set_var('checked_alert_new_msg','checked');
+		else
+			$GLOBALS['phpgw']->template->set_var('checked_alert_new_msg','');
+
+		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['mainscreen_showmail'])
+			$GLOBALS['phpgw']->template->set_var('checked_mainscreen_showmail','checked');
+		else
+			$GLOBALS['phpgw']->template->set_var('checked_mainscreen_showmail','');
+
+		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['use_shortcuts'])
+			$GLOBALS['phpgw']->template->set_var('checked_shortcuts','checked');
+		else
+			$GLOBALS['phpgw']->template->set_var('checked_shortcuts','');
+
+		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['auto_save_draft'])
+			$GLOBALS['phpgw']->template->set_var('checked_auto_save_draft','checked');
+		else
+			$GLOBALS['phpgw']->template->set_var('checked_auto_save_draft','');
+
+		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['signature'])
+			$GLOBALS['phpgw']->template->set_var('text_signature',$GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['signature']);
+		else
+			$GLOBALS['phpgw']->template->set_var('text_signature','');
+
+		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['hide_folders'])
+			$GLOBALS['phpgw']->template->set_var('checked_menu','checked');
+		else
+			$GLOBALS['phpgw']->template->set_var('checked_menu','');
+
+		if($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['line_height'])
+			$GLOBALS['phpgw']->template->set_var('line_height_option_'.$GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['line_height'].'_selected','selected');
+		else
+			$GLOBALS['phpgw']->template->set_var('line_height_option_20_selected','selected');
+		
+		if($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['font_size'])
+			$GLOBALS['phpgw']->template->set_var('font_size_option_'.$GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['font_size'].'_selected','selected');
+		else
+			$GLOBALS['phpgw']->template->set_var('font_size_option_11_selected','selected');
+	}
+	else //Save Config
+	{
+		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['max_email_per_page'])
+			$GLOBALS['phpgw']->preferences->change('expressoMail','max_email_per_page',$_POST['max_emails_per_page']);
+		else
+			$GLOBALS['phpgw']->preferences->add('expressoMail','max_email_per_page',$_POST['max_emails_per_page']);
+		
+		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['save_deleted_msg'])
+			$GLOBALS['phpgw']->preferences->change('expressoMail','save_deleted_msg',$_POST['save_deleted_msg']);
+		else
+			$GLOBALS['phpgw']->preferences->add('expressoMail','save_deleted_msg',$_POST['save_deleted_msg']);
+
+		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['delete_trash_messages_after_n_days'])
+			$GLOBALS['phpgw']->preferences->change('expressoMail','delete_trash_messages_after_n_days',$_POST['delete_trash_messages_after_n_days']);
+		else
+			$GLOBALS['phpgw']->preferences->add('expressoMail','delete_trash_messages_after_n_days',$_POST['delete_trash_messages_after_n_days']);
+
+		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['delete_and_show_previous_message'])
+			$GLOBALS['phpgw']->preferences->change('expressoMail','delete_and_show_previous_message',$_POST['delete_and_show_previous_message']);
+		else
+			$GLOBALS['phpgw']->preferences->add('expressoMail','delete_and_show_previous_message',$_POST['delete_and_show_previous_message']);
+		
+		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['alert_new_msg'])
+			$GLOBALS['phpgw']->preferences->change('expressoMail','alert_new_msg',$_POST['alert_new_msg']);
+		else
+			$GLOBALS['phpgw']->preferences->add('expressoMail','alert_new_msg',$_POST['alert_new_msg']);
+
+		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['mainscreen_showmail'])
+			$GLOBALS['phpgw']->preferences->change('expressoMail','mainscreen_showmail',$_POST['mainscreen_showmail']);
+		else
+			$GLOBALS['phpgw']->preferences->add('expressoMail','mainscreen_showmail',$_POST['mainscreen_showmail']);
+
+		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['use_shortcuts'])
+			$GLOBALS['phpgw']->preferences->change('expressoMail','use_shortcuts',$_POST['use_shortcuts']);
+		else
+			$GLOBALS['phpgw']->preferences->add('expressoMail','use_shortcuts',$_POST['use_shortcuts']);
+			
+		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['auto_save_draft'])
+			$GLOBALS['phpgw']->preferences->change('expressoMail','auto_save_draft',$_POST['auto_save_draft']);
+		else
+			$GLOBALS['phpgw']->preferences->add('expressoMail','auto_save_draft',$_POST['auto_save_draft']);	
+
+		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['signature'])
+			$GLOBALS['phpgw']->preferences->change('expressoMail','signature',$_POST['signature']);
+		else
+			$GLOBALS['phpgw']->preferences->add('expressoMail','signature',$_POST['signature']);
+
+		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['hide_folders'])
+			$GLOBALS['phpgw']->preferences->change('expressoMail','hide_folders',$_POST['check_menu']);
+		else
+			$GLOBALS['phpgw']->preferences->add('expressoMail','hide_folders',$_POST['check_menu']);
+			
+		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['save_in_folder'])
+			$GLOBALS['phpgw']->preferences->change('expressoMail','save_in_folder',$_POST['save_in_folder']);
+		else
+			$GLOBALS['phpgw']->preferences->add('expressoMail','save_in_folder',$_POST['save_in_folder']);
+
+		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['line_height'])
+			$GLOBALS['phpgw']->preferences->change('expressoMail','line_height',$_POST['line_height']);
+		else
+			$GLOBALS['phpgw']->preferences->add('expressoMail','line_height',$_POST['line_height']);
+		
+		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['font_size'])
+			$GLOBALS['phpgw']->preferences->change('expressoMail','font_size',$_POST['font_size']);
+		else
+			$GLOBALS['phpgw']->preferences->add('expressoMail','font_size',$_POST['font_size']);		
+
+		$GLOBALS['phpgw']->preferences->save_repository();
+		
+		// Back to preferences.
+		$url = ($GLOBALS['phpgw']->link('/'.'expressoMail1_2'.'/index.php'));
+		$GLOBALS['phpgw']->redirect($url);
+	}
+	
+	$GLOBALS['phpgw']->common->phpgw_header();
+	print parse_navbar();
+
+	$GLOBALS['phpgw']->template->set_file(array(
+		'expressoMail_prefs' => 'preferences.tpl'
+	));
+
+	$GLOBALS['phpgw']->template->set_var('lang_config_expressoMail',lang('Config for ExpressoMail'));
+	$GLOBALS['phpgw']->template->set_var('lang_max_emails_per_page',lang('What is the maximum number of messages per page?'));
+	$GLOBALS['phpgw']->template->set_var('lang_save_deleted_msg',lang('Save deleted messages in trash folder?'));
+	$GLOBALS['phpgw']->template->set_var('lang_delete_trash_messages_after_n_days',lang('Delete trash messages after how many days?'));
+	$GLOBALS['phpgw']->template->set_var('lang_delete_and_show_previous_message',lang('Show previous message, after delete actual message?'));
+	$GLOBALS['phpgw']->template->set_var('lang_alert_new_msg',lang('Do you wanna receive an alert for new messages?'));
+	$GLOBALS['phpgw']->template->set_var('lang_hook_home',lang('Show default view on main screen?'));
+	$GLOBALS['phpgw']->template->set_var('lang_save_in_folder',lang('Save sent messages in folder'));
+	$GLOBALS['phpgw']->template->set_var('lang_hide_menu',lang('Hide menu folders?'));
+	$GLOBALS['phpgw']->template->set_var('lang_line_height',lang('What is the height of the lines in the list of messages?'));
+	$GLOBALS['phpgw']->template->set_var('lang_font_size',lang('What the font size in the list of messages?'));
+	$GLOBALS['phpgw']->template->set_var('lang_use_shortcuts',lang('Use shortcuts?'));
+	$GLOBALS['phpgw']->template->set_var('lang_auto_save_draft',lang('Auto save draft'));
+	$GLOBALS['phpgw']->template->set_var('lang_signature',lang('Signature'));
+	$GLOBALS['phpgw']->template->set_var('lang_none',lang('None'));
+	$GLOBALS['phpgw']->template->set_var('one_day',lang('1 Day'));
+	$GLOBALS['phpgw']->template->set_var('two_days',lang('2 Days'));
+	$GLOBALS['phpgw']->template->set_var('three_days',lang('3 Days'));
+	$GLOBALS['phpgw']->template->set_var('four_days',lang('4 Days'));
+	$GLOBALS['phpgw']->template->set_var('five_days',lang('5 Day'));
+	$GLOBALS['phpgw']->template->set_var('small',lang('Small'));
+	$GLOBALS['phpgw']->template->set_var('medium',lang('Medium'));
+	$GLOBALS['phpgw']->template->set_var('normal',lang('Normal'));
+	$GLOBALS['phpgw']->template->set_var('big',lang('Big'));
+
+	$boemailadmin	= CreateObject('emailadmin.bo');
+	$emailadmin_profile = $boemailadmin->getProfileList();
+	$_SESSION['phpgw_info']['expressomail']['email_server'] = $boemailadmin->getProfile($emailadmin_profile[0]['profileID']);
+	$_SESSION['phpgw_info']['expressomail']['user'] = $GLOBALS['phpgw_info']['user'];
+	$imap = CreateObject('expressoMail1_2.imap_functions');	
+	$save_in_folder_selected = $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['save_in_folder'];
+	// First access on ExpressoMail, load default preferences...
+	if(!$GLOBALS['phpgw_info']['user']['preferences']['expressoMail']) {
+		$GLOBALS['phpgw']->template->set_var('checked_save_deleted_msg','checked');
+		$GLOBALS['phpgw']->template->set_var('checked_delete_and_show_previous_message','checked');
+		$GLOBALS['phpgw']->template->set_var('checked_alert_new_msg','checked');
+		$GLOBALS['phpgw']->template->set_var('checked_mainscreen_showmail','checked');
+		$save_in_folder_selected = "INBOX".$_SESSION['phpgw_info']['expressomail']['email_server']['imapDelimiter']."Enviados";
+	}
+	$o_folders = "<option value='-1' ".(!$save_in_folder_selected ? 'selected' : '' ).">".lang("Select on send")."</option>";
+	foreach($imap -> get_folders_list() as $id => $folder)
+		$o_folders.= "<option value='".$folder['folder_id']."' ".($save_in_folder_selected == $folder['folder_id'] ? 'selected' : '' ).">".$folder['folder_name']."</option>";		
+	$GLOBALS['phpgw']->template->set_var('value_save_in_folder',$o_folders);	
+
+	$GLOBALS['phpgw']->template->set_var('lang_save',lang('Save'));
+	$GLOBALS['phpgw']->template->set_var('lang_cancel',lang('Cancel'));
+	
+	$GLOBALS['phpgw']->template->set_var('save_action',$GLOBALS['phpgw']->link('/'.'expressoMail1_2'.'/preferences.php'));
+	$GLOBALS['phpgw']->template->set_var('th_bg',$GLOBALS['phpgw_info']["theme"][th_bg]);
+
+	$tr_color = $GLOBALS['phpgw']->nextmatchs->alternate_row_color($tr_color);
+	$GLOBALS['phpgw']->template->set_var('tr_color1',$GLOBALS['phpgw_info']['theme']['row_on']);
+	$GLOBALS['phpgw']->template->set_var('tr_color2',$GLOBALS['phpgw_info']['theme']['row_off']);
+
+	$GLOBALS['phpgw']->template->parse('out','expressoMail_prefs',True);
+	$GLOBALS['phpgw']->template->p('out');
+	$GLOBALS['phpgw']->common->phpgw_footer();
+?>
Index: tags/expressoMail1_2/1.2211/docs/change_log.txt
===================================================================
--- tags/expressoMail1_2/1.2211/docs/change_log.txt	(revision 51)
+++ tags/expressoMail1_2/1.2211/docs/change_log.txt	(revision 51)
@@ -0,0 +1,101 @@
+Esse arquivo descreve todas as correções, alterações e novas implementações do 
+módulo ExpressoMail 1.2, e a partir da versão 07/12/2006 [1.2]
+Nilton Emilio Buhrer Neto.
+
+--------------------------- NOTA IMPORTANTE --------------------------
+
+A partir de Agosto de 2007, todos os registros de bugs aqui relatados foram
+transferidos para o site do ExpressoLivre, no Wiki-Trac do módulo.
+Vide: http://www.expressolivre.org/dev/wiki/mail/changelog
+
+----------------------------------------------------------------------
+06/02/2007 - [1.2022]
+- Fixado o layer que compreende o menu da nova mensagem (Enviar, Salvar,Pesquisar);
+- Implementado a pesquisa rápida de mensagens, em todas as pastas, na janela principal do módulo;
+- Corrigido problema ao imprimir mensagens com figuras (não estava aparecendo as figuras);
+- Corrigido problema do autocompletar, no Internet Explorer, quando tinha um scroll na aba, o layer em branco não estava posicionado corretamente;
+- Corrigido problema com envio de mensagens para grupos pessoais, quando o link vinha do módulo Contact Center;
+- Corrigido problema com mensagens que continham anexos TXT, que se expandia no corpo da mensagem. Agora não expande mais.
+
+16/02/2007 - [1.2023]
+- Inserido um atraso na abertura do menu Ferramentas, para não atrapalhar a navegação;
+- Implementado uma RegExp para que links dentro das mensagens sejam abertos em nova janela;
+- Corrigido problema da abertura da janela do "Enviar e Arquivar", que estava conflitando com o módulo IM;
+
+27/02/2007 - [1.2024]
+- Corrigido problemas eventuais ocasionados pelas novas versões do Firefox 1.5 (1.5.0.10) e 2.0 (2.0.0.2), que gerou problema
+no carregamento dos Javascripts sob demanda.
+
+03/03/2007 - [1.2025]
+- Corrigido problema na lista de mensagens, quando há assuntos com caracteres especiais.
+- Implementada mais uma funcionalidade: em Compartilhar Pastas, o usuário poderá liberar o seu nome/email para ser utilizado
+no envio de mensagens por outros usuários.
+- Corrigido problemas no manuseio da funcionalidade de compartilhar pastas.
+- Corrigido bug no DropDownContact (2 palavras) e scroll escondemos o DropDownContact caso o scroll seja utilizado.
+- Corrigido Scroll com Paleta de Cores no Texto Rico
+- Ordenado as teclas de TAB em nova mensagem.
+
+06/03/2007 - [1.2026]
+- Alterada a maneira de como está implementada, a funcionalidade de liberar usuários, para envio pela sua caixa postal. Agora
+o usuário que envia, seta o "Sender", e o usuário compartilhado permanece no "From", seguindo o padrão correto.
+- Corrigido problema no checkbox Ocultar Menu Pastas, na tela de Preferencias, que não estava salvando quando ia pelo link
+das "Minhas Preferências".
+- Corrigido problema ao Salvar Rascunho, onde os destinatários (Para,CC) estavam sendo salvos com charset incorreto.
+
+13/03/2007 - [1.2027]
+- Corrigido problema ao abrir mensagem formato HTML, contendo a tag HEADER: Influenciava no layout inteiro da página.
+- Corrigido problema ao inserir assinatura com apóstrofo, aspas, e outros caracteres especiais (addslashes);
+- Corrigido problema nas pastas com espaço: Ao enviar e salvar automático nessas pastas, dava problema.
+- Corrigido problema de visualização de algumas mensagens encaminhadas pelo Evolution, ThunderBird, etc.
+- Adicionada função getLang na classe Functions, para ser utilizada dentro das classes PHP do ExpressoMail.
+- Adicionada função replace_links na classe imap_functions, que será utilizada futuramente para habilitar links dentro das mensagens.
+
+29/03/2007 - [1.2028]
+- Corrigido problema ao encaminhar mensagens com anexos, pois não preservava o encoding original (base64,qprint,text).
+- Corrigido problema ao fazer download de anexos com extensão em caixa alta e com "." (pontos) no seu nome.
+- Corrigido problema ao fazer download de anexos no formato qprint. Função imap_qprint() contém um bug, e foi substituída pela
+função quoted_printable_decode().
+- Incluído validação do email a ser bloqueado pelo botão "Bloquear Remetente".
+- Incluído validação do email ao criar um regra na opção Filtros.
+- Corrigido problema que dava nas preferências do usuário, com a pasta de mensagens Enviadas. Quando mudava o cyrus delimiter
+no Expresso ("." ou "/"), a pasta de Enviados salva no banco ficava com delimitador diferente do atual, dando problema ao salvar
+mensagens enviadas e ao abrir janela de Preferências.
+
+01/04/2007 - [1.2029]
+- Corrigido problema na leitura de algumas mensagens do tipo text/plain, multipart e charset=utf-8. Dependendo da estrutura da
+mensagem, o atributo charset vinha em branco e ficava em outro lugar não padrão (parameters).
+em outro parametro não padrão.
+- Adicionada funcionalidade que compatibiliza mensagens encapsuladas, e com formato 7bit, serem visualizadas no ExpressoMail.
+
+10/05/2007 - [1.2030]
+- Implementado mesma funcionalidade do expandir Campo "Para" para o campo "CC", abrir uma mensagem. O objetivo é evitar travamento
+do navegador quando existem muito destinatários a serem expandidos com o plugin do Contact Center.
+- Corrigido problema de mensagens que têm nome de arquivos nos atributos "parameters" e "dparameters" de sua estrutura.
+- Implementado ocultação de usuários e grupos no expressoMail e na Calendar.
+- Corrigido imagem down.button.png que aparecia com fundo branco no IE;
+- Alterado nome do link "Mais opções" para "Opções", no menu de mensagem aberta;
+- Colocado link "Imprimir" entre os links "Opções" e "Encaminhar", no menu de mensagem aberta;
+
+10/05/2007 - [1.2031]
+- Mensagens plain com subtype = "mixed", com anexo, estavam sendo abertas no corpo da mensagem.
+- Correção de todas as chamadas da função imap_open, para não gerar erro com conexões não assinadas "/notls/novalidate-cert"
+- Implementado Busca Rápida de Detalhes do Remetente da Mensagem, se no Contato Pessoal e Geral.
+
+30/05/2007 - [1.2032]
+- Corrigido problema ao montar lista de mensagens, quando alguma delas tinha no campo "Para", caracteres especiais.
+- Modificada a implementação da Busca rápida de Detalhes do Remetente da Mensagem, para preparar a integração com os demais serviços.
+
+09/07/2007 - [1.2033]
+- Corrigido problema na funcionalidade filtros, que não permitia adicionar filtro quando se definia tamanho máximo de mensagem.
+- Corrigido problema no campo "Responder Para", quando esse possuía formato HTML.
+- Modificado link do botão Cancelar, do template das preferências.
+- Corrigido problema na busca rápida.
+
+02/08/2007 - [1.21]
+- Feito um "refactor" da classe imap_functions, para reduzir as conexoes criadas com o IMAP.
+- Implementado filtros por flag (todas, não lidas, lidas, respondidas, importantes) na lista de mensagens.
+- O link da Ajuda do módulo foi movido para a Ajuda Geral do Expresso, ao lado de Sugestões.
+- O link Dicas e a página foram removidos.
+- Alterado alguns valores de ajuste de layout.
+- Corrigido problema dos Filtros de mensagens, quando esses possuíam caracteres especiais.
+- Implementado suporte a caracteres especiais nas Pastas.
Index: tags/expressoMail1_2/1.2211/help/dicas.html
===================================================================
--- tags/expressoMail1_2/1.2211/help/dicas.html	(revision 2)
+++ tags/expressoMail1_2/1.2211/help/dicas.html	(revision 2)
@@ -0,0 +1,74 @@
+<html>
+	<head>
+		<title>Expresso Livre</title>
+	</head>
+	<body style="margin:0px;padding:0">
+	<table width="100%"><tr><td align="right" background="images/fundo_topo.jpg"><a name="0"><img src="images/topo.jpg?1"></a></td></tr></table>
+	<div style="margin:10px">
+
+	<font face="Arial" size="2"><center><b>Dicas importantes de utilização</b></center></font><br>
+	<font face="Arial" size="2">
+		O <b><i>Expresso Mail 1.2</i></b> possui várias inovações e modificações.<br>Veja a seguir as dúvidas mais freqüentes:<br><br>		
+		<font face="Arial" size="2">
+		<div style="cursor:pointer" width="100%" onClick="javascript:location.href='#1'"><b><i>&nbsp;&nbsp;1.&nbsp;</i></b><font size="2" style="text-decoration:underline" color="DARKBLUE">Por que mudou o layout?</font></div>
+		<div style="cursor:pointer" width="100%" onClick="javascript:location.href='#2'"><b><i>&nbsp;&nbsp;2.&nbsp;</i></b><font size="2" style="text-decoration:underline" color="DARKBLUE">Onde está o menu Mais ações?</font></div>
+		<div style="cursor:pointer" width="100%" onClick="javascript:location.href='#3'"><b><i>&nbsp;&nbsp;3.&nbsp;</i></b><font size="2" style="text-decoration:underline" color="DARKBLUE">Como mover mensagens?</font></div>
+		<div style="cursor:pointer" width="100%" onClick="javascript:location.href='#4'"><b><i>&nbsp;&nbsp;4.&nbsp;</i></b><font size="2" style="text-decoration:underline" color="DARKBLUE">Como criar Pastas e subpastas?</font></div>
+		<div style="cursor:pointer" width="100%" onClick="javascript:location.href='#5'"><b><i>&nbsp;&nbsp;5.&nbsp;</i></b><font size="2" style="text-decoration:underline" color="DARKBLUE">Como pesquisar mensagens?</font></div>
+		<div style="cursor:pointer" width="100%" onClick="javascript:location.href='#6'"><b><i>&nbsp;&nbsp;6.&nbsp;</i></b><font size="2" style="text-decoration:underline" color="DARKBLUE">Como enviar novas mensagens?</font></div>
+		<div style="cursor:pointer" width="100%" onClick="javascript:location.href='#7'"><b><i>&nbsp;&nbsp;7.&nbsp;</i></b><font size="2" style="text-decoration:underline" color="DARKBLUE">Como ver mais informações de uma mensagem?</font></div>
+		<div style="cursor:pointer" width="100%" onClick="javascript:location.href='#8'"><b><i>&nbsp;&nbsp;8.&nbsp;</i></b><font size="2" style="text-decoration:underline" color="DARKBLUE">Como me proteger contra mensagens indesejáveis?</font></div>
+		<div style="cursor:pointer" width="100%" onClick="javascript:location.href='#9'"><b><i>&nbsp;&nbsp;9.&nbsp;</i></b><font size="2" style="text-decoration:underline" color="DARKBLUE">E as minhas preferências continuam as mesmas? </font></div>		
+		<div style="cursor:pointer" width="100%" onClick="javascript:location.href='#10'"><b><i>10.&nbsp;</i></b><font size="2" style="text-decoration:underline" color="DARKBLUE">Mais Dúvidas....</font></div><br>
+		<br><br></font>
+		<b><a name="1">1.&nbsp;</a>Por que mudou o layout?</b><p style="text-align:justify">As pastas agora estão dispostas na área esquerda do
+		Expresso Mail, facilitando a navegação entre elas. Foi extinto o menu principal, sendo substituído pelo
+		menu na área esquerda da tela. Essa área esquerda da tela pode ser ocultada (em Ferramentas / Preferências ), para aumentar sua visualização
+		das mensagens. A barra de capacidade da sua caixa postal foi movida para cima. Este novo layout vem 
+		para melhorar a visualização das ferramentas à sua disposição.<div style="cursor:pointer" align="right" width="100%" onClick="javascript:location.href='#0'" title="Subir para o topo da página"><img border=0 src ='../templates/default/images/arrow_descendant.gif'><font color="DARKBLUE" size="1"><b>Voltar</b></font></div></p>
+		<b><a name="2">2.&nbsp;</a>Onde está o menu Mais ações?</b><p style="text-align:justify">Para efetuar ações como marcar, apagar e exportar, que antes ficavam
+		acessíveis pelo menu principal, agora são feitas rapidamente clicando com o botão direito
+		sobre as mensagens selecionadas.<div style="cursor:pointer" align="right" width="100%" onClick="javascript:location.href='#0'" title="Subir para o topo da página"><img border=0 src ='../templates/default/images/arrow_descendant.gif'><font color="DARKBLUE" size="1"><b>Voltar</b></font></div></p>
+		<b><a name="3">3.&nbsp;</a>Como mover mensagens? </b><p style="text-align:justify">Com a implementação do item arrastar e soltar (<i>Drag'N Drop</i>), 
+		para mover as mensagens selecionadas, basta arrastá-las para a pasta de destino e soltar.
+		Caso a mensagem esteja aberta (sendo lida), apenas clique sobre o título na aba da mensagem, e arraste 
+		sobre a sua pasta de destino.<div style="cursor:pointer" align="right" width="100%" onClick="javascript:location.href='#0'" title="Subir para o topo da página"><img border=0 src ='../templates/default/images/arrow_descendant.gif'><font color="DARKBLUE" size="1"><b>Voltar</b></font></div></p>
+		<b><a name="4">4.&nbsp;</a>Como criar Pastas e subpastas? </b><p style="text-align:justify">O item <i>Editar Pastas</i> foi totalmente refeito. Além 
+		de ficar mais intuitivo para o usuário, permite criar subpastas. Basta clicar uma vez sobre a pasta
+		para selecioná-la, e escolher a ação desejada. Caso queria criar uma subpasta, clique em <i>Nova Pasta</i>.
+		Agora, as pastas principais estão mais protegidas, não permitindo excluir ou renomear 
+		as pastas principais.<div style="cursor:pointer" align="right" width="100%" onClick="javascript:location.href='#0'" title="Subir para o topo da página"><img border=0 src ='../templates/default/images/arrow_descendant.gif'><font color="DARKBLUE" size="1"><b>Voltar</b></font></div></p>
+		<b><a name="5">5.&nbsp;</a>Como pesquisar mensagens?</b><p style="text-align:justify"> O item <i>Pesquisar</i>, assim como a manutenção de pastas, também está
+		totalmente diferente. Preencha os campos de pesquisa referentes ao campos da mensagem pelos quais deseja
+		pesquisar, selecione as pastas em que deve ser feita a pesquisa e clique em <i>Pesquisar</i>. O resultado
+		da pesquisa abre na parte de baixo da própria janela, economizando tempo e espaço. Ao clicar na mensagem
+		resultante, a mensagem se abre na tela atrás.<div style="cursor:pointer" align="right" width="100%" onClick="javascript:location.href='#0'" title="Subir para o topo da página"><img border=0 src ='../templates/default/images/arrow_descendant.gif'><font color="DARKBLUE" size="1"><b>Voltar</b></font></div>
+		</p>
+		<b><a name="6">6.&nbsp;</a>Como enviar novas mensagens?</b><p style="text-align:justify"> Na tela de envio de nova mensagem, não existem mais botões, apenas
+		links. Haviam muitas reclamações com relação ao botão <i>Enviar e Salvar</i>, então agora ao clicar neste
+		link, abre uma janela pop-up onde basta selecionar a pasta e clicar em <i>Enviar e Salvar</i>. Além disso, é 
+		possível exibir o código HTML da mensagem clicando em <i>Ver código HTML</i>.<div style="cursor:pointer" align="right" width="100%" onClick="javascript:location.href='#0'" title="Subir para o topo da página"><img border=0 src ='../templates/default/images/arrow_descendant.gif'><font color="DARKBLUE" size="1"><b>Voltar</b></font></div>
+		</p>
+		<b><a name="7">7.&nbsp;</a>Como ver mais informações de uma mensagem?</b><p style="text-align:justify"> Cabeçalho e várias opções da mensagem ficam ocultos, para aumentar
+		a visualização da mensagem. Para mostrar estas informações, clique em <i>Mais opções</i>.
+		<div style="cursor:pointer" align="right" width="100%" onClick="javascript:location.href='#0'" title="Subir para o topo da página"><img border=0 src ='../templates/default/images/arrow_descendant.gif'><font color="DARKBLUE" size="1"><b>Voltar</b></font></div></p>
+		<b><a name="8">8.&nbsp;</a>Como me proteger contra mensagens indesejáveis?</b><p style="text-align:justify"> O ExpressoMail sempre teve um recurso de criação de
+		filtros para mensagens. Porém, agora este recurso está mais rápido e simples de usar. Acesse este recurso
+		no menu à esquerda, clicando em <i>Filtros</i>. Crie então uma regra para filtro de mensagens, escolhendo
+		 as condições em que essa regra será aplicada e o que ela fará com as mensagens analisadas pela regra.
+		<div style="cursor:pointer" align="right" width="100%" onClick="javascript:location.href='#0'" title="Subir para o topo da página"><img border=0 src ='../templates/default/images/arrow_descendant.gif'><font color="DARKBLUE" size="1"><b>Voltar</b></font></div></p>
+		<b><a name="9">9.&nbsp;</a>E as minhas preferências continuam as mesmas? </b><p style="text-align:justify"> Sim, além das preferências já existentes da versão anterior, o novo menu de <i>Preferências</i> traz novas opções de configuração do seu
+		ExpressoMail. Pode ser acessado através do menu na parte esquerda da tela.
+		<div style="cursor:pointer" align="right" width="100%" onClick="javascript:location.href='#0'" title="Subir para o topo da página"><img border=0 src ='../templates/default/images/arrow_descendant.gif'><font color="DARKBLUE" size="1"><b>Voltar</b></font></div></p>
+		<b><a name="10">10.&nbsp;</a>Dúvidas na utilização do Expresso</b><p style="text-align:justify">Você pode solucionar quaisquer dúvidas sobre utilização
+		 e configuração do Expresso, consultando o manual on-line, acessível através do menu <i>Ferramentas</i>
+		 na parte esquerda da tela, mandando sua dúvida por e-mail clicando no link <i>Sugestões</i> ou ainda,
+		 se os meios anteriores não funcionaram, entrando em contato com a Central de Atendimento Celepar, 
+		 no telefone (41)3350-5007.
+		<div style="cursor:pointer" align="right" width="100%" onClick="javascript:location.href='#0'" title="Subir para o topo da página"><img border=0 src ='../templates/default/images/arrow_descendant.gif'><font color="DARKBLUE" size="1"><b>Voltar</b></font></div></p><br>
+		</font>
+		<div style="margin-right:10px" align='right'><br><font face="Arial" size="1"><a href="#" onclick="javascript:window.close()">Fechar janela</a></font></div>
+		<center><img src="../../phpgwapi/templates/celepar/images/logo_celepar.gif"></center>
+	</div>	
+	</body> 
+</html>
Index: tags/expressoMail1_2/1.2211/controller.php
===================================================================
--- tags/expressoMail1_2/1.2211/controller.php	(revision 2)
+++ tags/expressoMail1_2/1.2211/controller.php	(revision 2)
@@ -0,0 +1,64 @@
+<?php
+	//	Explode action from cExecuteForm function
+	$cExecuteFormReturn = false;
+ 	if($_POST['_action']) { 		
+ 		if($_FILES) {
+ 			$count_files = $_POST['countFiles'];
+			$array_files = array(); 		
+ 			for($idx = 1; $idx <= $count_files; $idx++) { 		
+ 				if($_FILES['file_'.$idx] && !$_FILES['file_'.$idx]['error'])
+ 					$array_files[] = $_FILES['file_'.$idx]; 					 
+ 			}
+ 			$_POST['FILES'] = $array_files;
+ 		} 		  		
+ 		list($app,$class,$method) = explode('.',@$_POST['_action']);
+ 		$cExecuteFormReturn = true;
+ 	}
+ 	//	Explode action from cExecute function
+ 	else if($_GET['action'])
+		list($app,$class,$method) = explode('.',@$_GET['action']);
+	// NO ACTION
+	else
+		return $_SESSION['response'] = 'false';
+	
+	// Load dinamically class file.
+	if($app == '$this')
+		$filename = 'inc/class.'.$class.'.inc.php';
+	else
+		$filename = '../'.$app.'/inc/class.'.$class.'.inc.php';
+		
+	include_once($filename);	
+	
+	// Create new Object  (class loaded).	
+	$obj = new $class;
+	
+	// Prepare parameters for execution.	
+	$params = array();
+	
+	// If array $_POST is not null , the submit method is POST. 
+	if($_POST) {
+		$params = $_POST;
+	}
+	// If array $_POST is null , and the array $_GET > 1, the submit method is GET.
+	else if(count($_GET) > 1)	{		
+		array_shift($_GET);
+		$params = $_GET;
+	}
+
+	$result = array();
+	
+	
+	// if params is not empty, then class method with parameters.	
+	if($params)
+		$result = $obj -> $method($params);
+	else 		
+		$result = $obj -> $method();
+		
+	// Return result serialized.	
+	
+
+	if(!$cExecuteFormReturn)
+		echo serialize($result);
+	else
+		$_SESSION['response'] = $result;
+?>
Index: tags/expressoMail1_2/1.2211/inc/class.db_functions.inc.php
===================================================================
--- tags/expressoMail1_2/1.2211/inc/class.db_functions.inc.php	(revision 205)
+++ tags/expressoMail1_2/1.2211/inc/class.db_functions.inc.php	(revision 205)
@@ -0,0 +1,260 @@
+<?php
+define('PHPGW_INCLUDE_ROOT','../');	
+define('PHPGW_API_INC','../phpgwapi/inc');	
+include_once(PHPGW_API_INC.'/class.db.inc.php');
+	
+class db_functions
+{	
+	
+	var $db;
+	var $user_id;
+	
+	function db_functions(){
+		$this->db = new db();		
+		$this->db->Halt_On_Error = 'no';
+		$this->db->connect(
+				$_SESSION['phpgw_info']['expressomail']['server']['db_name'], 
+				$_SESSION['phpgw_info']['expressomail']['server']['db_host'],
+				$_SESSION['phpgw_info']['expressomail']['server']['db_port'],
+				$_SESSION['phpgw_info']['expressomail']['server']['db_user'],
+				$_SESSION['phpgw_info']['expressomail']['server']['db_pass'],
+				$_SESSION['phpgw_info']['expressomail']['server']['db_type']
+		);		
+		$this -> user_id = $_SESSION['phpgw_info']['expressomail']['user']['account_id'];	
+	}
+
+	// BEGIN of functions.
+	function get_cc_contacts()
+	{				
+		$result = array();
+		$stringDropDownContacts = '';
+		// Pesquisa no CC os nomes e email dos contatos.
+ 		$query = 'select A.names_ordered, C.connection_value from phpgw_cc_contact A,'.
+  		'phpgw_cc_contact_conns B, phpgw_cc_connections C where '.
+     	'A.id_contact = B.id_contact and B.id_connection = C.id_connection '.
+        'and B.id_typeof_contact_connection = 1 and '.
+        'A.id_owner ='.$this -> user_id.' order by A.names_ordered';
+				
+        if (!$this->db->query($query))
+        	return null;
+				
+		
+		while($this->db->next_record())
+			$result[] = $this->db->row();
+
+		if (count($result) != 0) 
+		{
+			// Monta string				
+			foreach($result as $contact)
+				$stringDropDownContacts = $stringDropDownContacts . $contact['names_ordered']. ';' . $contact['connection_value'] . ',';
+			//Retira ultima virgula.
+			$stringDropDownContacts = substr($stringDropDownContacts,0,(strlen($stringDropDownContacts) - 1));
+		}
+		else 
+			return null;
+
+		return $stringDropDownContacts;
+	}
+	
+	function get_cc_groups() 
+	{
+		// Pesquisa no CC os Grupos Pessoais.
+		$stringDropDownContacts = '';			
+		$result = array();
+		$query = 'select title, short_name from phpgw_cc_groups where owner ='.$this -> user_id.' order by title';
+		// Executa a query 
+		if (!$this->db->query($query))
+        	return null;
+		// Retorna cada resultado            	
+		while($this->db->next_record())
+			$result[] = $this->db->row();
+		// Se houver grupos ....
+		if (count($result) != 0) 
+		{	
+			foreach($result as $group)
+				$stringDropDownContacts .=  $group['title']. ';' . $group['short_name'] . ',';
+			//Retira ultima virgula.
+			$stringDropDownContacts = substr($stringDropDownContacts,0,(strlen($stringDropDownContacts) - 1));
+		}
+		else
+			return null;
+			
+		return $stringDropDownContacts;
+	}
+	
+	function getContactsByGroupAlias($alias)
+	{
+		
+		$query = "select C.id_connection, A.names_ordered, C.connection_value from phpgw_cc_contact A, ".
+		"phpgw_cc_contact_conns B, phpgw_cc_connections C,phpgw_cc_contact_grps D,phpgw_cc_groups E where ".
+		"A.id_contact = B.id_contact and B.id_connection = C.id_connection ".
+		"and B.id_typeof_contact_connection = 1 and ".
+		"A.id_owner =".$this -> user_id." and ".			
+		"D.id_group = E.id_group and ".
+		"D.id_connection = C.id_connection and E.short_name = '".$alias.
+		"' order by A.names_ordered";
+
+		if (!$this->db->query($query))
+		{
+			exit ('Query failed! File: '.__FILE__.' on line'.__LINE__);
+		}
+
+		$return = false;
+
+		while($this->db->next_record())
+		{
+			$return[] = $this->db->row(); 
+		}
+
+		return $return;
+	}
+
+	function getAddrs($array_addrs) {
+		$array_addrs_final = array();				
+
+		for($i = 0; $i < count($array_addrs); $i++){
+			$j = count($array_addrs_final);
+
+			if(!strchr($array_addrs[$i],'@') 
+					&& strchr($array_addrs[$i],'<')
+					 && strchr($array_addrs[$i],'>')) {		
+
+				$alias = substr($array_addrs[$i], strpos($array_addrs[$i],'<'), strpos($array_addrs[$i],'>'));				
+		 		$alias = str_replace('<','', str_replace('>','',$alias));		 		        	           		
+		 		$arrayContacts = $this -> getContactsByGroupAlias($alias);
+
+				if($arrayContacts) {
+					foreach($arrayContacts as $index => $contact){
+						if($contact['names_ordered']) {
+							$array_addrs_final[$j] = '"'.$contact['names_ordered'].'" <'.$contact['connection_value'].'>';
+						}
+						else 
+							$array_addrs_final[$j] = $contact['connection_value'];
+
+						$j++;
+					}
+				}
+	   		}
+	   		else
+	   			$array_addrs_final[$j++] = $array_addrs[$i]; 							
+		}
+		return $array_addrs_final;
+	}
+
+	function get_dropdown_contacts(){
+		
+		$contacts = $this -> get_cc_contacts();
+		$groups = $this -> get_cc_groups();
+		
+		if(($contacts) && ($groups))
+			$stringDropDownContacts = $contacts . ',' . $groups;
+		elseif ((!$contacts) && (!$groups))
+			$stringDropDownContacts = '';
+		elseif (($contacts) && (!$groups))
+			$stringDropDownContacts = $contacts;
+		elseif ((!$contacts) && ($groups))
+			$stringDropDownContacts = $groups;
+					
+		return $stringDropDownContacts;	
+	}
+	/*
+	function update_preferences($params){
+		
+		$aux = explode("##",$params['prefe_string']);
+		$new_prefe = array();
+		
+		foreach($aux as $key=>$tmp){
+			if($key == 0){
+				$new_prefe['max_email_per_page'] = $tmp;
+			}
+			if($key == 1){
+				$new_prefe['save_deleted_msg'] = $tmp;
+			}
+			if($key == 2){
+				$new_prefe['delete_trash_messages_after_n_days'] = $tmp;
+			}
+			if($key == 3){
+				$new_prefe['delete_and_show_previous_message'] = $tmp;
+			}
+			if($key == 4){
+				$new_prefe['alert_new_msg'] = $tmp;
+			}
+			if($key == 5){
+				$new_prefe['mainscreen_showmail'] = $tmp;
+			}
+			if($key == 10){
+				$new_prefe['signature'] = $tmp;
+			}
+			if($key == 7){
+				$new_prefe['hide_folders'] = $tmp;
+			}
+			if($key == 6){
+				$new_prefe['save_in_folder'] = $tmp;
+			}
+			if($key == 8){
+				$new_prefe['line_height'] = $tmp;
+			}
+			if($key == 9){
+				$new_prefe['font_size'] = $tmp;
+			}
+			if($key == 11){
+				$new_prefe['use_shortcuts'] = $tmp;
+			}
+		}
+		
+		$string_serial =  serialize($new_prefe);
+		$string_serial = get_magic_quotes_gpc() ? $string_serial : addslashes($string_serial);
+		$query = "update phpgw_preferences set preference_value = '".$string_serial."' where preference_app = 'expressoMail'".
+				 " and preference_owner = '".$this->user_id."'";
+		
+		if (!$this->db->query($query))
+        	return "Failed!";
+		else
+			return "OK!";
+	}
+	*/
+	function update_preferences($params){
+		$string_serial = urldecode($params['prefe_string']);				
+		$string_serial = get_magic_quotes_gpc() ? $string_serial : addslashes($string_serial);
+		$query = "update phpgw_preferences set preference_value = '".$string_serial."' where preference_app = 'expressoMail'".
+				 " and preference_owner = '".$this->user_id."'";
+		
+		if (!$this->db->query($query))
+        	return $this->db->error;
+		else
+			return array("success" => true);
+	}
+	function getUserByEmail($params){	
+		// Follow the referral
+		$email = $params['email'];
+		$query = 'select A.names_ordered, C.connection_name, C.connection_value, A.photo'. 
+				' from phpgw_cc_contact A, phpgw_cc_contact_conns B, '.
+				'phpgw_cc_connections C where A.id_contact = B.id_contact'. 
+ 				' and B.id_connection = C.id_connection and A.id_contact ='. 
+				'(select A.id_contact from phpgw_cc_contact A, phpgw_cc_contact_conns B,'. 
+				'phpgw_cc_connections C where A.id_contact = B.id_contact'. 
+				' and B.id_connection = C.id_connection and A.id_owner = '.$this -> user_id.
+				' and C.connection_value = \''.$email.'\') and '.
+				'C.connection_is_default = true and B.id_typeof_contact_connection = 2';
+
+        if (!$this->db->query($query))
+        	return null;
+
+
+		if($this->db->next_record()) {
+			$result = $this->db->row();
+
+			$obj =  array("cn" => $result['names_ordered'],
+					  "email" => $email,
+					  "type" => "personal",
+					  "telefone" =>  $result['connection_value']);
+
+			if($result['photo'])
+				$_SESSION['phpgw_info']['expressomail']['contact_photo'] =  array($result['photo']);				
+
+			return $obj;
+		}
+		return $result;
+	}
+}
+?>
Index: tags/expressoMail1_2/1.2211/inc/hook_preferences.inc.php
===================================================================
--- tags/expressoMail1_2/1.2211/inc/hook_preferences.inc.php	(revision 2)
+++ tags/expressoMail1_2/1.2211/inc/hook_preferences.inc.php	(revision 2)
@@ -0,0 +1,11 @@
+<?php
+{
+// Only Modify the $file and $title variables.....
+	$title = 'expressoMail1_2';
+	$file = Array(
+		'Preferences' => $GLOBALS['phpgw']->link('/'.$title.'/preferences.php'),
+	);
+//Do not modify below this line
+	display_section($appname,$title,$file);
+}
+?>
Index: tags/expressoMail1_2/1.2211/inc/class.imap_functions.inc.php
===================================================================
--- tags/expressoMail1_2/1.2211/inc/class.imap_functions.inc.php	(revision 278)
+++ tags/expressoMail1_2/1.2211/inc/class.imap_functions.inc.php	(revision 278)
@@ -0,0 +1,2313 @@
+<?php
+include_once("class.functions.inc.php");
+include_once("class.ldap_functions.inc.php");
+include_once("class.exporteml.inc.php");
+
+class imap_functions
+{
+	var $public_functions = array
+	(	
+		'get_range_msgs'				=> True,
+		'get_info_msg'					=> True,
+		'get_folders_list'				=> True
+	);
+
+	var $ldap;
+	var $mbox;
+	var $imap_port;
+	var $has_cid;
+	var $imap_options = '';
+	var $functions;
+
+	function imap_functions (){
+	 	$this->username 	  = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
+		$this->password 	  = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
+		$this->imap_server	  = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
+		$this->imap_port	  = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
+		$this->imap_delimiter = $_SESSION['phpgw_info']['expressomail']['email_server']['imapDelimiter'];
+		$this->functions	  = new functions();		
+		$this->has_cid = false;
+		
+		if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
+		{
+			$this->imap_options = '/tls/novalidate-cert';
+		}
+		else
+		{
+			$this->imap_options = '/notls/novalidate-cert';
+		}
+	}
+	// BEGIN of functions.
+	function open_mbox($folder = False)
+	{
+		$folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
+	 	$this->mbox = @imap_open("{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder, $this->username, $this->password) or die(serialize(array('imap_error' => imap_last_error())));
+		return $this->mbox;
+	 }
+
+	function get_range_msgs2($params)
+	{
+		include("class.imap_attachment.inc.php");
+		$imap_attachment = new imap_attachment();
+		$folder = $params['folder'];
+		$msg_range_begin = $params['msg_range_begin'];
+		$msg_range_end = $params['msg_range_end'];
+		$sort_box_type = $params['sort_box_type'];		
+		$sort_box_reverse = $params['sort_box_reverse'];
+		$search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
+		$sort_array_msg = $this-> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);				
+		
+		$return = array();
+		$i = 0;
+		$num_msgs = (is_array($sort_array_msg) ? count($sort_array_msg) : 0);
+		if($num_msgs) { 
+			for ($msg_range_begin; (($msg_range_begin <= $msg_range_end) && ($msg_range_begin <= $num_msgs)); $msg_range_begin++)
+		{
+			$msg_number = $sort_array_msg[$msg_range_begin-1];
+
+			$header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
+			if (!is_object($header))
+				return false;			
+			
+			$return[$i]['Recent'] = $header->Recent;
+			$return[$i]['Unseen'] = $header->Unseen;
+			if($header->Answered =='A' && $header->Draft == 'X'){
+				$return[$i]['Forwarded'] = 'F';
+			}
+			else {
+				$return[$i]['Answered']	= $header->Answered;
+				$return[$i]['Draft']	= $header->Draft;	
+			}
+			$return[$i]['Deleted'] = $header->Deleted;
+			$return[$i]['Flagged'] = $header->Flagged;
+			
+			$return[$i]['msg_number'] = $msg_number;
+			//$return[$i]['msg_folder'] = $folder;
+			
+			$date_msg = date("d/m/Y",$header->udate);
+			if (date("d/m/Y") == $date_msg)
+				$return[$i]['udate'] = date("H:i",$header->udate);
+			else
+				$return[$i]['udate'] = $date_msg;
+			
+			$from = $header->from;
+			$return[$i]['from'] = array();
+			$tmp = imap_mime_header_decode($from[0]->personal);
+			$return[$i]['from']['name'] = $this->decode_string($tmp[0]->text);
+			$return[$i]['from']['email'] = $this->decode_string($from[0]->mailbox) . "@" . $from[0]->host;
+			if(!$return[$i]['from']['name'])
+				$return[$i]['from']['name'] = $return[$i]['from']['email'];
+			$to = $header->to;
+			$return[$i]['to'] = array();
+			$tmp = imap_mime_header_decode($to[0]->personal);
+			$return[$i]['to']['name'] = $this->decode_string($this->decode_string($tmp[0]->text));
+			$return[$i]['to']['email'] = $this->decode_string($to[0]->mailbox) . "@" . $to[0]->host;
+			if(!$return[$i]['to']['name'])
+				$return[$i]['to']['name'] = $return[$i]['to']['email'];
+			$return[$i]['subject'] = $this->decode_string($header->fetchsubject);
+
+			$return[$i]['Size'] = $header->Size;
+			
+			$return[$i]['attachment'] = array();
+			$return[$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);			
+			$i++;
+		}
+		}
+		$return['num_msgs'] = $num_msgs;		
+		
+		return $return;
+	}
+	
+	function decode_string($string)
+	{	
+		if ((strpos(strtolower($string), '=?iso-8859-1') !== false) || (strpos(strtolower($string), '=?windows-1252') !== false))
+		{
+			$tmp = imap_mime_header_decode($string);
+			foreach ($tmp as $tmp1)
+				$return .= $this->htmlspecialchars_encode($tmp1->text);
+			return $return;
+		}
+		else if (strpos(strtolower($string), '=?utf-8') !== false)
+		{
+			$elements = imap_mime_header_decode($string);
+	  		for($i = 0;$i < count($elements);$i++) {
+	   			$charset = $elements[$i]->charset;
+	   			$text =$elements[$i]->text;
+	   			if(!strcasecmp($charset, "utf-8") ||
+	       			!strcasecmp($charset, "utf-7"))	{
+	     			$text = iconv($charset, "ISO-8859-1", $text);
+	       		}
+	   			$decoded .= $this->htmlspecialchars_encode($text);
+	  		}
+	  		return $decoded;
+		}
+		else
+			return $this->htmlspecialchars_encode($string);
+	}
+	
+	function get_info_msg($params)
+	{
+		$return = array();
+		$msg_number = $params['msg_number'];
+		$msg_folder = $params['msg_folder'];
+		
+		if(!$this->mbox)
+			$this->mbox = $this->open_mbox($msg_folder);		
+		
+		$header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
+		if (!$header) {
+			$return['status_get_msg_info'] = "false";
+			return $return;
+		}
+		$all_header = explode("\n", imap_fetchheader($this->mbox, $msg_number, FT_UID));
+		$return_get_body = $this->get_body_msg($msg_number, $msg_folder);
+		
+		$return['body'] 		= $return_get_body['body'];
+		$return['attachments'] 	= $return_get_body['attachments'];
+		$return['thumbs'] 		= $return_get_body['thumbs'];
+		$return['signature']	= $return_get_body['signature'];
+		
+		foreach($all_header as $line) {
+			if (eregi("^Disposition-Notification-To", $line)) {
+				eregi("^([^:]*): (.*)", $line, &$arg);
+				$return['DispositionNotificationTo'] = $arg[2];
+			}
+		}
+		$return['Recent']	= $header->Recent;
+		$return['Unseen']	= $header->Unseen;
+		$return['Deleted']	= $header->Deleted;		
+		$return['Flagged']	= $header->Flagged;
+
+		if($header->Answered =='A' && $header->Draft == 'X'){
+			$return['Forwarded'] = 'F';
+		}
+		else {
+			$return['Answered']	= $header->Answered;
+			$return['Draft']	= $header->Draft;	
+		}
+
+		$return['msg_number'] = $msg_number;
+		$return['msg_folder'] = $msg_folder;
+	
+		$date_msg = date("d/m/Y",$header->udate);
+		if (date("d/m/Y") == $date_msg)
+			$return['udate'] = date("H:i",$header->udate);
+		else
+			$return['udate'] = $date_msg;
+		
+		$return['msg_day'] = $date_msg; 
+		$return['msg_hour'] = date("H:i",$header->udate);
+		
+		if (date("d/m/Y") == $date_msg) //no dia
+		{
+			$return['fulldate'] = date("d/m/Y H:i",$header->udate);
+			$return['smalldate'] = date("H:i",$header->udate);
+			
+			$timestamp_now = strtotime("now");
+			$timestamp_msg_time = $header->udate;
+			$timestamp_diff = $timestamp_now - $timestamp_msg_time;
+			
+			if (gmdate("H",$timestamp_diff) > 0)
+			{
+				$return['fulldate'] .= " (" . gmdate("H:i", $timestamp_diff) . ' ' . $this->functions->getLang('hours ago') . ')';
+			}
+			else
+			{
+				if (gmdate("i",$timestamp_diff) == 0){
+					$return['fulldate'] .= ' ('. $this->functions->getLang('now').')';
+				}
+				elseif (gmdate("i",$timestamp_diff) == 1){
+					$return['fulldate'] .= ' (1 '. $this->functions->getLang('minute ago').')';
+				}
+				else{
+					$return['fulldate'] .= " (" . gmdate("i",$timestamp_diff) .' '. $this->functions->getLang('minutes ago') . ')';
+				}
+			}
+		}
+		else{
+			$return['fulldate'] = date("d/m/Y H:i",$header->udate);
+			$return['smalldate'] = date("d/m/Y",$header->udate);
+		}
+		
+		$from = $header->from;
+		$return['from'] = array();
+		$tmp = imap_mime_header_decode($from[0]->personal);
+		$return['from']['name'] = $this->decode_string($tmp[0]->text);
+		$return['from']['email'] = $this->decode_string($from[0]->mailbox . "@" . $from[0]->host);
+		if ($return['from']['name'])
+		{
+			if (substr($return['from']['name'], 0, 1) == '"')
+				$return['from']['full'] = $return['from']['name'] . ' ' . '&lt;' . $return['from']['email'] . '&gt;';
+			else
+				$return['from']['full'] = '"' . $return['from']['name'] . '" ' . '&lt;' . $return['from']['email'] . '&gt;';
+		}
+		else
+			$return['from']['full'] = $return['from']['email'];
+		
+		// Sender attribute
+		$sender = $header->sender;
+		$return['sender'] = array();
+		$tmp = imap_mime_header_decode($sender[0]->personal);
+		$return['sender']['name'] = $this->decode_string($tmp[0]->text);
+		$return['sender']['email'] = $this->decode_string($sender[0]->mailbox . "@" . $sender[0]->host);
+		if ($return['sender']['name'])
+		{
+			if (substr($return['sender']['name'], 0, 1) == '"')
+				$return['sender']['full'] = $return['sender']['name'] . ' ' . '&lt;' . $return['sender']['email'] . '&gt;';
+			else
+				$return['sender']['full'] = '"' . $return['sender']['name'] . '" ' . '&lt;' . $return['sender']['email'] . '&gt;';
+		}
+		else
+			$return['sender']['full'] = $return['sender']['email'];
+
+		if($return['from']['full'] == $return['sender']['full'])
+			$return['sender'] = null;
+		$to = $header->to;
+		$return['toaddress2'] = "";
+		if (!empty($to))
+		{
+			foreach ($to as $tmp)
+			{
+				if (!empty($tmp->personal))
+				{
+					$personal_tmp = imap_mime_header_decode($tmp->personal);
+					$return['toaddress2'] .= '"' . $personal_tmp[0]->text . '"';
+					$return['toaddress2'] .= " ";
+					$return['toaddress2'] .= "&lt;";
+					$return['toaddress2'] .= $tmp->mailbox . "@" . $tmp->host;
+					$return['toaddress2'] .= "&gt;";
+					$return['toaddress2'] .= ", ";
+				}
+				else
+				{
+					$return['toaddress2'] .= $tmp->mailbox . "@" . $tmp->host;
+					$return['toaddress2'] .= ", ";
+				}
+			}
+			$return['toaddress2'] = $this->del_last_two_caracters($return['toaddress2']);
+		}
+		else
+		{
+			$return['toaddress2'] = "&lt;Empty&gt;";
+		}	
+		
+		$cc = $header->cc;
+		$return['cc'] = "";
+		if (!empty($cc))
+		{
+			foreach ($cc as $tmp_cc)
+			{
+				if (!empty($tmp_cc->personal))
+				{
+					$personal_tmp_cc = imap_mime_header_decode($tmp_cc->personal);
+					$return['cc'] .= '"' . $personal_tmp_cc[0]->text . '"';
+					$return['cc'] .= " ";
+					$return['cc'] .= "&lt;";
+					$return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
+					$return['cc'] .= "&gt;";
+					$return['cc'] .= ", ";
+				}
+				else
+				{
+					$return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
+					$return['cc'] .= ", ";
+				}
+			}
+			$return['cc'] = $this->del_last_two_caracters($return['cc']);
+		}
+		else
+		{
+			$return['cc'] = "";
+		}	
+		
+		$reply_to = $header->reply_to;
+		$return['reply_to'] = "";
+		if (is_object($reply_to[0]))
+		{
+			if ($return['from']['email'] != ($reply_to[0]->mailbox."@".$reply_to[0]->host))
+			{
+				if (!empty($reply_to[0]->personal))
+				{
+					$personal_reply_to = imap_mime_header_decode($tmp_reply_to->personal);
+					if(!empty($personal_reply_to[0]->text)) {
+						$return['reply_to'] .= '"' . $personal_reply_to[0]->text . '"';
+						$return['reply_to'] .= " ";
+						$return['reply_to'] .= "&lt;";
+						$return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
+						$return['reply_to'] .= "&gt;";
+					}
+					else {
+						$return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
+					}
+				}
+				else
+				{
+					$return['reply_to'] .= $reply_to[0]->mailbox . "@" . $reply_to[0]->host;
+				}
+			}
+		}
+		$return['reply_to'] = $this->decode_string($return['reply_to']);
+		$return['subject'] = $this->decode_string($header->fetchsubject);
+		$return['Size'] = $header->Size;
+		$return['reply_toaddress'] = $header->reply_toaddress;
+		return $return;
+	}
+	
+	function get_body_msg($msg_number, $msg_folder)
+	{
+		include_once("class.message_components.inc.php");
+		$msg = &new message_components($this->mbox);
+		$msg->fetch_structure($msg_number);
+		$return = array();
+		$return['attachments'] = $this-> download_attachment($msg,$msg_number);		
+		if(!$this->has_cid)
+		{
+			$return['thumbs']  = $this->get_thumbs($msg,$msg_number,urlencode($msg_folder));
+			$return['signature'] = $this->get_signature($msg,$msg_number,$msg_folder);
+		}			
+		
+		if(!$msg->structure[$msg_number]->parts) //Simple message, only 1 piece
+		{
+			$attachment = array(); //No attachments
+			
+			$content = '';
+			if (strtolower($msg->structure[$msg_number]->subtype) == "plain")
+			{
+				$content .= nl2br($this->decodeBody((imap_body($this->mbox, $msg_number, FT_UID)), $msg->encoding[$msg_number][0], $msg->charset[$msg_number][0]));
+			}
+			else if (strtolower($msg->structure[$msg_number]->subtype) == "html")
+			{
+				$content .= $this->decodeBody(imap_body($this->mbox, $msg_number, FT_UID), $msg->encoding[$msg_number][0], $msg->charset[$msg_number][0]);
+			}
+		}
+		else 
+		{ //Complicated message, multiple parts
+			$html_body = '';
+			$content = '';
+			$has_multipart = true;
+			$this->has_cid = false;
+			
+			if (strtolower($msg->structure[$msg_number]->subtype) == "related")
+				$this->has_cid = true;
+			
+			if (strtolower($msg->structure[$msg_number]->subtype) == "alternative")
+				$show_only_html = true;			
+			else
+				$show_only_html = false;
+
+			foreach($msg->pid[$msg_number] as $values => $msg_part)
+			{
+				
+				$file_type = strtolower($msg->file_type[$msg_number][$values]);
+				if($file_type == "message/rfc822")
+					$has_multipart = false;
+	
+				if($file_type == "multipart/alternative")
+					$has_multipart = false;
+	
+				if(($file_type == "text/plain" 
+					|| $file_type == "text/html")
+					&& $file_type != 'attachment')
+				{
+					if($file_type == "text/plain" && !$show_only_html && $has_multipart)
+					{
+						// if TXT file size > 100kb, then it will not expand.
+						if(!($file_type == "text/plain" && $msg->fsize[$msg_number][$values] > 102400)) {
+							$content .= nl2br(htmlentities($this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values])));							
+						}
+					}
+					// if HTML attachment file size > 300kb, then it will not expand.
+					else if($file_type == "text/html"  && $msg->fsize[$msg_number][$values] < 307200)
+					{
+						$content .= $this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]);
+						$show_only_html = true;
+					}
+				}
+				else if($file_type == "message/delivery-status"){
+					$content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
+					$content .= nl2br($this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]));						
+
+				}
+				else if($file_type == "message/rfc822" || $file_type == "text/rfc822-headers"){
+					
+					include_once("class.imap_attachment.inc.php");
+					$att = new imap_attachment();
+					$attachments =  $att -> get_attachment_info($this->mbox,$msg_number);
+					if($attachments['number_attachments'] > 0) {												
+						foreach($attachments ['attachment'] as $index => $attachment){
+							if(strtolower($attachment['type']) == "delivery-status" ||
+								strtolower($attachment['type']) == "rfc822" ||								
+								strtolower($attachment['type']) == "rfc822-headers" ||
+								strtolower($attachment['type']) == "plain"
+							){
+								$obj = imap_rfc822_parse_headers(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values]);					
+								$content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";					
+								$content .= "<br><table  style='margin:2px;border:1px solid black;background:#EAEAEA'>";
+								$content .= "<tr><td><b>".$this->functions->getLang("Subject").":</b></td><td>".$this->decode_string($obj->subject)."</td></tr>";
+								$content .= "<tr><td><b>".$this->functions->getLang("From").":</b></td><td>".$this->decode_string($obj->from[0]->mailbox."@".$obj->from[0]->host)."</td></tr>";
+								$content .= "<tr><td><b>".$this->functions->getLang("Date").":</b></td><td>".$obj->date."</td></tr>";
+								$content .= "<tr><td><b>".$this->functions->getLang("TO").":</b></td><td>".$this->decode_string($obj->to[0]->mailbox."@".$obj->to[0]->host)."</td></tr>";
+								$content .= !$obj->cc ? "</table><br>" :"<tr><td><b>".$this->functions->getLang("CC").":</b></td><td>".$this->decode_string($obj->cc[0]->mailbox."@".$obj->cc[0]->host)."</td></tr></table><br>";								
+								$ix_part = 	strtolower($attachment['type']) == "delivery-status" ? 1 : 0;
+								$content .= nl2br($this->decodeBody(imap_fetchbody($this->mbox, $msg_number, ($attachment['part_in_msg']+$ix_part).".1", FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]));								
+								break;			
+							}
+						}
+					}
+				}
+			}
+			if($file_type == "text/plain" && ($show_only_html &&  $msg_part == 1) ||  (!$show_only_html &&  $msg_part == 3)){
+				if(strtolower($msg->structure[$msg_number]->subtype) == "mixed" &&  $msg_part == 1)
+					$content .= nl2br(imap_base64(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID)));
+				else if(!strtolower($msg->structure[$msg_number]->subtype) == "mixed")
+					$content .= nl2br(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID));				
+			}
+		} 
+		// Force message with flag Seen (imap_fetchbody not works correctly)
+		$params = array('folder' => $msg_folder, "msgs_to_set" => $msg_number, "flag" => "seen");				
+		$this->set_messages_flag($params);
+		$content = $this->process_embedded_images($msg,$msg_number,$content, $msg_folder);
+		$content = $this->replace_special_characters($content);
+		$return['body'] = $content;
+		return $return;
+	}
+	
+	function htmlfilter($body)
+	{
+		require_once('htmlfilter.inc');
+		
+		$tag_list = Array(
+				false,
+				'blink',
+				'object',
+				'meta',
+				'html',
+				'link',
+				'frame',
+				'iframe',
+				'layer',
+				'ilayer',
+				'plaintext'
+		);
+
+		/**
+		* A very exclusive set:
+		*/
+		// $tag_list = Array(true, "b", "a", "i", "img", "strong", "em", "p");
+		$rm_tags_with_content = Array(
+				'script',
+				'style',
+				'applet',
+				'embed',
+				'head',
+				'frameset',
+				'xml',
+				'xmp'
+		);
+
+		$self_closing_tags =  Array(
+				'img',
+				'br',
+				'hr',
+				'input'
+		);
+
+		$force_tag_closing = true;
+
+		$rm_attnames = Array(
+    			'/.*/' =>
+				Array(
+					'/target/i',
+					//'/^on.*/i', -> onClick, dos compromissos da agenda.
+					'/^dynsrc/i',
+					'/^datasrc/i',
+					'/^data.*/i',
+					'/^lowsrc/i'
+				)
+		);
+
+		/**
+		 * Yeah-yeah, so this looks horrible. Check out htmlfilter.inc for
+		 * some idea of what's going on here. :)
+		 */
+
+		$bad_attvals = Array(
+    		'/.*/' =>
+	    	Array(
+	    	      '/.*/' =>
+		    	      Array(
+	    	    	        Array(
+            	    	          '/^([\'\"])\s*\S+\s*script\s*:*(.*)([\'\"])/si',
+                		          //'/^([\'\"])\s*https*\s*:(.*)([\'\"])/si', -> doclinks notes
+                        		  '/^([\'\"])\s*mocha\s*:*(.*)([\'\"])/si',
+	                        	  '/^([\'\"])\s*about\s*:(.*)([\'\"])/si'
+	    	                      ),
+    	    	            Array(
+        		   	              '\\1oddjob:\\2\\1',
+                		          //'\\1uucp:\\2\\1', -> doclinks notes
+                    		      '\\1amaretto:\\2\\1',
+                        		  '\\1round:\\2\\1'
+                          		)
+		                    ),     
+          
+		          '/^style/i' =>
+    		              Array(
+        		                Array(
+            		                  '/expression/i',
+                		              '/behaviou*r/i',
+                    		          '/binding/i',
+                        		      '/include-source/i',
+                            		  '/url\s*\(\s*([\'\"]*)\s*https*:.*([\'\"]*)\s*\)/si',
+		                              '/url\s*\(\s*([\'\"]*)\s*\S+\s*script:.*([\'\"]*)\s*\)/si'
+    		                         ),
+        		                Array(
+            		                  'idiocy',
+                		              'idiocy',
+                    		          'idiocy',
+                        		      'idiocy',
+                            		  'url(\\1http://securityfocus.com/\\1)',
+	                            	  'url(\\1http://securityfocus.com/\\1)'
+	    	                         )
+    	    	                )
+        	    	  )
+		    );
+
+		$add_attr_to_tag = Array(
+				'/^a$/i' => Array('target' => '"_new"')
+		);
+    	
+    	
+		$trusted_body = sanitize($body,
+				$tag_list,
+				$rm_tags_with_content,
+				$self_closing_tags,
+				$force_tag_closing,
+				$rm_attnames,
+				$bad_attvals,
+				$add_attr_to_tag
+		);
+    	
+	    return $trusted_body;
+	}
+	
+	function decodeBody($body, $encoding, $charset=null)
+	{
+		/**
+		* replace e-mail by anchor.
+		*/
+		// HTML Filter
+		//$body = preg_replace("#(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1<a href=# onclick=\"javascript:new_message('new_by_message', '\\2@\\3')\">\\2@\\3</a>", $body);
+    	$body = str_replace("\r\n", "\n", $body);
+		if ($encoding == 'quoted-printable')
+	    {
+			
+			for($i=0;$i<256;$i++) {
+				$c1=dechex($i);
+				if(strlen($c1)==1){$c1="0".$c1;}
+				$c1="=".$c1;
+				$myqprinta[]=$c1;
+				$myqprintb[]=chr($i);
+			}	    	
+			$body = str_replace($myqprinta,$myqprintb,($body));
+			$body = quoted_printable_decode($body);
+        	while (ereg("=\n", $body)) 
+        	{
+           		$body = ereg_replace ("=\n", '', $body);
+        	}
+    	}
+    	else if ($encoding == 'base64') 
+    	{
+        	$body = base64_decode($body);
+    	}
+    	/*else if ($encoding == '7bit') 
+    	{
+        	$body = quoted_printable_decode($body);        	        	        	
+    	}*/
+		// All other encodings are returned raw.
+		if (strtolower($charset) == "utf-8")
+			return utf8_decode($body);
+    	else
+			return $body;
+	}
+	
+	function process_embedded_images($msg, $msgno, $body, $msg_folder)
+	{
+		if (count($msg->inline_id[$msgno]) > 0)
+		{
+			foreach ($msg->inline_id[$msgno] as $index => $cid)
+			{
+				$cid = eregi_replace("<", "", $cid);
+				$cid = eregi_replace(">", "", $cid);
+				$msg_part = $msg->pid[$msgno][$index];
+				//$body = eregi_replace("alt=\"\"", "", $body);
+				$body = eregi_replace("<br/>", "", $body);
+				$body = str_replace("src=\"cid:".$cid."\"", " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
+				$body = str_replace("src='cid:".$cid."'", " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
+				$body = str_replace("src=cid:".$cid, " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
+			}
+		}
+		
+		return $body;
+	}
+	
+	function replace_special_characters($body)
+	{
+		// Suspected TAGS!
+		/*$tag_list = Array(   
+			'blink','object','meta',
+			'html','link','frame',
+			'iframe','layer','ilayer',
+			'plaintext','script','style','img',
+			'applet','embed','head',
+			'frameset','xml','xmp');
+		*/
+
+		// Layout problem: Change html elements 
+		// with absolute position to relate position, CASE INSENSITIVE. 
+		$body = @eregi_replace("POSITION: ABSOLUTE;","",$body);
+
+		$tag_list = Array('head','blink','object','frame',
+			'iframe','layer','ilayer','plaintext','script',
+			'applet','embed','frameset','xml','xmp','style');
+
+		$body = $this-> replace_links($body);
+		$blocked_tags = array();		
+		foreach($tag_list as $index => $tag) {
+			$new_body = eregi_replace("<$tag", "<!--$tag", $body);
+			if($body != $new_body) {
+				$blocked_tags[] = $tag;
+			}
+			$body = eregi_replace("</$tag>", "</$tag-->", $new_body);
+		}
+
+		return  "<span>".$body;
+	}
+
+	function replace_links($body) {					
+		// Search for links,then open the link in new window.
+		//$body = @ereg_replace('[a-zA-Z]+://(([.]?[a-zA-Z0-9_/-])*)', '<a href="\\0" title="'.$this->functions->getLang("Open in New Window").'">\\0</a>',$body);	  
+  		//Search for emails, then open a new message tab.
+  		//$body = @ereg_replace('[a-zA-Z0-9!#$%&\'*+/=?^_`{|}~]+@([.]?[a-zA-Z0-9_/-])*', '<a title=\''.$this->functions->getLang("New Message").' -> \\0\'" onclick="Element(\'msg_number\').value=\'\\0\';new_message(\'new\',\'null\')" href="#">\\0</a>',$body);  		
+  		$matches = array();
+		// Verify exception.
+		@preg_match("/<a href=\"notes:\/\/\//",$body,$matches);
+		// It no has exception,then open the link in new window.
+		if(!count($matches)){
+			$body = @eregi_replace("<a (.*) href=", "<a \\1 target='_blank' href=", $body);
+			$body = @str_replace("<a href=", "<a target='_blank' href=", $body);
+			$body = @eregi_replace("target=\"\"", "target='_blank'", $body);
+			$body = @eregi_replace("target=''", "target='_blank'", $body);
+		}
+   		return $body;
+	}
+
+	function get_signature($msg, $msg_number, $msg_folder)
+	{ 
+		foreach ($msg->file_type[$msg_number] as $index => $file_type)
+		{
+			$file_type = strtolower($file_type);
+			if(strtolower($msg->encoding[$msg_number][$index]) == 'base64') 
+			{
+				if ($file_type == 'application/x-pkcs7-signature') 
+				{
+					$export_mail = new ExportEml();
+					$params['folder'] = $msg_folder;
+					$params['msgs_to_export'] = $msg_number;
+				    $tempDir = ini_get("session.save_path");
+					$cert_file = $tempDir."/certificate_".base_convert(microtime(), 10, 36).".crt";					
+					$result = openssl_pkcs7_verify($export_mail->export_msg($params),PKCS7_NOVERIFY,$cert_file);
+					if (file_exists($cert_file))
+					{
+						$handle = fopen ($cert_file,"r");
+						$pemout = fread($handle,filesize($cert_file));
+						fclose($handle);
+						$cert=openssl_x509_parse($pemout);
+						$temp = "\\nSigned by: ".$cert[subject][CN];
+						$temp .= "\\nEmail Address: ".$cert[subject][emailAddress];
+						$temp .= "\\nCertificate issued by: ".$cert[issuer][CN]."\\n";
+					}
+				    /* Message verified */
+				    if ($result === true)
+					    $sign = $temp;
+				     else
+					    $sign = "void";
+				}
+			}
+		}
+   		return $sign;	
+	}
+
+	function get_thumbs($msg, $msg_number, $msg_folder)
+	{
+		$thumbs_array = array();
+		$i = 0;
+    	foreach ($msg->file_type[$msg_number] as $index => $file_type)
+    	{
+    		$file_type = strtolower($file_type);
+    		if(strtolower($msg->encoding[$msg_number][$index]) == 'base64') {
+	    		if (($file_type == 'image/jpeg') || ($file_type == 'image/pjpeg') || ($file_type == 'image/gif') || ($file_type == 'image/png')) {
+	    			$img = "<IMG id='".$msg_folder.";;".$msg_number.";;".$i.";;".$msg->pid[$msg_number][$index].";;".$msg->encoding[$msg_number][$index]."' style='border:2px solid #fde7bc;padding:5px' title='".$this->functions->getLang("Click here do view (+)")."'src=./inc/show_thumbs.php?file_type=".$file_type."&msg_num=".$msg_number."&msg_folder=".$msg_folder."&msg_part=".$msg->pid[$msg_number][$index].">";
+	    			$href = "<a onMouseDown='save_image(event,this)' href='#".$msg_folder.";;".$msg_number.";;".$i.";;".$msg->pid[$msg_number][$index].";;".$msg->encoding[$msg_number][$index]."' onClick=\"window.open('./inc/show_img.php?msg_num=".$msg_number."&msg_folder=".$msg_folder."&msg_part=".$msg->pid[$msg_number][$index]."','mywindow','width=700,height=600,scrollbars=yes');\">". $img ."</a>";
+					$thumbs_array[] = $href;
+	    		}
+    			$i++;
+    		}
+    	}
+    	return $thumbs_array;
+	}
+		
+	/*function delete_msg($params)
+	{
+		$folder = $params['folder'];
+		$msgs_to_delete = explode(",",$params['msgs_to_delete']);
+		
+		$mbox_stream = $this->open_mbox($folder);
+		
+		foreach ($msgs_to_delete as $msg_number){
+			imap_delete($mbox_stream, $msg_number, FT_UID);
+		}
+		imap_close($mbox_stream, CL_EXPUNGE);
+		return $params['msgs_to_delete'];
+	}*/
+
+	// Novo
+	function delete_msgs($params)
+	{
+		
+		$folder = $params['folder'];
+		$folder =  mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1");
+		$msgs_number = explode(",",$params['msgs_number']);
+		$border_ID = $params['border_ID'];
+		
+		$return = array();
+		
+		if ($params['get_previous_msg'])
+			$return['previous_msg'] = $this->get_info_previous_msg($params);
+
+		//$mbox_stream = $this->open_mbox($folder);
+	 	$mbox_stream = @imap_open("{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder, $this->username, $this->password) or die(serialize(array('imap_error' => imap_last_error())));
+		
+		foreach ($msgs_number as $msg_number)
+		{
+			if (imap_delete($mbox_stream, $msg_number, FT_UID));
+				$return['msgs_number'][] = $msg_number;
+		}
+		
+		$return['folder'] = $folder;
+		$return['border_ID'] = $border_ID;
+		
+		if($mbox_stream)
+			imap_close($mbox_stream, CL_EXPUNGE);
+		return $return;
+	}
+
+		
+	function refresh($params)
+	{
+		include("class.imap_attachment.inc.php");
+		$imap_attachment = new imap_attachment();		
+		$folder = $params['folder'];
+		$msg_range_begin = $params['msg_range_begin'];
+		$msg_range_end = $params['msg_range_end'];
+		$msgs_existent = $params['msgs_existent'];
+		$sort_box_type = $params['sort_box_type'];		
+		$sort_box_reverse = $params['sort_box_reverse'];
+		$msgs_in_the_server = array();
+		$search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
+		$sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
+
+		if(!count($sort_array_msg))
+			return array();
+			
+		$num_msgs = (count($sort_array_msg) - imap_num_recent($this->mbox));
+		$msgs_in_the_client = explode(",", $msgs_existent);
+
+		
+		for ($msg_range_begin; (($msg_range_begin <= $msg_range_end) && ($msg_range_begin <= count($sort_array_msg))); $msg_range_begin++)
+		{
+			$msgs_in_the_server[] = $sort_array_msg[$msg_range_begin-1];
+		}
+		if ((count($msgs_in_the_server) < 1) && ($msg_range_begin != 0))
+		{
+			$range = $msg_range_end - $msg_range_begin;
+			$msg_range_begin = $msg_range_begin - $range;
+			$msg_range_end = $msg_range_end - $range;
+			for ($msg_range_begin; (($msg_range_begin <= $msg_range_end) && ($msg_range_begin <= count($sort_array_msg))); $msg_range_begin++)
+			{
+				$msgs_in_the_server[] = $sort_array_msg[$msg_range_begin-1];
+			}
+		}
+		
+		$msg_to_insert  = array_diff($msgs_in_the_server, $msgs_in_the_client);
+		$msg_to_delete = array_diff($msgs_in_the_client, $msgs_in_the_server);
+		
+		$msgs_to_exec = array();
+		if ((count($msg_to_insert)) && ($msgs_existent))
+		{
+			foreach($msg_to_insert as $index => $msg_number)
+			{
+				if ($msgs_in_the_server[$index+1])
+				{
+					//$msgs_to_exec[$msg_number] = 'Inserir mensage numero ' . $msg_number . ' antes da ' . $msgs_in_the_server[$index+1];
+					$msgs_to_exec[$msg_number] = 'box.insertBefore(new_msg, Element("'.$msgs_in_the_server[$index+1].'"));';
+				}
+				else
+				{
+					//$msgs_to_exec[$msg_number] = 'Inserir mensage numero ' . $msg_number . ' no final (append)';
+					$msgs_to_exec[$msg_number] = 'box.appendChild(new_msg);';
+				}
+			}
+			ksort($msgs_to_exec);
+		}
+		elseif(!$msgs_existent)
+		{
+			foreach($msgs_in_the_server as $index => $msg_number)
+			{
+				$msgs_to_exec[$msg_number] = 'box.appendChild(new_msg);';
+			}
+		}
+		
+		$return = array();
+		$i = 0;
+		foreach($msgs_to_exec as $msg_number => $command)
+		{
+			$header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox , $msg_number), 80, 255);
+			if (!is_object($header))
+				return false;
+			
+			$return[$i]['msg_number']	= $msg_number;
+			$return[$i]['command']		= $command;
+			
+			$return[$i]['msg_folder']	= $folder;
+			$return[$i]['Recent']		= $header->Recent;
+			$return[$i]['Unseen']		= $header->Unseen;
+			$return[$i]['Answered']		= $header->Answered;
+			$return[$i]['Deleted']		= $header->Deleted;
+			$return[$i]['Draft']		= $header->Draft;
+			$return[$i]['Flagged']		= $header->Flagged;
+
+			$date_msg = date("d/m/Y",$header->udate);
+			if (date("d/m/Y") == $date_msg)
+				$return[$i]['udate'] = date("H:i",$header->udate);
+			else
+				$return[$i]['udate'] = $date_msg;
+			
+			$from = $header->from;
+			$return[$i]['from'] = array();
+			$tmp = imap_mime_header_decode($from[0]->personal);
+			$return[$i]['from']['name'] = $tmp[0]->text;
+			$return[$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
+			//$return[$i]['from']['full'] ='"' . $return[$i]['from']['name'] . '" ' . '<' . $return[$i]['from']['email'] . '>'; 
+			if(!$return[$i]['from']['name'])
+				$return[$i]['from']['name'] = $return[$i]['from']['email'];
+			
+			/*$toaddress = imap_mime_header_decode($header->toaddress);
+			$return[$i]['toaddress'] = '';
+			foreach ($toaddress as $tmp)
+				$return[$i]['toaddress'] .= $tmp->text;*/
+			$to = $header->to;
+			$return[$i]['to'] = array();
+			$tmp = imap_mime_header_decode($to[0]->personal);
+			$return[$i]['to']['name'] = $tmp[0]->text;
+			$return[$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
+			$return[$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
+			
+			$return[$i]['subject'] = $this->decode_string($header->fetchsubject);
+
+			$return[$i]['Size'] = $header->Size;
+			$return[$i]['reply_toaddress'] = $header->reply_toaddress;
+			
+			$return[$i]['attachment'] = array();
+			$return[$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
+			$i++;
+		}
+		$return['new_msgs'] = imap_num_recent($this->mbox);
+		$return['msgs_to_delete'] = $msg_to_delete;
+		if($this->mbox)
+			imap_close($this->mbox);
+		return $return;
+	}
+
+	function get_folders_list()
+	{
+		$mbox_stream = $this->open_mbox();		
+		$serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
+		$folders_list = imap_getmailboxes($mbox_stream, $serverString, "*");
+		$tmp = array();
+		$result = array();
+		
+		if (is_array($folders_list)) {
+  			reset($folders_list);
+			
+			$i = 0;
+  			while (list($key, $val) = each($folders_list)) {
+  				$status = imap_status($mbox_stream, $val->name, SA_UNSEEN);
+  				$result[$i]['folder_unseen'] = $status->unseen;
+			
+  				//$tmp_folder_id = explode("}", imap_utf7_decode($val->name));
+  				$tmp_folder_id = explode("}", mb_convert_encoding($val->name, "ISO_8859-1", "UTF7-IMAP" ));
+  				$folder_id = $tmp_folder_id[1];
+				$result[$i]['folder_id'] = $folder_id;
+				
+				$tmp_folder_parent = explode($this->imap_delimiter, $folder_id);
+				$result[$i]['folder_name'] = array_pop($tmp_folder_parent);
+				$result[$i]['folder_name'] = $result[$i]['folder_name'] == 'INBOX' ? 'Inbox' : $result[$i]['folder_name'];
+				
+				$tmp_folder_parent = implode($this->imap_delimiter, $tmp_folder_parent);
+				$result[$i]['folder_parent'] = $tmp_folder_parent == 'INBOX' ? '' : $tmp_folder_parent;
+					
+				if (($val->attributes == 32) && ($result[$i]['folder_name'] != 'Inbox'))
+					$result[$i]['folder_hasChildren'] = 1;
+				else
+					$result[$i]['folder_hasChildren'] = 0;
+
+				$i++;				
+  			}
+		}
+		
+		foreach ($result as $folder_info)
+		{
+			$array_tmp[] = $folder_info['folder_id'];
+		}
+		
+		natcasesort($array_tmp);
+		
+		foreach ($array_tmp as $key => $folder_id)
+		{
+			$result2[] = $result[$key];
+		}
+		
+		return array_merge($result2, $this->get_quota());
+	}
+	
+	function create_mailbox($arr)
+	{
+		$namebox	= $arr['newp'];
+		$mbox_stream = $this->open_mbox();
+		$imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
+		$namebox =  mb_convert_encoding($namebox, "UTF7-IMAP", "UTF-8");
+		
+		$result = "Ok";
+		if(!imap_createmailbox($mbox_stream,"{".$imap_server."}$namebox"))
+		{
+			$result = implode("<br />\n", imap_errors());
+		}	
+		
+		if($mbox_stream)
+			imap_close($mbox_stream);
+					
+		return $result;
+		
+	}
+	
+	function create_extra_mailbox($arr)
+	{
+		$nameboxs = explode(";",$arr['nw_folders']);
+		$result = "";
+		$mbox_stream = $this->open_mbox();
+		$imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
+		foreach($nameboxs as $key=>$tmp){			
+			if($tmp != ""){
+				if(!imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}$tmp"))){
+					$result = implode("<br />\n", imap_errors());
+					if($mbox_stream)
+						imap_close($mbox_stream);					
+					return $result;
+				}
+			}
+		}
+		if($mbox_stream)
+			imap_close($mbox_stream);
+		return true;
+	}
+	
+	function delete_mailbox($arr)
+	{
+		$namebox = $arr['del_past'];
+		$imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
+		$mbox_stream = $this->open_mbox();
+		//$del_folder = imap_deletemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox");
+		
+		$result = "Ok";
+		$namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
+		if(!imap_deletemailbox($mbox_stream,"{".$imap_server."}$namebox"))
+		{
+			$result = implode("<br />\n", imap_errors());
+		}
+		if($mbox_stream)
+			imap_close($mbox_stream);
+		return $result;
+	}
+	
+	function ren_mailbox($arr)
+	{
+		$namebox = $arr['current'];
+		$new_box = $arr['rename'];
+		$imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
+		$mbox_stream = $this->open_mbox();
+		//$ren_folder = imap_renamemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox","{".$imap_server."}INBOX.$new_box");
+		
+		$result = "Ok";
+		$namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
+		$new_box = mb_convert_encoding($new_box, "UTF7-IMAP","UTF-8");
+		
+		if(!imap_renamemailbox($mbox_stream,"{".$imap_server."}$namebox","{".$imap_server."}$new_box"))
+		{
+			$result = imap_errors();			
+		}
+		if($mbox_stream)
+			imap_close($mbox_stream);
+		return $result;
+		
+	}
+	
+	function get_num_msgs($params)
+	{
+		$folder = $params['folder'];
+		if(!$this->mbox) {
+			$this->mbox = $this->open_mbox($folder);
+			if(!$this->mbox)
+			return imap_last_error();
+		}		
+		$num_msgs = imap_num_msg($this->mbox);
+		if($this->mbox)
+			imap_close($this->mbox);
+		
+		return $num_msgs;
+	}
+	
+	function send_mail($params)
+	{
+		include_once("class.phpmailer.php");
+		$mail = new PHPMailer();
+		include_once("class.db_functions.inc.php");
+		$db = new db_functions();
+		$fromaddress = $params['input_from'] ? explode(';',$params['input_from']) : "";
+		$toaddress = implode(',',$db->getAddrs(explode(',',$params['input_to'])));
+		$ccaddress = implode(',',$db->getAddrs(explode(',',$params['input_cc'])));
+		$ccoaddress = implode(',',$db->getAddrs(explode(',',$params['input_cco'])));
+		$subject = $params['input_subject'];
+		$msg_uid = $params['msg_id'];
+		$return_receipt = $params['input_return_receipt'];
+		$body = $params['body'];
+		//echo "<script language=\"javascript\">javascript:alert('".$body."');</script>";
+		$attachments = $params['FILES'];
+		$forwarding_attachments = $params['forwarding_attachments'];
+		 
+		$folder =$params['folder'];
+		$folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");		
+		$folder_name = $params['folder_name'];		
+		// Fix problem with cyrus delimiter changes.
+		// Dots in names: enabled/disabled.				
+		$folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
+		$folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
+		// End Fix.
+		if ($folder != 'null'){			
+			$mail->SaveMessageInFolder = $folder;
+		}
+////////////////////////////////////////////////////////////////////////////////////////////////////
+		$mail->SMTPDebug = false;
+				
+		$mail->IsSMTP();
+		$mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
+		$mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
+		$mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
+		$mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
+		if($fromaddress){
+			$mail->Sender = $mail->From;
+			$mail->SenderName = $mail->FromName;
+			$mail->FromName = $fromaddress[0];
+			$mail->From = $fromaddress[1];
+		}
+				
+		$this->add_recipients("to", $toaddress, &$mail);
+		$this->add_recipients("cc", $ccaddress, &$mail);
+		$this->add_recipients("cco", $ccoaddress, &$mail);
+		$mail->Subject = $subject;
+		$mail->IsHTML(true);
+		$mail->Body = $params['body'];
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+		//	Build CID for embedded Images!!!
+		$pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&amp;msg_num=(.+)?&amp;msg_part=(.+)?)"/isU';
+		$cid_imgs = '';
+		$name_cid_files = array();
+		preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
+		$cid_array = array();
+		foreach($cid_imgs[4] as $j => $val){
+				if ( !array_key_exists($cid_imgs[3][$j].$val, $cid_array) )
+      			{
+                $cid_array[$cid_imgs[3][$j].$val] = base_convert(microtime(), 10, 36);
+		        }
+		        $cid = $cid_array[$cid_imgs[3][$j].$val]; 
+        		$mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
+        		
+				if ($msg_uid != $cid_imgs[3][$j]) // The image isn't in the same mail?
+				{
+					$fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[3][$j], $cid_imgs[4][$j], 'base64');
+					$fileName = "image_".($j).".jpg";
+					$fileCode = "base64";
+					$fileType = "image/jpg";
+				}
+				else
+				{
+					$attach_img = $forwarding_attachments[$cid_imgs[4][$j]-2];
+					$file_description = unserialize(rawurldecode($attach_img));
+
+					foreach($file_description as $i => $descriptor){				
+						$file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
+					}
+					$fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
+					$fileName = $file_description[2];
+					$fileCode = $file_description[4];
+					$fileType = $this->get_file_type($file_description[2]);
+					unset($forwarding_attachments[$cid_imgs[4][$j]-2]);
+				}
+				$tempDir = ini_get("session.save_path");
+				$file = "cid_image_".base_convert(microtime(), 10, 36).".dat";					
+				$f = fopen($tempDir.'/'.$file,"w");
+				fputs($f,$fileContent);
+				fclose($f);
+				if ($fileContent)
+					$mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
+				//else
+				//	return "Error loading image attachment content";						
+
+		}
+////////////////////////////////////////////////////////////////////////////////////////////////////
+		//	Build Uploading Attachments!!!
+		if (count($attachments))
+		{
+			$total_uploaded_size = 0;
+			$upload_max_filesize = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024;
+			foreach ($attachments as $attach)
+			{
+				$mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name
+				$total_uploaded_size = $total_uploaded_size + $attach['size'];
+			}
+			if( $total_uploaded_size > $upload_max_filesize)
+				return 'false';			
+		}			
+////////////////////////////////////////////////////////////////////////////////////////////////////
+		//	Build Forwarding Attachments!!!
+		if (count($forwarding_attachments) > 0)
+		{
+			// Bug fixed for array_search function
+			if(count($name_cid_files) > 0) {
+				$name_cid_files[count($name_cid_files)] = $name_cid_files[0];
+				$name_cid_files[0] = null;
+			}			
+			
+			foreach($forwarding_attachments as $forwarding_attachment)
+			{
+					$file_description = unserialize(rawurldecode($forwarding_attachment));
+					$tmp = array_values($file_description);
+					foreach($file_description as $i => $descriptor){				
+						$tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
+					}
+					$file_description = $tmp;					
+					$fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
+					$fileName = $file_description[2];
+					if(!array_search(trim($fileName),$name_cid_files)) {
+						$mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
+				}
+			}
+		}
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+		// Disposition-Notification-To
+		if ($return_receipt)
+			$mail->ConfirmReadingTo = $_SESSION['phpgw_info']['expressomail']['user']['email'];
+////////////////////////////////////////////////////////////////////////////////////////////////////
+		$sent = $mail->Send();
+		if(!$sent)
+		{
+   			return $mail->ErrorInfo;
+		}
+		else
+		{
+			if($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True") 
+			{
+				$userid = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
+				$userip = $_SESSION['phpgw_info']['expressomail']['user']['session_ip'];
+				$now = date("d/m/y H:i:s");
+				$addrs = $toaddress.$ccaddress.$ccoaddress;
+				$sent = trim($sent);									   			
+   				error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log");
+			}
+   			return true;
+		}
+	}
+
+	function add_recipients($recipient_type, $full_address, $mail)
+	{
+		$parse_address = imap_rfc822_parse_adrlist($full_address, "");		
+		foreach ($parse_address as $val) 
+		{
+			//echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
+			if ($val->mailbox == "INVALID_ADDRESS")
+				continue;
+			
+			if (empty($val->personal))
+			{
+				switch($recipient_type)
+				{
+					case "to":
+						$mail->AddAddress($val->mailbox."@".$val->host);
+						break;
+					case "cc":
+						$mail->AddCC($val->mailbox."@".$val->host);
+						break;
+					case "cco":
+						$mail->AddBCC($val->mailbox."@".$val->host);
+						break;
+				}
+			}
+			else
+			{
+				switch($recipient_type)
+				{
+					case "to":
+						$mail->AddAddress($val->mailbox."@".$val->host, $val->personal);
+						break;
+					case "cc":
+						$mail->AddCC($val->mailbox."@".$val->host, $val->personal);
+						break;
+					case "cco":
+						$mail->AddBCC($val->mailbox."@".$val->host, $val->personal);
+						break;
+				}
+			}
+		}
+		return true;
+	}
+	
+	function get_forwarding_attachment($msg_folder, $msg_number, $msg_part, $encoding)
+	{
+		$mbox_stream = $this->open_mbox($msg_folder);			
+		$fileContent = imap_fetchbody($mbox_stream, $msg_number, $msg_part, FT_UID);		
+		if($encoding == 'base64')
+			$fileContent = imap_base64($fileContent);
+		else if($encoding == 'quoted-printable')
+			$fileContent = quoted_printable_decode($fileContent);				
+		return $fileContent;
+	}
+	
+	function del_last_caracter($string)
+	{
+		$string = substr($string,0,(strlen($string) - 1));
+		return $string;	
+	}
+	
+	function del_last_two_caracters($string)
+	{
+		$string = substr($string,0,(strlen($string) - 2));
+		return $string;	
+	}
+	
+	function imap_sortfrom($sort_box_reverse, $search_box_type)
+	{
+		$sortfrom = array();
+		$sortfrom_uid = array();
+		
+		$num_msgs = imap_num_msg($this->mbox);
+		for ($i=1; $i<=$num_msgs; $i++)
+		{
+			$header = imap_headerinfo($this->mbox, $i, 80, 255);
+			// List UNSEEN messages.
+			if($search_box_type == "UNSEEN" &&  (!trim($header->Recent) && !trim($header->Unseen))){
+				continue;
+			}
+			// List SEEN messages.
+			elseif($search_box_type == "SEEN" && (trim($header->Recent) || trim($header->Unseen))){
+				continue;
+			}
+			// List ANSWERED messages.			
+			elseif($search_box_type == "ANSWERED" && !trim($header->Answered)){
+				continue;				
+			}
+			// List FLAGGED messages.			
+			elseif($search_box_type == "FLAGGED" && !trim($header->Flagged)){
+				continue;
+			}
+						
+			if (($header->from[0]->mailbox . "@" . $header->from[0]->host) == $_SESSION['phpgw_info']['expressomail']['user']['email'])				
+				$from = $header->to;
+			else
+				$from = $header->from;
+			
+			$tmp = imap_mime_header_decode($from[0]->personal);			
+			
+			if ($tmp[0]->text != "")
+				$sortfrom[$i] = $tmp[0]->text;
+			else
+				$sortfrom[$i] = $from[0]->mailbox . "@" . $from[0]->host;
+		}
+		
+		natcasesort($sortfrom);
+		
+		foreach($sortfrom as $index => $header_msg)
+		{	
+			$sortfrom_uid[] = imap_uid($this->mbox, $index);
+		}
+		
+		if ($sort_box_reverse)
+			$sortfrom_uid = array_reverse($sortfrom_uid);
+		
+		return $sortfrom_uid;
+	}
+
+	function move_search_messages($params){		
+		$params['selected_messages'] = urldecode($params['selected_messages']);	
+		$params['new_folder'] = urldecode($params['new_folder']);
+		$params['new_folder_name'] = urldecode($params['new_folder_name']);
+		$sel_msgs = explode(",", $params['selected_messages']);
+		@reset($sel_msgs);	
+		$sorted_msgs = array();
+		foreach($sel_msgs as $idx => $sel_msg) {
+			$sel_msg = explode(";", $sel_msg);
+			 if(array_key_exists($sel_msg[0], $sorted_msgs)){
+			 	$sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
+			 }	
+			 else {
+				$sorted_msgs[$sel_msg[0]] = $sel_msg[1];
+			 }
+		}
+		@ksort($sorted_msgs);
+		$last_return = false;		
+		foreach($sorted_msgs as $folder => $msgs_number) {			
+			$params['msgs_number'] = $msgs_number;
+			$params['folder'] = $folder;	
+			if($params['new_folder'] && $folder != $params['new_folder']){
+				$last_return = $this -> move_messages($params);				
+			}
+			elseif(!$params['new_folder'] || $params['delete'] ){
+				$last_return = $this -> delete_msgs($params);
+				$last_return['deleted'] = true;
+			}
+		}
+		return $last_return;
+	}
+	
+	function move_messages($params)
+	{
+		$folder = $params['folder'];		
+		$mbox_stream = $this->open_mbox($folder);		
+		$newmailbox = ($params['new_folder']);
+		$newmailbox = mb_convert_encoding($newmailbox, "UTF7-IMAP","ISO_8859-1");
+		$new_folder_name = $params['new_folder_name'];
+		$msgs_number = $params['msgs_number'];
+		$return = array('msgs_number' => $msgs_number,
+						'folder' => $folder,
+						'new_folder_name' => $new_folder_name,
+						'border_ID' => $params['border_ID']);
+		
+		// Caso estejamos no box principal, não é necessário pegar a informação da mensagem anterior. 		
+		if (($params['get_previous_msg']) && ($params['border_ID'] != 'null') && ($params['border_ID'] != ''))
+			$return['previous_msg'] = $this->get_info_previous_msg($params);
+		
+		$mbox_stream = $this->open_mbox($folder);	
+		if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
+			imap_expunge($mbox_stream);
+			if($mbox_stream)
+				imap_close($mbox_stream);
+			return $return;
+		}else {
+			if(strstr(imap_last_error(),'Over quota')) {				
+				$accountID	= $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminUsername'];
+				$pass		= $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminPW'];									
+				$userID 	= $_SESSION['phpgw_info']['expressomail']['user']['userid'];								
+				$server 	= $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
+				$mbox		= @imap_open("{".$this->imap_server.":".$this->imap_port.$this->imap_options."}INBOX", $accountID, $pass) or die(serialize(array('imap_error' => imap_last_error())));
+				if(!$mbox)
+					return imap_last_error();
+				$quota 	= imap_get_quotaroot($mbox_stream, "INBOX");				
+				if(! imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, 2.1 * $quota['usage'])) {
+					if($mbox_stream)
+						imap_close($mbox_stream);
+					if($mbox)									
+						imap_close($mbox);
+					return "move_messages(): Error setting quota for MOVE or DELETE!! ". "user".$this->imap_delimiter.$userID." line ".__LINE__."\n";								
+				}
+				if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
+					imap_expunge($mbox_stream);
+					if($mbox_stream)
+						imap_close($mbox_stream);
+					// return to original quota limit.
+					if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
+						if($mbox)
+							imap_close($mbox);
+						return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";								
+					}
+					return $return;													
+				}
+				else {
+					if($mbox_stream)
+						imap_close($mbox_stream);
+					if(!imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, $quota['limit'])) {
+						if($mbox)
+							imap_close($mbox);
+						return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";								
+					}
+					return imap_last_error();				
+				}
+				
+			}
+			else {
+				if($mbox_stream)
+					imap_close($mbox_stream);
+				return "move_messages() line ".__LINE__.": ". imap_last_error()." folder:".$newmailbox;
+			}
+		}		
+	}
+	
+	function save_msg($params)
+	{
+		
+		include_once("class.phpmailer.php");
+		$mail = new PHPMailer();
+		include_once("class.db_functions.inc.php");
+		$toaddress = $params['input_to'];
+		$ccaddress = $params['input_cc'];
+		$subject = $params['input_subject'];
+		$body = $params['body'];
+		$body = str_replace("%nbsp;","&nbsp;",$params['body']);
+		$body = preg_replace("/\n/"," ",$body);
+		$body = preg_replace("/\r/","",$body);
+		$forwarding_attachments = $params['forwarding_attachments'];
+		$attachments = $params['FILES'];
+		$return_files = $params['FILES'];
+		 
+		$folder = $params['folder'];
+		$folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");		
+		// Fix problem with cyrus delimiter changes.
+		// Dots in names: enabled/disabled.				
+		$folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
+		$folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
+		// End Fix.
+					
+		$mail->SaveMessageInFolder = $folder;
+		$mail->SMTPDebug = false;
+						
+		$mail->IsSMTP();
+		$mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
+		$mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
+		$mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
+		$mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
+		
+		$mail->Sender = $mail->From;
+		$mail->SenderName = $mail->FromName;
+		$mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
+		$mail->From =  $_SESSION['phpgw_info']['expressomail']['user']['email'];
+				
+		$this->add_recipients("to", $toaddress, &$mail);
+		$this->add_recipients("cc", $ccaddress, &$mail);
+		$mail->Subject = $subject;
+		$mail->IsHTML(true);
+		$mail->Body = $body;
+		
+	
+	//	Build Forwarding Attachments!!!		
+		if (count($forwarding_attachments) > 0)
+		{
+			foreach($forwarding_attachments as $forwarding_attachment)
+			{
+				$file_description = unserialize(rawurldecode($forwarding_attachment));
+				$tmp = array_values($file_description);
+				foreach($file_description as $i => $descriptor){				
+					$tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
+				}
+				$file_description = $tmp;
+				
+				$fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
+				$fileName = $file_description[2];
+				
+				$file_description[5] = strlen($fileContent); //Size of file
+				$return_forward[] = $file_description;
+			
+					$mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
+			}
+		}
+		
+		if ((count($return_forward) > 0) && (count($return_files) > 0))
+			$return_files = array_merge_recursive($return_forward,$return_files);
+		else
+			if (count($return_files) < 1)
+				$return_files = $return_forward;
+	
+		//	Build Uploading Attachments!!!
+		if (count($attachments))
+			foreach ($attachments as $attach)
+				$mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name			
+	
+	
+		
+		if(!empty($mail->AltBody))
+            $mail->ContentType = "multipart/alternative";
+
+        $mail->error_count = 0; // reset errors
+        $mail->SetMessageType();
+        $header = $mail->CreateHeader();
+        $body = $mail->CreateBody();
+        
+       	if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
+		{
+			$imap_options = '/tls/novalidate-cert';
+		}
+		else
+		{
+			$imap_options = '/notls/novalidate-cert';
+		}
+		$username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
+		$password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
+		$imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
+		$imap_port 	= $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
+		$mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$folder, $username, $password);
+	
+		$new_header = str_replace("\n", "\r\n", $header);
+		$new_body = str_replace("\n", "\r\n", $body);
+		
+		$return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$folder, $new_header . $new_body, "\\Seen \\Draft");
+		$status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
+		$return['msg_no'] = $status->uidnext - 1;
+		$return['folder_id'] = $folder;
+		
+		if($mbox_stream)
+			imap_close($mbox_stream);
+				
+		foreach ($return_files as $index => $_attachment) {
+			if (array_key_exists("name",$_attachment)){
+				unset($return_files[$index]);
+				$return_files[$index] = $_attachment['name']."_SIZE_".$return_files[$index][1] = $_attachment['size'];
+			}
+			else
+			{
+				unset($return_files[$index]);
+				$return_files[$index] = $_attachment[2]."_SIZE_". $return_files[$index][1] = $_attachment[5];
+			}
+		}
+		
+		$return['files'] = serialize($return_files);
+				
+		if (!$return['append'])
+			$return['append'] = imap_last_error();
+		
+		return $return;
+	}
+	
+	function set_messages_flag($params)
+	{
+		$folder = $params['folder'];
+		$msgs_to_set = $params['msgs_to_set'];
+		$flag = $params['flag'];
+		$return = array();
+		$return["msgs_to_set"] = $msgs_to_set;
+		$return["flag"] = $flag;
+		
+		if(!$this->mbox)
+			$this->mbox = $this->open_mbox($folder);
+		
+		if ($flag == "unseen")
+			$return["status"] = imap_clearflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
+		elseif ($flag == "seen")
+			$return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
+		elseif ($flag == "answered"){
+			$return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered", ST_UID);
+			imap_clearflag_full($this->mbox, $msgs_to_set, "\\Draft", ST_UID);
+		}
+		elseif ($flag == "forwarded")
+			$return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Answered \\Draft", ST_UID);
+		elseif ($flag == "flagged")
+			$return["status"] = imap_setflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
+		elseif ($flag == "unflagged")
+			$return["status"] = imap_clearflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
+		
+		if($this->mbox)
+			imap_close($this->mbox);
+		return $return;
+	}
+	
+	function get_file_type($file_name)
+	{
+		$file_name = strtolower($file_name);
+	   	$strFileType = strrev(substr(strrev($file_name),0,4));
+	   	if ($strFileType == ".asf") 
+   			return "video/x-ms-asf";
+	   	if ($strFileType == ".avi")
+   			return "video/avi";
+	   	if ($strFileType == ".doc")
+   			return "application/msword";
+	   	if ($strFileType == ".zip")
+   			return "application/zip";
+	   	if ($strFileType == ".xls")
+   			return "application/vnd.ms-excel";
+	   	if ($strFileType == ".gif")
+   			return "image/gif";
+	   	if ($strFileType == ".jpg" || $strFileType == "jpeg")
+   			return "image/jpeg";
+   		if ($strFileType == ".png")
+   			return "image/png";
+	   	if ($strFileType == ".wav")
+   			return "audio/wav";
+	   	if ($strFileType == ".mp3")
+   			return "audio/mpeg3";
+	   	if ($strFileType == ".mpg" || $strFileType == "mpeg")
+   			return "video/mpeg";
+	   	if ($strFileType == ".rtf")
+   			return "application/rtf";
+	   	if ($strFileType == ".htm" || $strFileType == "html")
+   			return "text/html";
+	   	if ($strFileType == ".xml") 
+   			return "text/xml";
+	   	if ($strFileType == ".xsl") 
+   			return "text/xsl";
+	   	if ($strFileType == ".css") 
+   			return "text/css";
+	   	if ($strFileType == ".php") 
+   			return "text/php";
+	   	if ($strFileType == ".asp") 
+   			return "text/asp";
+	   	if ($strFileType == ".pdf")
+   			return "application/pdf";
+	   	if ($strFileType == ".txt")
+   			return "text/plain";
+	   	if ($strFileType == ".wmv")
+   			return "video/x-ms-wmv";
+		if ($strFileType == ".sxc")
+			return "application/vnd.sun.xml.calc";
+		if ($strFileType == ".stc")
+			return "application/vnd.sun.xml.calc.template";
+		if ($strFileType == ".sxd")
+			return "application/vnd.sun.xml.draw";
+		if ($strFileType == ".std")
+			return "application/vnd.sun.xml.draw.template";
+		if ($strFileType == ".sxi")
+			return "application/vnd.sun.xml.impress";
+		if ($strFileType == ".sti")
+			return "application/vnd.sun.xml.impress.template";
+		if ($strFileType == ".sxm")
+			return "application/vnd.sun.xml.math";
+		if ($strFileType == ".sxw")
+			return "application/vnd.sun.xml.writer";
+		if ($strFileType == ".sxq")
+			return "application/vnd.sun.xml.writer.global";
+		if ($strFileType == ".stw")
+			return "application/vnd.sun.xml.writer.template";
+   		
+   		
+   		return "application/octet-stream";  		
+	}
+	
+	function htmlspecialchars_encode($str)
+	{
+		/*// replace  '  and  "  with htmlspecialchars */
+		$str = ereg_replace('&', '&amp;', $str);
+		// any ampersand & that ia already in a "&amp;" should NOT be encoded
+		//$str = preg_replace("/&(?![:alnum:]*;)/", "&amp;", $str);
+		$str = ereg_replace('"', '&quot;', $str);
+		$str = ereg_replace('\'', '&#039;', $str);
+		
+		$str = ereg_replace('<', '&lt;', $str);
+		$str = ereg_replace('>', '&gt;', $str);
+		// these {  and  }  must be html encoded or else they conflict with the template system
+		$str = str_replace("{", '&#123;', $str);
+		$str = str_replace("}", '&#125;', $str);
+		return $str;
+	}
+	function htmlspecialchars_decode($str)
+	{
+		/*// replace  '  and  "  with htmlspecialchars */
+		$str = ereg_replace('&amp;','&',  $str);
+		// any ampersand & that ia already in a "&amp;" should NOT be encoded
+		//$str = preg_replace("/&(?![:alnum:]*;)/", "&amp;", $str);
+		$str = ereg_replace('&quot;', '"', $str);
+		$str = ereg_replace('&#039;', '\'', $str);
+		$str = ereg_replace('&lt;','<', $str);
+		$str = ereg_replace('&gt;', '>', $str);
+		// these {  and  }  must be html encoded or else they conflict with the template system
+		$str = str_replace('&#123;', "{", $str);
+		$str = str_replace( '&#125;',"}", $str);
+		return $str;
+	}
+	
+	function get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse){
+		
+		if(!$this->mbox)
+			$this->mbox = $this->open_mbox($folder);
+		
+		switch($sort_box_type){
+			case 'SORTFROM':
+				return $this->imap_sortfrom($sort_box_reverse, $search_box_type);				
+			case 'SORTSUBJECT':
+				return imap_sort($this->mbox, SORTSUBJECT, $sort_box_reverse, SE_UID, $search_box_type);				
+			case 'SORTSIZE':
+				return imap_sort($this->mbox, SORTSIZE, $sort_box_reverse, SE_UID, $search_box_type);				
+			default:
+				return imap_sort($this->mbox, SORTARRIVAL, $sort_box_reverse, SE_UID, $search_box_type);						
+		}		
+	}	
+	
+	function get_info_next_msg($params)
+	{
+		$msg_number = $params['msg_number'];
+		$folder = $params['msg_folder'];
+		$sort_box_type = $params['sort_box_type'];
+		$sort_box_reverse = $params['sort_box_reverse'];
+		$reuse_border = $params['reuse_border'];
+		$search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
+		$sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);				
+		$i = 0;
+		
+		while($sort_array_msg[$i] != $msg_number)
+		{
+			$i++;
+		}
+
+		if ($i == (count($sort_array_msg)-1))
+		{
+			$params['status'] = 'false';
+			$params['command_to_exec'] = "delete_border('". $reuse_border ."');";
+			return $params;
+		}
+		
+		$params = array();
+		$params['msg_number'] = $sort_array_msg[($i+1)];
+		$params['msg_folder'] = $folder;
+		
+		$return = $this->get_info_msg($params);		
+		$return["reuse_border"] = $reuse_border;
+		return $return;
+	}
+
+	function get_info_previous_msg($params)
+	{
+		$msg_number = $params['msgs_number'];
+		$folder = $params['folder'];
+		$sort_box_type = $params['sort_box_type'];
+		$sort_box_reverse = $params['sort_box_reverse'];
+		$reuse_border = $params['reuse_border'];
+		$search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
+		$sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
+		$i = 0;
+		
+		while($sort_array_msg[$i] != $msg_number)
+		{
+			$i++;
+		}
+		
+		if ($i == 0){
+			$params['status'] = 'false';
+			$params['command_to_exec'] = "delete_border('". $reuse_border ."');";
+			return $params;
+		}
+		
+		$params = array();
+		$params['msg_number'] = $sort_array_msg[($i-1)];
+		$params['msg_folder'] = $folder;
+		
+		$return = $this->get_info_msg($params);
+		$return["reuse_border"] = $reuse_border;
+		return $return;
+	}
+	
+	// This function updates the values: quota, paging and new messages menu.
+	function get_menu_values($params){
+		$return_array = array();
+		$return_array = $this->get_quota($params);
+		
+		$mbox_stream = $this->open_mbox($params['folder']);
+		$return_array['num_msgs'] = imap_num_msg($mbox_stream);		
+		if($mbox_stream)
+			imap_close($mbox_stream);
+				
+		return $return_array; 
+	}
+	
+	function get_quota(){
+		
+		if(!$this->mbox)
+			$this->mbox = $this->open_mbox();
+		
+		$quota = imap_get_quotaroot($this->mbox, "INBOX");
+		if($this->mbox)
+			imap_close($this->mbox);
+			
+		if (!$quota){
+			return array(
+				'quota_percent' => 0,
+				'quota_used' => 0,
+				'quota_limit' =>  0
+			);
+		}
+		
+		if(count($quota) && $quota['limit']) {
+			$quota_limit = (($quota['limit']/1024)* 100 + .5 )* .01;
+			$quota_used  = (($quota['usage']/1024)* 100 + .5 )* .01;
+			if($quota_used >= $quota_limit)
+				$quota_used = $quota_limit;
+			$quotaPercent = ($quota_used / $quota_limit)*100;
+			$quotaPercent = (($quotaPercent)* 100 + .5 )* .01;
+
+			return array(
+				'quota_percent' => floor($quotaPercent),
+				'quota_used' => floor($quota_used),
+				'quota_limit' =>  floor($quota_limit)
+			);
+		}
+		else 
+			return array();
+	}
+	
+	function send_notification($params){
+		require_once("class.phpmailer.php");
+		$mail = new PHPMailer();
+		 
+		$toaddress = $params['notificationto'];
+		
+		$subject = 'Confirmação de leitura: ' . $params['subject'];
+		$body = 'Sua mensagem: ' . $params['subject'] . '<br>';
+		$body .= 'foi lida por: ' . $_SESSION['phpgw_info']['expressomail']['user']['fullname'] . ' &lt;' . $_SESSION['phpgw_info']['expressomail']['user']['email'] . '&gt; em ' . date("d/m/Y H:i");
+		$mail->SMTPDebug = false;
+		$mail->IsSMTP();
+		$mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
+		$mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
+		$mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
+		$mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
+		$mail->AddAddress($toaddress);
+		$mail->Subject = $this->htmlspecialchars_decode($subject);
+
+		$mail->IsHTML(true);
+		$mail->Body = $body;
+		
+		if(!$mail->Send()){
+   			return $mail->ErrorInfo;
+		}
+		else
+   			return true;
+	}
+	
+	function empty_trash()
+	{
+		$folder = 'INBOX' . $this->imap_delimiter . 'Lixeira';
+		$mbox_stream = $this->open_mbox($folder);
+		$return = imap_delete($mbox_stream,'1:*');
+		if($mbox_stream)
+			imap_close($mbox_stream, CL_EXPUNGE);
+		return $return;
+	}
+	
+	function search($params)
+	{
+		include("class.imap_attachment.inc.php");
+		$imap_attachment = new imap_attachment();				
+		$criteria = $params['criteria'];
+		$return = array();
+		$folders = $this->get_folders_list();
+		
+		$j = 0;
+		foreach($folders as $folder)
+		{
+			$mbox_stream = $this->open_mbox($folder);
+			$messages = imap_search($mbox_stream, $criteria, SE_UID);
+			
+			if ($messages == '')
+				continue;
+		
+			$i = 0;
+			$return[$j] = array();
+			$return[$j]['folder_name'] = $folder['name'];
+			
+			foreach($messages as $msg_number)
+			{
+				$header = @imap_headerinfo($mbox_stream, imap_msgno($mbox_stream, $msg_number), 80, 255);
+				if (!is_object($header))
+					return false;
+				
+				$return[$j][$i]['msg_folder']	= $folder['name'];
+				$return[$j][$i]['msg_number']	= $msg_number;
+				$return[$j][$i]['Recent']		= $header->Recent;
+				$return[$j][$i]['Unseen']		= $header->Unseen;
+				$return[$j][$i]['Answered']	= $header->Answered;
+				$return[$j][$i]['Deleted']		= $header->Deleted;
+				$return[$j][$i]['Draft']		= $header->Draft;
+				$return[$j][$i]['Flagged']		= $header->Flagged;
+	
+				$date_msg = date("d/m/Y",$header->udate);
+				if (date("d/m/Y") == $date_msg)
+					$return[$j][$i]['udate'] = date("H:i",$header->udate);
+				else
+					$return[$j][$i]['udate'] = $date_msg;
+			
+				$fromaddress = imap_mime_header_decode($header->fromaddress);
+				$return[$j][$i]['fromaddress'] = '';
+				foreach ($fromaddress as $tmp)
+					$return[$j][$i]['fromaddress'] .= $this->replace_maior_menor($tmp->text);
+			
+				$from = $header->from;
+				$return[$j][$i]['from'] = array();
+				$tmp = imap_mime_header_decode($from[0]->personal);
+				$return[$j][$i]['from']['name'] = $tmp[0]->text;
+				$return[$j][$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
+				$return[$j][$i]['from']['full'] ='"' . $return[$j][$i]['from']['name'] . '" ' . '<' . $return[$j][$i]['from']['email'] . '>'; 
+
+				$to = $header->to;
+				$return[$j][$i]['to'] = array();
+				$tmp = imap_mime_header_decode($to[0]->personal);
+				$return[$j][$i]['to']['name'] = $tmp[0]->text;
+				$return[$j][$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
+				$return[$j][$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>'; 
+
+				$subject = imap_mime_header_decode($header->fetchsubject);
+				$return[$j][$i]['subject'] = '';
+				foreach ($subject as $tmp)
+					$return[$j][$i]['subject'] .= $tmp->text;
+
+				$return[$j][$i]['Size'] = $header->Size;
+				$return[$j][$i]['reply_toaddress'] = $header->reply_toaddress;
+			
+				$return[$j][$i]['attachment'] = array();
+				$return[$j][$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($mbox_stream, $msg_number);
+						
+				$i++;
+			}
+			$j++;
+			if($mbox_stream)
+				imap_close($mbox_stream);
+		}
+	
+		return $return;
+	}
+	
+	function delete_and_show_previous_message($params)
+	{
+		$return = $this->get_info_previous_msg($params);
+		
+		$params_tmp1 = array();
+		$params_tmp1['msgs_to_delete'] = $params['msg_number'];
+		$params_tmp1['folder'] = $params['msg_folder'];
+		$return_tmp1 = $this->delete_msg($params_tmp1);
+		
+		$return['msg_number_deleted'] = $return_tmp1;
+		
+		return $return;
+	}
+		
+	
+	function automatic_trash_cleanness($params)
+	{
+		$before_date = date("m/d/Y", strtotime("-".$params['before_date']." day"));
+		$criteria =  'BEFORE "'.$before_date.'"';
+		$mbox_stream = $this->open_mbox('INBOX'.$this->imap_delimiter."Lixeira");
+		$messages = imap_search($mbox_stream, $criteria, SE_UID);
+		if (is_array($messages)){
+			foreach ($messages as $msg_number){
+				imap_delete($mbox_stream, $msg_number, FT_UID);
+			}
+		}
+		if($mbox_stream)
+			imap_close($mbox_stream, CL_EXPUNGE);
+		return $messages;
+	}
+// 	Fix the search problem with special characters!!!!
+	function remove_accents($string) {
+		return strtr($string, 
+	 	"?Ó??ó?Ý?úÁÀÃÂÄÇÉÈÊËÍÌ?ÎÏÑÕÔÓÒÖÚÙ?ÛÜ?áàãâäçéèêëíì?îïñóòõôöúù?ûüýÿ", 
+	 	"SOZsozYYuAAAAACEEEEIIIIINOOOOOUUUUUsaaaaaceeeeiiiiinooooouuuuuyy");
+	}
+
+	function search_msg($params = ''){
+		$retorno = "";
+		$mbox_stream = "";
+		$search = explode(",",$params['condition']);
+		if($search){
+			$search_criteria = '';
+			foreach($search as $tmp)
+			{
+				$tmp1 = explode("##",$tmp);
+				$name_box = $tmp1[0];
+				$criteria = explode("<=>",rawurldecode($tmp1[1]));				
+				$criteria[1] = $this->remove_accents($criteria[1]);
+				
+				if(!is_resource($mbox_stream))
+					$mbox_stream = $this->open_mbox();
+				else
+					imap_reopen($mbox_stream, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$name_box);
+				
+				if($criteria[0] == "ALL ") {					
+					$all_criterias = array ("TO","SUBJECT","FROM","CC");
+					foreach($all_criterias as $criteria_fixed)
+					{
+						$filter = $criteria_fixed . ' "' . $criteria[1] . '"';
+						$search_criteria = imap_search($mbox_stream, $filter, SE_UID);
+						
+						if($search_criteria && count($search_criteria) < 50)
+						{
+							foreach($search_criteria as $new_search){
+								$m_token = trim("##".$name_box . "--" . $this->get_msg($new_search,$name_box,$mbox_stream) . "--".$new_search."##"."\n");
+								if(!@strstr($retorno,$m_token))
+									$retorno .= $m_token;
+							}
+						}						
+						else if(count($search_criteria) >= 50)							
+							return "many results";						
+					}
+				}
+				else {
+					$filter = $criteria[0] . '"' . $criteria[1] . '"';
+					$search_criteria = imap_search($mbox_stream, $filter, SE_UID);
+											
+					if($search_criteria) {
+						foreach($search_criteria as $new_search){
+							$retorno .= trim("##".$name_box . "--" . $this->get_msg($new_search,$name_box,$mbox_stream) . "--".$new_search."##"."\n");
+						}
+					}
+				}
+			}
+		}
+		if($mbox_stream)
+			imap_close($mbox_stream);		
+						
+		return $retorno ? $retorno : "none";
+	}
+	
+	function get_msg($uid_msg,$name_box, $mbox_stream )
+	{
+		$header = @imap_headerinfo($mbox_stream, imap_msgno($mbox_stream, $uid_msg), 80, 255);         
+		$subject = $this->decode_string($header->fetchsubject);
+		$from = $header->from[0]->mailbox;
+		if($header->from[0]->personal != "")
+			$from = $header->from[0]->personal;
+		$ret_msg = $this->decode_string($from) . "--" . $subject . "--". date("d/m/Y",$header ->udate)."--". $this->size_msg($header->Size);
+		return $ret_msg;                    
+	}	
+	
+	function size_msg($size){
+		$var = floor($size/1024);
+		if($var >= 1){
+			return $var." kb";	
+		}else{
+			return $size ." b";	
+		}
+	}
+
+	function ob_array($the_object)
+	{
+	   $the_array=array();
+	   if(!is_scalar($the_object))
+	   {
+	       foreach($the_object as $id => $object)
+	       {
+	           if(is_scalar($object))
+	           {
+	               $the_array[$id]=$object;
+	           }
+	           else
+	           {
+	               $the_array[$id]=$this->ob_array($object);
+	           }
+	       }
+	       return $the_array;
+	   }
+	   else
+	   {
+	       return $the_object;
+	   }
+	}
+	
+	function getacl()
+	{
+		$this->ldap = new ldap_functions();
+		
+		$return = array();
+		$mbox_stream = $this->open_mbox();	
+		$mbox_acl = imap_getacl($mbox_stream, 'INBOX');
+		
+		$i = 0;
+		foreach ($mbox_acl as $user => $acl)
+		{
+			if ($user != $this->username)
+			{
+				$return[$i]['uid'] = $user;
+				$return[$i]['cn'] = $this->ldap->uid2cn($user);
+			}
+			$i++;
+		}
+		return $return;
+	}
+	
+	function setacl($params)
+	{
+		$old_users = $this->getacl();
+		if (!count($old_users))
+			$old_users = array();
+		
+		$tmp_array = array();
+		foreach ($old_users as $index => $user_info)
+		{
+			$tmp_array[$index] = $user_info['uid'];
+		}
+		$old_users = $tmp_array;
+		
+		$users = unserialize($params['users']);
+		if (!count($users))
+			$users = array();
+		
+		//$add_share = array_diff($users, $old_users);
+		$remove_share = array_diff($old_users, $users);
+
+		$mbox_stream = $this->open_mbox();
+
+		$serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
+		$mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
+
+		/*if (count($add_share))
+		{
+			foreach ($add_share as $index=>$uid)
+			{
+		        if (is_array($mailboxes_list))
+        		{
+                	foreach ($mailboxes_list as $key => $val)
+                	{
+                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
+						imap_setacl ($mbox_stream, $folder, "$uid", "lrswipcda");
+                	}
+        		}
+			}
+		}*/
+		
+		if (count($remove_share))
+		{
+			foreach ($remove_share as $index=>$uid)
+			{
+		        if (is_array($mailboxes_list))
+        		{
+                	foreach ($mailboxes_list as $key => $val)
+                	{
+                        $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
+						imap_setacl ($mbox_stream, $folder, "$uid", "");
+                	}
+        		}
+			}	
+		}
+		
+		return true;
+	}
+	
+	function getaclfromuser($params)
+	{
+		$useracl = $params['user'];
+		
+		$return = array();
+		$return[$useracl] = 'false';
+		$mbox_stream = $this->open_mbox();	
+		$mbox_acl = imap_getacl($mbox_stream, 'INBOX');
+		
+		foreach ($mbox_acl as $user => $acl)
+		{
+			if (($user != $this->username) && ($user == $useracl))
+			{
+				$return[$user] = $acl;
+			}
+		}
+		return $return;
+	}
+
+	function getacltouser($user)
+	{
+		$return = array();
+		$mbox_stream = $this->open_mbox();
+		$mbox_acl = imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
+		return $mbox_acl[$this->username];
+	}
+	
+
+	function setaclfromuser($params)
+	{
+		$user = $params['user'];
+		$acl = $params['acl'];
+		
+		$mbox_stream = $this->open_mbox();
+
+		$serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
+		$mailboxes_list = imap_getmailboxes($mbox_stream, $serverString, "user".$this->imap_delimiter.$this->username."*");
+
+		if (is_array($mailboxes_list))
+		{
+			foreach ($mailboxes_list as $key => $val)
+			{
+				$folder = str_replace($serverString, "", imap_utf7_decode($val->name));
+				if (!imap_setacl ($mbox_stream, $folder, $user, $acl))
+				{
+					return imap_last_error();
+				}
+			}
+		}
+		
+		return true;
+	}
+	
+	function download_attachment($msg,$msgno)
+	{
+		$array_parts_attachments = array();		
+		$array_parts_attachments['names'] = '';
+		include("class.imap_attachment.inc.php");
+		$imap_attachment = new imap_attachment();		
+		
+		if (count($msg->fname[$msgno]) > 0)
+		{
+			$i = 0;
+			foreach ($msg->fname[$msgno] as $index=>$fname)
+			{
+				$array_parts_attachments[$i]['pid'] = $msg->pid[$msgno][$index];
+				$array_parts_attachments[$i]['name'] = $imap_attachment->flat_mime_decode($fname);
+				$array_parts_attachments[$i]['name'] = $array_parts_attachments[$i]['name'] ? $array_parts_attachments[$i]['name'] : "attachment.bin";
+				$array_parts_attachments[$i]['encoding'] = $msg->encoding[$msgno][$index];
+				$array_parts_attachments['names'] .= $array_parts_attachments[$i]['name'] . ', ';
+				$array_parts_attachments[$i]['fsize'] = $msg->fsize[$msgno][$index];
+				$i++;
+			}
+		}
+		$array_parts_attachments['names'] = substr($array_parts_attachments['names'],0,(strlen($array_parts_attachments['names']) - 2));
+		return $array_parts_attachments;
+	}	
+
+	function spam($params)
+	{
+		$is_spam = $params['spam'];
+		$folder = $params['folder'];
+		$mbox_stream = $this->open_mbox($folder);
+		$msgs_number = explode(',',$params['msgs_number']);
+
+		foreach($msgs_number as $msg_number) {
+			$header = imap_fetchheader($mbox_stream, imap_msgno($mbox_stream, $msg_number));
+			$body = imap_body($mbox_stream, imap_msgno($mbox_stream, $msg_number));
+			$msg = $header . $body;
+			$email = $_SESSION['phpgw_info']['expressomail']['user']['email'];
+			$username = $this->username;
+			strtok($email, '@');
+			$domain = strtok('@');
+
+			//Encontrar a assinatura do dspam no cabecalho
+			$v = explode("\r\n", $header);
+			foreach ($v as $linha){
+				if (eregi("^X-DSPAM-Signature", $linha)) {
+					
+					$args = explode(" ",$linha);
+					$signature = $args[1];
+				}
+			}
+
+			// feed dspam
+			switch($is_spam){
+				case 'true':  $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_spam']; break;
+				case 'false': $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_ham']; break;
+			}
+			$tags = array('##EMAIL##', '##USERNAME##', '##DOMAIN##', '##SIGNATURE##');
+			$cmd = str_replace($tags,array($email,$username,$domain,$signature),$cmd);
+ 			system($cmd);
+		}
+		imap_close($mbox_stream);
+		return false;
+	}
+}
+?>
Index: tags/expressoMail1_2/1.2211/inc/class.user.inc.php
===================================================================
--- tags/expressoMail1_2/1.2211/inc/class.user.inc.php	(revision 2)
+++ tags/expressoMail1_2/1.2211/inc/class.user.inc.php	(revision 2)
@@ -0,0 +1,44 @@
+<?php
+	class user{
+		
+		function get_user(){
+			
+			return "<br><font color='blue'>GET USER</font>".			
+						"<br>usuario =".$_SESSION['phpgw_info']['expressomail']['user']['userid'].
+						"<br>senha =".$_SESSION['phpgw_info']['expressomail']['user']['passwd'];			
+		}
+							
+		function verify_user($params){
+			
+			$userId = $params['userid'];
+			$delay =  $params['delay'];
+			
+			if($delay)
+				sleep($delay);
+			
+			$result = '';					
+			
+			if($userId == $_SESSION['phpgw_info']['expressomail']['user']['userid'])				
+				$result =  '<br><font color="green">VERIFY USER ... VERIFIED</font>';			
+			else			
+				$result =  '<br><font color="red">VERIFY USER ... NOT VERIFIED</font>';
+			
+			return $result;											
+		}
+		
+		function verify_user_get($params){
+			
+			return $params;
+		}	
+		
+		function verify_user_post($params){
+			
+			return $this -> verify_user($params);
+		}
+		
+		function get_email(){
+			return $_SESSION['phpgw_info']['expressomail']['user']['email'];	
+		}
+		
+	}
+?>
Index: tags/expressoMail1_2/1.2211/inc/class.exporteml.inc.php
===================================================================
--- tags/expressoMail1_2/1.2211/inc/class.exporteml.inc.php	(revision 177)
+++ tags/expressoMail1_2/1.2211/inc/class.exporteml.inc.php	(revision 177)
@@ -0,0 +1,286 @@
+<?php
+/***************************************************************************************\
+* Export EML Format Message Mail														*
+* Written by Nilton Neto (Celepar) <niltonneto@celepar.pr.gov.br>						*
+* ------------------------------------------------------------------------------------	*
+*  This program is free software; you can redistribute it and/or modify it				*
+*   under the terms of the GNU General Public License as published by the				*
+*  Free Software Foundation; either version 2 of the License, or (at your				*
+*  option) any later version.															*
+\****************************************************************************************/
+// BEGIN CLASS
+class ExportEml
+{
+	var $msg;
+	var $folder;
+	var $mbox_stream;
+	
+	function connectImap(){
+	
+		$username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
+		$password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
+		$imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
+		$imap_port 	= $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
+		
+		if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
+		{
+			$imap_options = '/tls/novalidate-cert';
+		}
+		else
+		{
+			$imap_options = '/notls/novalidate-cert';
+		}
+		$this->mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$this->folder, $username, $password);
+	}
+	
+	//export message to EML Format
+	function parseEml($header, $body)	
+	{		
+		$sEmailHeader = $header;
+		$sEmailBody = $body;
+		$sEMail = $sEmailHeader . "\r\n\r\n" . $sEmailBody;		
+		return $sEMail;
+	}
+	
+	// create EML File.
+    function createFileEml($sEMLData, $tempDir, $id)  
+    {
+        if($id)
+        {
+            $header    = imap_headerinfo($this->mbox_stream, imap_msgno($this->mbox_stream, $id), 80, 255);
+            $subject = $this->decode_subject($header->fetchsubject);
+            
+            if (strlen($subject) > 60)
+                $subject = substr($subject, 0, 59);
+ 
+            $subject = ereg_replace('/', '\'', $subject);            
+            $file =    $subject."_".$id.".eml";
+        }    
+        else{
+            $file =    "email_".md5(microtime()).".eml";
+        }
+        
+        $f = fopen($tempDir.'/'.$file,"w");
+        if(!$f)
+            return False;
+        
+        fputs($f,$sEMLData);
+        fclose($f);
+        
+        return $file;
+    } 
+
+	function createFileZip($files, $tempDir){		
+		$tmp_zip_filename =	"email_".md5(microtime()).".zip";
+		$command = "cd " . $tempDir . "; nice zip -m " . $tmp_zip_filename . " " . $files;			
+		if(!exec($command)) {
+			$command = 'cd ' . $tempDir . '; rm '.$files;
+			exec($command);
+			return null;
+		}
+		
+		return $tmp_zip_filename;
+				
+	}
+
+	function export_all($params){
+		
+		$this->folder = $params['folder'];
+		$this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
+		$fileNames = "";
+		$tempDir = ini_get("session.save_path");
+		$this->connectImap();
+		
+		$msgs = imap_search($this->mbox_stream,"ALL",SE_UID);
+		foreach($msgs as $nMsgs){
+			$header	 	= $this-> getHeader($nMsgs);									
+			$body		= $this-> getBody($nMsgs);			
+			$sEMLData 	= $this -> parseEml($header, $body);
+			$fileName 	= $this -> CreateFileEml($sEMLData, $tempDir,$nMsgs);
+			if(!$fileName)	{
+				$error = True;					
+				break;
+			}
+			else
+				$fileNames .= "\"".$fileName."\" ";			
+			
+		}
+		imap_close($this->mbox_stream);
+		
+		$nameFileZip = 'False';			
+		if($fileNames && !$error) {			
+			$nameFileZip = $this -> createFileZip($fileNames, $tempDir);
+			if($nameFileZip)			
+				$file = $tempDir.'/'.$nameFileZip;
+			else {
+				$file = false;
+			}								
+		}
+		else 
+			$file = false;
+			
+		return $file;
+		
+	}
+
+	function makeAll($params) {
+		
+		$this-> folder = $params['folder'];
+		$this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
+		$array_ids = explode(',', $params['msgs_to_export']);	
+		$error = False;		
+		$fileNames = "";
+		$tempDir = ini_get("session.save_path");
+		$this->connectImap();
+				
+		for($i = 0; $i < count($array_ids); $i++) {
+				
+			$header	 	= $this-> getHeader($array_ids[$i]);											
+			$body		= $this-> getBody($array_ids[$i]);			
+			$sEMLData 	= $this -> parseEml($header, $body);			
+			$fileName 	= $this -> CreateFileEml($sEMLData, $tempDir, $array_ids[$i]);
+			
+			if(!$fileName)	{
+				$error = True;					
+				break;
+			}
+			else
+				$fileNames .= "\"".$fileName."\" ";			
+			
+		}
+		imap_close($this->mbox_stream);
+		
+		
+		$nameFileZip = 'False';			
+		if($fileNames && !$error) {			
+			$nameFileZip = $this -> createFileZip($fileNames, $tempDir);
+			if($nameFileZip)			
+				$file = $tempDir.'/'.$nameFileZip;
+			else {
+				$file = false;
+			}								
+		}
+		else 
+			$file = false;
+			
+		return $file;
+	}
+
+	function export_msg($params) {
+		$this-> folder = $params['folder'];
+		$this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
+		$id_number = $params['msgs_to_export'];
+		$tempDir = ini_get("session.save_path");
+		
+		$this->connectImap();
+		$header	 	= $this-> getHeader($id_number);
+		$body		= $this-> getBody($id_number);
+		
+		$file = "source_".md5(microtime()).".txt";
+		$f = fopen($tempDir.'/'.$file,"w");
+		fputs($f,$header ."\r\n\r\n". $body);
+		fclose($f);
+		
+		imap_close($this->mbox_stream);
+		return $tempDir.'/'.$file;
+	}
+
+	function remove_accents($string) {
+		/*
+			$array1 = array("á", "à", "â", "ã", "ä", "é", "è", "ê", "ë", "í", "ì", "î", "ï", "ó", "ò", "ô", "õ", "ö", "ú", "ù", "û", "ü", "ç" , "?", "\"", "!", "@", "#", "$", "%", "š", "&", "*", "(", ")", "-", "=", "+", "Ž", "`", "[", "]", "{", "}", "~", "^", ",", "<", ">", ";", ":", "/", "?", "\\", "|", "¹", "²", "³", "£", "¢", "¬", "§", "ª", "º", "°", "Á", "À", "Â", "Ã", "Ä", "É", "È", "Ê", "Ë", "Í", "Ì", "Î", "Ï", "Ó", "Ò", "Ô", "Õ", "Ö", "Ú", "Ù", "Û", "Ü", "Ç");
+			$array2 = array("a", "a", "a", "a", "a", "e", "e", "e", "e", "i", "i", "i", "i", "o", "o", "o", "o", "o", "u", "u", "u", "u", "c" , "" , ""  , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" ,  "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "A", "A", "A", "A", "A", "E", "E", "E", "E", "I", "I", "I", "I", "O", "O", "O", "O", "O", "U", "U", "U", "U", "C");
+		  	return str_replace( $array1, $array2, $string );
+		*/
+		return strtr($string,
+			"áàâãäéèêëíìîïóòôõöúùûüç?\"!@#$%š&*()-=+Ž`[]{}~^,<>;:/?\\|¹²³£¢¬§ªº°ÁÀÂÃÄÉÈÊËÍÌÎÏÓÒÔÕÖÚÙÛÜÇ",
+			"aaaaaeeeeiiiiooooouuuuc__________________________________________AAAAAEEEEIIIIOOOOOUUUUC");
+	}
+	
+	function download_all_attachments($params) {
+		
+		$id_number = $params['num_msg'];		
+		$attachments =unserialize(rawurldecode($params['s_attachments']));
+		
+		$tempDir = ini_get("session.save_path");
+		$tempSubDir = md5(microtime());
+		$fileNames = '';
+		exec('mkdir ' . $tempDir . '/'.$tempSubDir.'; cd ' . $tempDir . '/'.$tempSubDir);
+		$this-> folder = $params['folder'];
+		$this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
+		$this->connectImap();
+		include("class.imap_attachment.inc.php");
+		$imap_attachment = new imap_attachment();
+		$attachments = $imap_attachment->download_attachment($this->mbox_stream, $id_number);
+		
+		foreach($attachments as $i => $attachment){
+			if($i && $i == 'names')
+				continue;
+																		
+			
+			$fileName = $this->remove_accents($attachment['name']);
+			$f = fopen($tempDir . '/'.$tempSubDir.'/'.$fileName,"wb");
+			if(!$f)
+				return False;			
+						
+			$fileNames .= "'".$fileName."' ";
+			$fileContent = imap_fetchbody($this->mbox_stream, $id_number,$attachment['pid'], FT_UID);
+			if($attachment['encoding'] == 'base64')
+				fputs($f,imap_base64($fileContent));
+			else		
+				fputs($f,$fileContent);
+				
+			fclose($f);
+		
+		}
+		imap_close($this->mbox_stream);
+		$nameFileZip = '';
+		
+		if($fileNames) {
+			$nameFileZip = $this -> createFileZip($fileNames, $tempDir . '/'.$tempSubDir);						
+			if($nameFileZip)
+				$file =  $tempDir . '/'.$tempSubDir.'/'.$nameFileZip;
+			else {
+				$file = false;
+			}
+		}
+		else 
+			$file = false;
+				
+		return $file;
+	}
+
+	function getHeader($msg_number){			
+		return imap_fetchheader($this->mbox_stream, $msg_number, FT_UID);
+	}
+	
+	function getBody($msg_number){
+		return imap_body($this->mbox_stream, $msg_number, FT_UID);
+	}
+
+	function decode_subject($string){
+		if ((strpos(strtolower($string), '=?iso-8859-1') !== false) 
+			|| (strpos(strtolower($string), '=?windows-1252') !== false)){
+			$elements = imap_mime_header_decode($string);
+			foreach ($elements as $el)
+				$return .= $el->text;
+		}
+		else if (strpos(strtolower($string), '=?utf-8') !== false) {
+			$elements = imap_mime_header_decode($string);
+			foreach ($elements as $el){
+	   			$charset = $el->charset;
+	   			$text	 = $el->text;
+	   			if(!strcasecmp($charset, "utf-8") ||
+	       			!strcasecmp($charset, "utf-7"))	{
+	     			$text = iconv($charset, "ISO-8859-1", $text);
+	       		}
+	       		$return .= $text;
+	  		}
+		}
+		else
+			$return = $string;
+
+		return $this->remove_accents($return);		
+	}
+}
+// END CLASS
+?>
Index: tags/expressoMail1_2/1.2211/inc/htmlfilter.inc
===================================================================
--- tags/expressoMail1_2/1.2211/inc/htmlfilter.inc	(revision 3)
+++ tags/expressoMail1_2/1.2211/inc/htmlfilter.inc	(revision 3)
@@ -0,0 +1,1021 @@
+<?php
+/**
+ * htmlfilter.inc
+ * ---------------
+ * This set of functions allows you to filter html in order to remove
+ * any malicious tags from it. Useful in cases when you need to filter
+ * user input for any cross-site-scripting attempts.
+ *
+ * Copyright (C) 2002-2004 by Duke University
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  
+ * 02110-1301  USA
+ *
+ * @Author  Konstantin Riabitsev <icon@linux.duke.edu>
+ */
+
+/**
+ * This is a debugging function used throughout the code. To enable
+ * debugging you have to specify a global variable called "debug" before
+ * calling sanitize() and set it to true. 
+ *
+ * Note: Although insignificantly, debugging does slow you down even
+ * when $debug is set to false. If you wish to get rid of all
+ * debugging calls, run the following command:
+ *
+ * fgrep -v 'spew("' htmlfilter.inc > htmlfilter.inc.new
+ *
+ * htmlfilter.inc.new will contain no debugging calls.
+ *
+ * @param  $message  A string with the message to output.
+ * @return           void.
+ */
+function spew($message){
+    global $debug;
+    if ($debug == true){
+        echo "$message";
+    }
+}
+
+/**
+ * This function returns the final tag out of the tag name, an array
+ * of attributes, and the type of the tag. This function is called by 
+ * sanitize internally.
+ *
+ * @param  $tagname  the name of the tag.
+ * @param  $attary   the array of attributes and their values
+ * @param  $tagtype  The type of the tag (see in comments).
+ * @return           a string with the final tag representation.
+ */
+function tagprint($tagname, $attary, $tagtype){
+    $me = 'tagprint';
+    if ($tagtype == 2){
+        $fulltag = '</' . $tagname . '>';
+    } else {
+        $fulltag = '<' . $tagname;
+        if (is_array($attary) && sizeof($attary)){
+            $atts = Array();
+            while (list($attname, $attvalue) = each($attary)){
+                array_push($atts, "$attname=$attvalue");
+            }
+            $fulltag .= ' ' . join(' ', $atts);
+        }
+        if ($tagtype == 3){
+            $fulltag .= ' /';
+        }
+        $fulltag .= '>';
+    }
+    spew("$me: $fulltag\n");
+    return $fulltag;
+}
+
+/**
+ * A small helper function to use with array_walk. Modifies a by-ref
+ * value and makes it lowercase.
+ *
+ * @param  $val a value passed by-ref.
+ * @return      void since it modifies a by-ref value.
+ */
+function casenormalize(&$val){
+    $val = strtolower($val);
+}
+
+/**
+ * This function skips any whitespace from the current position within
+ * a string and to the next non-whitespace value.
+ * 
+ * @param  $body   the string
+ * @param  $offset the offset within the string where we should start
+ *                 looking for the next non-whitespace character.
+ * @return         the location within the $body where the next
+ *                 non-whitespace char is located.
+ */
+function skipspace($body, $offset){
+    $me = 'skipspace';
+    preg_match('/^(\s*)/s', substr($body, $offset), $matches);
+    if (sizeof($matches{1})){
+        $count = strlen($matches{1});
+        spew("$me: skipped $count chars\n");
+        $offset += $count;
+    }
+    return $offset;
+}
+
+/**
+ * This function looks for the next character within a string.  It's
+ * really just a glorified "strpos", except it catches the failures
+ * nicely.
+ *
+ * @param  $body   The string to look for needle in.
+ * @param  $offset Start looking from this position.
+ * @param  $needle The character/string to look for.
+ * @return         location of the next occurance of the needle, or
+ *                 strlen($body) if needle wasn't found.
+ */
+function findnxstr($body, $offset, $needle){
+    $me = 'findnxstr';
+    $pos = strpos($body, $needle, $offset);
+    if ($pos === FALSE){
+        $pos = strlen($body);
+        spew("$me: end of body reached\n");
+    }
+    spew("$me: '$needle' found at pos $pos\n");
+    return $pos;
+}
+
+/**
+ * This function takes a PCRE-style regexp and tries to match it
+ * within the string.
+ *
+ * @param  $body   The string to look for needle in.
+ * @param  $offset Start looking from here.
+ * @param  $reg    A PCRE-style regex to match.
+ * @return         Returns a false if no matches found, or an array
+ *                 with the following members:
+ *                 - integer with the location of the match within $body
+ *                 - string with whatever content between offset and the match
+ *                 - string with whatever it is we matched
+ */
+function findnxreg($body, $offset, $reg){
+    $me = 'findnxreg';
+    $matches = Array();
+    $retarr = Array();
+    $preg_rule = '%^(.*?)(' . $reg . ')%s';
+    preg_match($preg_rule, substr($body, $offset), $matches);
+    if (!isset($matches{0})){
+        spew("$me: No matches found.\n");
+        $retarr = false;
+    } else {
+        $retarr{0} = $offset + strlen($matches{1});
+        $retarr{1} = $matches{1};
+        $retarr{2} = $matches{2};
+        spew("$me: '$reg' found at pos $offset matching '".$matches{2}."'\n");
+    }
+    return $retarr;
+}
+
+/**
+ * This function looks for the next tag.
+ *
+ * @param  $body   String where to look for the next tag.
+ * @param  $offset Start looking from here.
+ * @return         false if no more tags exist in the body, or
+ *                 an array with the following members:
+ *                 - string with the name of the tag
+ *                 - array with attributes and their values
+ *                 - integer with tag type (1, 2, or 3)
+ *                 - integer where the tag starts (starting "<")
+ *                 - integer where the tag ends (ending ">")
+ *                 first three members will be false, if the tag is invalid.
+ */
+function getnxtag($body, $offset){
+    $me = 'getnxtag';
+    if ($offset > strlen($body)){
+        spew("$me: Past the end of body\n");
+        return false;
+    }
+    $lt = findnxstr($body, $offset, '<');
+    if ($lt == strlen($body)){
+        spew("$me: No more tags found!\n");
+        return false;
+    }
+    /**
+     * We are here:
+     * blah blah <tag attribute="value">
+     * \---------^
+     */
+    spew("$me: Found '<' at pos $lt\n");
+    $pos = skipspace($body, $lt + 1);
+    if ($pos >= strlen($body)){
+        spew("$me: End of body reached.\n");
+        return Array(false, false, false, $lt, strlen($body));
+    }
+    /**
+     * There are 3 kinds of tags:
+     * 1. Opening tag, e.g.:
+     *    <a href="blah">
+     * 2. Closing tag, e.g.:
+     *    </a>
+     * 3. XHTML-style content-less tag, e.g.:
+     *    <img src="blah"/>
+     */
+    $tagtype = false;
+    switch (substr($body, $pos, 1)){
+    case '/':
+        spew("$me: This is a closing tag (type 2)\n");
+        $tagtype = 2;
+        $pos++;
+        break;
+    case '!':
+        /**
+         * A comment or an SGML declaration.
+         */
+        if (substr($body, $pos+1, 2) == '--'){
+            spew("$me: A comment found. Stripping.\n");
+            $gt = strpos($body, '-->', $pos);
+            if ($gt === false){
+                $gt = strlen($body);
+            } else {
+                $gt += 2;
+            }
+            return Array(false, false, false, $lt, $gt);
+        } else {
+            spew("$me: An SGML declaration found. Stripping.\n");
+            $gt = findnxstr($body, $pos, '>');
+            return Array(false, false, false, $lt, $gt);
+        }
+        break;
+    default:
+        /**
+         * Assume tagtype 1 for now. If it's type 3, we'll switch values
+         * later.
+         */
+        $tagtype = 1;
+        break;
+    }
+    
+    $tag_start = $pos;
+    $tagname = '';
+    /**
+     * Look for next [\W-_], which will indicate the end of the tag name.
+     */
+    $regary = findnxreg($body, $pos, '[^\w\-_]');
+    if ($regary == false){
+        spew("$me: End of body reached while analyzing tag name\n");
+        return Array(false, false, false, $lt, strlen($body));
+    }
+    list($pos, $tagname, $match) = $regary;
+    $tagname = strtolower($tagname);
+    
+    /**
+     * $match can be either of these:
+     * '>'  indicating the end of the tag entirely.
+     * '\s' indicating the end of the tag name.
+     * '/'  indicating that this is type-3 xhtml tag.
+     * 
+     * Whatever else we find there indicates an invalid tag.
+     */
+    switch ($match){
+    case '/':
+        /**
+         * This is an xhtml-style tag with a closing / at the
+         * end, like so: <img src="blah"/>. Check if it's followed
+         * by the closing bracket. If not, then this tag is invalid
+         */
+        if (substr($body, $pos, 2) == '/>'){
+            spew("$me: XHTML-style tag found.\n");
+            $pos++;
+            spew("$me: Setting tagtype to 3\n");
+            $tagtype = 3;
+        } else {
+            spew("$me: Found invalid character '/'.\n");
+            $gt = findnxstr($body, $pos, '>');
+            spew("$me: Tag is invalid. Returning.\n");
+            $retary = Array(false, false, false, $lt, $gt);
+            return $retary;
+        }
+    case '>':
+        spew("$me: End of tag found at $pos\n");
+        spew("$me: Tagname is '$tagname'\n");
+        spew("$me: This tag has no attributes\n");
+        return Array($tagname, false, $tagtype, $lt, $pos);
+        break;
+    default:
+        /**
+         * Check if it's whitespace
+         */
+        if (preg_match('/\s/', $match)){
+            spew("$me: Tagname is '$tagname'\n");
+        } else {
+            /**
+             * This is an invalid tag! Look for the next closing ">".
+             */
+            spew("$me: Invalid characters found in tag name: $match\n");
+            $gt = findnxstr($body, $lt, '>');
+            return Array(false, false, false, $lt, $gt);
+        }
+    }
+    
+    /**
+     * At this point we're here:
+     * <tagname  attribute='blah'>
+     * \-------^
+     *
+     * At this point we loop in order to find all attributes.
+     */
+    $attname = '';
+    $atttype = false;
+    $attary = Array();
+    
+    while ($pos <= strlen($body)){
+        $pos = skipspace($body, $pos);
+        if ($pos == strlen($body)){
+            /**
+             * Non-closed tag.
+             */
+            spew("$me: End of body reached before end of tag. Discarding.\n");
+            return Array(false, false, false, $lt, $pos);
+        }
+        /**
+         * See if we arrived at a ">" or "/>", which means that we reached
+         * the end of the tag.
+         */
+        $matches = Array();
+        preg_match('%^(\s*)(>|/>)%s', substr($body, $pos), $matches);
+        if (isset($matches{0}) && $matches{0}){
+            /**
+             * Yep. So we did.
+             */
+            spew("$me: Arrived at the end of the tag.\n");
+            $pos += strlen($matches{1});
+            if ($matches{2} == '/>'){
+                $tagtype = 3;
+                $pos++;
+            }
+            return Array($tagname, $attary, $tagtype, $lt, $pos);
+        }
+        
+        /**
+         * There are several types of attributes, with optional
+         * [:space:] between members.
+         * Type 1:
+         *   attrname[:space:]=[:space:]'CDATA'
+         * Type 2:
+         *   attrname[:space:]=[:space:]"CDATA"
+         * Type 3:
+         *   attr[:space:]=[:space:]CDATA
+         * Type 4:
+         *   attrname
+         *
+         * We leave types 1 and 2 the same, type 3 we check for
+         * '"' and convert to "&quot" if needed, then wrap in
+         * double quotes. Type 4 we convert into:
+         * attrname="yes".
+         */
+        $regary = findnxreg($body, $pos, '[^\w\-_]');
+        if ($regary == false){
+            /**
+             * Looks like body ended before the end of tag.
+             */
+            spew("$me: End of body found before end of tag.\n");
+            spew("$me: Invalid, returning\n");
+            return Array(false, false, false, $lt, strlen($body));
+        }
+        list($pos, $attname, $match) = $regary;
+        $attname = strtolower($attname);
+        spew("$me: Attribute '$attname' found\n");
+        /**
+         * We arrived at the end of attribute name. Several things possible
+         * here:
+         * '>'  means the end of the tag and this is attribute type 4
+         * '/'  if followed by '>' means the same thing as above
+         * '\s' means a lot of things -- look what it's followed by.
+         *      anything else means the attribute is invalid.
+         */
+        switch($match){
+        case '/':
+            /**
+             * This is an xhtml-style tag with a closing / at the
+             * end, like so: <img src="blah"/>. Check if it's followed
+             * by the closing bracket. If not, then this tag is invalid
+             */
+            if (substr($body, $pos, 2) == '/>'){
+                spew("$me: This is an xhtml-style tag.\n");
+                $pos++;
+                spew("$me: Setting tagtype to 3\n");
+                $tagtype = 3;
+            } else {
+                spew("$me: Found invalid character '/'.\n");
+                $gt = findnxstr($body, $pos, '>');
+                spew("$me: Tag is invalid. Returning.\n");
+                $retary = Array(false, false, false, $lt, $gt);
+                return $retary;
+            }
+        case '>':
+            spew("$me: found type 4 attribute.\n");
+            spew("$me: Additionally, end of tag found at $pos\n");
+            spew("$me: Attname is '$attname'\n");
+            spew("$me: Setting attvalue to 'yes'\n");
+            $attary{$attname} = '"yes"';
+            return Array($tagname, $attary, $tagtype, $lt, $pos);
+            break;
+        default:
+            /**
+             * Skip whitespace and see what we arrive at.
+             */
+            $pos = skipspace($body, $pos);
+            $char = substr($body, $pos, 1);
+            /**
+             * Two things are valid here:
+             * '=' means this is attribute type 1 2 or 3.
+             * \w means this was attribute type 4.
+             * anything else we ignore and re-loop. End of tag and
+             * invalid stuff will be caught by our checks at the beginning
+             * of the loop.
+             */
+            if ($char == '='){
+                spew("$me: Attribute type 1, 2, or 3 found.\n");
+                $pos++;
+                $pos = skipspace($body, $pos);
+                /**
+                 * Here are 3 possibilities:
+                 * "'"  attribute type 1
+                 * '"'  attribute type 2
+                 * everything else is the content of tag type 3
+                 */
+                $quot = substr($body, $pos, 1);
+                if ($quot == '\''){
+                    spew("$me: In fact, this is attribute type 1\n");
+                    spew("$me: looking for closing quote\n");
+                    $regary = findnxreg($body, $pos+1, '\'');
+                    if ($regary == false){
+                        spew("$me: end of body reached before end of val\n");
+                        spew("$me: Returning\n");
+                        return Array(false, false, false, $lt, strlen($body));
+                    }
+                    list($pos, $attval, $match) = $regary;
+                    spew("$me: Attvalue is '$attval'\n");
+                    $pos++;
+                    $attary{$attname} = '\'' . $attval . '\'';
+                } else if ($quot == '"'){
+                    spew("$me: In fact, this is attribute type 2\n");
+                    spew("$me: looking for closing quote\n");
+                    $regary = findnxreg($body, $pos+1, '\"');
+                    if ($regary == false){
+                        spew("$me: end of body reached before end of val\n");
+                        spew("$me: Returning\n");
+                        return Array(false, false, false, $lt, strlen($body));
+                    }
+                    list($pos, $attval, $match) = $regary;
+                    spew("$me: Attvalue is \"$attval\"\n");
+                    $pos++;
+                    $attary{$attname} = '"' . $attval . '"';
+                } else {
+                    spew("$me: This looks like attribute type 3\n");
+                    /**
+                     * These are hateful. Look for \s, or >.
+                     */
+                    spew("$me: Looking for end of attval\n");
+                    $regary = findnxreg($body, $pos, '[\s>]');
+                    if ($regary == false){
+                        spew("$me: end of body reached before end of val\n");
+                        spew("$me: Returning\n");
+                        return Array(false, false, false, $lt, strlen($body));
+                    }
+                    list($pos, $attval, $match) = $regary;
+                    /**
+                     * If it's ">" it will be caught at the top.
+                     */
+                    spew("$me: translating '\"' into &quot;\n");
+                    $attval = preg_replace('/\"/s', '&quot;', $attval);
+                    spew("$me: wrapping in quotes\n");
+                    $attary{$attname} = '"' . $attval . '"';
+                }
+            } else if (preg_match('|[\w/>]|', $char)) {
+                /**
+                 * That was attribute type 4.
+                 */
+                spew("$me: attribute type 4 found.\n");
+                spew("$me: Setting value to 'yes'\n");
+                $attary{$attname} = '"yes"';
+            } else {
+                /**
+                 * An illegal character. Find next '>' and return.
+                 */
+                spew("$me: illegal character '$char' found.\n");
+                spew("$me: returning\n");
+                $gt = findnxstr($body, $pos, '>');
+                return Array(false, false, false, $lt, $gt);
+            }
+        }
+    }
+    /**
+     * The fact that we got here indicates that the tag end was never
+     * found. Return invalid tag indication so it gets stripped.
+     */
+    spew("$me: No tag end found\n");
+    return Array(false, false, false, $lt, strlen($body));
+}
+
+/**
+ * Translates entities into literal values so they can be checked.
+ *
+ * @param $attvalue the by-ref value to check.
+ * @param $regex    the regular expression to check against.
+ * @param $hex      whether the entites are hexadecimal.
+ * @return          True or False depending on whether there were matches.
+ */
+function deent(&$attvalue, $regex, $hex=false){
+    $me = 'deent';
+    spew("$me: matching '$regex' against: $attvalue\n");
+    $ret_match = false;
+    preg_match_all($regex, $attvalue, $matches);
+    if (is_array($matches) && sizeof($matches[0]) > 0){
+        spew("$me: found " . sizeof($matches[0]) . " matches\n");
+        $repl = Array();
+        for ($i = 0; $i < sizeof($matches[0]); $i++){
+            $numval = $matches[1][$i];
+            spew("$me: numval is $numval\n");
+            if ($hex){
+                $numval = hexdec($numval);
+                spew("$me: hex! Numval is now $numval\n");
+            }
+            $repl{$matches[0][$i]} = chr($numval);
+        }
+        $attvalue = strtr($attvalue, $repl);
+        spew("$me: attvalue after translation: $attvalue\n");
+        return true;
+    } else {
+        spew("$me: no matches! Returning false.\n");
+        return false;
+    }
+}
+
+/**
+ * This function checks attribute values for entity-encoded values
+ * and returns them translated into 8-bit strings so we can run
+ * checks on them.
+ *
+ * @param  $attvalue A string to run entity check against.
+ * @return           Nothing, modifies a reference value.
+ */
+function defang(&$attvalue){
+    $me = 'defang';
+    /**
+     * Skip this if there aren't ampersands or backslashes.
+     */
+    spew("$me: Checking '$attvalue' for suspicious content\n");
+    if (strpos($attvalue, '&') === false
+        && strpos($attvalue, '\\') === false){
+        spew("$me: no suspicious content found, returning.\n");
+        return;
+    }
+    $m = false;
+    do {
+        $m = false;
+        $m = $m || deent($attvalue, '/\&#0*(\d+);*/s');
+        $m = $m || deent($attvalue, '/\&#x0*((\d|[a-f])+);*/si', true);
+        $m = $m || deent($attvalue, '/\\\\(\d+)/s', true);
+        spew("$me: m=$m\n");
+    } while ($m == true);
+    $attvalue = stripslashes($attvalue);
+    spew("$me: translated into: $attvalue\n");
+}
+
+/**
+ * Kill any tabs, newlines, or carriage returns. Our friends the
+ * makers of the browser with 95% market value decided that it'd
+ * be funny to make "java[tab]script" be just as good as "javascript".
+ * 
+ * @param  attvalue  The attribute value before extraneous spaces removed.
+ * @return attvalue  Nothing, modifies a reference value.
+ */
+function unspace(&$attvalue){
+    $me = 'unspace';
+    if (strcspn($attvalue, "\t\r\n\0 ") != strlen($attvalue)){
+        spew("$me: Killing whitespace.\n");
+        $attvalue = str_replace(Array("\t", "\r", "\n", "\0", " "), 
+                                Array('',   '',   '',   '',   ''), $attvalue);
+    }
+    spew("$me: after unspace: $attvalue\n");
+}
+
+/**
+ * This function runs various checks against the attributes.
+ *
+ * @param  $tagname         String with the name of the tag.
+ * @param  $attary          Array with all tag attributes.
+ * @param  $rm_attnames     See description for sanitize
+ * @param  $bad_attvals     See description for sanitize
+ * @param  $add_attr_to_tag See description for sanitize
+ * @return                  Array with modified attributes.
+ */
+function fixatts($tagname, 
+                 $attary, 
+                 $rm_attnames,
+                 $bad_attvals,
+                 $add_attr_to_tag
+                 ){
+    $me = 'fixatts';
+    spew("$me: Fixing attributes\n");
+    while (list($attname, $attvalue) = each($attary)){
+        /**
+         * See if this attribute should be removed.
+         */
+        foreach ($rm_attnames as $matchtag=>$matchattrs){
+            if (preg_match($matchtag, $tagname)){
+                foreach ($matchattrs as $matchattr){
+                    if (preg_match($matchattr, $attname)){
+                        spew("$me: Attribute '$attname' defined as bad.\n");
+                        spew("$me: Removing.\n");
+                        unset($attary{$attname});
+                        continue;
+                    }
+                }
+            }
+        }
+        /**
+         * Remove any backslashes, entities, or extraneous whitespace.
+         */
+        defang($attvalue);
+        unspace($attvalue);
+        
+        /**
+         * Now let's run checks on the attvalues.
+         * I don't expect anyone to comprehend this. If you do,
+         * get in touch with me so I can drive to where you live and
+         * shake your hand personally. :)
+         */
+        foreach ($bad_attvals as $matchtag=>$matchattrs){
+            if (preg_match($matchtag, $tagname)){
+                foreach ($matchattrs as $matchattr=>$valary){
+                    if (preg_match($matchattr, $attname)){
+                        /**
+                         * There are two arrays in valary.
+                         * First is matches.
+                         * Second one is replacements
+                         */
+                        list($valmatch, $valrepl) = $valary;
+                        $newvalue = preg_replace($valmatch,$valrepl,$attvalue);
+                        if ($newvalue != $attvalue){
+                            spew("$me: attvalue is now $newvalue\n");
+                            $attary{$attname} = $newvalue;
+                        }
+                    }
+                }
+            }
+        }
+    }
+    /**
+     * See if we need to append any attributes to this tag.
+     */
+    foreach ($add_attr_to_tag as $matchtag=>$addattary){
+        if (preg_match($matchtag, $tagname)){
+            $attary = array_merge($attary, $addattary);
+            spew("$me: Added attributes to this tag\n");
+        }
+    }
+    return $attary;
+}
+
+/**
+ * This is the main function and the one you should actually be calling.
+ * There are several variables you should be aware of an which need
+ * special description.
+ *
+ * $tag_list
+ * ----------
+ * This is a simple one-dimentional array of strings, except for the
+ * very first one. The first member should be einter false or true.
+ * In case it's FALSE, the following list will be considered a list of
+ * tags that should be explicitly REMOVED from the body, and all
+ * others that did not match the list will be allowed.  If the first
+ * member is TRUE, then the list is the list of tags that should be
+ * explicitly ALLOWED -- any tag not matching this list will be
+ * discarded.
+ *
+ * Examples:
+ * $tag_list = Array(
+ *                   false,   
+ *                   "blink", 
+ *                   "link",
+ *		     "object",
+ *		     "meta",
+ *                   "marquee",
+ *                   "html"
+ *		            );
+ *
+ * This will allow all tags except for blink, link, object, meta, marquee, 
+ * and html.
+ *
+ * $tag_list = Array(
+ *                   true, 
+ *                   "b", 
+ *                   "a", 
+ *                   "i", 
+ *                   "img", 
+ *                   "strong", 
+ *                   "em", 
+ *                   "p"
+ *                  );
+ *
+ * This will remove all tags from the body except b, a, i, img, strong, em and
+ * p.
+ *
+ * $rm_tags_with_content
+ * ---------------------
+ * This is a simple one-dimentional array of strings, which specifies the
+ * tags to be removed with any and all content between the beginning and
+ * the end of the tag.
+ * Example:
+ * $rm_tags_with_content = Array(
+ *                               "script",
+ *                               "style", 
+ *                               "applet",
+ *                               "embed"
+ *                              );
+ *
+ * This will remove the following structure:
+ * <script>
+ *  window.alert("Isn't cross-site-scripting fun?!");
+ * </script>
+ * 
+ * $self_closing_tags
+ * ------------------
+ * This is a simple one-dimentional array of strings, which specifies which
+ * tags contain no content and should not be forcefully closed if this option
+ * is turned on (see further).
+ * Example:
+ * $self_closing_tags =  Array(
+ *                             "img",
+ *                             "br", 
+ *                             "hr",
+ *                             "input"
+ *                            );    
+ *
+ * $force_tag_closing
+ * ------------------
+ * Set it to true to forcefully close any tags opened within the document.
+ * This is good if you want to take care of people who like to screw up
+ * the pages by leaving unclosed tags like <a>, <b>, <i>, etc.
+ *
+ * $rm_attnames
+ * -------------
+ * Now we come to parameters that are more obscure. This parameter is
+ * a nested array which is used to specify which attributes should be
+ * removed. It goes like so:
+ * 
+ * $rm_attnames = Array(
+ *   "PCRE regex to match tag name" =>
+ *     Array(
+ *           "PCRE regex to match attribute name"
+ *           )
+ *   );
+ *
+ * Example:
+ * $rm_attnames = Array(
+ *   "|.*|" =>
+ *     Array(
+ *           "|target|i",
+ *           "|^on.*|i"  
+ *          )
+ *   );
+ *
+ * This will match all attributes (.*), and specify that all attributes
+ * named "target" and starting with "on" should be removed. This will take
+ * care of the following problem:
+ * <em onmouseover="window.alert('muahahahaha')">
+ * The "onmouseover" will be removed.
+ *
+ * $bad_attvals
+ * ------------
+ * This is where it gets ugly. This is a nested array with many levels.
+ * It goes like so:
+ *
+ * $bad_attvals = Array(
+ *   "pcre regex to match tag name" =>
+ *     Array(
+ *           "pcre regex to match attribute name" =>
+ *             Array(
+ *                   "pcre regex to match attribute value"
+ *                  )
+ *             Array(
+ *                   "pcre regex replace a match from above with"
+ *                  )
+ *          )
+ *   );
+ *
+ * An extensive example:
+ *
+ * $bad_attvals = Array(
+ *   "|.*|" =>
+ *      Array(
+ *            "/^src|background|href|action/i" =>
+ *                Array(
+ *                      Array(
+ *                            "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si"
+ *                            ),
+ *                      Array(
+ *                            "\\1http://veryfunny.com/\\2"
+ *                            )
+ *                      ),
+ *            "/^style/i" =>
+ *                Array(
+ *                      Array(
+ *                            "/expression/si",
+ *                            "/url\(([\'\"])\s*https*:.*([\'\"])\)/si",
+ *                            "/url\(([\'\"])\s*\S+script:.*([\'\"])\)/si"
+ *                           ),
+ *                      Array(
+ *                            "idiocy",
+ *                            "url(\\1http://veryfunny.com/\\2)",
+ *                            "url(\\1http://veryfynny.com/\\2)"
+ *                           )
+ *                      )
+ *            )
+ *  );
+ *
+ * This will take care of nearly all known cross-site scripting exploits,
+ * plus some (see my filter sample at 
+ * http://www.mricon.com/html/phpfilter.html for a working version).
+ *
+ * $add_attr_to_tag
+ * ----------------
+ * This is a useful little feature which lets you add attributes to 
+ * certain tags. It is a nested array as well, but not at all like
+ * the previous one. It goes like so:
+ * 
+ * $add_attr_to_tag = Array(
+ *   "PCRE regex to match tag name" =>
+ *     Array(
+ *           "attribute name"=>'"attribute value"'
+ *          )
+ *   );
+ * 
+ * Note: don't forget quotes around attribute value.
+ * 
+ * Example:
+ * 
+ * $add_attr_to_tag = Array(
+ *   "/^a$/si" => 
+ *     Array(
+ *           'target'=>'"_new"'
+ *          )
+ *   );
+ * 
+ * This will change all <a> tags and add target="_new" to them so all links
+ * open in a new window.
+ *
+ *
+ *
+ * @param $body                 the string with HTML you wish to filter
+ * @param $tag_list             see description above
+ * @param $rm_tags_with_content see description above
+ * @param $self_closing_tags    see description above
+ * @param $force_tag_closing    see description above
+ * @param $rm_attnames          see description above
+ * @param $bad_attvals          see description above
+ * @param $add_attr_to_tag      see description above
+ * @return                      sanitized html safe to show on your pages.
+ */
+function sanitize($body, 
+                  $tag_list, 
+                  $rm_tags_with_content,
+                  $self_closing_tags,
+                  $force_tag_closing,
+                  $rm_attnames,
+                  $bad_attvals,
+                  $add_attr_to_tag
+                  ){
+    $me = 'sanitize';
+    /**
+     * Normalize rm_tags and rm_tags_with_content.
+     */
+    @array_walk($tag_list, 'casenormalize');
+    @array_walk($rm_tags_with_content, 'casenormalize');
+    @array_walk($self_closing_tags, 'casenormalize');
+    /**
+     * See if tag_list is of tags to remove or tags to allow.
+     * false  means remove these tags
+     * true   means allow these tags
+     */
+    $rm_tags = array_shift($tag_list);
+    $curpos = 0;
+    $open_tags = Array();
+    //$trusted = "<!-- begin sanitized html -->\n";
+    $trusted = "";
+    $skip_content = false;
+    /**
+     * Take care of netscape's stupid javascript entities like
+     * &{alert('boo')};
+     */
+    $body = preg_replace('/&(\{.*?\};)/si', '&amp;\\1', $body);
+    spew("$me: invoking the loop\n");
+    while (($curtag = getnxtag($body, $curpos)) != FALSE){
+        list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
+        spew("$me: grabbing free-standing content\n");
+        $free_content = substr($body, $curpos, $lt - $curpos);
+        spew("$me: " . strlen($free_content) . " chars grabbed\n");
+        if ($skip_content == false){
+            spew("$me: appending free content to trusted.\n");
+            $trusted .= $free_content;
+        } else {
+            spew("$me: Skipping free content.\n");
+        }
+        if ($tagname != FALSE){
+            spew("$me: tagname is '$tagname'\n");
+            if ($tagtype == 2){
+                spew("$me: This is a closing tag\n");
+                if ($skip_content == $tagname){
+                    /**
+                     * Got to the end of tag we needed to remove.
+                     */
+                    spew("$me: Finished removing tag with content\n");
+                    $tagname = false;
+                    $skip_content = false;
+                } else {
+                    if ($skip_content == false){
+                        if (isset($open_tags{$tagname}) && 
+                            $open_tags{$tagname} > 0){
+                            spew("$me: popping '$tagname' from open_tags\n");
+                            $open_tags{$tagname}--;
+                        } else {
+                            spew("$me: '$tagname' was never opened\n");
+                            spew("$me: removing\n");
+                            $tagname = false;
+                        }
+                    } else {
+                        spew("$me: Skipping this tag\n");
+                    }
+                }
+            } else {
+                /**
+                 * $rm_tags_with_content
+                 */
+                if ($skip_content == false){
+                    /**
+                     * See if this is a self-closing type and change
+                     * tagtype appropriately.
+                     */
+                    if ($tagtype == 1
+                        && in_array($tagname, $self_closing_tags)){
+                        spew("$me: Self-closing tag. Changing tagtype.\n");
+                        $tagtype = 3;
+                    }
+                    /**
+                     * See if we should skip this tag and any content
+                     * inside it.
+                     */
+                    if ($tagtype == 1 
+                        && in_array($tagname, $rm_tags_with_content)){
+                        spew("$me: removing this tag with content\n");
+                        $skip_content = $tagname;
+                    } else {
+                        if (($rm_tags == false 
+                             && in_array($tagname, $tag_list)) ||
+                            ($rm_tags == true 
+                             && !in_array($tagname, $tag_list))){
+                            spew("$me: Removing this tag.\n");
+                            $tagname = false;
+                        } else {
+                            if ($tagtype == 1){
+                                spew("$me: adding '$tagname' to open_tags\n");
+                                if (isset($open_tags{$tagname})){
+                                    $open_tags{$tagname}++;
+                                } else {
+                                    $open_tags{$tagname} = 1;
+                                }
+                            }
+                            /**
+                             * This is where we run other checks.
+                             */
+                            if (is_array($attary) && sizeof($attary) > 0){
+                                $attary = fixatts($tagname,
+                                                  $attary,
+                                                  $rm_attnames,
+                                                  $bad_attvals,
+                                                  $add_attr_to_tag);
+                            }
+                        }
+                    }
+                } else {
+                    spew("$me: Skipping this tag\n");
+                }
+            }
+            if ($tagname != false && $skip_content == false){
+                spew("$me: Appending tag to trusted.\n");
+                $trusted .= tagprint($tagname, $attary, $tagtype);
+            }
+        } else {
+            spew("$me: Removing invalid tag\n");
+        }
+        $curpos = $gt + 1;
+    }
+    spew("$me: Appending any leftover content\n");
+    $trusted .= substr($body, $curpos, strlen($body) - $curpos);
+    if ($force_tag_closing == true){
+        foreach ($open_tags as $tagname=>$opentimes){
+            while ($opentimes > 0){
+                spew("$me: '$tagname' left open. Closing by force.\n");
+                $trusted .= '</' . $tagname . '>';
+                $opentimes--;
+            }
+        }
+        $trusted .= "\n";
+    }
+    //$trusted .= "<!-- end sanitized html -->\n";
+    return $trusted;
+}
+?>
Index: tags/expressoMail1_2/1.2211/inc/gotodownload.php
===================================================================
--- tags/expressoMail1_2/1.2211/inc/gotodownload.php	(revision 178)
+++ tags/expressoMail1_2/1.2211/inc/gotodownload.php	(revision 178)
@@ -0,0 +1,159 @@
+<?
+	$msg_number = $_GET['msg_number'];
+	$idx_file = $_GET['idx_file'];
+	$newfilename = $_GET['newfilename'];
+	$msg_part = $_GET['msg_part'];
+	$msg_folder = $_GET['msg_folder'];
+	$msg_folder = mb_convert_encoding($msg_folder,"UTF7-IMAP", mb_detect_encoding($msg_folder, "UTF-8, ISO-8859-1", true));
+		
+	$encoding = strtolower($_GET['encoding']);
+	$fileContent = "";
+	
+	if($msg_number && $msg_part && $msg_folder && (intval($idx_file == '0' ? '1' : $idx_file))) {
+		$username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
+		$password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
+		$imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
+		$imap_port 	= $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];		
+		if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
+		{
+			$imap_options = '/tls/novalidate-cert';
+		}
+		else
+		{
+			$imap_options = '/notls/novalidate-cert';
+		}
+		$mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$msg_folder, $username, $password);   	
+   		$fileContent = imap_fetchbody($mbox_stream, $msg_number, $msg_part, FT_UID);
+		include("class.imap_attachment.inc.php");
+		$imap_attachment = new imap_attachment();	   		
+		$a = $imap_attachment->download_attachment($mbox_stream, $msg_number);
+		
+		$filename = $a[$idx_file]['name'];
+	}
+	else
+		$filename = $idx_file;
+			
+   	$filename 	 = $filename 	? $filename 	: "attachment.bin";
+   	$newfilename = $newfilename ? $newfilename 	: $filename;
+   	$strFileType = strrev(substr(strrev(strtolower($filename)),0,4));
+	
+   	downloadFile($strFileType, $filename, $newfilename, $fileContent, $encoding);
+   
+   function downloadFile($strFileType, $strFileName, $newFileName, $fileContent, $encoding) {
+   	$ContentType = "application/octet-stream";
+
+   	if ($strFileType == ".asf") 
+   		$ContentType = "video/x-ms-asf";
+   	if ($strFileType == ".avi")
+   		$ContentType = "video/avi";
+   	if ($strFileType == ".doc")
+   		$ContentType = "application/msword";
+   	if ($strFileType == ".zip")
+   		$ContentType = "application/zip";
+   	if ($strFileType == ".xls")
+   		$ContentType = "application/vnd.ms-excel";
+   	if ($strFileType == ".gif")
+   		$ContentType = "image/gif";
+   	if ($strFileType == ".jpg" || $strFileType == "jpeg")
+   		$ContentType = "image/jpeg";
+   	if ($strFileType == ".wav")
+   		$ContentType = "audio/wav";
+   	if ($strFileType == ".mp3")
+   		$ContentType = "audio/mpeg3";
+   	if ($strFileType == ".mpg" || $strFileType == "mpeg")
+   		$ContentType = "video/mpeg";
+   	if ($strFileType == ".rtf")
+   		$ContentType = "application/rtf";
+   	if ($strFileType == ".htm" || $strFileType == "html")
+   		$ContentType = "text/html";
+   	if ($strFileType == ".xml") 
+   		$ContentType = "text/xml";
+   	if ($strFileType == ".xsl") 
+   		$ContentType = "text/xsl";
+   	if ($strFileType == ".css") 
+   		$ContentType = "text/css";
+   	if ($strFileType == ".php") 
+   		$ContentType = "text/php";
+   	if ($strFileType == ".asp") 
+   		$ContentType = "text/asp";
+   	if ($strFileType == ".pdf")
+   		$ContentType = "application/pdf";
+   	if ($strFileType == ".txt")
+   		$ContentType = "text/plain";
+   	if ($strFileType == ".log")
+   		$ContentType = "text/plain";
+   	if ($strFileType == ".wmv")
+   		$ContentType = "video/x-ms-wmv";
+	if ($strFileType == ".sxc")
+		$ContentType = "application/vnd.sun.xml.calc";
+	if ($strFileType == ".odt")
+		$ContentType = "application/vnd.oasis.opendocument.text";
+	if ($strFileType == ".stc")
+		$ContentType = "application/vnd.sun.xml.calc.template";
+	if ($strFileType == ".sxd")
+		$ContentType = "application/vnd.sun.xml.draw";
+	if ($strFileType == ".std")
+		$ContentType = "application/vnd.sun.xml.draw.template";
+	if ($strFileType == ".sxi")
+		$ContentType = "application/vnd.sun.xml.impress";
+	if ($strFileType == ".sti")
+		$ContentType = "application/vnd.sun.xml.impress.template";
+	if ($strFileType == ".sxm")
+		$ContentType = "application/vnd.sun.xml.math";
+	if ($strFileType == ".sxw")
+		$ContentType = "application/vnd.sun.xml.writer";
+	if ($strFileType == ".sxq")
+		$ContentType = "application/vnd.sun.xml.writer.global";
+	if ($strFileType == ".stw")
+		$ContentType = "application/vnd.sun.xml.writer.template";
+	if ($strFileType == ".ps")
+		$ContentType = "application/postscript";
+	if ($strFileType == ".pps")
+		$ContentType = "application/vnd.ms-powerpoint";
+	if ($strFileType == ".odt")
+		$ContentType = "application/vnd.oasis.opendocument.text";
+	if ($strFileType == ".ott")
+		$ContentType = "application/vnd.oasis.opendocument.text-template";
+	if ($strFileType == ".oth")
+		$ContentType = "application/vnd.oasis.opendocument.text-web";
+	if ($strFileType == ".odm")
+		$ContentType = "application/vnd.oasis.opendocument.text-master";
+	if ($strFileType == ".odg")
+		$ContentType = "application/vnd.oasis.opendocument.graphics";
+	if ($strFileType == ".otg")
+		$ContentType = "application/vnd.oasis.opendocument.graphics-template";
+	if ($strFileType == ".odp")
+		$ContentType = "application/vnd.oasis.opendocument.presentation";
+	if ($strFileType == ".otp")
+		$ContentType = "application/vnd.oasis.opendocument.presentation-template";
+	if ($strFileType == ".ods")
+		$ContentType = "application/vnd.oasis.opendocument.spreadsheet";
+	if ($strFileType == ".ots")
+		$ContentType = "application/vnd.oasis.opendocument.spreadsheet-template";
+	if ($strFileType == ".odc")
+		$ContentType = "application/vnd.oasis.opendocument.chart";
+	if ($strFileType == ".odf")
+		$ContentType = "application/vnd.oasis.opendocument.formula";
+	if ($strFileType == ".odi")
+		$ContentType = "application/vnd.oasis.opendocument.image";
+	if ($strFileType == ".ndl")
+		$ContentType = "application/vnd.lotus-notes";
+	
+   	header ("Content-Type: $ContentType");
+   	header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
+    header("Pragma: public");
+    header("Expires: 0"); // set expiration time
+    header ("Content-Disposition: attachment; filename=\"". addslashes($newFileName)."\"");   	
+    
+	if($fileContent) {
+		if($encoding == 'base64')
+			echo imap_base64($fileContent);
+		else if($encoding == 'quoted-printable')
+			echo quoted_printable_decode($fileContent);
+		else
+			echo $fileContent;
+	}
+	else
+		readfile($strFileName);
+   }
+   ?>
Index: tags/expressoMail1_2/1.2211/inc/show_thumbs.php
===================================================================
--- tags/expressoMail1_2/1.2211/inc/show_thumbs.php	(revision 178)
+++ tags/expressoMail1_2/1.2211/inc/show_thumbs.php	(revision 178)
@@ -0,0 +1,39 @@
+<?php
+	$username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
+	$password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
+	$imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
+	$imap_port 	= $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
+	if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
+	{
+		$imap_options = '/tls/novalidate-cert';
+	}
+	else
+	{
+		$imap_options = '/notls/novalidate-cert';
+	}
+
+	$file_type = $_GET['file_type'];
+	$msg_num = $_GET['msg_num'];
+	$msg_part = $_GET['msg_part'];
+	$msg_folder = $_GET['msg_folder'];
+	$msg_folder = mb_convert_encoding($msg_folder,"UTF7-IMAP", mb_detect_encoding($msg_folder, "UTF-8, ISO-8859-1", true));
+	$mb = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$msg_folder, $username, $password);
+
+	$image_mail = imap_fetchbody($mb, $msg_num, $msg_part, FT_UID);
+	$image = imap_base64($image_mail);
+	$image = imagecreatefromstring ($image);
+	
+	header("Content-Type: ".$file_type);
+	header("Content-Disposition: inline");
+ 
+	$pic = $image;
+    if ($pic) {
+        $width = imagesx($pic);
+        $height = imagesy($pic);
+        $twidth = 160; # width of the thumb 160 pixel
+        $theight = $twidth * $height / $width; # calculate height
+        $thumb = imagecreatetruecolor ($twidth, $theight);
+		imagecopyresized($thumb, $pic, 0, 0, 0, 0,$twidth, $theight, $width, $height); # resize image into thumb
+		imagejpeg($thumb,"",75); # Thumbnail as JPEG
+    }
+?>
Index: tags/expressoMail1_2/1.2211/inc/class.ScriptS.inc.php
===================================================================
--- tags/expressoMail1_2/1.2211/inc/class.ScriptS.inc.php	(revision 122)
+++ tags/expressoMail1_2/1.2211/inc/class.ScriptS.inc.php	(revision 122)
@@ -0,0 +1,514 @@
+<?php
+
+//Inclui o arquivo contendo a classe SieveS;
+include('class.SieveS.inc.php');
+
+class ScriptS {
+	
+	//Declaração de Variáveis;
+	var $SieveS;					// Var para criação do objeto;
+	var $reply;						// Var para resposta;
+	var $scriptfile;				// Nome do script;
+	var $username;					// Nome do usuario;
+	var $rules;						// Regras do sieve;
+	var $errstr;					// Erros retornados;
+	var $size;						// var tamanho;
+	var $so;						// para verificar se a regra foi criada por outro tipo serviço de filtros;
+	var $continuebit;
+	var $sizebit;
+	var $anyofbit;
+	var $keepbit;
+	var $regexbit;
+	var $newrules = array();
+	var $newout;
+	
+	function ScriptS(){
+
+		//Cria o objeto;
+		$this->SieveS     = new SieveS();
+		
+		//$this->scriptfile = $GLOBALS['HTTP_SESSION_VARS']['phpgw_info']['expressomail']['user']['account_lid'];
+		$this->scriptfile = $_SESSION['phpgw_info']['expressomail']['user']['account_lid'];
+		$this->username   = $this->scriptfile;
+		
+		$this->reply      = "";
+		$this->rules	  = "";	
+		$this->errstr	  = "";
+		$this->size		  = "";
+		
+		$this->continuebit 	= 1;
+    	$this->sizebit 		= 2;
+    	$this->anyofbit 	= 4;
+    	$this->keepbit 		= 8;
+    	$this->regexbit 	= 128;
+    	
+	}
+	
+	function init_a(){
+		
+		//Abre a conexão
+		$this->SieveS->start();
+		
+		$this->reply = $this->SieveS->getscript();
+		
+		if(!$this->reply){
+	
+			$aux = $this->SieveS->putscript($this->scriptfile, $this->createScript());
+			if(!$aux){
+				// Caso de erro, grava dentro da variável errstr;
+				$this->errstr = "O arquivo não foi criado";
+			}
+			// Mata a variavel;
+			unset($aux);
+			// Ativa o script;
+			$aux = $this->SieveS->activatescript($this->scriptfile);
+			
+			if(!$aux){
+				// Caso de erro, grava dentro da variavel errstr;
+				$this->errstr = "O arquivo não foi ativado";
+			}
+			else{
+				$this->reply = $this->SieveS->getscript();
+				$this->rules = $this->readScript($this->reply);
+			}
+		}else{
+			$this->rules = $this->readScript($this->reply);
+		}		
+
+		//Fecha a conexao
+		$this->SieveS->close();
+			
+		if($this->rules){		
+			return $this->rules;
+		}else{
+			return $this->errstr;
+		}
+			
+	}
+	
+	function rec_rules($params){
+		
+		$newr1  = array();
+		$newr2  = array();
+		$newr3  = array();
+	
+		$var_decode = rawurldecode($params['arfilter']);
+		
+		$narray  = explode("_end_",$var_decode);
+		
+		foreach($narray as $key=>$tmp){
+			if($tmp != ""){
+				$newr1[] = $tmp;
+			}
+		}
+		unset($key);
+		unset($tmp);
+		foreach($newr1 as $key=>$tmp){
+			$tmp2 = explode("_begin_##", $tmp);
+			foreach($tmp2 as $tmp3){
+				if($tmp3 != ""){
+					$newr2[] = trim($tmp3);		
+				}	
+			}	
+		}
+		
+		unset($tmp);
+		unset($tmp2);
+		unset($tmp3);
+
+		foreach($newr2 as $tmp){
+			if(trim($tmp) != ""){	
+				$tmp2 = explode("##",$tmp);
+				foreach($tmp2 as $tmp3){
+					$tmp4 .= trim($tmp3) . "&&";	
+				}
+				$newr3[] = substr($tmp4,0,(strlen($tmp4)-4));			
+				unset($tmp2);
+				unset($tmp3);
+				unset($tmp4);
+			}
+		}
+		
+		$tmp = $newr3[count($newr3)-1];
+		
+		if(substr($tmp,0,9) == "#vacation"){
+			$this->newout = array_pop($newr3);
+			foreach($newr3 as $key=>$tmp){
+				$this->newrules[] = $tmp;
+			}
+		}else{
+			foreach($newr3 as $tmp){
+				$this->newrules[] = $tmp;	
+			}
+		}
+				
+		unset($tmp);
+		$tmp  = explode("&&",$this->newout);
+		$tmp1 = explode(",",$tmp[2]); 
+		foreach($tmp1 as $key=>$tmp2){
+			$tmp3 .= stripslashes(trim($tmp2)).", ";
+		}
+		$tmp3 = substr($tmp3,0,(strlen($tmp3)-2));
+		
+		unset($tmp);
+		unset($tmp1);
+		unset($tmp2);
+		unset($key);
+		$tmp = explode("&&",$this->newout);
+		foreach($tmp as $key=>$tmp1){
+			if($key == 2){
+				$tmp2 .= trim($tmp3) . "&&";	
+			}else{
+				$tmp2 .= trim($tmp1) . "&&";	
+			}	
+		}
+		unset($this->newout);
+		$this->newout = substr($tmp2,0,(strlen($tmp2)-2));
+		
+		//Abre a conexao
+		$this->SieveS->start();
+		$this->errstr = "";
+		
+		// Escreve a nova regra;
+		$this->reply = $this->SieveS->getscript();
+		
+		if($this->reply){
+			$this->errstr = $this->SieveS->deletescript($this->scriptfile);		
+		}
+
+		//Escreve a(s) nova(s) regra(s);
+		$this->errstr = $this->SieveS->putscript($this->scriptfile,$this->write_rule());
+		
+		//Ativa o script;
+		$this->errstr = $this->SieveS->activatescript($this->scriptfile);
+		
+		//Fecha a conexao
+		$this->SieveS->close();
+		
+		if($this->errstr){
+			return "Ok";
+		}else{
+			return "Problemas na criação do arquivo!";
+		}
+	}
+
+        function convert_specialchar($input){
+	          $special_char = false;
+		  for ( $i = 0; $i < strlen($input); $i++ )
+		      if ( preg_match('/[ÁáÉéÍíÓóÚúÀàÈèÌìÒòÙùÇçÃãÕõÂâÊêÔô]/', $input[$i]) )
+		      {
+		          $special_char = true;
+		          $input = preg_replace('/'.$input[$i].'/', '=' . bin2hex($input[$i]), $input);
+		      }
+                   if ( $special_char )
+		   {
+		   /*  When using arrays with pattern and replacement, the keys are processed in the order they appear in the array. See preg_replace in php.net/preg_replace */
+		   $patterns[0] = '/=c3/i';
+		   $patterns[1] = '/ /';
+		   $replacements[1] = '';
+		   $replacements[0] = '_';
+		   $input = preg_replace($patterns, $replacements, $input);
+		   }
+                   return($input);
+        }
+
+	// Grava a nova regra;
+	function write_rule(){
+
+		// Variaveis;
+		$rule = array();
+		$vacation = array();
+		$newruletext = "";
+		$activerules = 0;
+		$regexused = 0;
+		$rejectused = 0;
+		$newscriptbody = "";
+    	$continue = 1;
+    	
+		// Recebe os valores das regras;
+		foreach($this->newrules as $tmp){
+		  $tmp1 = explode("&&",$tmp);
+		  $rule['priority']      = $tmp1[1];
+		  $rule['status']        = $tmp1[2];
+          $rule['from'] 	     = $this->convert_specialchar($tmp1[3]);
+          $rule['to']            = $this->convert_specialchar($tmp1[4]);
+	  $rule['subject'] = $this->convert_specialchar($tmp1[5]);
+          $rule['action'] 	     = $tmp1[6];
+	  $rule['action_arg']    = utf8_encode(preg_replace("/\\r\\n/","\r\n",$tmp1[7]));
+          $rule['flg'] 		     = $tmp1[8];   
+          $rule['field'] 		 = $tmp1[9];
+          $rule['field_val']     = $tmp1[10];
+          $rule['size'] 		   = $tmp1[11];
+          $rule['continue'] 	   = ($tmp1[8] & $this->continuebit);
+          $rule['gthan'] 		   = ($tmp1[8] & $this->sizebit); 
+          $rule['anyof'] 		   = ($tmp1[8] & $this->anyofbit);
+          $rule['keep'] 	   	   = ($tmp1[8] & $this->keepbit);
+          $rule['regexp'] 	       = ($tmp1[8] & $this->regexbit);
+          $rule['unconditional']   = 0;
+		  
+		  if (!$rule['from'] && !$rule['to'] && !$rule['subject'] && !$rule['field'] && !$rule['size'] && $rule['action']){
+			 $rule['unconditional'] = 1;
+		  }
+   		  unset($tmp1);
+	      
+	      // Monta as regras;
+	      if ($rule['status'] != 'ENABLED') {
+	      }
+	      else {
+	        $activerules = 1;
+	 
+	        // Condições para montagem das regras;
+	        $anyall = "allof";
+	        if ($rule['anyof']) $anyall = "anyof";
+	        if ($rule['regexp']) {
+	            $regexused = 1;
+	        }
+	        $started = 0;
+	 
+	        if (!$rule['unconditional']) {
+	            if (!$continue) $newruletext .= "els";
+	            $newruletext .= "if " . $anyall . " (";
+	            if ($rule['from']) {
+	                if (preg_match("/^\s*!/", $rule['from'])){
+	                    $newruletext .= 'not ';
+	                    $rule['from'] = preg_replace("/^\s*!/","",$rule['from']);
+	                }
+	                $match = ':contains';
+	                if (preg_match("/\*|\?/", $rule['from'])) $match = ':matches';
+	                if ($rule['regexp']) $match = ':regex';
+	                $newruletext .= "header " . $match . " [\"From\"]";
+	                $newruletext .= " \"" . $rule['from'] . "\"";
+	                $started = 1;
+	            }
+	            if ($rule['to']) {
+	                if ($started) $newruletext .= ", ";
+	                if (preg_match("/^\s*!/", $rule['to'])){
+	                    $newruletext .= 'not ';
+	                    $rule['to'] = preg_replace("/^\s*!/","",$rule['to']);
+	                }
+	                $match = ':contains';
+	                if (preg_match("/\*|\?/", $rule['to'])) $match = ':matches';
+	                if ($rule['regexp']) $match = ':regex';
+	                $newruletext .= "address " . $match . " [\"To\",\"TO\",\"Cc\",\"CC\"]";
+	                $newruletext .= " \"" . $rule['to'] . "\"";
+	                $started = 1;
+	            }
+	            if ($rule['subject']) {
+	                if ($started) $newruletext .= ", ";
+	                if (preg_match("/^\s*!/", $rule['subject'])){
+	                    $newruletext .= 'not ';
+	                    $rule['subject'] = preg_replace("/^\s*!/","",$rule['subject']);
+	                }
+	                $match = ':contains';
+	                if (preg_match("/\*|\?/", $rule['subject'])) $match = ':matches';
+	                if ($rule['regexp']) $match = ':regex';
+	                $newruletext .= "header " . $match . " \"subject\"";
+	                $newruletext .= " \"" . $rule['subject'] . "\"";
+	                $started = 1;
+	            }
+	            if ($rule['field'] && $rule['field_val']) {
+	                if ($started) $newruletext .= ", ";
+	                if (preg_match("/^\s*!/", $rule['field_val'])){
+	                    $newruletext .= 'not ';
+	                    $rule['field_val'] = preg_replace("/^\s*!/","",$rule['field_val']);
+	                }
+	                $match = ':contains';
+	                if (preg_match("/\*|\?/", $rule['field_val'])) $match = ':matches';
+	                if ($rule['regexp']) $match = ':regex';
+	                $newruletext .= "header " . $match . " \"" . $rule['field'] . "\"";
+	                $newruletext .= " \"" . $rule['field_val'] . "\"";
+	                $started = 1;
+	            }
+	            if ($rule['size']) {
+	                $xthan = " :under ";
+	                if ($rule['gthan']) $xthan = " :over ";
+	                if ($started) $newruletext .= ", ";
+	                $newruletext .= "size " . $xthan . $rule['size'] . "K";
+	                $started = 1;
+	            }
+	 
+	        }
+	 
+	        // Ações
+	        if (!$rule['unconditional']) $newruletext .= ") {\n\t";
+	
+	        if (preg_match("/folder/i",$rule['action'])) {
+	            $newruletext .= "fileinto \"" . $rule['action_arg'] . "\";";
+	        }
+	        if (preg_match("/reject/i",$rule['action'])) {
+	            $newruletext .= "reject text: \n" . $rule['action_arg'] . "\n.\n;";
+	            $rejectused = 1;
+	        }
+	        if (preg_match("/address/i",$rule['action'])) {
+	            $newruletext .= "redirect \"" . $rule['action_arg'] . "\";";
+	        }
+	        if (preg_match("/discard/i",$rule['action'])) {
+	            $newruletext .= "discard;";
+	        }
+	        if ($rule['keep']) $newruletext .= "\n\tfileinto \"INBOX\";";
+	        //if ($rule['keep']) $newruletext .= "\n\tkeep;";	        
+	        if (!$rule['unconditional']) $newruletext .= "\n}";
+	 
+	        $continue = 0;
+	        if ($rule['continue']) $continue = 1;
+	        if ($rule['unconditional']) $continue = 1;
+	 
+	        $newscriptbody .= $newruletext . "\n\n";
+	        unset($newruletext);
+	      }
+		}// Fim do Foreach;
+		
+		// Para a regras fora do escritorio;
+        unset($tmp);
+        if($this->newout != ""){
+	        $aux 					= explode("&&",$this->newout);
+	        $vacation['days'] 		= $aux[1];
+	        $vacation['addresses']	= $aux[2];	        
+	        $vacation['text']		= preg_replace("/\\\\n/","\r\n",$aux[3]);
+	        $vacation['status'] 	= $aux[4];
+	    }
+		
+		// Monta a regra para fora do escritorio;
+	    if ($vacation['status'] == 'on') {
+			$newscriptbody .= "vacation :days " . $vacation['days'] . " :addresses [";
+            $newscriptbody .= $vacation['addresses'];
+            $newscriptbody .= "] text:\n" . utf8_encode($vacation['text']) . "\n.\n;\n\n";
+	    }
+		
+		// Cria o cabeçalho do arquivo;
+		$newscripthead  = "";
+		$newscripthead .= "#Mail filter rules for " .$this->username . "\n";
+		$newscripthead .= '#Generated by ' . $this->username . ' using Expressomail ';
+		$newscripthead .= "\n";
+
+		// Continuação do cabeçalho do arquivo; 		
+	    if ($activerules) {
+	        $newscripthead .= "require [\"fileinto\"";
+	        if($regexused){
+	        	$newscripthead .= ",\"regex\"";
+	        }
+	        if($rejectused){
+	        	$newscripthead .= ",\"reject\"";
+	        }
+	        if($this->newout && $vacation['status'] == 'on'){
+	            $newscripthead .= ",\"vacation\"";
+	        }
+	        $newscripthead .= "];\n\n";
+	    }else{
+			if($vacation && $vacation['status'] == 'on'){
+			    $newscripthead .= "require [\"vacation\"];\n\n";
+			}
+	    }
+		
+		//preg_replace("/[\\n\\r]/","", $p); 		
+		
+  
+	    // Cria o rodapé do arquivo;
+	    $newscriptfoot  = "";
+	    $newscriptfoot .= "##PSEUDO script start\n";
+	    // Lê as regras;
+	    foreach($this->newrules as $tmp){
+			$newscriptfoot .= preg_replace("/[\\n\\r]/"," ",$tmp). "\n";
+	    }
+	    // Lê as regras fora do escritório;
+	    if($this->newout != ""){
+			$newscriptfoot .= preg_replace("/[\\n\\r]/"," ",$this->newout)."\n";
+	    }
+		$newscriptfoot .= "#mode&&basic\n";
+		
+		$newscript = $newscripthead . $newscriptbody . $newscriptfoot; 
+
+		// Destroi as variaveis;
+		unset($rule);
+		unset($vacation);
+		unset($activerules);
+		unset($regexused);
+		unset($rejectused);
+		unset($newscripthead);
+		unset($newscriptbody);
+    	unset($newscriptfoot);
+    	unset($continue);
+    	unset($this->newrules);
+    	unset($this->newout);
+		
+		// Retorna o script construido;
+		return $newscript;
+	
+	}// Fim da Função
+
+	// Cria o script sieve, caso nao possua;
+	function createScript(){
+		
+		// Cria o cabeçalho do arquivo;
+		$newScriptHead  = "";
+		$newScriptHead .= "#Mail filter rules for " .$this->username . "\n";
+		$newScriptHead .= '#Generated by ' . $this->username . ' using ExpressoMail ';	
+		$newScriptHead .= "\n";
+
+		//Cria o rodapé do arquivo;
+		$newScriptFoot  = "";
+		$newScriptFoot .= "##PSEUDO Script Start\n";
+		$newScriptFoot .= "#mode&&basic\n";
+		
+		//Para passar para o arquivo;
+		$newScript = $newScriptHead . $newScriptFoot;
+
+		return $newScript;
+	}
+	
+	//Lê o conteúdo do script;
+	function readScript($scriptName){
+		
+		// Verifica se a conexão foi bem sucedida;
+		if(!$scriptName){	
+			$this->errstr = "Não foi possível conectar com o Servidor";
+			return "false 2";	
+		}
+		
+		// Recebe o conteúdo do array;
+		$lines = array();
+		$lines = preg_split("/\n/",$scriptName);
+		
+		// Pega o tamanho da regra na primeira do script;
+		$size_rule = array_shift($lines);
+		
+		// Recebe o tamanho do script, pela primeira linha;
+		$this->size = trim($size_rule);
+		
+		// Verifica a composição do script;
+		$line = array_shift($lines);
+		if(!preg_match("/^# ?Mail(.*)rules for/", $line)){
+			$this->errstr = "Formato nao reconhecido";
+			return false;
+		}
+		
+		// Variaveis para a regra e o campo ferias;
+		$regexps  = array('^ *##PSEUDO','^ *#rule','^ *#vacation','^ *#mode');
+		$retorno['rule'] 	 = array();
+		$retorno['vacation'] = array();
+		$retorno['mode']	 = array();
+		
+		$line = array_shift($lines);
+		while (isset($line)){
+			foreach($regexps as $regp){
+				if(preg_match("/$regp/i",$line)){
+					// Recebe todas as regras criadas no servidor;
+					if(preg_match("/^ *#rule&&/i",$line)){
+						$retorno['rule'][] = $line . "\n";
+					}
+					if(preg_match("/^ *#vacation&&/i",$line)){
+						$retorno['vacation'][] = $line . "\n";	
+					}
+					if(preg_match("/^ *#mode&&(.*)/i",$line)){
+						$retorno['mode'][]= $line . "\n";						
+					}					
+				}
+			}
+			// Pega a proxima linha do sript;
+			$line = array_shift($lines);
+		}
+		return $retorno;	
+	}
+		
+}//Fim da Classe
+?>
Index: tags/expressoMail1_2/1.2211/inc/class.message_components.inc.php
===================================================================
--- tags/expressoMail1_2/1.2211/inc/class.message_components.inc.php	(revision 13)
+++ tags/expressoMail1_2/1.2211/inc/class.message_components.inc.php	(revision 13)
@@ -0,0 +1,289 @@
+<?php
+
+    class message_components {
+
+        /**
+         *+----------------------------------------------------------------------------------------------------+
+         *| IMAP message scanner - scans information provided by imap_fetchstructure()                         |
+         *|                                                                                                    |
+         *| Author: Richard York                                                                               |
+         *| mailto:richy at smilingsouls.net                                                                    |
+         *| http://www.smilingsouls.net                                                                        |
+         *|                                                                                                    |
+         *| (c) Copyright 2004, Richard York, All Rights Reseverd                                              |
+         *+----------------------------------------------------------------------------------------------------+
+         **
+        */
+
+        var $mailbox;           // (resource)              Imap stream
+
+        var $data_types;        // (array)(string)         Various message part types
+        var $encoding_types;    // (array)(string)         Various encoding types
+
+        // first array uses message id as key
+        // nested array is offset corresponding with the number of parts
+        
+        var $structure;         // (array)(object)         Contains the complete body structure
+        var $pid;               // (array)(array)(str)     part id
+        var $file_type;         // (array)(array)(str)     mime type
+        var $disposition;       // (array)(array)(str)     inline | attachment
+        var $fsize;             // (array)(array)(int)     part size in bytes
+        var $encoding;          // (array)(array)(str)     message encoding
+        var $charset;           // (array)(array)(int)     message charset
+        var $fname;             // (array)(array)(str)     original file name
+        var $inline_id;         // (array)(array)(str)     string containing the id for multipart/related
+        var $has_attachments;   // (array)(array)(bool)
+
+        /** 
+         * CONSTRUCTOR
+         *
+         * void message_components(resource imap stream)
+         **
+        */
+        
+        function message_components($mailbox)
+        {
+            $this->data_types = array();
+
+                $this->data_types[0] = 'text';
+                $this->data_types[1] = 'multipart';
+                $this->data_types[2] = 'message';
+                $this->data_types[3] = 'application';
+                $this->data_types[4] = 'audio';
+                $this->data_types[5] = 'image';
+                $this->data_types[6] = 'video';
+                $this->data_types[7] = 'other';
+
+            $this->encoding_types = array();
+
+                $this->encoding_types[0] = '7bit';
+                $this->encoding_types[1] = '8bit';
+                $this->encoding_types[2] = 'binary';
+                $this->encoding_types[3] = 'base64';
+                $this->encoding_types[4] = 'quoted-printable';
+                $this->encoding_types[5] = 'other';
+
+            $this->mailbox = $mailbox;
+
+            return;
+        }
+        
+        /**
+         * void fetch_structure(int message id[, array recursive subpart[, array recursive parent part id[, int recursive counter[, bool recursive is a sub part[, bool recursive skip part]]]]])
+         * Indexes the structure of a message body.
+         * 
+         * Gather message information returned by imap_fetchstructure()
+         * Recursively iterate through each parts array
+         * Concatenate part numbers in the following format `1.1` each part id is separated by a period, each referring 
+         * to a part or subpart of a multipart message.  Create part numbers as such that they are compatible with imap_fetchbody()
+         **
+        */
+
+        function fetch_structure($mid, $sub_part = null, $sub_pid = null, $n = 0, $is_sub_part = false, $skip_part = false)
+        {
+            if (!is_array($sub_part))
+            {
+                $this->structure[$mid] = imap_fetchstructure($this->mailbox, $mid, FT_UID);
+            }
+            if (isset($this->structure[$mid]->parts) || is_array($sub_part))
+            {
+                if ($is_sub_part == false)
+                {
+                    $parts = $this->structure[$mid]->parts;
+                }
+                else
+                {
+                    $parts = $sub_part;
+                    $n++;
+                }
+
+                for($p = 0, $i = 1; $p < count($parts); $n++, $p++, $i++)
+                {
+                    // Skip the following...
+                    // Skip multipart/mixed!
+                    // Skip subsequent multipart/alternative if this part is message/rfc822
+                    // Skip multipart/related
+
+                    $ftype        = (empty($parts[$p]->type))?           $this->data_types[0].'/'.strtolower($parts[$p]->subtype) : $this->data_types[$parts[$p]->type].'/'.strtolower($parts[$p]->subtype);
+                    $encoding     = (empty($parts[$p]->encoding))?       $this->encoding_types[0] : $this->encoding_types[$parts[$p]->encoding];
+                    if(!preg_match("/5./",phpversion()))
+	                    $charset      = $parts[$p]->parameters[0]->value;                    
+                    else
+                    	$charset      = $parts->p->parameters[0]->value;
+                    $skip_next    = ($ftype == 'message/rfc822')?        true : false;
+
+                    if ($ftype == 'multipart/mixed' || $skip_part == true && $ftype == 'multipart/alternative')      				
+                    //	Por niltonneto: Mensagens do ThunderBird com format=flowed nao abrem, por isso comentado essa condicao:
+                    // 	|| $ftype == 'multipart/related')                    
+                    {
+                        $n--;
+                    }
+
+                    else
+                    {
+                        $this->pid[$mid][$n]       = ($is_sub_part == false)? $i : $sub_pid.'.'.$i;
+                        $this->file_type[$mid][$n] = $ftype;
+                        $this->encoding[$mid][$n]  = $encoding;
+						$this->charset[$mid][$n]   = $charset;
+                        $this->fsize[$mid][$n]     = (!isset($parts[$p]->bytes) || empty($parts[$p]->bytes))? 0 : $parts[$p]->bytes;
+						$hasAttachment = false;
+                        # Force inline disposition if none is present
+                        //if ($parts[$p]->ifdisposition == true)
+                        //{ por niltonneto, as vezes, inline anexos nao eram exibidos.
+                            $this->disposition[$mid][$n] = strtolower($parts[$p]->disposition);
+
+                            //if (strtolower($parts[$p]->disposition) == 'attachment')
+                            //{ por jakjr, as vezes, inline anexos nao eram exibidos.
+                                if ($parts[$p]->ifdparameters == true)
+                                {
+                                    $params = $parts[$p]->dparameters;
+
+                                    foreach ($params as $param)
+                                    {
+                                        if((strtolower($param->attribute) == 'filename') || (strtolower($param->attribute) == 'name'))
+                                        {
+                                            $this->fname[$mid][$n] = $param->value;
+                                            $hasAttachment = true;
+                                            break;
+                                        }                                        
+                                    }
+                                }
+                                
+                                // Alguns web-mails utilizam o parameters
+                                if ($parts[$p]->ifparameters == true && !$hasAttachment)
+                                {
+                                    $params = $parts[$p]->parameters;
+                                    foreach ($params as $param)
+                                    {
+                                        if((strtolower($param->attribute) == 'filename') || (strtolower($param->attribute) == 'name'
+                                         || strtolower($param->attribute) == 'filename*') || strtolower($param->attribute) == 'name*')
+                                        {
+                                        	if(strstr(strtolower($param->value), "iso-8859-1''")){
+                                        		
+                                        		$value = explode("''",$param->value);
+                                        		$this->fname[$mid][$n] = rawurldecode($value[1]);
+                                        	}
+                                        	else
+                                            	$this->fname[$mid][$n] = $param->value;
+                                            	
+                                            break;
+                                        }
+                                        if(strtolower($param->attribute) == 'charset'){
+                                         	if($this->charset[$mid][$n] == '')
+                                         		$this->charset[$mid][$n] = $param->value;                                         	
+                                        }
+                                    }
+								}
+                            //}
+                        /*}
+                        else
+                        {
+                            $this->disposition[$mid][$n] = 'inline';
+                        }*/
+
+                        if ($parts[$p]->ifid == true)
+                        {
+                            $this->inline_id[$mid][$n] = $parts[$p]->id;
+                        }
+                    }
+
+                    if (isset($parts[$p]->parts) && is_array($parts[$p]->parts))
+                    {
+                        $this->has_attachments[$mid][$n] = true;
+                        $n = $this->fetch_structure($mid, $parts[$p]->parts, $this->pid[$mid][$n], $n, true, $skip_next);
+                    }
+                    else
+                    {
+                        $this->has_attachments[$mid][$n] = false;
+                    }
+                }
+
+                if ($is_sub_part == true)
+                {
+                    return $n;
+                }
+            }
+
+            // $parts is not an array... message is flat
+            else
+            {
+                $this->pid[$mid][0] = 1;
+
+                if (empty($this->structure[$mid]->type)) 
+                {
+                    $this->structure[$mid]->type        = (int) 0;
+                }
+                
+                if (isset($this->structure[$mid]->subtype))
+                {
+                    $this->file_type[$mid][0]            = $this->data_types[$this->structure[$mid]->type].'/'.strtolower($this->structure[$mid]->subtype);
+                }
+            
+                if (empty($this->structure[$mid]->encoding))
+                {
+                    $this->structure[$mid]->encoding    = (int) 0;
+                }
+                
+                $this->encoding[$mid][0]              = $this->encoding_types[$this->structure[$mid]->encoding];
+                if(!preg_match("/5./",phpversion()))
+					$this->charset[$mid][0] = $this->structure[$mid]->parameters[0]->value;
+				else
+					$this->charset[$mid][0] = $this->structure->mid->parameters[0]->value;
+
+                if (isset($this->structure[$mid]->bytes))
+                {
+                    $this->fsize[$mid][0]                = strtolower($this->structure[$mid]->bytes);
+                }
+                
+				if (isset($this->structure[$mid]->ifdparameters))
+				{
+					$params = $this->structure[$mid]->dparameters;
+					$n = 0;
+					if($params)
+					foreach ($params as $param)
+					{
+						if((strtolower($param->attribute) == 'filename') || (strtolower($param->attribute) == 'name'))
+						{
+							$this->fname[$mid][$n] = $param->value;
+							break;
+						}
+						$n++;
+					}
+				}
+				if (isset($this->structure[$mid]->ifparameters))
+				{
+					$params = $this->structure[$mid]->parameters;
+					$n = 0;
+					if($params)
+					foreach ($params as $param)
+					{
+						if(strtolower($param->attribute) == 'charset'){
+                        	if($this->charset[$mid][$n] == '')
+                            	$this->charset[$mid][$n] = $param->value;
+                        }
+						$n++;
+					}
+				}
+				$this->disposition[$mid][0] = $this->structure[$mid]->disposition;
+                //$this->disposition[$mid][0] = 'inline';
+            }
+
+            return;
+        }		
+    }
+    
+/*
+    // Example usage -- dump part ids for the specified message..
+
+    $msg =& new message_components($mb);
+    $msg->fetch_structure(12905);
+
+    echo '<pre>';    
+    //print_r($msg->pid[12905]);
+    echo count ($msg->fname[12905]);
+    echo '</pre>';
+
+    // also important to note that the offset numbering in the sub array isn't precise... $msg->pid[$mid][0]..
+    // I have a bug somewhere in there.. but I use foreach when accessing these arrays anyway.
+*/
+?>
Index: tags/expressoMail1_2/1.2211/inc/class.SieveS.inc.php
===================================================================
--- tags/expressoMail1_2/1.2211/inc/class.SieveS.inc.php	(revision 2)
+++ tags/expressoMail1_2/1.2211/inc/class.SieveS.inc.php	(revision 2)
@@ -0,0 +1,329 @@
+<?php
+//Conecta com o Servidor e o serviço Sieve;
+class SieveS{
+		
+	var $host;
+	var $port;
+	var $user;
+	var $pass;
+	var $proxy;
+	
+	var $implementation;
+	var $saslmethods;
+	var $extensions;
+	var $starttls_avail;
+	var $socket;
+	var $socket_timeout;
+	
+	var $scriptlist;
+	var $activescript;
+	var $errstr;
+	var $errnum;
+	var $ScriptS;
+	
+	function SieveS(){
+		
+		$this->host = $_SESSION['phpgw_info']['expressomail']['email_server']['imapSieveServer'];
+		$this->port = $_SESSION['phpgw_info']['expressomail']['email_server']['imapSievePort'];
+		$this->user = $_SESSION['phpgw_info']['expressomail']['user']['account_lid'];	
+		$this->pass = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
+		$this->proxy = '';
+		
+		$this->socket_timeout = 5;
+		$this->implementation = array('unknown');
+		$this->saslmethods 	  = array('unknown');
+		$this->extensions 	  = array('unknown');
+		$this->starttls_avail = false;
+		$this->scriptlist     = array();
+		$this->activescript   = '';
+		$this->errstr 		  = '';
+		$this->errnum 		  = ''; 
+		
+	}	
+	
+	function start(){
+		// Cria a conexao;
+		if(!isset($this->socket)){
+			$this->socket = fsockopen($this->host, $this->port, $this->errnum, $this->errstr, "60");
+
+		}
+		// Verifica a conexao;
+		if(!$this->socket){
+			return "não conectado";
+		}
+		
+		$said = $this->read();
+		if (!preg_match("/timsieved/i",$said)) {
+		    $this->close();
+		    $this->errstr = "start: bad response from $this->host: $said";
+		    return false;
+		}
+		
+		if (preg_match("/IMPLEMENTATION/",$said)){
+		  while (!preg_match("/^OK/",$said)) {
+		    if (preg_match("/^\"IMPLEMENTATION\" +\"(.*)\"/",$said,$bits)){
+				$this->implementation = $bits[1];
+		    }
+		    elseif (preg_match("/^\"SASL\" +\"(.*)\"/",$said,$bits)) {
+				$auth_types = $bits[1];
+				$this->saslmethods = split(" ", $auth_types);
+		    }
+		    elseif (preg_match("/^\"SIEVE\" +\"(.*)\"/",$said,$bits)) {
+				$extensions = $bits[1];
+				$this->extensions = split(" ", $extensions);
+		    }
+	        elseif (preg_match("/^\"STARTTLS\"/",$said)){
+	           $this->starttls_avail = true;
+	        }
+		    $said = $this->read();
+		  }
+		}
+		else
+		{
+		    // assume cyrus v1.
+		    if (preg_match("/\"(.+)\" +\"(.+)\"/",$said,$bits)) {
+				$this->implementation = $bits[1];
+				$sasl_str = $bits[2];  // should look like: SASL={PLAIN,...}
+		    }
+			if (preg_match("/SASL=\{(.+)\}/",$sasl_str,$morebits)) {
+			    $auth_types = $morebits[1];
+			    $this->saslmethods = split(", ", $auth_types);
+			}else {
+				// a bit desperate if we get here.
+				$this->implementation = $said;
+				$this->saslmethods = $said;
+		    }
+		}
+		
+		$authstr = $this->proxy . "\x00" . $this->user . "\x00" . $this->pass;
+		$encoded = base64_encode($authstr);		
+		$len = strlen($encoded);
+
+		//fputs($this->socket,"AUTHENTICATE \"PLAIN\" \{$len+}\r\n");
+		//fputs($this->socket,"$encoded\r\n");
+
+		fwrite($this->socket, 'AUTHENTICATE "PLAIN" {' . $len . '+}' . "\r\n");
+		fwrite($this->socket,"$encoded\r\n");
+		
+		$said = $this->read();
+	
+		if (preg_match("/NO/",$said)) {
+		    $this->close();
+		    $this->errstr = "start: authentication failure connecting to $this->host";
+		    return false;
+		}
+		elseif (!preg_match("/OK/",$said)) {
+		    $this->close();
+		    $this->errstr = "start: bad authentication response from $this->host: $said";
+		    return false;
+		}
+	
+		return true;
+		
+	}
+	
+	function close(){
+	
+		if(!$this->socket){
+			return true;	
+		}	
+		fputs($this->socket,"LOGOUT\r\n");
+		$rc = fclose($this->socket);
+		if($rc != 1){
+			$this->errstr = "close: failed closing socket to $this->server";
+			return false;
+		}
+		return true;
+	}
+	
+	function read(){
+	
+		$buffer = '';
+		
+		// Verifca a conexao;
+		if(!$this->socket){
+			return $buffer;
+		}
+		
+		//Funções do php
+		socket_set_timeout($this->socket,$this->socket_timeout);
+		socket_set_blocking($this->socket,true);
+		
+		//Lê um caracter de cada vez e o adiciona na variavel buffer;
+		while(!feof($this->socket)){
+			$char = fread($this->socket,1);
+			
+			$status = socket_get_status($this->socket);
+			if($status['timed_out'])
+				return $buffer;
+			
+			if(($char == "\n") || ($char == "\r")){
+				if($char == "\r")
+					fread($this->socket,1);
+				return $buffer;
+			}
+			$buffer .= $char;
+		}
+		return $buffer;
+	}
+/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+// Manipulação dos scripts
+/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+		
+	function listscripts(){
+		
+		$bits = '';
+
+		//Verifica a conexao
+		if(!$this->socket){
+			$this->errstr = "listscripts: sem conexão para o servidor $this->host";
+			return false;
+		}
+
+		$scripts = array();
+		fputs($this->socket,"LISTSCRIPTS\r\n");
+	
+		$said = $this->read();
+		while (!preg_match("/^OK/",$said) && !preg_match("/^NO/",$said)) {
+	
+		    // Cyrus v1 script lines look like '"script*"' with the 
+		    // asterisk denoting the active script. Cyrus v2 script 
+		    // lines will look like '"script" ACTIVE' if active.
+	
+		    if (preg_match("/^\"(.+)\"\s*(.+)*$/m",$said,$bits)) {
+			if (preg_match("/\*$/",$bits[1])){
+			    $bits[1] = preg_replace("/\*$/","",$bits[1]);
+			    $this->activescript = $bits[1];
+			}
+			if (isset($bits[2]) && $bits[2] == 'ACTIVE')
+			    $this->activescript = $bits[1];
+			array_push($scripts,$bits[1]);
+		    }
+		    $said = $this->read();
+		}
+	
+		if (preg_match("/^OK/",$said)) {
+		    $this->scriptlist = $scripts;
+            return $this->scriptlist;
+        }
+		
+	}
+	
+	// Pega o conteudo do script no servidor	
+	function getscript(){
+
+		$scriptfile = $this->listscripts();
+		
+		// verifica se existe o script;
+		if($scriptfile == ""){
+			return "Falta o script";
+		}
+		
+		if(!$this->socket){
+			return "Falha na conexao";	
+		}
+		
+		$script = '';
+		
+		fputs($this->socket,"GETSCRIPT \"$scriptfile[0]\"\r\n");
+		$said = $this->read();
+		while ((!preg_match("/^OK/",$said)) && (!preg_match("/^NO/",$said))) {
+		    // replace newlines which read() removed
+		    if (!preg_match("/\n$/",$said)) $said .= "\n";
+		    $script .= $said;
+		    $said = $this->read();
+		}
+		
+		if($said == "OK"){
+			return $script;	
+		}else{
+			return false;
+		}
+	}
+
+	//envia para o servidor o nome do script($scriptfile) e seu conteudo($script)
+	function putscript ($scriptfile,$script) {
+		if (!isset($scriptfile)) {
+	            $this->errstr = "Não foi possível enviar o script para o servidor";
+	            return false;
+	    }
+		if (!isset($script)) {
+	            $this->errstr = "Não foi possível enviar o script para o servidor";
+	            return false;
+	    }
+		if (!$this->socket) {
+	            $this->errstr = "Sem conexão com o servidor $this->server";
+	            return false;
+	    }
+	
+		$len = strlen($script);
+
+		//fputs($this->socket,"PUTSCRIPT \"$scriptfile\" \{$len+}\r\n");
+		//fputs($this->socket,"$script\r\n");
+	
+		fwrite($this->socket, 'PUTSCRIPT "'.$scriptfile.'" {' . $len . '+}' . "\r\n");	
+		fwrite($this->socket,"$script\r\n");
+	
+		$said = '';
+		while ($said == '') {
+		    $said = $this->read();
+		}
+	 
+	    if (preg_match("/^OK/",$said)) {
+		    return true;
+		}
+	
+	    $this->errstr = "Não foi possível enviar o $scriptfile: $said";
+	    return false;
+    }
+    
+    // Ativa o script para o servico sieve;
+    function activatescript ($scriptfile) {
+		if (!isset($scriptfile)) {
+	            $this->errstr = "activatescript: no script file specified";
+	            return false;
+	    }
+	
+	    if (!$this->socket) {
+	            $this->errstr = "activatescript: no connection open to $this->server";
+	            return false;
+	    }
+	
+		fputs($this->socket,"SETACTIVE \"$scriptfile\"\r\n");
+	
+		$said = $this->read();
+	
+		if (preg_match("/^OK/",$said)) {
+	            return true;
+	    }
+	
+		$this->errstr = "activatescript: could not activate script $scriptfile: $said";
+	    return false;
+    }
+
+    // Deleta o script do serviço sieve;
+    function deletescript ($scriptName) {
+    	if(!isset($scriptName)){
+    		$this->errstr = "deletescript: no script file specified";
+    		return false;
+    	}
+    	
+    	// Verifica a conexão;
+    	if(!$this->socket){
+    		$this->errstr = "deletescript : no connection open to $this->server";
+    		return false;
+    	}
+    
+    	fputs($this->socket,"DELETESCRIPT \"$scriptName\"\r\n");
+    	
+    	$said = $this->read();
+    	
+    	if(preg_match("/^OK/",$said)) {
+    		return true;	
+    	}
+    	
+    	$this->errstr = "deletescript: could not delete script $scriptName: $said";
+    	return false;
+    }
+}
+?>
Index: tags/expressoMail1_2/1.2211/inc/class.imap_attachment.inc.php
===================================================================
--- tags/expressoMail1_2/1.2211/inc/class.imap_attachment.inc.php	(revision 271)
+++ tags/expressoMail1_2/1.2211/inc/class.imap_attachment.inc.php	(revision 271)
@@ -0,0 +1,89 @@
+<?php			
+class imap_attachment
+{
+	function get_attachment_info($mbox_stream, $msg_number) 
+	{	
+		$structure = imap_fetchstructure($mbox_stream,$msg_number,FT_UID);
+		$contentParts = count($structure->parts);
+	
+		$msg_info['number_attachments'] = $contentParts -1;
+	
+		if($contentParts > 1)
+		{
+	 		for($i=1; $i<$contentParts; $i++)
+			{
+				$msg_info['attachment'][$i]['part_in_msg']	= ($i+1);
+				$msg_info['attachment'][$i]['name']				= urlencode($structure->parts[$i]->dparameters[0]->value);
+				$msg_info['attachment'][$i]['type']				= $structure->parts[$i]->subtype;
+				$msg_info['attachment'][$i]['bytes']			= $structure->parts[$i]->bytes;
+   			}
+  		}
+  		return $msg_info;
+	}
+
+	function get_attachment_headerinfo($mbox, $msgno)
+	{
+		include_once("class.message_components.inc.php");
+
+		$msg =& new message_components($mbox);
+		$msg->fetch_structure($msgno);
+
+		$msg_info = array();
+		$msg_info['names'] = '';
+
+		$msg_info['number_attachments'] = count($msg->fname[$msgno]);
+		
+		if ($msg_info['number_attachments'])
+		{
+			foreach ($msg->fname[$msgno] as $fname)
+			{
+				$msg_info['names'] .= $this->flat_mime_decode($fname) . ', ';
+   			}
+		}
+		$msg_info['names'] = substr($msg_info['names'],0,(strlen($msg_info['names']) - 2));
+		
+		return $msg_info;
+	}
+	
+	function download_attachment($mbox, $msgno)
+	{
+		include_once("class.message_components.inc.php");
+
+		$msg =& new message_components($mbox);
+		$msg->fetch_structure($msgno);
+		$array_parts_attachments = array();		
+		$array_parts_attachments['names'] = '';
+		
+		//print_r($msg->fname[$msgno]);
+		
+		if (count($msg->fname[$msgno]) > 0)
+		{
+			$i = 0;
+			foreach ($msg->fname[$msgno] as $index=>$fname)
+			{
+				$array_parts_attachments[$i]['pid'] = $msg->pid[$msgno][$index];
+				$array_parts_attachments[$i]['name'] = $this->decode_mimeheader($fname);
+				//$array_parts_attachments[$i]['name'] = $this->flat_mime_decode($fname);
+				$array_parts_attachments[$i]['name'] = $array_parts_attachments[$i]['name'] ? $array_parts_attachments[$i]['name'] : "attachment.bin";
+				$array_parts_attachments[$i]['encoding'] = $msg->encoding[$msgno][$index];
+				$array_parts_attachments['names'] .= $array_parts_attachments[$i]['name'] . ', ';
+				$array_parts_attachments[$i]['fsize'] = $msg->fsize[$msgno][$index];
+				$i++;
+			}
+		}
+		$array_parts_attachments['names'] = substr($array_parts_attachments['names'],0,(strlen($array_parts_attachments['names']) - 2));
+		return $array_parts_attachments;
+	}
+	
+	function decode_mimeheader($string) {
+        return mb_decode_mimeheader($string);
+    }
+	function flat_mime_decode($string) {
+	   	$array = imap_mime_header_decode($string);
+	   	$str = "";
+	   	foreach ($array as $key => $part)
+	   		$str .= @eregi_replace("\{", "[",@eregi_replace("\}", "]",$part->text));
+	   	
+   		return $str;
+	}
+}
Index: tags/expressoMail1_2/1.2211/inc/show_img.php
===================================================================
--- tags/expressoMail1_2/1.2211/inc/show_img.php	(revision 178)
+++ tags/expressoMail1_2/1.2211/inc/show_img.php	(revision 178)
@@ -0,0 +1,50 @@
+<?php	
+	header("Content-Type: image/jpeg");
+	if($_GET['msg_num'] && $_GET['msg_part'] && $_GET['msg_folder']) {
+		$username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
+		$password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
+		$imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
+		$imap_port 	= $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
+	if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
+	{
+		$imap_options = '/tls/novalidate-cert';
+	}
+	else
+	{
+		$imap_options = '/notls/novalidate-cert';
+	}
+		
+		$msg_num = $_GET['msg_num'];
+		$msg_part = $_GET['msg_part'];
+		$msg_folder = $_GET['msg_folder'];
+		$msg_folder = mb_convert_encoding($msg_folder,"UTF7-IMAP", mb_detect_encoding($msg_folder, "UTF-8, ISO-8859-1", true));
+		
+	$mb = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$msg_folder, $username, $password);
+		
+		$image_mail = imap_fetchbody($mb, $msg_num, $msg_part, FT_UID);	
+
+		header("Content-Disposition: inline");
+		$image = imap_base64($image_mail);
+		echo $image;		
+	}
+	else if($_SESSION['phpgw_info']['expressomail']['contact_photo']){	
+		$data  = $_SESSION['phpgw_info']['expressomail']['contact_photo'];
+				
+		if($data) {
+			
+			$photo = imagecreatefromstring($data[0]);
+			if($photo){
+				$width = imagesx($photo);
+				$height = imagesy($photo);
+				$twidth = 60;
+				$theight = 80;
+				$small_photo = imagecreatetruecolor ($twidth, $theight);
+				imagecopyresampled($small_photo, $photo, 0, 0, 0, 0,$twidth, $theight, $width, $height);
+				imagejpeg($small_photo,'',100);
+				unset($_SESSION['phpgw_info']['expressomail']['contact_photo']);
+			}
+		}
+	}
+	else
+		readfile("./../../contactcenter/templates/default/images/photo_celepar.png");
+?>
Index: tags/expressoMail1_2/1.2211/inc/show_embedded_attach.php
===================================================================
--- tags/expressoMail1_2/1.2211/inc/show_embedded_attach.php	(revision 205)
+++ tags/expressoMail1_2/1.2211/inc/show_embedded_attach.php	(revision 205)
@@ -0,0 +1,33 @@
+<?php
+	$username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
+	$password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
+	$imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
+	$imap_port 	= $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
+	$msg_folder = $_GET['msg_folder'];
+	$msg_folder = mb_convert_encoding($msg_folder,"UTF7-IMAP", mb_detect_encoding($msg_folder, "UTF-8, ISO-8859-1", true));
+	if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
+	{
+		$imap_options = '/tls/novalidate-cert';
+	}
+	else
+	{
+		$imap_options = '/notls/novalidate-cert';
+	}
+	
+	if (is_array($_SESSION['phpgw_info']['expressomail']['email_server']))
+	{
+		$mb = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$msg_folder, $username, $password);
+	
+		if ($mb)
+		{
+			$msgno = $_GET['msg_num'];
+			$embedded_part = $_GET['msg_part'];
+	
+			$embedded_body = imap_fetchbody($mb, $msgno, $embedded_part, FT_UID);
+	
+			header("Content-Type: image/jpeg");
+			header("Content-Disposition: inline");
+			echo imap_base64($embedded_body);
+		}
+	}
+?>
Index: tags/expressoMail1_2/1.2211/inc/hook_admin.inc.php
===================================================================
--- tags/expressoMail1_2/1.2211/inc/hook_admin.inc.php	(revision 69)
+++ tags/expressoMail1_2/1.2211/inc/hook_admin.inc.php	(revision 69)
@@ -0,0 +1,22 @@
+<?php
+	/**************************************************************************\
+	* eGroupWare                                                               *
+	* http://www.egroupware.org                                                *
+	* Written by Joseph Engo <jengo@phpgroupware.org>                          *
+	* --------------------------------------------                             *
+	*  This program is free software; you can redistribute it and/or modify it *
+	*  under the terms of the GNU General Public License as published by the   *
+	*  Free Software Foundation; either version 2 of the License, or (at your  *
+	*  option) any later version.                                              *
+	\**************************************************************************/
+
+{
+// Only Modify the $file and $title variables.....
+	$title = $appname;
+	$file = Array(
+		'Site Configuration' => $GLOBALS['phpgw']->link('/index.php','menuaction=admin.uiconfig.index&appname=' . $appname),
+	);
+//Do not modify below this line
+	display_section($appname,$title,$file);
+}
+?>
Index: tags/expressoMail1_2/1.2211/inc/hook_home.inc.php
===================================================================
--- tags/expressoMail1_2/1.2211/inc/hook_home.inc.php	(revision 139)
+++ tags/expressoMail1_2/1.2211/inc/hook_home.inc.php	(revision 139)
@@ -0,0 +1,94 @@
+<?php
+	
+	$current_app = 'expressoMail1_2';
+	$current_name	 = 'ExpressoMail 1.2';
+  	$homedisplay = $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['mainscreen_showmail'];
+  	$homedisplay = 'True';
+	if($homedisplay=='True')
+	{
+		$homedisplay = 1;
+	}	
+	$homedisplay = intval($homedisplay);
+	
+	$prev_currentapp = $GLOBALS['phpgw_info']['flags']['currentapp'];
+	$GLOBALS['phpgw_info']['flags']['currentapp'] = $current_app;
+	 
+	if(intval($homedisplay))
+	{
+		$boemailadmin	= CreateObject('emailadmin.bo');
+		$emailadmin_profile = $boemailadmin->getProfileList();
+		$_SESSION['phpgw_info']['expressomail']['email_server'] = $boemailadmin->getProfile($emailadmin_profile[0]['profileID']);
+		$_SESSION['phpgw_info']['expressomail']['user'] = $GLOBALS['phpgw_info']['user'];
+		$_SESSION['phpgw_info']['expressomail']['server'] = $GLOBALS['phpgw_info']['server'];
+		$expressoMail	= CreateObject($current_app.'.imap_functions');
+		$mbox_stream = $expressoMail-> open_mbox(); 		
+		$messages	 = imap_sort($mbox_stream, SORTARRIVAL, true, SE_UID);
+		$num_new_messages = 0;
+		$subjects = array();
+		
+		for ($i = 0; $i < count($messages);$i++)
+		{
+			$msg_number = $messages[$i];
+			$header = @imap_headerinfo($mbox_stream, imap_msgno($mbox_stream, $msg_number), 80, 255);
+			if (!is_object($header))
+				return false;			
+
+			if($header->Recent != 'N' && $header->Unseen != 'U')
+				continue;
+			$new_m++;
+			if($new_m <= 10) { 				
+				$date_msg = date("d/m/Y",$header->udate);
+				if (date("d/m/Y") == $date_msg)
+					$date = date("H:i",$header->udate);
+				else
+					$date = $date_msg;
+				$subject = $expressoMail->decode_string($header->fetchsubject);				
+				$text = "<div style='overflow:hidden;white-space:nowrap'>".$date." .: ".$subject."</div>";
+				if(strlen($text) > 105)
+					$text = substr($text,0,105).' ...';
+			
+				$link_msg = $GLOBALS['phpgw']->link(
+						'/'.$current_app.'/index.php',
+						'msgball[msgnum]='.$msg_number.'&msgball[folder]=INBOX');
+				$data[] = array('text' => $text, 'link' => $link_msg);		
+			}			
+		}
+				
+		imap_close($mbox_stream);
+				
+		$title = $current_name." - ".($new_m > 1 ? lang("You have %1 new messages!","<font color=red>".$new_m."</font>") : ($new_m == 1 ? str_replace("1","<font color=red>1</font>",lang("you have 1 new message!")) : lang("you have no new messages")));			
+		$GLOBALS['phpgw']->translation->add_app($current_app);
+
+		if ((isset($prev_currentapp)) && ($prev_currentapp)	&& ($GLOBALS['phpgw_info']['flags']['currentapp'] != $prev_currentapp))		
+			$GLOBALS['phpgw_info']['flags']['currentapp'] = $prev_currentapp;
+		
+		$portalbox = CreateObject('phpgwapi.listbox',
+			Array(
+				'title'     => $title,
+				'primary'   => $GLOBALS['phpgw_info']['theme']['navbar_bg'],
+				'secondary' => $GLOBALS['phpgw_info']['theme']['navbar_bg'],
+				'tertiary'  => $GLOBALS['phpgw_info']['theme']['navbar_bg'],
+				'width'     => '100%',
+				'outerborderwidth' => '0',
+				'header_background_image' => $GLOBALS['phpgw']->common->image('phpgwapi/templates/phpgw_website','bg_filler')
+			)
+		);
+
+		$app_id = $GLOBALS['phpgw']->applications->name2id('expressoMail');
+		$GLOBALS['portal_order'][] = $app_id;
+
+		$var = Array(
+			'up'       => Array('url' => '/set_box.php', 'app' => $app_id),
+			'down'     => Array('url' => '/set_box.php', 'app' => $app_id),
+			'close'    => Array('url' => '/set_box.php', 'app' => $app_id),
+			'question' => Array('url' => '/set_box.php', 'app' => $app_id),
+			'edit'     => Array('url' => '/set_box.php', 'app' => $app_id)
+		);
+
+		while(list($key,$value) = each($var))		
+			$portalbox->set_controls($key,$value);
+
+		$portalbox->data = $data;
+					
+		echo "\n".'<!-- BEGIN Mailbox info -->'."\n".$portalbox->draw($extra_data).'<!-- END Mailbox info -->'."\n";
+	}
Index: tags/expressoMail1_2/1.2211/inc/load_lang.php
===================================================================
--- tags/expressoMail1_2/1.2211/inc/load_lang.php	(revision 2)
+++ tags/expressoMail1_2/1.2211/inc/load_lang.php	(revision 2)
@@ -0,0 +1,25 @@
+<?
+// Load the lang of the module.
+	if(!$_SESSION['phpgw_info']['expressomail']['lang']) 
+	{
+		$array_keys = array();
+		$fn = '../setup/phpgw_'.$_SESSION['phpgw_info']['expressomail']['user']['preferences']['common']['lang'].'.lang';			
+		if (file_exists($fn)){
+			$fp = fopen($fn,'r');
+			while ($data = fgets($fp,16000))	{
+				list($message_id,$app_name,$null,$content) = explode("\t",substr($data,0,-1));			
+				$_SESSION['phpgw_info']['expressomail']['lang'][$message_id] =  $content;
+			}
+			fclose($fp);
+		}
+	}
+	$script  = "array_lang[0] = new Array();";
+	$script .= "array_lang[1] = new Array();";		
+	$i = 0;
+	foreach($_SESSION['phpgw_info']['expressomail']['lang'] as $key => $value) {		
+		$script .= "array_lang[0][".$i."] = '".str_replace("'","\'",strtolower($key))."';";		
+		$script .= "array_lang[1][".$i."] = '".str_replace("'","\'",$value)."';";
+		$i++;					
+	}
+	echo $script;
+?>
Index: tags/expressoMail1_2/1.2211/inc/class.ldap_functions.inc.php
===================================================================
--- tags/expressoMail1_2/1.2211/inc/class.ldap_functions.inc.php	(revision 271)
+++ tags/expressoMail1_2/1.2211/inc/class.ldap_functions.inc.php	(revision 271)
@@ -0,0 +1,564 @@
+<?php			
+include_once("class.imap_functions.inc.php");
+
+function ldapRebind($ldap_connection, $ldap_url)
+{
+	@ldap_bind($ldap_connection, $_SESSION['phpgw_info']['expressomail']['ldap_server']['acc'],$_SESSION['phpgw_info']['expressomail']['ldap_server']['pw']);
+}
+			
+class ldap_functions
+{
+	var $ds;
+	var $ldap_host;
+	var $ldap_context;
+	var $imap;
+	
+	// usa o host e context do contact center.
+	function ldapConnect($refer = false){
+		$this->ldap_host 	= $_SESSION['phpgw_info']['expressomail']['ldap_server']['host'];
+		$this->ldap_context = $_SESSION['phpgw_info']['expressomail']['ldap_server']['dn'];
+		$this->ds 			= ldap_connect($this->ldap_host);
+		ldap_set_option($this->ds, LDAP_OPT_PROTOCOL_VERSION, 3);
+		ldap_set_option($this->ds, LDAP_OPT_REFERRALS, $refer);
+		if ($refer)
+		{
+			ldap_set_rebind_proc($this->ds, ldapRebind);
+		}
+		@ldap_bind($this->ds, $_SESSION['phpgw_info']['expressomail']['ldap_server']['acc'],$_SESSION['phpgw_info']['expressomail']['ldap_server']['pw']);				
+	}
+
+	//Teste jakjr retornando o DS
+	function ldapConnect2($refer = false){
+		$ds = ldap_connect($_SESSION['phpgw_info']['expressomail']['ldap_server']['host']);
+		
+		if (!$ds)
+			return false;
+		
+		ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
+		ldap_set_option($ds, LDAP_OPT_REFERRALS, $refer);
+		if ($refer)
+			ldap_set_rebind_proc($ds, ldapRebind);
+		@ldap_bind($ds, $_SESSION['phpgw_info']['expressomail']['ldap_server']['acc'],$_SESSION['phpgw_info']['expressomail']['ldap_server']['pw']);
+		
+		return $ds;				
+	}
+
+
+	// usa o host e context do setup.
+	function ldapRootConnect($refer = false){
+		$this->ldap_host 	= $_SESSION['phpgw_info']['expressomail']['server']['ldap_host'];
+		$this->ldap_context = $_SESSION['phpgw_info']['expressomail']['server']['ldap_context'];
+		$this->ds 			= ldap_connect($this->ldap_host);
+		ldap_set_option($this->ds, LDAP_OPT_PROTOCOL_VERSION, 3);
+		ldap_set_option($this->ds, LDAP_OPT_REFERRALS, $refer);
+		ldap_bind($this->ds, $_SESSION['phpgw_info']['expressomail']['server']['ldap_root_dn'],$_SESSION['phpgw_info']['expressomail']['server']['ldap_root_pw']);				
+
+	}
+
+	function quicksearch($params)
+	{	
+		include_once("class.functions.inc.php");
+		$functions = new functions;						
+
+		$search_for	= $params['search_for'];
+		$field		= $params['field'];
+		$ID			= $params['ID'];
+		
+		$contacts_result = array();
+		$contacts_result['field'] = $field;
+		$contacts_result['ID'] = $ID;
+		
+		// follow the referral
+		$this->ldapConnect(true);
+		
+		if ($this->ds)
+		{
+			if (($field != 'null') && ($ID != 'null'))
+			{
+				$filter="(& (|(phpgwAccountType=u)(phpgwAccountType=l)) (|(cn=*$search_for*)(mail=$search_for*)) (!(phpgwaccountvisible=-1)) )";
+				$justthese = array("cn", "mail", "telephoneNumber", "mobile", "phpgwAccountVisible", "uid");
+			}
+			else
+			{
+				$filter="(& (phpgwAccountType=u)(cn=*$search_for*) (!(phpgwaccountvisible=-1)) )";
+				$justthese = array("cn", "mail", "telephoneNumber", "mobile", "phpgwAccountVisible", "jpegPhoto", "uid");
+			}
+			
+			$sr=ldap_search($this->ds, $this->ldap_context, $filter, $justthese);
+			$count_entries = ldap_count_entries($this->ds,$sr);
+
+			// Get user org dn.			
+			$user_dn = $_SESSION['phpgw_info']['expressomail']['user']['account_dn'];
+			$user_sector_dn = ldap_explode_dn ( $user_dn, false );
+			array_shift($user_sector_dn);
+			array_shift($user_sector_dn);
+			$user_sector_dn = implode(",", $user_sector_dn);
+			
+			// New search only on user sector
+			if ($count_entries > 200)
+			{
+				// Close old ldap conection
+				ldap_close($this->ds);
+				
+				// Reopen a local ldap connection, following referral
+				$this->ldapRootConnect(true);
+				
+				$sr=ldap_search($this->ds, $user_sector_dn, $filter, $justthese);
+				$count_entries = ldap_count_entries($this->ds,$sr);
+				
+				if ($count_entries > 200){
+					$return = array();
+					$return['status'] = false;
+					$return['error'] = "many results";
+					return $return;
+				}
+				else
+				{
+					$quickSearch_only_in_userSector = true;
+				}
+			}
+			
+			$info = ldap_get_entries($this->ds, $sr);
+			
+			$tmp = array();
+			$tmp_users_from_user_org = array();
+			for ($i=0; $i<$info["count"]; $i++)
+			{
+				// Usuario sempre serao da minha org.
+				if ($quickSearch_only_in_userSector)
+				{
+					$tmp[$info[$i]["mail"][0] . '%' . $info[$i]["telephonenumber"][0] . '%'. $info[$i]["mobile"][0] . '%' . $info[$i]["uid"][0] . '%' . $info[$i]["jpegphoto"]['count']] = $info[$i]["cn"][0];
+				}
+				else
+				{
+					if (preg_match("/$user_sector_dn/i", $info[$i]['dn']))
+					{
+						$tmp_users_from_user_org[$info[$i]["mail"][0] . '%' . $info[$i]["telephonenumber"][0] . '%'. $info[$i]["mobile"][0] . '%' . $info[$i]["uid"][0] . '%' . $info[$i]["jpegphoto"]['count']] = $info[$i]["cn"][0];
+					}
+					else
+					{
+						$tmp[$info[$i]["mail"][0] . '%' . $info[$i]["telephonenumber"][0] . '%'. $info[$i]["mobile"][0] . '%' . $info[$i]["uid"][0] . '%' . $info[$i]["jpegphoto"]['count']] = $info[$i]["cn"][0];
+					}
+				}
+			}
+			natcasesort($tmp_users_from_user_org);
+			natcasesort($tmp);
+			
+			if (($field != 'null') && ($ID != 'null'))
+			{
+				$i = 0;
+				
+				$tmp = array_merge($tmp, $tmp_users_from_user_org);
+				natcasesort($tmp);
+				
+				foreach ($tmp as $info => $cn)
+				{
+					$contacts_result[$i] = array();
+					$contacts_result[$i]["cn"] = $cn;
+					list ($contacts_result[$i]["mail"], $contacts_result[$i]["phone"], $contacts_result[$i]["mobile"]) = split ('%', $info);
+					$i++;
+				}
+				$contacts_result['quickSearch_only_in_userSector'] = $quickSearch_only_in_userSector;
+			}
+			else
+			{
+				$options_users_from_user_org = '';
+				$options = '';
+
+				/* List of users from user org */
+				$i = 0;
+				foreach ($tmp_users_from_user_org as $info => $cn)
+				{
+					$contacts_result[$i] = array();
+					$options_users_from_user_org .= $this->make_quicksearch_card($info, $cn);
+					$i++;
+				}
+
+				/* List of users from others org */
+				foreach ($tmp as $info => $cn)
+				{
+					$contacts_result[$i] = array();
+					$options .= $this->make_quicksearch_card($info, $cn);
+					$i++;
+				}
+				
+				if ($quickSearch_only_in_userSector)
+				{
+					if ($options != '')
+					{
+						$head_option =
+							'<tr class="quicksearchcontacts_unselected">' .
+								'<td colspan="2" width="100%" align="center">' .
+									$functions->getLang('More than 200 results were found') . '.<br>' .
+									$functions->getLang('Showing only the results found in your organization') . '.';
+								'</td>' .
+							'</tr>';
+						$contacts_result = $head_option . $options_users_from_user_org . $options;
+					}
+					else
+					{
+						$return = array();
+						$return['status'] = false;
+						$return['error'] = "many results";
+						return $return;
+					}
+				}
+				else
+				{
+					if (($options_users_from_user_org != '') && ($options != ''))
+					{
+						$head_option0 =
+							'<tr class="quicksearchcontacts_unselected">' .
+								'<td colspan="2" width="100%" align="center" style="background:#EEEEEE"><B>' .
+									$functions->getLang('Users from your organization') . '.';
+								'</B></td>' .
+							'</tr>';
+
+						$head_option1 =
+							'<tr class="quicksearchcontacts_unselected">' .
+								'<td colspan="2" width="100%" align="center" style="background:#EEEEEE"><B>' .
+									$functions->getLang('Users from others organizations') . '.';
+								'</B></td>' .
+							'</tr>';
+					}
+					$contacts_result = $head_option0 . $options_users_from_user_org . $head_option1 . $options;
+				}
+			}
+		}
+		ldap_close($this->ds);
+		return $contacts_result;
+	}
+
+	function make_quicksearch_card($info, $cn)
+	{
+		include_once("class.functions.inc.php");
+		$functions = new functions;						
+		
+		$contacts_result = array();
+		$contacts_result["cn"] = $cn;
+		list ($contacts_result["mail"], $contacts_result["phone"], $contacts_result["mobile"], $contacts_result["uid"], $contacts_result["jpegphoto"]) = split ('%', $info);
+					
+		if ($contacts_result['jpegphoto'])
+			$photo_link = '<img src="./inc/show_user_photo.php?mail='.$contacts_result['mail'].'">';
+		else
+			$photo_link = '<img src="./templates/default/images/photo.png">';
+					
+		$phoneUser = $contacts_result['phone'];
+					
+		if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['voip_enabled'] && $phoneUser) {
+			$phoneUser = '<a title="'.$functions->getLang("Call to Comercial Number").'" href="#" onclick="InfoContact.connectVoip(\''.$phoneUser.'\',\'com\')">'.$phoneUser.'</a>';
+			if($contacts_result['mobile']){
+				$phoneUser .= ' / <a title="'.$functions->getLang("Call to Mobile Number").'" href="#" onclick="InfoContact.connectVoip(\''.$contacts_result['mobile'].'\',\'mob\')">'.$contacts_result['mobile'].'</a>';
+			}
+		}
+		$option =
+			'<tr class="quicksearchcontacts_unselected">' .
+				'<td class="cc" width="1%">' .
+					'<a title="'.$functions->getLang("Write message").'" onClick="javascript:QuickSearchUser.create_new_message(\''.$contacts_result["cn"].'\', \''.$contacts_result["mail"].'\')">' .
+						$photo_link .
+					'</a>' .
+				'</td>' .
+				'<td class="cc">' .
+					'<span name="cn">' . $contacts_result['cn'] . '</span>' . '<br>' .
+					'<a title="'.$functions->getLang("Write message").'" onClick="javascript:QuickSearchUser.create_new_message(\''.$contacts_result["cn"].'\', \''.$contacts_result["mail"].'\')">' .
+						'<font color=blue>' .
+							'<span name="mail">' . $contacts_result['mail'] . '</span>' . '<br>' .
+						'</font>' .
+					'</a>' .
+					$phoneUser .
+				'</td>' .
+			'</tr>';
+		return $option;
+	}
+
+	function get_organizations($params){
+		$organizations = array();
+		$referral = $params['referral'];
+		$this->ldapConnect($referral);
+		if ($this->ds) {
+			$filter="ou=*";		
+			$justthese = array("ou");
+			$sr = ldap_list($this->ds, $this->ldap_context, $filter, $justthese);
+			$info = ldap_get_entries($this->ds, $sr);
+			
+			for ($i=0; $i<$info["count"]; $i++)
+				$organizations[$i] = $info[$i]["ou"][0];
+
+			ldap_close($this->ds);
+			sort($organizations);					
+		}
+		return $organizations;
+	}
+
+	function get_organizations2($params){
+		$organizations = array();
+		$referral = $params['referral'];
+		$this->ldapRootConnect($referral);
+		if ($this->ds) {
+			$filter="ou=*";		
+			$justthese = array("ou");
+			$sr = ldap_list($this->ds, $this->ldap_context, $filter, $justthese);
+			$info = ldap_get_entries($this->ds, $sr);
+			
+			for ($i=0; $i<$info["count"]; $i++)
+			{
+				$organizations[$i]['ou'] = $info[$i]["ou"][0];
+				$organizations[$i]['dn'] = $info[$i]["dn"];
+			}
+			
+			ldap_close($this->ds);
+			sort($organizations);					
+		}
+		return $organizations;
+	}
+
+	function catalogsearch($params)
+	{	
+		$this->ldapConnect(true);
+		$cn	= $params['search_for'] ? "*".$params['search_for']."*" : "*";
+		$user_context = "ou=".$params['organization'].",".$this->ldap_context;		
+		$max_result	  = $params['max_result'] ? $params['max_result'] : '200';		
+		$error = False;
+		
+		if ($this->ds) {											
+			$justthese = array("cn", "mail", "phpgwaccounttype", "phpgwAccountVisible");
+			$filter="(&(|(phpgwAccountType=u)(phpgwAccountType=l))(cn=".$cn."))";
+			$sr=ldap_search($this->ds, $user_context, $filter, $justthese);
+			
+			$count_entries = ldap_count_entries($this->ds,$sr);
+			if ($count_entries > $max_result){
+				$info = null;
+				$error = True;						
+			}
+			else
+				$info = ldap_get_entries($this->ds, $sr);		
+			
+			ldap_close($this->ds);			
+			
+			$u_tmp = array();
+			$g_tmp = array();
+			
+			for ($i=0; $i<$info["count"]; $i++){
+				if ($info[$i]["phpgwaccountvisible"][0] == '-1')
+					continue;
+				if((strtoupper($info[$i]["phpgwaccounttype"][0]) == 'U') && ($info[$i]["phpgwaccountvisible"][0] != '-1'))
+					$u_tmp[$info[$i]["mail"][0]] = $info[$i]["cn"][0];
+				else
+					$g_tmp[$info[$i]["mail"][0]] = $info[$i]["cn"][0];
+			}										
+			
+			natcasesort($u_tmp);
+			natcasesort($g_tmp);
+			
+			$i = 0;
+			$users = array();			
+			
+			foreach ($u_tmp as $mail => $cn){				
+				$users[$i++] = array("name" => $cn, "email" => $mail);
+			}
+			unset($u_tmp);
+			
+			$i = 0;			
+			$groups = array();
+			
+			foreach ($g_tmp as $mail => $cn){				
+				$groups[$i++] = array("name" => $cn, "email" => $mail);
+			}
+			unset($g_tmp);
+			
+			return  array('users' => $users, 'groups' => $groups, 'error' => $error);
+		}				
+		return null;
+	}
+	
+	function get_emails_ldap(){
+
+		$result['mail']= array();
+		$result['mailalter']= array();		
+		$user = $_SESSION['phpgw_info']['expressomail']['user']['account_lid'];
+		$this->ldapRootConnect(false);
+		if ($this->ds) {
+			$filter="uid=".$user;		
+			$justthese = array("mail","mailAlternateAddress");
+			$sr = ldap_search($this->ds,$this->ldap_context, $filter, $justthese);
+			$ent = ldap_get_entries($this->ds, $sr);
+			ldap_close($this->ds);
+			
+			for ($i=0; $i<$ent["count"]; $i++){
+				$result['mail'][] = $ent[$i]["mail"][0];
+				$result['mailalter'][] = $ent[$i]["mailalternateaddress"][0];				
+			}
+		}
+		return $result;
+	}
+	
+	//Busca usuários de um contexto e já retorna as options do select;
+	function get_available_users($params)
+    {
+        $this->ldapRootConnect();
+        //Monta lista de Grupos e Usuários
+        $users = Array();
+        $groups = Array();
+        $user_context= $params['context'];
+        $owner = $_SESSION['phpgw_info']['expressomail']['user']['owner'];
+
+        if ($this->ds)
+        {
+            $justthese = array("gidNumber","cn");
+            if ($params['type'] == 'search')
+                $sr=ldap_search($this->ds, $user_context, ("(&(cn=*)(phpgwaccounttype=g)(!(phpgwaccountvisible=-1)))"),$justthese);
+            else
+                $sr=ldap_list($this->ds, $user_context, ("(&(cn=*)(phpgwaccounttype=g)(!(phpgwaccountvisible=-1)))"),$justthese);
+            $info = ldap_get_entries($this->ds, $sr);
+            for ($i=0; $i<$info["count"]; $i++)
+                $groups[$uids=$info[$i]["gidnumber"][0]] = Array('name'    =>    $uids=$info[$i]["cn"][0], 'type'    =>    g);            
+            $justthese = array("phpgwaccountvisible","uidNumber","cn");
+            if ($params['type'] == 'search')
+                $sr=ldap_search($this->ds, $user_context, ("(&(cn=*)(phpgwaccounttype=u)(!(phpgwaccountvisible=-1)))"),$justthese);
+            else
+                $sr=ldap_list($this->ds, $user_context, ("(&(cn=*)(phpgwaccounttype=u)(!(phpgwaccountvisible=-1)))"),$justthese);
+
+            $info = ldap_get_entries($this->ds, $sr);
+            for ($i=0; $i<$info["count"]; $i++)
+            {
+                if ($info[$i]["phpgwaccountvisible"][0] == '-1')
+                    continue;
+                $users[$uids=$info[$i]["uidnumber"][0]] = Array('name'    =>    $uids=$info[$i]["cn"][0], 'type'    =>    u);
+            }
+        }
+        ldap_close($this->ds);
+            
+        @asort($users);
+        @reset($users);    
+        @asort($groups);
+        @reset($groups);
+        $user_options ='';
+        $group_options ='';
+
+        foreach($groups as $id => $user_array) {
+                $newId = $id.'U';
+                $group_options .= '<option  value="'.$newId.'">'.utf8_decode($user_array['name']).'</option>'."\n";
+        }
+        foreach($users as $id => $user_array) {
+            if($owner != $id){
+                $newId = $id.'U';
+                $user_options .= '<option  value="'.$newId.'">'.utf8_decode($user_array['name']).'</option>'."\n";
+            }
+        }
+        return array("users" => $user_options, "groups" => $group_options);
+    }
+
+	//Busca usuários de um contexto e já retorna as options do select;
+	function get_available_users2($params)
+	{
+		$this->ldapRootConnect();
+		
+		$context= $params['context'];
+		$justthese = array("cn", "uid", "cn");
+		$filter = "(&(phpgwaccounttype=u)(!(phpgwaccountvisible=-1)))";
+
+	    if ($this->ds) 
+	    {
+			$sr=ldap_search($this->ds, $context, $filter, $justthese);
+			$entries = ldap_get_entries($this->ds, $sr);
+			
+			for ($i=0; $i<$entries["count"]; $i++){
+				if($_SESSION['phpgw_info']['expressomail']['user']['account_lid'] != $entries[$i]["uid"][0]){
+					$u_tmp[$entries[$i]["uid"][0]] = $entries[$i]["cn"][0];
+				}
+			}
+			
+			natcasesort($u_tmp);
+
+			$i = 0;
+			$users = array();
+			
+			if (count($u_tmp))
+			{
+				foreach ($u_tmp as $uidnumber => $cn)
+				{
+					$options .= "<option value=$uidnumber>$cn</option>";
+				}
+				unset($u_tmp);
+			}
+
+			ldap_close($this->ds);
+    		return $options;
+		}
+	}
+	
+	function uid2cn($uid)
+	{	
+		// do not follow the referral
+		$this->ldapRootConnect(false);
+		if ($this->ds)
+		{
+			$filter="(&(phpgwAccountType=u)(uid=$uid))";		
+			$justthese = array("cn");
+			$sr=ldap_search($this->ds, $this->ldap_context, $filter, $justthese);
+			
+			$info = ldap_get_entries($this->ds, $sr);
+			return $info[0]["cn"][0];
+		}
+		return false;
+	}
+	function getSharedUsersFrom($params){		
+		$uids = explode(";",$params['uids']);
+
+		$this->imap = new imap_functions();
+		$filter = '';
+
+		foreach($uids as $index => $uid){
+			$params = array();		
+			$acl = $this->imap->getacltouser($uid);
+			if(preg_match("/a/",$acl))
+				$filter .= "(uid=$uid)";
+		}
+
+		$this->ldapRootConnect(false);
+		$filter="(&(phpgwAccountType=u)(|$filter))";
+		if ($this->ds) {					
+			$justthese = array("cn","mail");
+			$sr		=	ldap_search($this->ds, $this->ldap_context, $filter, $justthese);
+			ldap_sort($this->ds,$sr,"cn");			
+			$info 	= 	ldap_get_entries($this->ds, $sr);
+			$info['myname'] = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];						
+			return $info;
+		}
+	}
+
+	function getUserByEmail($params)
+	{
+		$filter="(&(phpgwAccountType=u)(mail=" . $params['email'] . "))";
+		$ldap_context = $_SESSION['phpgw_info']['expressomail']['ldap_server']['dn'];
+		$justthese = array("cn","uid","telephoneNumber","jpegPhoto","mobile");
+
+		// Follow the referral
+		$ds = $this->ldapConnect2(true);
+		if ($ds)
+		{			
+			$sr=ldap_search($ds, $ldap_context, $filter, $justthese);
+			
+			if (!$sr)
+				return null;
+			
+			$entry = ldap_first_entry($ds, $sr);
+			
+			if($entry) {						
+				$obj =  array("cn" => ldap_get_values($ds, $entry, "cn"),
+						  "email" => $params['email'],
+						  "uid" => ldap_get_values($ds, $entry, "uid"),
+						  "type" => "global",
+						  "mobile" =>  @ldap_get_values($ds, $entry, "mobile"),
+						  "telefone" =>  @ldap_get_values($ds, $entry, "telephonenumber")
+					);
+
+				$_SESSION['phpgw_info']['expressomail']['contact_photo'] = ldap_get_values_len($ds, $entry, "jpegphoto");
+				ldap_close($ds);
+				return $obj;
+			}
+		}
+		return null;
+	}
+}
+?>
Index: tags/expressoMail1_2/1.2211/inc/class.functions.inc.php
===================================================================
--- tags/expressoMail1_2/1.2211/inc/class.functions.inc.php	(revision 94)
+++ tags/expressoMail1_2/1.2211/inc/class.functions.inc.php	(revision 94)
@@ -0,0 +1,115 @@
+<?php
+	class Functions{
+		
+		
+		function CallVoipConnect($params){
+			$fromNumber = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['telephone_number'];
+			if(!$fromNumber)
+				return false;
+			$fromNumber = substr($fromNumber,strlen($fromNumber) - 4, strlen($fromNumber) - 1);
+			$toNumber	= $params['to'] ? substr($params['to'],strlen($params['to']) - 4, strlen($params['to']) - 1) : 0;
+			
+			$voipServer	= $_SESSION['phpgw_info']['expressomail']['server']['voip_server'];
+			$voipUrl	= $_SESSION['phpgw_info']['expressomail']['server']['voip_url'];
+			$voipPort	= $_SESSION['phpgw_info']['expressomail']['server']['voip_port'];
+			
+			// Se for celular, passa os digitos do número e conecta com outro VoIP Server.....
+			if($params['typePhone'] == 'mob'){
+				$toNumber	= $params['to'];
+				$voipServer	= $_SESSION['phpgw_info']['expressomail']['server']['voip_server'];
+				$voipUrl	= $_SESSION['phpgw_info']['expressomail']['server']['voip_url'];
+				$voipPort	= $_SESSION['phpgw_info']['expressomail']['server']['voip_port'];				
+			}	
+				
+			if(!$voipServer || !$voipUrl || !$voipPort)
+				return false;
+			$url		= "http://".$voipServer.":".$voipPort.$voipUrl."?magic=1333&acao=liga&ramal=".$fromNumber."&numero=".$toNumber;			
+			$sMethod = 'GET ';
+            $crlf = "\r\n";
+            $sRequest = " HTTP/1.1" . $crlf;
+            $sRequest .= "Host: localhost" . $crlf;
+            $sRequest .= "Accept: */* " . $crlf;
+            $sRequest .= "Connection: Close" . $crlf . $crlf;            
+            $sRequest = $sMethod . $url . $sRequest;    
+            $sockHttp = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);            
+            if (!$sockHttp)  {
+                return false;
+            }
+            $resSocketConnect = socket_connect($sockHttp, $voipServer, $voipPort);
+            if (!$resSocketConnect) {
+                return false;
+            }
+            $resSocketWrite = socket_write($sockHttp, $sRequest, strlen($sRequest));
+            if (!$resSocketWrite) {
+                return false;
+            }    
+            $sResponse = '';    
+            while ($sRead = socket_read($sockHttp, 512)) {
+                $sResponse .= $sRead;
+            }            
+            
+            socket_close($sockHttp);            
+            $pos = strpos($sResponse, $crlf . $crlf);
+            return substr($sResponse, $pos + 2 * strlen($crlf));									
+		}
+
+		function getDirContents($dir){
+			//$dir = dirname($dir);
+	
+		   	if (!is_dir($dir)) 	{
+		   			return 'Error: Cannot load files in :'. $dir.' !';
+		   	}
+		   	
+		   	if ($root=@opendir($dir))	{
+		       
+		       while ($file=readdir($root))	{	           
+		           if($file!="." && $file!="..")
+			           $files[]=$dir."/".$file;           
+		       }
+		       
+		   	}
+		   	
+		   return $files;
+		}
+				
+		function getFilesJs($includeFiles = '', $update_version = ''){
+			
+			$files = $this -> getDirContents('js');
+			$str_files = '';
+			
+			if($includeFiles) {
+				$includeFiles = explode(",",trim($includeFiles));
+				// Bug fixed for array_search function
+				$includeFiles[count($includeFiles)] = $includeFiles[0];
+				$includeFiles[0] = null;
+				// End Bug fixed.
+			}														
+			for($i = 0; $i < count($files); $i++) {				
+				if(count(explode('.js',$files[$i])) > 1) {
+					if($includeFiles  && array_search(trim($files[$i]),$includeFiles)){	
+						$str_files .= "<script src='".$files[$i]."?".$update_version."' type='text/javascript'></script>";						
+					}
+				}
+			}
+			
+			return $str_files;
+		}								
+
+		function getReturnExecuteForm(){
+			$response = $_SESSION['response'];
+			$_SESSION['response'] = null;
+			return $response;
+		}
+		
+		function getLang($key){
+			if ($_SESSION['phpgw_info']['expressomail']['lang'][$key])
+			return $_SESSION['phpgw_info']['expressomail']['lang'][$key];			
+			else
+				return ($key . '*');
+		}
+
+		function get_preferences()	{
+			return $_SESSION['phpgw_info']['user']['preferences']['expressoMail'];
+		}
+	}
+?>
Index: tags/expressoMail1_2/1.2211/inc/class.phpmailer.php
===================================================================
--- tags/expressoMail1_2/1.2211/inc/class.phpmailer.php	(revision 117)
+++ tags/expressoMail1_2/1.2211/inc/class.phpmailer.php	(revision 117)
@@ -0,0 +1,1543 @@
+<?php
+////////////////////////////////////////////////////
+// PHPMailer - PHP email class
+//
+// Class for sending email using either
+// sendmail, PHP mail(), or SMTP.  Methods are
+// based upon the standard AspEmail(tm) classes.
+//
+// Copyright (C) 2001 - 2003  Brent R. Matzelle
+//
+// License: LGPL, see LICENSE
+////////////////////////////////////////////////////
+
+/**
+ * PHPMailer - PHP email transport class
+ * @package PHPMailer
+ * @author Brent R. Matzelle
+ * @copyright 2001 - 2003 Brent R. Matzelle
+ */
+class PHPMailer
+{
+    /////////////////////////////////////////////////
+    // PUBLIC VARIABLES
+    /////////////////////////////////////////////////
+
+    /**
+     * Email priority (1 = High, 3 = Normal, 5 = low).
+     * @var int
+     */
+    var $Priority          = 3;
+
+    /**
+     * Sets the CharSet of the message.
+     * @var string
+     */
+    var $CharSet           = "iso-8859-1";
+
+    /**
+     * Sets the Content-type of the message.
+     * @var string
+     */
+    var $ContentType        = "text/plain";
+
+    /**
+     * Sets the Encoding of the message. Options for this are "8bit",
+     * "7bit", "binary", "base64", and "quoted-printable".
+     * @var string
+     */
+    var $Encoding          = "quoted-printable";
+
+    /**
+     * Holds the most recent mailer error message.
+     * @var string
+     */
+    var $ErrorInfo         = "";
+
+    /**
+     * Sets the From email address for the message.
+     * @var string
+     */
+    var $From               = "root@localhost";
+
+    /**
+     * Sets the From name of the message.
+     * @var string
+     */
+    var $FromName           = "Root User";
+
+    /**
+     * Sets the Sender email (Return-Path) of the message.  If not empty,
+     * will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
+     * @var string
+     */
+    var $Sender            = "";
+	var $SenderName		= "";
+    /**
+     * Sets the Subject of the message.
+     * @var string
+     */
+    var $Subject           = "teste";
+
+    /**
+     * Sets the Body of the message.  This can be either an HTML or text body.
+     * If HTML then run IsHTML(true).
+     * @var string
+     */
+    var $Body               = "";
+
+    /**
+     * Sets the text-only body of the message.  This automatically sets the
+     * email to multipart/alternative.  This body can be read by mail
+     * clients that do not have HTML email capability such as mutt. Clients
+     * that can read HTML will view the normal Body.
+     * @var string
+     */
+    var $AltBody           = "";
+
+    /**
+     * Sets word wrapping on the body of the message to a given number of 
+     * characters.
+     * @var int
+     */
+    var $WordWrap          = 0;
+
+    /**
+     * Method to send mail: ("mail", "sendmail", or "smtp").
+     * @var string
+     */
+    var $Mailer            = "mail";
+
+    /**
+     * Sets the path of the sendmail program.
+     * @var string
+     */
+    var $Sendmail          = "/usr/sbin/sendmail";
+    
+    /**
+     * Path to PHPMailer plugins.  This is now only useful if the SMTP class 
+     * is in a different directory than the PHP include path.  
+     * @var string
+     */
+    var $PluginDir         = "";
+
+    /**
+     *  Holds PHPMailer version.
+     *  @var string
+     */
+    var $Version           = "1.2";
+
+    /**
+     * Sets the email address that a reading confirmation will be sent.
+     * @var string
+     */
+    var $ConfirmReadingTo  = "";
+
+    /**
+     *  Sets the hostname to use in Message-Id and Received headers
+     *  and as default HELO string. If empty, the value returned
+     *  by SERVER_NAME is used or 'localhost.localdomain'.
+     *  @var string
+     */
+    var $Hostname          = "";
+	
+	var $SaveMessageInFolder = "";
+	var $SaveMessageAsDraft = "";
+
+    /////////////////////////////////////////////////
+    // SMTP VARIABLES
+    /////////////////////////////////////////////////
+
+    /**
+     *  Sets the SMTP hosts.  All hosts must be separated by a
+     *  semicolon.  You can also specify a different port
+     *  for each host by using this format: [hostname:port]
+     *  (e.g. "smtp1.example.com:25;smtp2.example.com").
+     *  Hosts will be tried in order.
+     *  @var string
+     */
+    var $Host        = "localhost";
+
+    /**
+     *  Sets the default SMTP server port.
+     *  @var int
+     */
+    var $Port        = 25;
+
+    /**
+     *  Sets the SMTP HELO of the message (Default is $Hostname).
+     *  @var string
+     */
+    var $Helo        = "";
+
+    /**
+     *  Sets SMTP authentication. Utilizes the Username and Password variables.
+     *  @var bool
+     */
+    var $SMTPAuth     = false;
+
+    /**
+     *  Sets SMTP username.
+     *  @var string
+     */
+    var $Username     = "";
+
+    /**
+     *  Sets SMTP password.
+     *  @var string
+     */
+    var $Password     = "";
+
+    /**
+     *  Sets the SMTP server timeout in seconds. This function will not 
+     *  work with the win32 version.
+     *  @var int
+     */
+    var $Timeout      = 300;
+
+    /**
+     *  Sets SMTP class debugging on or off.
+     *  @var bool
+     */
+    var $SMTPDebug    = false;
+
+    /**
+     * Prevents the SMTP connection from being closed after each mail 
+     * sending.  If this is set to true then to close the connection 
+     * requires an explicit call to SmtpClose(). 
+     * @var bool
+     */
+    var $SMTPKeepAlive = false;
+
+    /**#@+
+     * @access private
+     */
+    var $smtp            = NULL;
+    var $to              = array();
+    var $cc              = array();
+    var $bcc             = array();
+    var $ReplyTo         = array();
+    var $attachment      = array();
+    var $CustomHeader    = array();
+    var $message_type    = "";
+    var $boundary        = array();
+    var $language        = array();
+    var $error_count     = 0;
+    var $LE              = "\n";
+    /**#@-*/
+    
+    /////////////////////////////////////////////////
+    // VARIABLE METHODS
+    /////////////////////////////////////////////////
+
+    /**
+     * Sets message type to HTML.  
+     * @param bool $bool
+     * @return void
+     */
+    function IsHTML($bool) {
+        if($bool == true)
+            $this->ContentType = "text/html";
+        else
+            $this->ContentType = "text/plain";
+    }
+
+    /**
+     * Sets Mailer to send message using SMTP.
+     * @return void
+     */
+    function IsSMTP() {
+        $this->Mailer = "smtp";
+    }
+
+    /**
+     * Sets Mailer to send message using PHP mail() function.
+     * @return void
+     */
+    function IsMail() {
+        $this->Mailer = "mail";
+    }
+
+    /**
+     * Sets Mailer to send message using the $Sendmail program.
+     * @return void
+     */
+    function IsSendmail() {
+        $this->Mailer = "sendmail";
+    }
+
+    /**
+     * Sets Mailer to send message using the qmail MTA. 
+     * @return void
+     */
+    function IsQmail() {
+        $this->Sendmail = "/var/qmail/bin/sendmail";
+        $this->Mailer = "sendmail";
+    }
+
+
+    /////////////////////////////////////////////////
+    // RECIPIENT METHODS
+    /////////////////////////////////////////////////
+
+    /**
+     * Adds a "To" address.  
+     * @param string $address
+     * @param string $name
+     * @return void
+     */
+    function AddAddress($address, $name = "") {
+        $cur = count($this->to);
+        $this->to[$cur][0] = trim($address);
+        $this->to[$cur][1] = $name;
+    }
+
+    /**
+     * Adds a "Cc" address. Note: this function works
+     * with the SMTP mailer on win32, not with the "mail"
+     * mailer.  
+     * @param string $address
+     * @param string $name
+     * @return void
+    */
+    function AddCC($address, $name = "") {
+        $cur = count($this->cc);
+        $this->cc[$cur][0] = trim($address);
+        $this->cc[$cur][1] = $name;
+    }
+
+    /**
+     * Adds a "Bcc" address. Note: this function works
+     * with the SMTP mailer on win32, not with the "mail"
+     * mailer.  
+     * @param string $address
+     * @param string $name
+     * @return void
+     */
+    function AddBCC($address, $name = "") {
+        $cur = count($this->bcc);
+        $this->bcc[$cur][0] = trim($address);
+        $this->bcc[$cur][1] = $name;
+    }
+
+    /**
+     * Adds a "Reply-to" address.  
+     * @param string $address
+     * @param string $name
+     * @return void
+     */
+    function AddReplyTo($address, $name = "") {
+        $cur = count($this->ReplyTo);
+        $this->ReplyTo[$cur][0] = trim($address);
+        $this->ReplyTo[$cur][1] = $name;
+    }
+
+
+    /////////////////////////////////////////////////
+    // MAIL SENDING METHODS
+    /////////////////////////////////////////////////
+
+    /**
+     * Creates message and assigns Mailer. If the message is
+     * not sent successfully then it returns false.  Use the ErrorInfo
+     * variable to view description of the error.  
+     * @return bool
+     */
+    function Send() {
+        $header = "";
+        $body = "";
+        $result = true;
+		
+        if(((count($this->to) + count($this->cc) + count($this->bcc)) < 1) && (!$this->SaveMessageAsDraft))
+        {
+            $this->SetError($this->Lang("provide_address"));
+            return false;
+        }
+
+        // Set whether the message is multipart/alternative
+        if(!empty($this->AltBody))
+            $this->ContentType = "multipart/alternative";
+
+        $this->error_count = 0; // reset errors
+        $this->SetMessageType();
+        $header .= $this->CreateHeader();
+        $body = $this->CreateBody();
+		
+        if($body == "") { return false; }
+		
+        // Choose the mailer
+        switch($this->Mailer)
+        {
+            case "sendmail":
+                $result = $this->SendmailSend($header, $body);
+                break;
+            case "mail":
+                $result = $this->MailSend($header, $body);
+                break;
+            case "smtp":
+                $result = $this->SmtpSend($header, $body);
+                break;
+            default:
+            $this->SetError($this->Mailer . $this->Lang("mailer_not_supported"));
+                $result = false;
+                break;
+        }
+
+        return $result;
+    }
+    
+    /**
+     * Sends mail using the $Sendmail program.  
+     * @access private
+     * @return bool
+     */
+    function SendmailSend($header, $body) {
+        if ($this->Sender != "")
+            $sendmail = sprintf("%s -oi -f %s -t", $this->Sendmail, $this->Sender);
+        else
+            $sendmail = sprintf("%s -oi -t", $this->Sendmail);
+
+        if(!@$mail = popen($sendmail, "w"))
+        {
+            $this->SetError($this->Lang("execute") . $this->Sendmail);
+            return false;
+        }
+
+        fputs($mail, $header);
+        fputs($mail, $body);
+        
+        $result = pclose($mail) >> 8 & 0xFF;
+        if($result != 0)
+        {
+            $this->SetError($this->Lang("execute") . $this->Sendmail);
+            return false;
+        }
+
+        return true;
+    }
+
+    /**
+     * Sends mail using the PHP mail() function.  
+     * @access private
+     * @return bool
+     */
+    function MailSend($header, $body) {
+        $to = "";
+        for($i = 0; $i < count($this->to); $i++)
+        {
+            if($i != 0) { $to .= ", "; }
+            $to .= $this->to[$i][0];
+        }
+
+        if ($this->Sender != "" && strlen(ini_get("safe_mode"))< 1)
+        {
+            $old_from = ini_get("sendmail_from");
+            ini_set("sendmail_from", $this->Sender);
+            $params = sprintf("-oi -f %s", $this->Sender);
+            $rt = @mail($to, $this->EncodeHeader($this->Subject), $body, 
+                        $header, $params);
+        }
+        else
+            $rt = @mail($to, $this->EncodeHeader($this->Subject), $body, $header);
+
+        if (isset($old_from))
+            ini_set("sendmail_from", $old_from);
+
+        if(!$rt)
+        {
+            $this->SetError($this->Lang("instantiate"));
+            return false;
+        }
+
+        return true;
+    }
+
+    /**
+     * Sends mail via SMTP using PhpSMTP (Author:
+     * Chris Ryan).  Returns bool.  Returns false if there is a
+     * bad MAIL FROM, RCPT, or DATA input.
+     * @access private
+     * @return bool
+     */
+    function SmtpSend($header, $body) {
+        include_once($this->PluginDir . "class.smtp.php");
+        $error = "";
+        $bad_rcpt = array();
+
+        if(!$this->SmtpConnect())
+            return false;
+
+        $smtp_from = ($this->Sender == "") ? $this->From : $this->Sender;
+        if(!$this->smtp->Mail($smtp_from))
+        {
+            $error = $this->Lang("from_failed") . $smtp_from;
+            $this->SetError($error);
+            $this->smtp->Reset();
+            return false;
+        }
+
+        // Attempt to send attach all recipients
+        for($i = 0; $i < count($this->to); $i++)
+        {
+            if(!$this->smtp->Recipient($this->to[$i][0]))
+                $bad_rcpt[] = $this->to[$i][0];
+        }
+        for($i = 0; $i < count($this->cc); $i++)
+        {
+            if(!$this->smtp->Recipient($this->cc[$i][0]))
+                $bad_rcpt[] = $this->cc[$i][0];
+        }
+        for($i = 0; $i < count($this->bcc); $i++)
+        {
+            if(!$this->smtp->Recipient($this->bcc[$i][0]))
+                $bad_rcpt[] = $this->bcc[$i][0];
+        }
+
+        if(count($bad_rcpt) > 0) // Create error message
+        {
+            //Postfix version 2.3.8-2
+            $smtp_code_error = substr($this->smtp->error['smtp_msg'], 0, 5);
+            //Postfix version 2.1.5-9
+            $array_error = explode(":", $this->smtp->error['smtp_msg']);
+            
+            for($i = 0; $i < count($bad_rcpt); $i++)
+            {
+                if($i != 0) { $error .= ", "; }
+                $error .= $bad_rcpt[$i];
+            }
+            if (($smtp_code_error == '5.7.1') || (trim($array_error[2]) == 'Access denied'))
+            	$error = $this->Lang("not_allowed") . $error;
+            else
+            	$error = $this->Lang("recipients_failed") . $error;
+            $this->SetError($error);
+            $this->smtp->Reset();
+            return false;
+        }
+        $smtpSent = $this->smtp->Data($header . $body);
+        if(!$smtpSent)
+        {
+            $this->SetError($this->Lang("data_not_accepted") .' '. $this->smtp->error['error'] .','. $this->smtp->error['smtp_code'].','. $this->smtp->error['smtp_msg']);
+            $this->smtp->Reset();
+            return false;
+        }
+        if($this->SMTPKeepAlive == true)
+            $this->smtp->Reset();
+        else
+            $this->SmtpClose();
+
+    	if ($this->SaveMessageInFolder){
+			$username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
+			$password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
+			$imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
+			$imap_port 	= $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
+			
+			if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
+			{
+				$imap_options = '/tls/novalidate-cert';
+			}
+			else
+			{
+				$imap_options = '/notls/novalidate-cert';
+			}	 	
+			$mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$this->SaveMessageInFolder, $username, $password);
+		
+			$new_header = str_replace("\n", "\r\n", $header);
+			$new_body = str_replace("\n", "\r\n", $body);
+			
+			if ($this->SaveMessageAsDraft){
+				imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$this->SaveMessageInFolder, $new_header . $new_body, "\\Seen \\Draft");
+				return true;
+			}
+			else
+				imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$this->SaveMessageInFolder, $new_header . $new_body, "\\Seen");
+    	}    	
+        
+        return $smtpSent;
+    }
+
+    /**
+     * Initiates a connection to an SMTP server.  Returns false if the 
+     * operation failed.
+     * @access private
+     * @return bool
+     */
+    function SmtpConnect() {
+        if($this->smtp == NULL) { $this->smtp = new SMTP(); }
+
+        $this->smtp->do_debug = $this->SMTPDebug;
+        $hosts = explode(";", $this->Host);
+        $index = 0;
+        $connection = ($this->smtp->Connected()); 
+
+        // Retry while there is no connection
+        while($index < count($hosts) && $connection == false)
+        {
+            if(strstr($hosts[$index], ":"))
+                list($host, $port) = explode(":", $hosts[$index]);
+            else
+            {
+                $host = $hosts[$index];
+                $port = $this->Port;
+            }
+
+            if($this->smtp->Connect($host, $port, $this->Timeout))
+            {
+                if ($this->Helo != '')
+                    $this->smtp->Hello($this->Helo);
+                else
+                    $this->smtp->Hello($this->ServerHostname());
+        
+                if($this->SMTPAuth)
+                {
+                    if(!$this->smtp->Authenticate($this->Username, 
+                                                  $this->Password))
+                    {
+                        $this->SetError($this->Lang("authenticate"));
+                        $this->smtp->Reset();
+                        $connection = false;
+                    }
+                }
+                $connection = true;
+            }
+            $index++;
+        }
+        if(!$connection)
+            $this->SetError($this->Lang("connect_host"));
+
+        return $connection;
+    }
+
+    /**
+     * Closes the active SMTP session if one exists.
+     * @return void
+     */
+    function SmtpClose() {
+        if($this->smtp != NULL)
+        {
+            if($this->smtp->Connected())
+            {
+                $this->smtp->Quit();
+                $this->smtp->Close();
+            }
+        }
+    }
+
+    /**
+     * Sets the language for all class error messages.  Returns false 
+     * if it cannot load the language file.  The default language type
+     * is English.
+     * @param string $lang_type Type of language (e.g. Portuguese: "br")
+     * @param string $lang_path Path to the language file directory
+     * @access public
+     * @return bool
+     */
+    function SetLanguage($lang_type, $lang_path = "setup/") {
+        if(file_exists($lang_path.'phpmailer.lang-'.$lang_type.'.php'))
+            include($lang_path.'phpmailer.lang-'.$lang_type.'.php');
+        else if(file_exists($lang_path.'phpmailer.lang-en.php'))
+            include($lang_path.'phpmailer.lang-en.php');
+        else
+        {
+            $this->SetError("Could not load language file");
+            return false;
+        }
+        $this->language = $PHPMAILER_LANG;
+    
+        return true;
+    }
+
+    /////////////////////////////////////////////////
+    // MESSAGE CREATION METHODS
+    /////////////////////////////////////////////////
+
+    /**
+     * Creates recipient headers.  
+     * @access private
+     * @return string
+     */
+    function AddrAppend($type, $addr) {
+        $addr_str = $type . ": ";
+        $addr_str .= $this->AddrFormat($addr[0]);
+        if(count($addr) > 1)
+        {
+            for($i = 1; $i < count($addr); $i++)
+                $addr_str .= ", " . $this->AddrFormat($addr[$i]);
+        }
+        $addr_str .= $this->LE;
+
+        return $addr_str;
+    }
+    
+    /**
+     * Formats an address correctly. 
+     * @access private
+     * @return string
+     */
+    function AddrFormat($addr) {
+        if(empty($addr[1]))
+            $formatted = $addr[0];
+        else
+        {
+            $formatted = $this->EncodeHeader($addr[1], 'phrase') . " <" . 
+                         $addr[0] . ">";
+        }
+
+        return $formatted;
+    }
+
+    /**
+     * Wraps message for use with mailers that do not
+     * automatically perform wrapping and for quoted-printable.
+     * Original written by philippe.  
+     * @access private
+     * @return string
+     */
+    function WrapText($message, $length, $qp_mode = false) {
+        $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
+
+        $message = $this->FixEOL($message);
+        if (substr($message, -1) == $this->LE)
+            $message = substr($message, 0, -1);
+
+        $line = explode($this->LE, $message);
+        $message = "";
+        for ($i=0 ;$i < count($line); $i++)
+        {
+          $line_part = explode(" ", $line[$i]);
+          $buf = "";
+          for ($e = 0; $e<count($line_part); $e++)
+          {
+              $word = $line_part[$e];
+              if ($qp_mode and (strlen($word) > $length))
+              {
+                $space_left = $length - strlen($buf) - 1;
+                if ($e != 0)
+                {
+                    if ($space_left > 20)
+                    {
+                        $len = $space_left;
+                        if (substr($word, $len - 1, 1) == "=")
+                          $len--;
+                        elseif (substr($word, $len - 2, 1) == "=")
+                          $len -= 2;
+                        $part = substr($word, 0, $len);
+                        $word = substr($word, $len);
+                        $buf .= " " . $part;
+                        $message .= $buf . sprintf("=%s", $this->LE);
+                    }
+                    else
+                    {
+                        $message .= $buf . $soft_break;
+                    }
+                    $buf = "";
+                }
+                while (strlen($word) > 0)
+                {
+                    $len = $length;
+                    if (substr($word, $len - 1, 1) == "=")
+                        $len--;
+                    elseif (substr($word, $len - 2, 1) == "=")
+                        $len -= 2;
+                    $part = substr($word, 0, $len);
+                    $word = substr($word, $len);
+
+                    if (strlen($word) > 0)
+                        $message .= $part . sprintf("=%s", $this->LE);
+                    else
+                        $buf = $part;
+                }
+              }
+              else
+              {
+                $buf_o = $buf;
+                $buf .= ($e == 0) ? $word : (" " . $word); 
+
+                if (strlen($buf) > $length and $buf_o != "")
+                {
+                    $message .= $buf_o . $soft_break;
+                    $buf = $word;
+                }
+              }
+          }
+          $message .= $buf . $this->LE;
+        }
+
+        return $message;
+    }
+    
+    /**
+     * Set the body wrapping.
+     * @access private
+     * @return void
+     */
+    function SetWordWrap() {
+        if($this->WordWrap < 1)
+            return;
+            
+        switch($this->message_type)
+        {
+           case "alt":
+              // fall through
+           case "alt_attachments":
+              $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap);
+              break;
+           default:
+              $this->Body = $this->WrapText($this->Body, $this->WordWrap);
+              break;
+        }
+    }
+
+    /**
+     * Assembles message header.  
+     * @access private
+     * @return string
+     */
+    function CreateHeader() {
+        $result = "";
+        
+        // Set the boundaries
+        $uniq_id = md5(uniqid(time()));
+        $this->boundary[1] = "b1_" . $uniq_id;
+        $this->boundary[2] = "b2_" . $uniq_id;
+
+        $result .= $this->HeaderLine("Date", $this->RFCDate());
+        if($this->Sender == "")
+            $result .= $this->HeaderLine("Return-Path", trim($this->From));
+        else
+            $result .= $this->HeaderLine("Return-Path", trim($this->Sender));
+        
+        // To be created automatically by mail()
+        if($this->Mailer != "mail")
+        {
+            if(count($this->to) > 0)
+                $result .= $this->AddrAppend("To", $this->to);
+            else if ((count($this->cc) == 0) && (!$this->SaveMessageAsDraft))
+                $result .= $this->HeaderLine("To", "undisclosed-recipients:;");
+            if(count($this->cc) > 0)
+                $result .= $this->AddrAppend("Cc", $this->cc);
+        }
+
+		if (!$this->SaveMessageAsDraft){
+	        $from = array();
+    	    $from[0][0] = trim($this->From);
+        	$from[0][1] = $this->FromName;
+	        $result .= $this->AddrAppend("From", $from);
+		} 
+		if($this->Sender) {
+			$sender = array();
+			$sender[0][0] = trim($this->Sender);
+        	$sender[0][1] = $this->SenderName;
+        	$result .= $this->AddrAppend("Sender", $sender);
+		}
+
+        // sendmail and mail() extract Bcc from the header before sending
+        if((($this->Mailer == "sendmail") || ($this->Mailer == "mail")) && (count($this->bcc) > 0))
+            $result .= $this->AddrAppend("Bcc", $this->bcc);
+
+        if(count($this->ReplyTo) > 0)
+            $result .= $this->AddrAppend("Reply-to", $this->ReplyTo);
+
+        // mail() sets the subject itself
+        if($this->Mailer != "mail")
+            $result .= $this->HeaderLine("Subject", $this->EncodeHeader(trim($this->Subject)));
+
+        $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
+        $result .= $this->HeaderLine("X-Priority", $this->Priority);
+        $result .= $this->HeaderLine("X-Mailer", "ExpressoMail [version " . $this->Version . "]");
+        
+        if($this->ConfirmReadingTo != "")
+        {
+            $result .= $this->HeaderLine("Disposition-Notification-To", 
+                       "<" . trim($this->ConfirmReadingTo) . ">");
+        }
+
+        // Add custom headers
+        for($index = 0; $index < count($this->CustomHeader); $index++)
+        {
+            $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), 
+                       $this->EncodeHeader(trim($this->CustomHeader[$index][1])));
+        }
+        $result .= $this->HeaderLine("MIME-Version", "1.0");
+
+        switch($this->message_type)
+        {
+            case "plain":
+                $result .= $this->HeaderLine("Content-Transfer-Encoding", $this->Encoding);
+                $result .= sprintf("Content-Type: %s; charset=\"%s\"",
+                                    $this->ContentType, $this->CharSet);
+                break;
+            case "attachments":
+                // fall through
+            case "alt_attachments":
+                if($this->InlineImageExists())
+                {
+                    $result .= sprintf("Content-Type: %s;%s\ttype=\"text/html\";%s\tboundary=\"%s\"%s", 
+                                    "multipart/related", $this->LE, $this->LE, 
+                                    $this->boundary[1], $this->LE);
+                }
+                else
+                {
+                    $result .= $this->HeaderLine("Content-Type", "multipart/mixed;");
+                    $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
+                }
+                break;
+            case "alt":
+                $result .= $this->HeaderLine("Content-Type", "multipart/alternative;");
+                $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
+                break;
+        }
+
+        if($this->Mailer != "mail")
+            $result .= $this->LE.$this->LE;
+
+        return $result;
+    }
+
+    /**
+     * Assembles the message body.  Returns an empty string on failure.
+     * @access private
+     * @return string
+     */
+    function CreateBody() {
+        $result = "";
+
+        $this->SetWordWrap();
+        switch($this->message_type)
+        {
+            case "alt":
+                $result .= $this->GetBoundary($this->boundary[1], "", 
+                                              "text/plain", "");
+                $result .= $this->EncodeString($this->AltBody, $this->Encoding);
+                $result .= $this->LE.$this->LE;
+                $result .= $this->GetBoundary($this->boundary[1], "", 
+                                              "text/html", "");
+                
+                $result .= $this->EncodeString($this->Body, $this->Encoding);
+                $result .= $this->LE.$this->LE;
+    
+                $result .= $this->EndBoundary($this->boundary[1]);
+                break;
+            case "plain":
+                $result .= $this->EncodeString($this->Body, $this->Encoding);
+                break;
+            case "attachments":
+                $result .= $this->GetBoundary($this->boundary[1], "", "", "");
+                $result .= $this->EncodeString($this->Body, $this->Encoding);
+                $result .= $this->LE;
+     
+                $result .= $this->AttachAll();
+                break;
+            case "alt_attachments":
+                $result .= sprintf("--%s%s", $this->boundary[1], $this->LE);
+                $result .= sprintf("Content-Type: %s;%s" .
+                                   "\tboundary=\"%s\"%s",
+                                   "multipart/alternative", $this->LE, 
+                                   $this->boundary[2], $this->LE.$this->LE);
+    
+                // Create text body
+                $result .= $this->GetBoundary($this->boundary[2], "", 
+                                              "text/plain", "") . $this->LE;
+
+                $result .= $this->EncodeString($this->AltBody, $this->Encoding);
+                $result .= $this->LE.$this->LE;
+    
+                // Create the HTML body
+                $result .= $this->GetBoundary($this->boundary[2], "", 
+                                              "text/html", "") . $this->LE;
+    
+                $result .= $this->EncodeString($this->Body, $this->Encoding);
+                $result .= $this->LE.$this->LE;
+
+                $result .= $this->EndBoundary($this->boundary[2]);
+                
+                $result .= $this->AttachAll();
+                break;
+        }
+        if($this->IsError())
+            $result = "";
+
+        return $result;
+    }
+
+    /**
+     * Returns the start of a message boundary.
+     * @access private
+     */
+    function GetBoundary($boundary, $charSet, $contentType, $encoding) {
+        $result = "";
+        if($charSet == "") { $charSet = $this->CharSet; }
+        if($contentType == "") { $contentType = $this->ContentType; }
+        if($encoding == "") { $encoding = $this->Encoding; }
+
+        $result .= $this->TextLine("--" . $boundary);
+        $result .= sprintf("Content-Type: %s; charset = \"%s\"", 
+                            $contentType, $charSet);
+        $result .= $this->LE;
+        $result .= $this->HeaderLine("Content-Transfer-Encoding", $encoding);
+        $result .= $this->LE;
+       
+        return $result;
+    }
+    
+    /**
+     * Returns the end of a message boundary.
+     * @access private
+     */
+    function EndBoundary($boundary) {
+        return $this->LE . "--" . $boundary . "--" . $this->LE; 
+    }
+    
+    /**
+     * Sets the message type.
+     * @access private
+     * @return void
+     */
+    function SetMessageType() {
+        if(count($this->attachment) < 1 && strlen($this->AltBody) < 1)
+            $this->message_type = "plain";
+        else
+        {
+            if(count($this->attachment) > 0)
+                $this->message_type = "attachments";
+            if(strlen($this->AltBody) > 0 && count($this->attachment) < 1)
+                $this->message_type = "alt";
+            if(strlen($this->AltBody) > 0 && count($this->attachment) > 0)
+                $this->message_type = "alt_attachments";
+        }
+    }
+
+    /**
+     * Returns a formatted header line.
+     * @access private
+     * @return string
+     */
+    function HeaderLine($name, $value) {
+        return $name . ": " . $value . $this->LE;
+    }
+
+    /**
+     * Returns a formatted mail line.
+     * @access private
+     * @return string
+     */
+    function TextLine($value) {
+        return $value . $this->LE;
+    }
+
+    /////////////////////////////////////////////////
+    // ATTACHMENT METHODS
+    /////////////////////////////////////////////////
+
+    /**
+     * Adds an attachment from a path on the filesystem.
+     * Returns false if the file could not be found
+     * or accessed.
+     * @param string $path Path to the attachment.
+     * @param string $name Overrides the attachment name.
+     * @param string $encoding File encoding (see $Encoding).
+     * @param string $type File extension (MIME) type.
+     * @return bool
+     */
+    function AddAttachment($path, $name = "", $encoding = "base64", 
+                           $type = "application/octet-stream") {
+        if(!@is_file($path))
+        {
+            $this->SetError($this->Lang("file_access") . $path);
+            return false;
+        }
+
+        $filename = basename($path);
+        if($name == "")
+            $name = $filename;
+
+        $cur = count($this->attachment);
+        $this->attachment[$cur][0] = $path;
+        $this->attachment[$cur][1] = $filename;
+        $this->attachment[$cur][2] = $name;
+        $this->attachment[$cur][3] = $encoding;
+        $this->attachment[$cur][4] = $type;
+        $this->attachment[$cur][5] = false; // isStringAttachment
+        $this->attachment[$cur][6] = "attachment";
+        $this->attachment[$cur][7] = 0;
+
+        return true;
+    }
+
+    /**
+     * Attaches all fs, string, and binary attachments to the message.
+     * Returns an empty string on failure.
+     * @access private
+     * @return string
+     */
+    function AttachAll() {
+        // Return text of body
+        $mime = array();
+
+        // Add all attachments
+        for($i = 0; $i < count($this->attachment); $i++)
+        {
+            // Check for string attachment
+            $bString = $this->attachment[$i][5];
+            if ($bString)
+                $string = $this->attachment[$i][0];
+            else
+                $path = $this->attachment[$i][0];
+
+            $filename    = $this->attachment[$i][1];
+            $name        = $this->attachment[$i][2];
+            $encoding    = $this->attachment[$i][3];
+            $type        = $this->attachment[$i][4];
+            $disposition = $this->attachment[$i][6];
+            $cid         = $this->attachment[$i][7];
+            
+            $mime[] = sprintf("--%s%s", $this->boundary[1], $this->LE);
+            $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $name, $this->LE);
+            $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE);
+
+            if($disposition == "inline")
+                $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
+
+            $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", 
+                              $disposition, $name, $this->LE.$this->LE);
+
+            // Encode as string attachment
+            if($bString)
+            {
+                $mime[] = $this->EncodeString($string, $encoding);
+                if($this->IsError()) { return ""; }
+                $mime[] = $this->LE.$this->LE;
+            }
+            else
+            {
+                $mime[] = $this->EncodeFile($path, $encoding);                
+                if($this->IsError()) { return ""; }
+                $mime[] = $this->LE.$this->LE;
+            }
+        }
+
+        $mime[] = sprintf("--%s--%s", $this->boundary[1], $this->LE);
+
+        return join("", $mime);
+    }
+    
+    /**
+     * Encodes attachment in requested format.  Returns an
+     * empty string on failure.
+     * @access private
+     * @return string
+     */
+    function EncodeFile ($path, $encoding = "base64") {
+        if(!@$fd = fopen($path, "rb"))
+        {
+            $this->SetError($this->Lang("file_open") . $path);
+            return "";
+        }
+        $magic_quotes = get_magic_quotes_runtime();
+        set_magic_quotes_runtime(0);
+        $file_buffer = fread($fd, filesize($path));
+        $file_buffer = $this->EncodeString($file_buffer, $encoding);
+        fclose($fd);
+        set_magic_quotes_runtime($magic_quotes);
+
+        return $file_buffer;
+    }
+
+    /**
+     * Encodes string to requested format. Returns an
+     * empty string on failure.
+     * @access private
+     * @return string
+     */
+    function EncodeString ($str, $encoding = "base64") {
+        $encoded = "";
+        switch(strtolower($encoding)) {
+          case "base64":
+              // chunk_split is found in PHP >= 3.0.6
+              $encoded = chunk_split(base64_encode($str), 76, $this->LE);
+              break;
+          case "7bit":
+          case "8bit":
+              $encoded = $this->FixEOL($str);
+              if (substr($encoded, -(strlen($this->LE))) != $this->LE)
+                $encoded .= $this->LE;
+              break;
+          case "binary":
+              $encoded = $str;
+              break;
+          case "quoted-printable":
+              $encoded = $this->EncodeQP($str);
+              break;
+          default:
+              $this->SetError($this->Lang("encoding") . $encoding);
+              break;
+        }
+        return $encoded;
+    }
+
+    /**
+     * Encode a header string to best of Q, B, quoted or none.  
+     * @access private
+     * @return string
+     */
+    function EncodeHeader ($str, $position = 'text') {
+      $x = 0;
+      
+      switch (strtolower($position)) {
+        case 'phrase':
+          if (!preg_match('/[\200-\377]/', $str)) {
+            // Can't use addslashes as we don't know what value has magic_quotes_sybase.
+            $encoded = addcslashes($str, "\0..\37\177\\\"");
+
+            if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str))
+              return ($encoded);
+            else
+              return ("\"$encoded\"");
+          }
+          $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
+          break;
+        case 'comment':
+          $x = preg_match_all('/[()"]/', $str, $matches);
+          // Fall-through
+        case 'text':
+        default:
+          $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
+          break;
+      }
+
+      if ($x == 0)
+        return ($str);
+
+      $maxlen = 75 - 7 - strlen($this->CharSet);
+      // Try to select the encoding which should produce the shortest output
+      if (strlen($str)/3 < $x) {
+        $encoding = 'B';
+        $encoded = base64_encode($str);
+        $maxlen -= $maxlen % 4;
+        $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
+      } else {
+        $encoding = 'Q';
+        $encoded = $this->EncodeQ($str, $position);
+        $encoded = $this->WrapText($encoded, $maxlen, true);
+        $encoded = str_replace("=".$this->LE, "\n", trim($encoded));
+      }
+
+      $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded);
+      $encoded = trim(str_replace("\n", $this->LE, $encoded));
+      
+      return $encoded;
+    }
+    
+    /**
+     * Encode string to quoted-printable.  
+     * @access private
+     * @return string
+     */
+    function EncodeQP ($str) {
+        $encoded = $this->FixEOL($str);
+        if (substr($encoded, -(strlen($this->LE))) != $this->LE)
+            $encoded .= $this->LE;
+
+        // Replace every high ascii, control and = characters
+        $encoded = preg_replace('/([\000-\010\013\014\016-\037\075\177-\377])/e',
+                  "'='.sprintf('%02X', ord('\\1'))", $encoded);
+        // Replace every spaces and tabs when it's the last character on a line
+        $encoded = preg_replace("/([\011\040])".$this->LE."/e",
+                  "'='.sprintf('%02X', ord('\\1')).'".$this->LE."'", $encoded);
+
+        // Maximum line length of 76 characters before CRLF (74 + space + '=')
+        $encoded = $this->WrapText($encoded, 74, true);
+		
+        return $encoded;
+    }
+
+    /**
+     * Encode string to q encoding.  
+     * @access private
+     * @return string
+     */
+    function EncodeQ ($str, $position = "text") {
+        // There should not be any EOL in the string
+        $encoded = preg_replace("[\r\n]", "", $str);
+        switch (strtolower($position)) {
+          case "phrase":
+            $encoded = preg_replace("/([^A-Za-z0-9!*+\/ -])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
+            break;
+          case "comment":
+            $encoded = preg_replace("/([\(\)\"])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
+          case "text":
+          default:
+            // Replace every high ascii, control =, ? and _ characters
+            $encoded = preg_replace('/([\000-\011\013\014\016-\037\075\077\137\177-\377])/e',
+                  "'='.sprintf('%02X', ord('\\1'))", $encoded);
+            break;
+        }
+        
+        // Replace every spaces to _ (more readable than =20)
+        $encoded = str_replace(" ", "_", $encoded);
+
+        return $encoded;
+    }
+
+    /**
+     * Adds a string or binary attachment (non-filesystem) to the list.
+     * This method can be used to attach ascii or binary data,
+     * such as a BLOB record from a database.
+     * @param string $string String attachment data.
+     * @param string $filename Name of the attachment.
+     * @param string $encoding File encoding (see $Encoding).
+     * @param string $type File extension (MIME) type.
+     * @return void
+     */
+    function AddStringAttachment($string, $filename, $encoding = "base64", 
+                                 $type = "application/octet-stream") {
+        // Append to $attachment array
+        $cur = count($this->attachment);
+        $this->attachment[$cur][0] = $string;
+        $this->attachment[$cur][1] = $filename;
+        $this->attachment[$cur][2] = $filename;
+        $this->attachment[$cur][3] = $encoding;
+        $this->attachment[$cur][4] = $type;
+        $this->attachment[$cur][5] = true; // isString
+        $this->attachment[$cur][6] = "attachment";
+        $this->attachment[$cur][7] = 0;
+    }
+    
+    /**
+     * Adds an embedded attachment.  This can include images, sounds, and 
+     * just about any other document.  Make sure to set the $type to an 
+     * image type.  For JPEG images use "image/jpeg" and for GIF images 
+     * use "image/gif".
+     * @param string $path Path to the attachment.
+     * @param string $cid Content ID of the attachment.  Use this to identify 
+     *        the Id for accessing the image in an HTML form.
+     * @param string $name Overrides the attachment name.
+     * @param string $encoding File encoding (see $Encoding).
+     * @param string $type File extension (MIME) type.  
+     * @return bool
+     */
+    function AddEmbeddedImage($path, $cid, $name = "", $encoding = "base64", 
+                              $type = "application/octet-stream") {
+    
+        if(!@is_file($path))
+        {
+            $this->SetError($this->Lang("file_access") . $path);
+            return false;
+        }
+
+        $filename = basename($path);
+        if($name == "")
+            $name = $filename;
+
+        // Append to $attachment array
+        $cur = count($this->attachment);
+        $this->attachment[$cur][0] = $path;
+        $this->attachment[$cur][1] = $filename;
+        $this->attachment[$cur][2] = $name;
+        $this->attachment[$cur][3] = $encoding;
+        $this->attachment[$cur][4] = $type;
+        $this->attachment[$cur][5] = false; // isStringAttachment
+        $this->attachment[$cur][6] = "inline";
+        $this->attachment[$cur][7] = $cid;
+    
+        return true;
+    }
+    
+    /**
+     * Returns true if an inline attachment is present.
+     * @access private
+     * @return bool
+     */
+    function InlineImageExists() {
+        $result = false;
+        for($i = 0; $i < count($this->attachment); $i++)
+        {
+            if($this->attachment[$i][6] == "inline")
+            {
+                $result = true;
+                break;
+            }
+        }
+        
+        return $result;
+    }
+
+    /////////////////////////////////////////////////
+    // MESSAGE RESET METHODS
+    /////////////////////////////////////////////////
+
+    /**
+     * Clears all recipients assigned in the TO array.  Returns void.
+     * @return void
+     */
+    function ClearAddresses() {
+        $this->to = array();
+    }
+
+    /**
+     * Clears all recipients assigned in the CC array.  Returns void.
+     * @return void
+     */
+    function ClearCCs() {
+        $this->cc = array();
+    }
+
+    /**
+     * Clears all recipients assigned in the BCC array.  Returns void.
+     * @return void
+     */
+    function ClearBCCs() {
+        $this->bcc = array();
+    }
+
+    /**
+     * Clears all recipients assigned in the ReplyTo array.  Returns void.
+     * @return void
+     */
+    function ClearReplyTos() {
+        $this->ReplyTo = array();
+    }
+
+    /**
+     * Clears all recipients assigned in the TO, CC and BCC
+     * array.  Returns void.
+     * @return void
+     */
+    function ClearAllRecipients() {
+        $this->to = array();
+        $this->cc = array();
+        $this->bcc = array();
+    }
+
+    /**
+     * Clears all previously set filesystem, string, and binary
+     * attachments.  Returns void.
+     * @return void
+     */
+    function ClearAttachments() {
+        $this->attachment = array();
+    }
+
+    /**
+     * Clears all custom headers.  Returns void.
+     * @return void
+     */
+    function ClearCustomHeaders() {
+        $this->CustomHeader = array();
+    }
+
+
+    /////////////////////////////////////////////////
+    // MISCELLANEOUS METHODS
+    /////////////////////////////////////////////////
+
+    /**
+     * Adds the error message to the error container.
+     * Returns void.
+     * @access private
+     * @return void
+     */
+    function SetError($msg) {
+        $this->error_count++;
+        $this->ErrorInfo = $msg;
+    }
+
+    /**
+     * Returns the proper RFC 822 formatted date. 
+     * @access private
+     * @return string
+     */
+    function RFCDate() {
+        $tz = date("Z");
+        $tzs = ($tz < 0) ? "-" : "+";
+        $tz = abs($tz);
+        $tz = ($tz/3600)*100 + ($tz%3600)/60;
+        $result = sprintf("%s %s%04d", date("D, j M Y H:i:s"), $tzs, $tz);
+
+        return $result;
+    }
+    
+    /**
+     * Returns the appropriate server variable.  Should work with both 
+     * PHP 4.1.0+ as well as older versions.  Returns an empty string 
+     * if nothing is found.
+     * @access private
+     * @return mixed
+     */
+    function ServerVar($varName) {
+        global $HTTP_SERVER_VARS;
+        global $HTTP_ENV_VARS;
+
+        if(!isset($_SERVER))
+        {
+            $_SERVER = $HTTP_SERVER_VARS;
+            if(!isset($_SERVER["REMOTE_ADDR"]))
+                $_SERVER = $HTTP_ENV_VARS; // must be Apache
+        }
+        
+        if(isset($_SERVER[$varName]))
+            return $_SERVER[$varName];
+        else
+            return "";
+    }
+
+    /**
+     * Returns the server hostname or 'localhost.localdomain' if unknown.
+     * @access private
+     * @return string
+     */
+    function ServerHostname() {
+        if ($this->Hostname != "")
+            $result = $this->Hostname;
+        elseif ($this->ServerVar('SERVER_NAME') != "")
+            $result = $this->ServerVar('SERVER_NAME');
+        else
+            $result = "localhost.localdomain";
+
+        return $result;
+    }
+
+    /**
+     * Returns a message in the appropriate language.
+     * @access private
+     * @return string
+     */
+    function Lang($key) {
+        if(count($this->language) < 1)
+            $this->SetLanguage("br"); // set the default language
+    
+        if(isset($this->language[$key]))
+            return $this->language[$key];
+        else
+            return "Language string failed to load: " . $key;
+    }
+    
+    /**
+     * Returns true if an error occurred.
+     * @return bool
+     */
+    function IsError() {
+        return ($this->error_count > 0);
+    }
+
+    /**
+     * Changes every end of line from CR or LF to CRLF.  
+     * @access private
+     * @return string
+     */
+    function FixEOL($str) {
+        $str = str_replace("\r\n", "\n", $str);
+        $str = str_replace("\r", "\n", $str);
+        $str = str_replace("\n", $this->LE, $str);
+        return $str;
+    }
+
+    /**
+     * Adds a custom header. 
+     * @return void
+     */
+    function AddCustomHeader($custom_header) {
+        $this->CustomHeader[] = explode(":", $custom_header, 2);
+    }
+}
+
+?>
Index: tags/expressoMail1_2/1.2211/inc/class.smtp.php
===================================================================
--- tags/expressoMail1_2/1.2211/inc/class.smtp.php	(revision 117)
+++ tags/expressoMail1_2/1.2211/inc/class.smtp.php	(revision 117)
@@ -0,0 +1,1045 @@
+<?php
+////////////////////////////////////////////////////
+// SMTP - PHP SMTP class
+//
+// Version 1.02
+//
+// Define an SMTP class that can be used to connect
+// and communicate with any SMTP server. It implements
+// all the SMTP functions defined in RFC821 except TURN.
+//
+// Author: Chris Ryan
+//
+// License: LGPL, see LICENSE
+////////////////////////////////////////////////////
+
+/**
+ * SMTP is rfc 821 compliant and implements all the rfc 821 SMTP
+ * commands except TURN which will always return a not implemented
+ * error. SMTP also provides some utility methods for sending mail
+ * to an SMTP server.
+ * @package PHPMailer
+ * @author Chris Ryan
+ */
+class SMTP
+{
+    /**
+     *  SMTP server port
+     *  @var int
+     */
+    var $SMTP_PORT = 25;
+    
+    /**
+     *  SMTP reply line ending
+     *  @var string
+     */
+    var $CRLF = "\r\n";
+    
+    /**
+     *  Sets whether debugging is turned on
+     *  @var bool
+     */
+    var $do_debug;       # the level of debug to perform
+
+    /**#@+
+     * @access private
+     */
+    var $smtp_conn;      # the socket to the server
+    var $error;          # error if any on the last call
+    var $helo_rply;      # the reply the server sent to us for HELO
+    /**#@-*/
+
+    /**
+     * Initialize the class so that the data is in a known state.
+     * @access public
+     * @return void
+     */
+    function SMTP() {
+        $this->smtp_conn = 0;
+        $this->error = null;
+        $this->helo_rply = null;
+
+        $this->do_debug = 0;
+    }
+
+    /*************************************************************
+     *                    CONNECTION FUNCTIONS                  *
+     ***********************************************************/
+
+    /**
+     * Connect to the server specified on the port specified.
+     * If the port is not specified use the default SMTP_PORT.
+     * If tval is specified then a connection will try and be
+     * established with the server for that number of seconds.
+     * If tval is not specified the default is 30 seconds to
+     * try on the connection.
+     *
+     * SMTP CODE SUCCESS: 220
+     * SMTP CODE FAILURE: 421
+     * @access public
+     * @return bool
+     */
+    function Connect($host,$port=0,$tval=30) {
+        # set the error val to null so there is no confusion
+        $this->error = null;
+
+        # make sure we are __not__ connected
+        if($this->connected()) {
+            # ok we are connected! what should we do?
+            # for now we will just give an error saying we
+            # are already connected
+            $this->error =
+                array("error" => "Already connected to a server");
+            return false;
+        }
+
+        if(empty($port)) {
+            $port = $this->SMTP_PORT;
+        }
+
+        #connect to the smtp server
+        $this->smtp_conn = fsockopen($host,    # the host of the server
+                                     $port,    # the port to use
+                                     $errno,   # error number if any
+                                     $errstr,  # error message if any
+                                     $tval);   # give up after ? secs
+        # verify we connected properly
+        if(empty($this->smtp_conn)) {
+            $this->error = array("error" => "Failed to connect to server",
+                                 "errno" => $errno,
+                                 "errstr" => $errstr);
+            if($this->do_debug >= 1) {
+                echo "SMTP -> ERROR: " . $this->error["error"] .
+                         ": $errstr ($errno)" . $this->CRLF;
+            }
+            return false;
+        }
+
+        # sometimes the SMTP server takes a little longer to respond
+        # so we will give it a longer timeout for the first read
+        // Windows still does not have support for this timeout function
+        if(substr(PHP_OS, 0, 3) != "WIN")
+           socket_set_timeout($this->smtp_conn, $tval, 0);
+
+        # get any announcement stuff
+        $announce = $this->get_lines();
+
+        # set the timeout  of any socket functions at 1/10 of a second
+        //if(function_exists("socket_set_timeout"))
+        //   socket_set_timeout($this->smtp_conn, 0, 100000);
+
+        if($this->do_debug >= 2) {
+            echo "SMTP -> FROM SERVER:" . $this->CRLF . $announce;
+        }
+
+        return true;
+    }
+
+    /**
+     * Performs SMTP authentication.  Must be run after running the
+     * Hello() method.  Returns true if successfully authenticated.
+     * @access public
+     * @return bool
+     */
+    function Authenticate($username, $password) {
+        // Start authentication
+        fputs($this->smtp_conn,"AUTH LOGIN" . $this->CRLF);
+
+        $rply = $this->get_lines();
+        $code = substr($rply,0,3);
+
+        if($code != 334) {
+            $this->error =
+                array("error" => "AUTH not accepted from server",
+                      "smtp_code" => $code,
+                      "smtp_msg" => substr($rply,4));
+            if($this->do_debug >= 1) {
+                echo "SMTP -> ERROR: " . $this->error["error"] .
+                         ": " . $rply . $this->CRLF;
+            }
+            return false;
+        }
+
+        // Send encoded username
+        fputs($this->smtp_conn, base64_encode($username) . $this->CRLF);
+
+        $rply = $this->get_lines();
+        $code = substr($rply,0,3);
+
+        if($code != 334) {
+            $this->error =
+                array("error" => "Username not accepted from server",
+                      "smtp_code" => $code,
+                      "smtp_msg" => substr($rply,4));
+            if($this->do_debug >= 1) {
+                echo "SMTP -> ERROR: " . $this->error["error"] .
+                         ": " . $rply . $this->CRLF;
+            }
+            return false;
+        }
+
+        // Send encoded password
+        fputs($this->smtp_conn, base64_encode($password) . $this->CRLF);
+
+        $rply = $this->get_lines();
+        $code = substr($rply,0,3);
+
+        if($code != 235) {
+            $this->error =
+                array("error" => "Password not accepted from server",
+                      "smtp_code" => $code,
+                      "smtp_msg" => substr($rply,4));
+            if($this->do_debug >= 1) {
+                echo "SMTP -> ERROR: " . $this->error["error"] .
+                         ": " . $rply . $this->CRLF;
+            }
+            return false;
+        }
+
+        return true;
+    }
+
+    /**
+     * Returns true if connected to a server otherwise false
+     * @access private
+     * @return bool
+     */
+    function Connected() {
+        if(!empty($this->smtp_conn)) {
+            $sock_status = socket_get_status($this->smtp_conn);
+            if($sock_status["eof"]) {
+                # hmm this is an odd situation... the socket is
+                # valid but we aren't connected anymore
+                if($this->do_debug >= 1) {
+                    echo "SMTP -> NOTICE:" . $this->CRLF .
+                         "EOF caught while checking if connected";
+                }
+                $this->Close();
+                return false;
+            }
+            return true; # everything looks good
+        }
+        return false;
+    }
+
+    /**
+     * Closes the socket and cleans up the state of the class.
+     * It is not considered good to use this function without
+     * first trying to use QUIT.
+     * @access public
+     * @return void
+     */
+    function Close() {
+        $this->error = null; # so there is no confusion
+        $this->helo_rply = null;
+        if(!empty($this->smtp_conn)) {
+            # close the connection and cleanup
+            fclose($this->smtp_conn);
+            $this->smtp_conn = 0;
+        }
+    }
+
+
+    /***************************************************************
+     *                        SMTP COMMANDS                       *
+     *************************************************************/
+
+    /**
+     * Issues a data command and sends the msg_data to the server
+     * finializing the mail transaction. $msg_data is the message
+     * that is to be send with the headers. Each header needs to be
+     * on a single line followed by a <CRLF> with the message headers
+     * and the message body being seperated by and additional <CRLF>.
+     *
+     * Implements rfc 821: DATA <CRLF>
+     *
+     * SMTP CODE INTERMEDIATE: 354
+     *     [data]
+     *     <CRLF>.<CRLF>
+     *     SMTP CODE SUCCESS: 250
+     *     SMTP CODE FAILURE: 552,554,451,452
+     * SMTP CODE FAILURE: 451,554
+     * SMTP CODE ERROR  : 500,501,503,421
+     * @access public
+     * @return bool
+     */
+    function Data($msg_data) {    	
+        $this->error = null; # so no confusion is caused
+
+        if(!$this->connected()) {
+            $this->error = array(
+                    "error" => "Called Data() without being connected");
+            return false;
+        }
+
+        fputs($this->smtp_conn,"DATA" . $this->CRLF);
+
+        $rply = $this->get_lines();
+        $code = substr($rply,0,3);
+
+        if($this->do_debug >= 2) {
+            echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
+        }
+
+        if($code != 354) {
+            $this->error =
+                array("error" => "DATA command not accepted from server",
+                      "smtp_code" => $code,
+                      "smtp_msg" => substr($rply,4));
+            if($this->do_debug >= 1) {
+                echo "SMTP -> ERROR: " . $this->error["error"] .
+                         ": " . $rply . $this->CRLF;
+            }
+            return false;
+        }
+
+        # the server is ready to accept data!
+        # according to rfc 821 we should not send more than 1000
+        # including the CRLF
+        # characters on a single line so we will break the data up
+        # into lines by \r and/or \n then if needed we will break
+        # each of those into smaller lines to fit within the limit.
+        # in addition we will be looking for lines that start with
+        # a period '.' and append and additional period '.' to that
+        # line. NOTE: this does not count towards are limit.
+
+        # normalize the line breaks so we know the explode works
+        $msg_data = str_replace("\r\n","\n",$msg_data);
+        $msg_data = str_replace("\r","\n",$msg_data);
+        $lines = explode("\n",$msg_data);
+
+        # we need to find a good way to determine is headers are
+        # in the msg_data or if it is a straight msg body
+        # currently I'm assuming rfc 822 definitions of msg headers
+        # and if the first field of the first line (':' sperated)
+        # does not contain a space then it _should_ be a header
+        # and we can process all lines before a blank "" line as
+        # headers.
+        $field = substr($lines[0],0,strpos($lines[0],":"));
+        $in_headers = false;
+        if(!empty($field) && !strstr($field," ")) {
+            $in_headers = true;
+        }
+
+        $max_line_length = 998; # used below; set here for ease in change
+
+        while(list(,$line) = @each($lines)) {
+            $lines_out = null;
+            if($line == "" && $in_headers) {
+                $in_headers = false;
+            }
+            # ok we need to break this line up into several
+            # smaller lines
+            while(strlen($line) > $max_line_length) {
+                $pos = strrpos(substr($line,0,$max_line_length)," ");
+
+                # Patch to fix DOS attack
+                if(!$pos) {
+                    $pos = $max_line_length - 1;
+                }
+
+                $lines_out[] = substr($line,0,$pos);
+                $line = substr($line,$pos + 1);
+                # if we are processing headers we need to
+                # add a LWSP-char to the front of the new line
+                # rfc 822 on long msg headers
+                if($in_headers) {
+                    $line = "\t" . $line;
+                }
+            }
+            $lines_out[] = $line;
+			$messageCode = "";
+            # now send the lines to the server
+            while(list(,$line_out) = @each($lines_out)) {
+                if(strlen($line_out) > 0)
+                {
+                    if(substr($line_out, 0, 1) == ".") {
+                        $line_out = "." . $line_out;
+                    }
+                }
+                fputs($this->smtp_conn,$line_out . $this->CRLF);
+            }
+        }
+		
+        # ok all the message data has been sent so lets get this
+        # over with aleady
+        fputs($this->smtp_conn, $this->CRLF . "." . $this->CRLF);
+
+        $rply = $this->get_lines();
+        $code = substr($rply,0,3);
+
+        if($this->do_debug >= 2) {
+            echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
+        }
+
+        if($code != 250) {
+            $this->error =
+                array("error" => "DATA not accepted from server",
+                      "smtp_code" => $code,
+                      "smtp_msg" => substr($rply,4));
+            if($this->do_debug >= 1) {
+                echo "SMTP -> ERROR: " . $this->error["error"] .
+                         ": " . $rply . $this->CRLF;
+            }
+            return false;
+        }
+        return $code == 250 ? substr($rply,-13) : true;
+    }
+
+    /**
+     * Expand takes the name and asks the server to list all the
+     * people who are members of the _list_. Expand will return
+     * back and array of the result or false if an error occurs.
+     * Each value in the array returned has the format of:
+     *     [ <full-name> <sp> ] <path>
+     * The definition of <path> is defined in rfc 821
+     *
+     * Implements rfc 821: EXPN <SP> <string> <CRLF>
+     *
+     * SMTP CODE SUCCESS: 250
+     * SMTP CODE FAILURE: 550
+     * SMTP CODE ERROR  : 500,501,502,504,421
+     * @access public
+     * @return string array
+     */
+    function Expand($name) {
+        $this->error = null; # so no confusion is caused
+
+        if(!$this->connected()) {
+            $this->error = array(
+                    "error" => "Called Expand() without being connected");
+            return false;
+        }
+
+        fputs($this->smtp_conn,"EXPN " . $name . $this->CRLF);
+
+        $rply = $this->get_lines();
+        $code = substr($rply,0,3);
+
+        if($this->do_debug >= 2) {
+            echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
+        }
+
+        if($code != 250) {
+            $this->error =
+                array("error" => "EXPN not accepted from server",
+                      "smtp_code" => $code,
+                      "smtp_msg" => substr($rply,4));
+            if($this->do_debug >= 1) {
+                echo "SMTP -> ERROR: " . $this->error["error"] .
+                         ": " . $rply . $this->CRLF;
+            }
+            return false;
+        }
+
+        # parse the reply and place in our array to return to user
+        $entries = explode($this->CRLF,$rply);
+        while(list(,$l) = @each($entries)) {
+            $list[] = substr($l,4);
+        }
+
+        return $list;
+    }
+
+    /**
+     * Sends the HELO command to the smtp server.
+     * This makes sure that we and the server are in
+     * the same known state.
+     *
+     * Implements from rfc 821: HELO <SP> <domain> <CRLF>
+     *
+     * SMTP CODE SUCCESS: 250
+     * SMTP CODE ERROR  : 500, 501, 504, 421
+     * @access public
+     * @return bool
+     */
+    function Hello($host="") {
+        $this->error = null; # so no confusion is caused
+
+        if(!$this->connected()) {
+            $this->error = array(
+                    "error" => "Called Hello() without being connected");
+            return false;
+        }
+
+        # if a hostname for the HELO wasn't specified determine
+        # a suitable one to send
+        if(empty($host)) {
+            # we need to determine some sort of appopiate default
+            # to send to the server
+            $host = "localhost";
+        }
+
+        // Send extended hello first (RFC 2821)
+        if(!$this->SendHello("EHLO", $host))
+        {
+            if(!$this->SendHello("HELO", $host))
+                return false;
+        }
+
+        return true;
+    }
+
+    /**
+     * Sends a HELO/EHLO command.
+     * @access private
+     * @return bool
+     */
+    function SendHello($hello, $host) {
+        fputs($this->smtp_conn, $hello . " " . $host . $this->CRLF);
+
+        $rply = $this->get_lines();
+        $code = substr($rply,0,3);
+
+        if($this->do_debug >= 2) {
+            echo "SMTP -> FROM SERVER: " . $this->CRLF . $rply;
+        }
+
+        if($code != 250) {
+            $this->error =
+                array("error" => $hello . " not accepted from server",
+                      "smtp_code" => $code,
+                      "smtp_msg" => substr($rply,4));
+            if($this->do_debug >= 1) {
+                echo "SMTP -> ERROR: " . $this->error["error"] .
+                         ": " . $rply . $this->CRLF;
+            }
+            return false;
+        }
+
+        $this->helo_rply = $rply;
+        
+        return true;
+    }
+
+    /**
+     * Gets help information on the keyword specified. If the keyword
+     * is not specified then returns generic help, ussually contianing
+     * A list of keywords that help is available on. This function
+     * returns the results back to the user. It is up to the user to
+     * handle the returned data. If an error occurs then false is
+     * returned with $this->error set appropiately.
+     *
+     * Implements rfc 821: HELP [ <SP> <string> ] <CRLF>
+     *
+     * SMTP CODE SUCCESS: 211,214
+     * SMTP CODE ERROR  : 500,501,502,504,421
+     * @access public
+     * @return string
+     */
+    function Help($keyword="") {
+        $this->error = null; # to avoid confusion
+
+        if(!$this->connected()) {
+            $this->error = array(
+                    "error" => "Called Help() without being connected");
+            return false;
+        }
+
+        $extra = "";
+        if(!empty($keyword)) {
+            $extra = " " . $keyword;
+        }
+
+        fputs($this->smtp_conn,"HELP" . $extra . $this->CRLF);
+
+        $rply = $this->get_lines();
+        $code = substr($rply,0,3);
+
+        if($this->do_debug >= 2) {
+            echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
+        }
+
+        if($code != 211 && $code != 214) {
+            $this->error =
+                array("error" => "HELP not accepted from server",
+                      "smtp_code" => $code,
+                      "smtp_msg" => substr($rply,4));
+            if($this->do_debug >= 1) {
+                echo "SMTP -> ERROR: " . $this->error["error"] .
+                         ": " . $rply . $this->CRLF;
+            }
+            return false;
+        }
+
+        return $rply;
+    }
+
+    /**
+     * Starts a mail transaction from the email address specified in
+     * $from. Returns true if successful or false otherwise. If True
+     * the mail transaction is started and then one or more Recipient
+     * commands may be called followed by a Data command.
+     *
+     * Implements rfc 821: MAIL <SP> FROM:<reverse-path> <CRLF>
+     *
+     * SMTP CODE SUCCESS: 250
+     * SMTP CODE SUCCESS: 552,451,452
+     * SMTP CODE SUCCESS: 500,501,421
+     * @access public
+     * @return bool
+     */
+    function Mail($from) {
+        $this->error = null; # so no confusion is caused
+
+        if(!$this->connected()) {
+            $this->error = array(
+                    "error" => "Called Mail() without being connected");
+            return false;
+        }
+
+        fputs($this->smtp_conn,"MAIL FROM:<" . $from . ">" . $this->CRLF);
+
+        $rply = $this->get_lines();
+        $code = substr($rply,0,3);
+
+        if($this->do_debug >= 2) {
+            echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
+        }
+
+        if($code != 250) {
+            $this->error =
+                array("error" => "MAIL not accepted from server",
+                      "smtp_code" => $code,
+                      "smtp_msg" => substr($rply,4));
+            if($this->do_debug >= 1) {
+                echo "SMTP -> ERROR: " . $this->error["error"] .
+                         ": " . $rply . $this->CRLF;
+            }
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * Sends the command NOOP to the SMTP server.
+     *
+     * Implements from rfc 821: NOOP <CRLF>
+     *
+     * SMTP CODE SUCCESS: 250
+     * SMTP CODE ERROR  : 500, 421
+     * @access public
+     * @return bool
+     */
+    function Noop() {
+        $this->error = null; # so no confusion is caused
+
+        if(!$this->connected()) {
+            $this->error = array(
+                    "error" => "Called Noop() without being connected");
+            return false;
+        }
+
+        fputs($this->smtp_conn,"NOOP" . $this->CRLF);
+
+        $rply = $this->get_lines();
+        $code = substr($rply,0,3);
+
+        if($this->do_debug >= 2) {
+            echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
+        }
+
+        if($code != 250) {
+            $this->error =
+                array("error" => "NOOP not accepted from server",
+                      "smtp_code" => $code,
+                      "smtp_msg" => substr($rply,4));
+            if($this->do_debug >= 1) {
+                echo "SMTP -> ERROR: " . $this->error["error"] .
+                         ": " . $rply . $this->CRLF;
+            }
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * Sends the quit command to the server and then closes the socket
+     * if there is no error or the $close_on_error argument is true.
+     *
+     * Implements from rfc 821: QUIT <CRLF>
+     *
+     * SMTP CODE SUCCESS: 221
+     * SMTP CODE ERROR  : 500
+     * @access public
+     * @return bool
+     */
+    function Quit($close_on_error=true) {
+        $this->error = null; # so there is no confusion
+
+        if(!$this->connected()) {
+            $this->error = array(
+                    "error" => "Called Quit() without being connected");
+            return false;
+        }
+
+        # send the quit command to the server
+        fputs($this->smtp_conn,"quit" . $this->CRLF);
+
+        # get any good-bye messages
+        $byemsg = $this->get_lines();
+
+        if($this->do_debug >= 2) {
+            echo "SMTP -> FROM SERVER:" . $this->CRLF . $byemsg;
+        }
+
+        $rval = true;
+        $e = null;
+
+        $code = substr($byemsg,0,3);
+        if($code != 221) {
+            # use e as a tmp var cause Close will overwrite $this->error
+            $e = array("error" => "SMTP server rejected quit command",
+                       "smtp_code" => $code,
+                       "smtp_rply" => substr($byemsg,4));
+            $rval = false;
+            if($this->do_debug >= 1) {
+                echo "SMTP -> ERROR: " . $e["error"] . ": " .
+                         $byemsg . $this->CRLF;
+            }
+        }
+
+        if(empty($e) || $close_on_error) {
+            $this->Close();
+        }
+
+        return $rval;
+    }
+
+    /**
+     * Sends the command RCPT to the SMTP server with the TO: argument of $to.
+     * Returns true if the recipient was accepted false if it was rejected.
+     *
+     * Implements from rfc 821: RCPT <SP> TO:<forward-path> <CRLF>
+     *
+     * SMTP CODE SUCCESS: 250,251
+     * SMTP CODE FAILURE: 550,551,552,553,450,451,452
+     * SMTP CODE ERROR  : 500,501,503,421
+     * @access public
+     * @return bool
+     */
+    function Recipient($to) {
+        $this->error = null; # so no confusion is caused
+
+        if(!$this->connected()) {
+            $this->error = array(
+                    "error" => "Called Recipient() without being connected");
+            return false;
+        }
+
+        fputs($this->smtp_conn,"RCPT TO:<" . $to . ">" . $this->CRLF);
+
+        $rply = $this->get_lines();
+        $code = substr($rply,0,3);
+
+        if($this->do_debug >= 2) {
+            echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
+        }
+
+        if($code != 250 && $code != 251) {
+            $this->error =
+                array("error" => "RCPT not accepted from server",
+                      "smtp_code" => $code,
+                      "smtp_msg" => substr($rply,4));
+            if($this->do_debug >= 1) {
+                echo "SMTP -> ERROR: " . $this->error["error"] .
+                         ": " . $rply . $this->CRLF;
+            }
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * Sends the RSET command to abort and transaction that is
+     * currently in progress. Returns true if successful false
+     * otherwise.
+     *
+     * Implements rfc 821: RSET <CRLF>
+     *
+     * SMTP CODE SUCCESS: 250
+     * SMTP CODE ERROR  : 500,501,504,421
+     * @access public
+     * @return bool
+     */
+    function Reset() {
+        $this->error = null; # so no confusion is caused
+
+        if(!$this->connected()) {
+            $this->error = array(
+                    "error" => "Called Reset() without being connected");
+            return false;
+        }
+
+        fputs($this->smtp_conn,"RSET" . $this->CRLF);
+
+        $rply = $this->get_lines();
+        $code = substr($rply,0,3);
+
+        if($this->do_debug >= 2) {
+            echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
+        }
+
+        if($code != 250) {
+            $this->error =
+                array("error" => "RSET failed",
+                      "smtp_code" => $code,
+                      "smtp_msg" => substr($rply,4));
+            if($this->do_debug >= 1) {
+                echo "SMTP -> ERROR: " . $this->error["error"] .
+                         ": " . $rply . $this->CRLF;
+            }
+            return false;
+        }
+
+        return true;
+    }
+
+    /**
+     * Starts a mail transaction from the email address specified in
+     * $from. Returns true if successful or false otherwise. If True
+     * the mail transaction is started and then one or more Recipient
+     * commands may be called followed by a Data command. This command
+     * will send the message to the users terminal if they are logged
+     * in.
+     *
+     * Implements rfc 821: SEND <SP> FROM:<reverse-path> <CRLF>
+     *
+     * SMTP CODE SUCCESS: 250
+     * SMTP CODE SUCCESS: 552,451,452
+     * SMTP CODE SUCCESS: 500,501,502,421
+     * @access public
+     * @return bool
+     */
+    function Send($from) {
+        $this->error = null; # so no confusion is caused
+
+        if(!$this->connected()) {
+            $this->error = array(
+                    "error" => "Called Send() without being connected");
+            return false;
+        }
+
+        fputs($this->smtp_conn,"SEND FROM:" . $from . $this->CRLF);
+
+        $rply = $this->get_lines();
+        $code = substr($rply,0,3);
+
+        if($this->do_debug >= 2) {
+            echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
+        }
+
+        if($code != 250) {
+            $this->error =
+                array("error" => "SEND not accepted from server",
+                      "smtp_code" => $code,
+                      "smtp_msg" => substr($rply,4));
+            if($this->do_debug >= 1) {
+                echo "SMTP -> ERROR: " . $this->error["error"] .
+                         ": " . $rply . $this->CRLF;
+            }
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * Starts a mail transaction from the email address specified in
+     * $from. Returns true if successful or false otherwise. If True
+     * the mail transaction is started and then one or more Recipient
+     * commands may be called followed by a Data command. This command
+     * will send the message to the users terminal if they are logged
+     * in and send them an email.
+     *
+     * Implements rfc 821: SAML <SP> FROM:<reverse-path> <CRLF>
+     *
+     * SMTP CODE SUCCESS: 250
+     * SMTP CODE SUCCESS: 552,451,452
+     * SMTP CODE SUCCESS: 500,501,502,421
+     * @access public
+     * @return bool
+     */
+    function SendAndMail($from) {
+        $this->error = null; # so no confusion is caused
+
+        if(!$this->connected()) {
+            $this->error = array(
+                "error" => "Called SendAndMail() without being connected");
+            return false;
+        }
+
+        fputs($this->smtp_conn,"SAML FROM:" . $from . $this->CRLF);
+
+        $rply = $this->get_lines();
+        $code = substr($rply,0,3);
+
+        if($this->do_debug >= 2) {
+            echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
+        }
+
+        if($code != 250) {
+            $this->error =
+                array("error" => "SAML not accepted from server",
+                      "smtp_code" => $code,
+                      "smtp_msg" => substr($rply,4));
+            if($this->do_debug >= 1) {
+                echo "SMTP -> ERROR: " . $this->error["error"] .
+                         ": " . $rply . $this->CRLF;
+            }
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * Starts a mail transaction from the email address specified in
+     * $from. Returns true if successful or false otherwise. If True
+     * the mail transaction is started and then one or more Recipient
+     * commands may be called followed by a Data command. This command
+     * will send the message to the users terminal if they are logged
+     * in or mail it to them if they are not.
+     *
+     * Implements rfc 821: SOML <SP> FROM:<reverse-path> <CRLF>
+     *
+     * SMTP CODE SUCCESS: 250
+     * SMTP CODE SUCCESS: 552,451,452
+     * SMTP CODE SUCCESS: 500,501,502,421
+     * @access public
+     * @return bool
+     */
+    function SendOrMail($from) {
+        $this->error = null; # so no confusion is caused
+
+        if(!$this->connected()) {
+            $this->error = array(
+                "error" => "Called SendOrMail() without being connected");
+            return false;
+        }
+
+        fputs($this->smtp_conn,"SOML FROM:" . $from . $this->CRLF);
+
+        $rply = $this->get_lines();
+        $code = substr($rply,0,3);
+
+        if($this->do_debug >= 2) {
+            echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
+        }
+
+        if($code != 250) {
+            $this->error =
+                array("error" => "SOML not accepted from server",
+                      "smtp_code" => $code,
+                      "smtp_msg" => substr($rply,4));
+            if($this->do_debug >= 1) {
+                echo "SMTP -> ERROR: " . $this->error["error"] .
+                         ": " . $rply . $this->CRLF;
+            }
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * This is an optional command for SMTP that this class does not
+     * support. This method is here to make the RFC821 Definition
+     * complete for this class and __may__ be implimented in the future
+     *
+     * Implements from rfc 821: TURN <CRLF>
+     *
+     * SMTP CODE SUCCESS: 250
+     * SMTP CODE FAILURE: 502
+     * SMTP CODE ERROR  : 500, 503
+     * @access public
+     * @return bool
+     */
+    function Turn() {
+        $this->error = array("error" => "This method, TURN, of the SMTP ".
+                                        "is not implemented");
+        if($this->do_debug >= 1) {
+            echo "SMTP -> NOTICE: " . $this->error["error"] . $this->CRLF;
+        }
+        return false;
+    }
+
+    /**
+     * Verifies that the name is recognized by the server.
+     * Returns false if the name could not be verified otherwise
+     * the response from the server is returned.
+     *
+     * Implements rfc 821: VRFY <SP> <string> <CRLF>
+     *
+     * SMTP CODE SUCCESS: 250,251
+     * SMTP CODE FAILURE: 550,551,553
+     * SMTP CODE ERROR  : 500,501,502,421
+     * @access public
+     * @return int
+     */
+    function Verify($name) {
+        $this->error = null; # so no confusion is caused
+
+        if(!$this->connected()) {
+            $this->error = array(
+                    "error" => "Called Verify() without being connected");
+            return false;
+        }
+
+        fputs($this->smtp_conn,"VRFY " . $name . $this->CRLF);
+
+        $rply = $this->get_lines();
+        $code = substr($rply,0,3);
+
+        if($this->do_debug >= 2) {
+            echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
+        }
+
+        if($code != 250 && $code != 251) {
+            $this->error =
+                array("error" => "VRFY failed on name '$name'",
+                      "smtp_code" => $code,
+                      "smtp_msg" => substr($rply,4));
+            if($this->do_debug >= 1) {
+                echo "SMTP -> ERROR: " . $this->error["error"] .
+                         ": " . $rply . $this->CRLF;
+            }
+            return false;
+        }
+        return $rply;
+    }
+
+    /*******************************************************************
+     *                       INTERNAL FUNCTIONS                       *
+     ******************************************************************/
+
+    /**
+     * Read in as many lines as possible
+     * either before eof or socket timeout occurs on the operation.
+     * With SMTP we can tell if we have more lines to read if the
+     * 4th character is '-' symbol. If it is a space then we don't
+     * need to read anything else.
+     * @access private
+     * @return string
+     */
+    function get_lines() {
+        $data = "";
+        while($str = fgets($this->smtp_conn,515)) {
+            if($this->do_debug >= 4) {
+                echo "SMTP -> get_lines(): \$data was \"$data\"" .
+                         $this->CRLF;
+                echo "SMTP -> get_lines(): \$str is \"$str\"" .
+                         $this->CRLF;
+            }
+            $data .= $str;
+            if($this->do_debug >= 4) {
+                echo "SMTP -> get_lines(): \$data is \"$data\"" . $this->CRLF;
+            }
+            # if the 4th character is a space then we are done reading
+            # so just break the loop
+            if(substr($str,3,1) == " ") { break; }
+        }
+        return $data;
+    }
+
+}
+
+
+ ?>
Index: tags/expressoMail1_2/1.2211/inc/show_user_photo.php
===================================================================
--- tags/expressoMail1_2/1.2211/inc/show_user_photo.php	(revision 175)
+++ tags/expressoMail1_2/1.2211/inc/show_user_photo.php	(revision 175)
@@ -0,0 +1,64 @@
+<?php
+	function ldapRebind($ldap_connection, $ldap_url)
+	{
+		@ldap_bind($ldap_connection, $_SESSION['phpgw_info']['expressomail']['ldap_server']['acc'],$_SESSION['phpgw_info']['expressomail']['ldap_server']['pw']);
+	}
+
+	if ($_SESSION['phpgw_info']['expressomail']['user']['account_lid'] == '')
+		exit;
+	
+	$mail = $_GET['mail'];
+	
+	if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)+$", $mail))
+		exit;
+	
+	$ldap_host 	= $_SESSION['phpgw_info']['expressomail']['ldap_server']['host'];
+	$ldap_context = $_SESSION['phpgw_info']['expressomail']['ldap_server']['dn'];
+	
+	$ldap_conn=ldap_connect($ldap_host);
+	ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
+	ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 1);
+	ldap_set_rebind_proc($ldap_conn, ldapRebind);
+	
+	$r=ldap_bind($ldap_conn, $_SESSION['phpgw_info']['expressomail']['ldap_server']['acc'],$_SESSION['phpgw_info']['expressomail']['ldap_server']['pw']);
+	
+	if (!$r)
+	{
+		echo 'Sem BIND: ' . ldap_error ( $ldap_conn );
+		exit;
+	}
+
+	$justthese = array("jpegPhoto");
+	$filter="(mail=$mail)";
+	$search=ldap_search($ldap_conn, $ldap_context, $filter, $justthese);
+
+	$entry = ldap_first_entry($ldap_conn, $search);
+	$contact = ldap_get_attributes($ldap_conn, $entry);
+	
+	if($contact['jpegPhoto'])
+	{
+		$contact['jpegPhoto'] = ldap_get_values_len ($ldap_conn, $entry, "jpegPhoto");
+		$image = imagecreatefromstring ($contact['jpegPhoto'][0]); 
+	}
+	else
+	{
+		$loadFile = "../templates/default/images/photo.png";
+		$image = imagecreatefrompng($loadFile);
+	}
+	
+	header("Content-Type: image/jpeg");
+	
+ 	$pic = $image;
+	if ($pic)
+	{
+		$width = imagesx($pic);
+		$height = imagesy($pic);
+		$twidth = 60; # width of the thumb 160 pixel
+		$theight = $twidth * $height / $width; # calculate height
+		$thumb = imagecreatetruecolor ($twidth, $theight);
+		imagecopyresampled($thumb, $pic, 0, 0, 0, 0,$twidth, $theight, $width, $height); # resize image into thumb
+		imagejpeg($thumb,"",80); # Thumbnail as JPEG
+	}
+														    
+	ldap_close($ldap_conn);
+?>
Index: tags/expressoMail1_2/1.2211/js/search.js
===================================================================
--- tags/expressoMail1_2/1.2211/js/search.js	(revision 271)
+++ tags/expressoMail1_2/1.2211/js/search.js	(revision 271)
@@ -0,0 +1,642 @@
+/**************************************************************************\
+ Início 
+\**************************************************************************/
+	function searchE(){
+		this.searchW   = new Array;
+		this.name_box_search = "";
+		this.all_boxes = new Array;
+		this.type = "";
+		this.fields = new Array("_ass","_de","_body","_para","_cc","_cco");
+	}
+	var search_tabs = 0; // Count the number of seach tabs
+	
+	//Monta os forms dentro da janela;
+	searchE.prototype.showForms = function(value){
+		// Principal
+		if(!Element("window_search")) {
+			var form_search = document.createElement("DIV");
+			form_search.style.visibility = 'hidden';
+			form_search.style.top = '0px';
+			form_search.style.left = '0px';
+			form_search.id = "window_search";
+			document.body.appendChild(form_search);			
+		}
+		
+		// Pesquisa
+		if(!Element("div_form_search")){
+			var div_form_search = document.createElement("DIV");
+			div_form_search.id = "div_form_search";
+			div_form_search.style.position = "absolute";
+			div_form_search.style.left = "10px";
+			div_form_search.style.top  = "10px";
+			div_form_search.style.width = "635px";
+			div_form_search.style.height = "200px";
+			div_form_search.style.borderStyle = "outset";
+			div_form_search.style.borderColor = "black";
+			div_form_search.style.borderWidth = "1px";
+			div_form_search.style.overflow = "hidden";
+			div_form_search.innerHTML = "";
+			var call_form_search = EsearchE.mount_form();
+			div_form_search.appendChild(call_form_search);
+			form_search.appendChild(div_form_search);
+
+		}	
+		
+		if(!Element("div_button_search")){
+			var div_button_search    = document.createElement("DIV");
+				div_button_search.id = "div_button_search";
+				div_button_search.style.position = "absolute";
+				div_button_search.style.left = "10px";
+				div_button_search.style.top = "223px";
+				div_button_search.style.width = "600px";
+				div_button_search.style.height = "25px";
+				div_button_search.innerHTML = "<table border='0' width='50%' cellpadding='0' cellspacing='0' align='right'>"+
+											  "<tr>"+
+											  "<td><input type='button' value=" + get_lang('Search') + " onclick='EsearchE.func_search()'></td>"+
+											  "<td><input type='button' value=" + get_lang('Clean') + " onclick='EsearchE.func_clean()'></td>"+
+											  "<td><input type='button' value=" + get_lang('Close') + " onclick='EsearchE.func_close(\"hidden\")'></td>"+
+											  "</tr>"+
+											  "</table>";
+				form_search.appendChild(div_button_search);
+		}
+		
+		if(!Element("table_layer")){
+			var table_layer    = "";
+		}
+		
+		if(value == "")
+			EsearchE.showWindow(Element("window_search"));
+	
+		// Cria as caixas postais;
+		EsearchE.mount_folders();
+
+		if(value){
+			Element("check_all_msg").checked = true;
+			EsearchE.all_mailboxes();
+			EsearchE.func_search(value);
+		}
+
+	}
+	
+	//Form
+	searchE.prototype.mount_form = function(value){
+		var form_sch = document.createElement("FORM");
+		form_sch.id  = "form_sch";
+		form_sch.innerHTML = "<table id='table_princ' border='0' cellpading='0' cellspacing='0' align='center'>"+
+						     "<tr>"+
+						     "<td colspan='2'><b>" + get_lang('Inform your search in the text fields') + " :</b></td>"+
+						     "<td rowspan='7'>&nbsp"+
+						     "</td>"+
+						     "<td rowspan='8'>"+
+						     "<table border='0' cellpading='0' cellspacing='0'>"+
+						     "<tr>"+
+						     "<td colspan='3' valign='top'>&nbsp;<b>" + get_lang('Search the messages in these folders') + " :</b></td>"+
+						     "</tr>"+
+						     "<tr>"+
+						     "<td valign='top'><div id='folders' style='width:160px; height:150px'></div></td>"+
+						     "<td>"+
+						     "<input type='button' id='incluir' name='incluir' value='>>' onclick='EsearchE.add_mailboxes()'><br>"+
+						     "<input type='button' id='excluir' name='excluir' value='<<' onclick='EsearchE.del_mailboxes()'></td>"+
+						     "</td>"+
+						     "<td><select multiple id='sel_search_nm_box1' name='sel_search_nm_box1' size='10' style='width:160px'></select></td>"+
+						     "</tr>"+
+						     "<tr>"+
+						     "<td valign='top'><input type='checkBox' id='check_all_msg' name='check_all_msg' onclick='EsearchE.all_mailboxes()'><b>" + get_lang('In all the folders') + "</b></td>"+
+						     "</tr>"+
+						     "</table>"+
+						     "</td>"+
+						     "</tr>"+
+						     "<tr>"+
+						     "<td align='right'>" + get_lang('From') + " .: </td>"+
+						     "<td><input type='text' id='txt_de' size='20'></td>"+
+						     "</tr>"+
+						     "<tr>"+
+						     "<td align='right'>" + get_lang('To') + ".: </td>"+
+						     "<td><input type='text' id='txt_para' size='20'></td>"+
+						     "</tr>"+						     
+						     "<tr>"+
+						     "<td align='right'>" + get_lang('Cc') + " .: </td>"+
+						     "<td><input type='text' id='txt_cc' size='20'></td>"+
+						     "</tr>"+
+						     "<tr>"+
+						     "<td align='right'>" + get_lang('Subject') + " .: </td>"+
+						     "<td><input type='text' id='txt_ass' size='20'></td>"+
+						     "</tr>"+
+						     "<tr>"+
+ 							 "<td align='right'>" + get_lang('Message body') + " .:</td>"+
+						     "<td><input type='text' id='txt_body' size='20'></td>"+
+						     "</tr>"+
+						     "</table>";
+		return form_sch;
+	}
+
+	// Pastas;
+	searchE.prototype.mount_folders = function(){
+		connector.loadScript("TreeS");
+
+		if( Element("div_folders_search") == null){
+			var div_folders = document.createElement("DIV");
+				div_folders.id = "div_folders_search";
+				div_folders.style.width = "155px";
+				div_folders.style.height = "152px";
+				div_folders.style.borderStyle = "outset";
+				div_folders.style.borderColor = "black";
+				div_folders.style.borderWidth = "1px";
+				div_folders.style.background  = "#F7F7F7";
+				div_folders.style.overflow = "auto";
+				div_folders.innerHTML = "";
+				var dest_div = Element("folders");
+				dest_div.appendChild(div_folders);
+		}		
+		ttree.make_tree(folders,"div_folders_search","_folders_tree_search","","","","");
+	}
+	
+	//This func returns the most recent date
+	function date_comp(a,b)
+	{
+		var data1 = a.match(/\d{2}\/\d{2}\/\d{4}--\d+? \w*b--\d*$/g);
+		data1 = data1[0].substr(0, data1[0].indexOf('--'))
+		with ( data1 ) 
+			data1 = Date.UTC(substr(6), substr(3, 2), substr(0, 2));
+		var data2 = b.match(/\d{2}\/\d{2}\/\d{4}--\d+? \w*b--\d*$/g);
+		data2 = data2[0].substr(0, data2[0].indexOf('--'))
+		with ( data2 )
+			data2 = Date.UTC(substr(6), substr(3, 2), substr(0, 2));
+		return data2 - data1;
+	}
+	
+	function box_comp(a,b)
+	{
+	var compare = [];
+	compare[0] = a.substr(0, a.indexOf('--'));
+	compare[0] = compare[0].toLowerCase();
+	var temp=compare[0];
+	compare[1] = b.substr(0, b.indexOf('--'))
+	compare[1] = compare[1].toLowerCase();
+	compare.sort();
+	if (temp != compare[0])
+		return +1;
+	else
+		return -1;
+	}
+
+	function who_comp(a,b)
+	{
+	var compare = [];
+	compare[0] = a.substr(a.indexOf('--')+2);
+	compare[0] = compare[0].toLowerCase();
+	var temp=compare[0];
+	compare[1] = b.substr(b.indexOf('--')+2);
+	compare[1] = compare[1].toLowerCase();
+	compare.sort();
+	if (temp != compare[0])
+		return +1;
+	else
+		return -1;
+	}
+
+	function subject_comp(a,b)
+	{
+	var compare = [];
+	compare[0] = a.substr(a.indexOf('--')+2);
+	compare[0] = compare[0].substr(compare[0].indexOf('--')+2);
+	compare[0] = compare[0].toLowerCase();
+	var temp=compare[0];
+	compare[1] = b.substr(b.indexOf('--')+2);
+	compare[1] = compare[1].substr(compare[1].indexOf('--')+2);
+	compare[1] = compare[1].toLowerCase();
+	compare.sort();
+	if (temp != compare[0])
+		return +1;
+	else
+		return -1;
+	}
+
+	function size_comp(a,b)
+	{
+		var data1 = a.match(/\d{2}\/\d{2}\/\d{4}--\d+? \w*b--\d*$/g);
+		data1 = data1[0].substr(data1[0].indexOf('--')+2)
+		data1 = data1.substr(0,data1.indexOf('--'))
+		var size_a = parseInt(data1.substr(0,data1.indexOf(' ')));
+		if (data1.match("k"))
+			size_a = size_a * 1024;
+		else
+			if (data1.match("m"))
+				size_a = size_a * 1048576;
+		
+		var data2 = b.match(/\d{2}\/\d{2}\/\d{4}--\d+? \w*b--\d*$/g);
+		data2 = data2[0].substr(data2[0].indexOf('--')+2)
+		data2 = data2.substr(0,data2.indexOf('--'))
+		var size_b = parseInt(data2.substr(0,data2.indexOf(' ')));
+		if (data2.match("k"))
+			size_b = size_b * 1024;
+		else
+			if (data2.match("m"))
+				size_b = size_b * 1048576;
+				
+		return size_b - size_a;
+	}
+
+	// Form resultado;
+	searchE.prototype.mount_result = function(data,sort_type){
+		var nw_array = new Array;
+		var var_tmp = data.substr(2, data.length - 4);
+		var_tmp  = var_tmp.split("####");
+		var cont = parseInt(0);
+		if (sort_type == 'SORTDATE')
+			var_tmp.sort(date_comp);
+		if (sort_type == 'SORTBOX')
+			var_tmp.sort(box_comp);	
+		if (sort_type == 'SORTSUBJECT')
+			var_tmp.sort(subject_comp);	
+		if (sort_type == 'SORTWHO')
+			var_tmp.sort(who_comp);	
+		if (sort_type == 'SORTSIZE')
+			var_tmp.sort(size_comp);	
+		
+		for(var i=0; i < var_tmp.length; i++){
+			if(var_tmp[i] != ""){
+				nw_array[cont] = var_tmp[i];
+				cont++;
+			}
+		}
+		search_tabs += 1;
+		var border_id = create_border(get_lang("Search Results"), "search_" + search_tabs);
+		var table = document.createElement("TABLE");
+		table.id    = "table_resultsearch_" + search_tabs;
+		table.width = "100%";
+		table.borderColorDark = "#bbbbbb";
+		table.frame = "void";
+		table.rules = "rows";
+		table.cellPadding = "0";
+		table.cellSpacing = "0";
+
+		var tbody = document.createElement("TBODY");
+		tbody.id    = "tbody_resultsearch_" + search_tabs;
+		if(nw_array.length > 0){
+			write_msg(nw_array.length + " "+ get_lang('results found'));			
+		}
+
+		for( var i=0; i < nw_array.length; i++){
+			var tr = document.createElement("TR");
+			tr.style.height = "30px";
+			tr.className = 'tr_msg_read';
+
+			if (nw_array[i].match(/.*--.*--\w*--\d{2}\/\d{2}\/\d{4}--\d+? \w*b--\d*$/g) == null) //subject with "--"
+			{
+				var aux1 = nw_array[i].match(/\d{2}\/\d{2}\/\d{4}--\d+? \w*b--\d*$/g);
+				aux1 = aux1[0].split("--");
+				nw_array[i] = nw_array[i].substr(0, nw_array[i].indexOf(aux1[0])-2);
+				var aux = [];
+				aux[0] = nw_array[i].substr(0, nw_array[i].indexOf('--'));
+				nw_array[i] = nw_array[i].substr(nw_array[i].indexOf('--')+2);
+				aux[1] = nw_array[i].substr(0, nw_array[i].indexOf('--'));
+				aux[2] = nw_array[i].substr(nw_array[i].indexOf('--')+2);
+				aux = aux.concat(aux1);
+			}
+			else
+			{
+			var aux = nw_array[i].split("--");
+			}
+			for(var j=0 ; j < aux.length ; j++){
+					var mailbox = aux[0];
+					var uid_msg = aux[5];
+					tr.id = mailbox + ";" + uid_msg;
+					var td = document.createElement("TD");					
+					
+				if( j <= 5){
+					if( j == 0){
+						td.style.width = "1%";					
+						var subject_encode = url_encode(aux[2]);
+						var td1 = '<input type="checkbox" id="check_box_search_message_'+tr.id+'"></input>';
+					}
+					if( j == 1){
+						td.style.width = "20%";					
+						var nm_box = aux[0].split(cyrus_delimiter);
+						var td1 = nm_box.pop();
+						td.setAttribute("NoWrap","true");
+						td.style.overflow = "hidden";
+						td.style.color = "#42795b";
+						td.style.fontWeight = "bold";
+						if(td1 == "INBOX"){
+							var td1  = get_lang("Inbox");
+						}
+					}
+					if( j == 2){
+						var subject_encode = url_encode(aux[2]);
+						td.width = "20%";					
+						var td1  =  '<div style="width:100%;overflow:hidden">'+aux[1]+"</div>";
+					}
+					if( j == 3){
+						var subject_encode = url_encode(aux[2]);
+						if (! subject_encode)
+							aux[2] = get_lang("no subject") + "...";
+						td.width = "30%";					
+						var td1  = '<div style="width:100%;overflow:hidden"><a href=javascript:void(0) onclick=EsearchE.open_msg(\"' + url_encode(mailbox) + '\",\"' + uid_msg + '\",\"' + subject_encode + '\")>' + aux[2] +'</a></div>';
+
+					}
+					if( j == 4){
+						td.width = "14%";					
+						td.align = "center";
+						var td1  = aux[3];
+					}
+					if( j == 5){
+						td.width = "15%";
+						td.align = "center";
+						var td1  = aux[4];
+					}
+
+					td.innerHTML = td1;
+					tr.appendChild(td);
+				}
+			}
+			aux.splice(0,(aux.length));	
+
+		subject = tr.firstChild;
+		subject = subject.nextSibling.nextSibling.nextSibling.firstChild.firstChild.innerHTML;
+//		_dragArea.makeDragged(tr, msg_number, subject, true);
+		_dragArea.makeDragged(tr, tr.firstChild.firstChild.id.substr(tr.firstChild.firstChild.id.indexOf(';')+1), subject, true);
+		tbody.appendChild(tr);
+		}
+		table.appendChild(tbody);
+		
+	var content_search =  Element('content_id_' + "search_" + search_tabs);	
+	// BEGIN MAKE THE SCROLL HEIGHT		
+	var defaultWidth = document.body.offsetWidth - 31;	
+	var menuHidden = Element("folderscol").style.display == 'none' ? true : false;
+	if(!menuHidden)
+		defaultWidth -= Element("folderscol").offsetWidth;			
+	var bar = Element("toolbar");
+	var offset = 0;
+	if(bar.style.visibility != 'hidden') 
+		offset = bar.offsetHeight ? bar.offsetHeight :  bar.clientHeight;		
+	var div_scroll_result = document.createElement("DIV");
+	div_scroll_result.id = "div_result_scroll_"+search_tabs;
+	div_scroll_result.style.background = 'WHITE';
+	div_scroll_result.style.height = document.body.clientHeight - offset - 120;
+	content_search.style.height = document.body.clientHeight - offset - 80;
+	div_scroll_result.style.overflow = "auto";
+	div_scroll_result.style.width = defaultWidth - (is_ie ? 7 : 0);
+	// END MAKE THE SCROLL HEIGHT		
+		
+	
+		if(is_ie)
+			Element("border_table").width = "99.5%";
+		
+		/* Put header */
+		var table_element = document.createElement("TABLE");
+		var tbody_element = document.createElement("TBODY");
+		table_element.setAttribute("id", "table_message_header_box");
+		table_element.className = "table_message_header_box";
+		tr_element = document.createElement("TR");
+		tr_element.className = "message_header";
+		td_element0 = document.createElement("TD");
+		td_element0.setAttribute("width", "1%");
+		chk_box_element = document.createElement("INPUT");
+		chk_box_element.id  = "chk_box_select_all_messages";
+		chk_box_element.setAttribute("type", "checkbox");
+		chk_box_element.className = "checkbox";
+		chk_box_element.onclick = function(){select_all_search_messages(this.checked,content_search.id);};
+		chk_box_element.onmouseover = function () {this.title=get_lang('Select all messages.')};
+		chk_box_element.onkeydown = function (e){
+			if (is_ie)
+			{
+				if ((window.event.keyCode) == 46)
+					delete_msgs(get_current_folder(),'selected','null');
+			}
+			else
+			{
+				if ((e.keyCode) == 46)
+					delete_msgs(get_current_folder(),'selected','null');
+			}
+		};
+		
+		td_element0.appendChild(chk_box_element);
+		td_element1 = document.createElement("TD");
+		td_element1.setAttribute("width", "20%");
+		td_element1.align = "left";
+		td_element1.onclick = function () { EsearchE.mount_result(data,'SORTBOX'); delete_border(border_id,false);};
+		td_element1.innerHTML = get_lang("Folder");
+		td_element2 = document.createElement("TD");
+		td_element2.setAttribute("width", "20%");
+		td_element2.align = "left";
+		td_element2.onclick = function () { EsearchE.mount_result(data,'SORTWHO'); delete_border(border_id,false);};
+		td_element2.innerHTML = get_lang("Who");
+		td_element3 = document.createElement("TD");
+		td_element3.setAttribute("width", "30%");
+		td_element3.align = "left";
+		td_element3.onclick = function () { EsearchE.mount_result(data,'SORTSUBJECT'); delete_border(border_id,false);};
+		td_element3.innerHTML = get_lang("Subject");
+		td_element4 = document.createElement("TD");
+		td_element4.setAttribute("width", "14%");
+		td_element4.align = "center";
+		td_element4.onclick = function () { EsearchE.mount_result(data,'SORTDATE'); delete_border(border_id,false);};
+		td_element4.innerHTML = get_lang("Date");
+		td_element5 = document.createElement("TD");
+		td_element5.setAttribute("width", "15%");
+		td_element5.align = "center";
+		td_element5.onclick = function () { EsearchE.mount_result(data,'SORTSIZE'); delete_border(border_id,false);};
+		td_element5.innerHTML = get_lang("Size");
+	
+		tr_element.appendChild(td_element0);
+		tr_element.appendChild(td_element1);
+		tr_element.appendChild(td_element2);
+		tr_element.appendChild(td_element3);
+		tr_element.appendChild(td_element4);
+		tr_element.appendChild(td_element5);
+		tbody_element.appendChild(tr_element);
+		table_element.appendChild(tbody_element);
+		content_search.appendChild(table_element);
+		/*end of "put header"*/
+
+		var span_options = document.createElement("SPAN");		
+		if (span_options)
+			span_options.innerHTML = '<span title="'+get_lang("Delete")+'" style="margin-top:3px;margin-left:8px" class="message_options" onclick="javascript:move_search_msgs(\''+content_search.id+'\');">'+get_lang("Delete")+'</span> | '+
+				'<span title="'+get_lang("Move")+'" class="message_options" onclick=wfolders.makeWindow(\"'+content_search.id+'\",\"move_to\")>'+get_lang("Move")+'</span>';
+		div_scroll_result.appendChild(table);
+		content_search.appendChild(div_scroll_result);	
+		if (span_options)
+			content_search.appendChild(span_options);
+	}
+
+	searchE.prototype.open_msg = function(mailbox, uid_msg, subject){
+		var handler_get_msg = function(data){
+			if(Element("border_id_" + uid_msg + "_r")){alert(get_lang("This message is already opened!"));}
+			else{draw_message(data,create_border(url_decode(subject), uid_msg + "_r"));}
+		}
+		var args   = "$this.imap_functions.get_info_msg";
+		var params = "msg_number=" + uid_msg + "&msg_folder=" + mailbox;
+		cExecute(args,handler_get_msg,params);
+
+	}
+
+	// Adiciona caixas postais na busca;
+	searchE.prototype.add_mailboxes = function(){
+		var sel = Element("sel_search_nm_box1");
+		var name_box     = this.name_box_search.split(cyrus_delimiter);
+		if(this.name_box_search == "")
+			return false;
+		var name_box_def = "";
+		if(name_box.length != 1){
+			name_box_def = name_box[(name_box.length-1)];
+		}else{
+			name_box_def = get_lang("Inbox");		
+		}
+		if( sel.length > 0){
+			for(var i=0; i < sel.options.length; i++){
+				if(sel.options[i].value == this.name_box_search){
+					alert(get_lang('This message is already selected!'));
+					return false;
+				}
+			}
+		}
+		var opt = new Option(lang_folder(name_box_def),this.name_box_search,false,true);
+		sel[sel.length] = opt;
+	}
+	// Remove as caixas postais na busca;
+	searchE.prototype.del_mailboxes = function(){
+		var sel = Element("sel_search_nm_box1");
+		if(sel.length > 0){
+			for(var i=0; i < sel.options.length; i++){
+				if(sel.options[i].selected == true){
+					sel.options[i] = null;
+					i--;
+				}
+			}
+		}
+	
+	}
+	// todas as caixas
+	searchE.prototype.all_mailboxes = function(){
+		var value = Element("check_all_msg").checked;
+		var cont = parseInt(0);
+		if(value){
+			if(EsearchE.all_boxes.length > 0){
+				EsearchE.all_boxes.splice(0,(EsearchE.all_boxes.length));			
+			}
+			for(var i=0; i < folders.length; i++){
+				EsearchE.all_boxes[cont] = folders[i].folder_id;
+				cont++;
+			}
+		}else{
+			EsearchE.all_boxes.splice(0,(EsearchE.all_boxes.length));
+		}
+	}
+
+	// Search;
+	searchE.prototype.func_search = function(value){
+		var fields = "##";
+			// Verifica se os campos estão preenchidos;
+			if(trim(Element("txt_ass").value) != ""){
+				fields += "SUBJECT " +  "<=>" +url_encode(Element("txt_ass").value) + " ";
+			}
+			if(trim(Element("txt_body").value) != ""){
+				fields += "BODY " + "<=>" + url_encode(Element("txt_body").value) + " ";
+			}
+			if(trim(Element("txt_de").value) != ""){
+				fields += "FROM " + "<=>" + url_encode(Element("txt_de").value) + " ";
+			}
+			if(trim(Element("txt_para").value) != ""){
+				fields += "TO " + "<=>" + url_encode(Element("txt_para").value) + " ";
+			}
+			if(trim(Element("txt_cc").value) != ""){
+				fields += "CC " + "<=>" + url_encode(Element("txt_cc").value) + " ";
+			}
+			if(value) {
+				fields = "##ALL " +  "<=>" +url_encode(value) + " ";
+			}
+
+		fields += "##";
+		if(fields == "####"){
+			alert(get_lang("Define some search parameters!"));
+			return false;
+		}
+		
+		if(Element("check_all_msg").checked){
+			var nm_box = new Array;
+			for(var i=0; i < EsearchE.all_boxes.length; i++){
+				nm_box[i] = EsearchE.all_boxes[i] + fields;
+			}
+		}else{
+			var nm_box = new Array;
+			var sel_combo = Element("sel_search_nm_box1");
+			if( sel_combo.options.length <= 0){
+				alert(get_lang("Define the boxes to search!"));
+				return false;
+			}
+			
+			for(var i=0; i < sel_combo.options.length; i++){
+				sel_combo.options[i].selected = true;
+			}
+			for(var i=0; i < sel_combo.options.length; i++){
+				if(sel_combo.options[i].selected == true){
+					nm_box[nm_box.length] = sel_combo.options[i].value + fields;
+				}
+			}
+		}
+		var handler = function(data){
+			if(data == "none"){alert(get_lang("None result was found."));}
+			else if(data == "many results"){alert(get_lang("More than %1 results. Please, try to refine your search.",50));}
+			else{EsearchE.mount_result(data);}
+		}
+		var args   = "$this.imap_functions.search_msg";
+		var params = "condition=" + nm_box;
+		cExecute(args,handler,params);
+	}
+	// clean;
+	searchE.prototype.func_clean = function(){
+		// Limpa os campos;
+		for(var i=0; i < this.fields.length; i++){
+			if(Element("txt" + this.fields[i]) != null){Element("txt" + this.fields[i]).value = "";}
+		}			
+	    if(Element("check_all_msg") != null){Element("check_all_msg").checked = false;}
+
+	    EsearchE.all_boxes.splice(0,(EsearchE.all_boxes.length));
+	  	EsearchE.del_mailboxes();
+	}
+
+	// close
+	searchE.prototype.func_close = function(type){
+		var _this = this;
+		_this.name_box_search = "";
+		EsearchE.all_boxes.splice(0,(EsearchE.all_boxes.length));
+		_this.type = type;
+		_this.searchW['window_search'].close();
+	}
+	// Monta a janela em tela;
+	searchE.prototype.showWindow = function(div){
+		if(!this.searchW[div.id]) {
+			div.style.width = "660px";
+			div.style.height = "255px";
+			div.style.visibility = "hidden";
+			div.style.position = "absolute";
+			div.style.zIndex = "10003";			
+			var title = ":: "+ get_lang("Search")+" ::";
+			var wHeight = div.offsetHeight + "px";
+			var wWidth =  div.offsetWidth   + "px";
+			
+			win = new dJSWin({			
+				id: 'ccList'+div.id,
+				content_id: div.id,
+				width: wWidth,
+				height: wHeight,
+				title_color: '#3978d6',
+				bg_color: '#eee',
+				title: title,						
+				title_text_color: 'white',
+				button_y_img: '../phpgwapi/images/win_min.gif',
+				button_x_img: '../phpgwapi/images/winclose.gif',
+				border: true });
+			this.searchW[div.id] = win;
+			win.draw();
+		}else{
+			var _this = this;
+			win = this.searchW[div.id];
+			if((_this.type == "close" && win.state == 0) || win.state == 2){EsearchE.func_clean();}
+			win.draw();
+		}
+		win.open();	
+	}
+// Cria o objeto
+	var EsearchE;
+	EsearchE = new searchE();
Index: tags/expressoMail1_2/1.2211/js/drag_area.js
===================================================================
--- tags/expressoMail1_2/1.2211/js/drag_area.js	(revision 2)
+++ tags/expressoMail1_2/1.2211/js/drag_area.js	(revision 2)
@@ -0,0 +1,211 @@
+function DragArea(){
+
+	this.msg_number = false;
+	this.subject	= false;
+	this.color_dd	= 'red';
+	this.from_list	= false;
+	this._mousemove = document.onmousemove;
+	this._mouseup = document.onmouseup;
+	this.div_dd = document.createElement("DIV");
+	this.id_messages_to_drag = new Array();
+	this.div_dd.style.position = 'absolute';
+	this.div_dd.style.zIndex = '15';
+	this.div_dd.style.border = '1px solid black';
+	this.div_dd.style.background ="#EEEEEE";
+	var value = "8.5";
+	this.div_dd.style.opacity = value/10;
+	this.div_dd.style.filter = 'alpha(opacity=' + value*10 + ')';	
+	this.div_dd.id = 'div_sel_messages';
+	this.div_dd.style.padding = "3px";
+	this.div_dd.style.width = "0px";
+	this.div_dd.style.height = "0px";
+	this.div_dd.style.display ='none';
+	this.envelope = new Image();
+	this.envelope.src = "templates/default/images/envelope.png";
+	document.body.appendChild(this.div_dd);
+	
+}
+
+DragArea.prototype.makeDragged = function(element, msg_number, subject, from_list){
+	element.oncontextmenu = function(e) {
+		return false;
+	}
+	var _this = this;
+	element.onmousedown = function (e){
+
+		var _button = is_ie ? window.event.button : e.which;
+	
+		if(_button == 2 || _button == 3) {
+			var _checkb = Element("check_box_message_"+ msg_number);
+
+			if(_checkb) {
+				if(!_checkb.checked) {
+					changeBgColor(is_ie ? window.event : e, msg_number);
+					_checkb.checked = true;
+				}
+				ConstructRightMenu(is_ie ? window.event : e);
+			}			
+			return false;
+		}
+
+		if(!_this.msg_number) {
+			_this.msg_number = msg_number;
+
+			if(!subject)
+				_this.subject = get_lang("No Subject");
+			//else if(subject.length > 40)
+			//	_this.subject = subject.substring(0,40) + '...';				
+			else
+				_this.subject	 = subject;
+
+			_this.from_list  = from_list;
+			_this.div_dd.style.width = "auto";
+			_this.div_dd.style.height = "auto";			
+		}
+		return true;
+	};	
+}
+DragArea.prototype.showLayerDrag = function(e){
+
+	var msg_number = _dragArea.from_list ? _dragArea.msg_number : _dragArea.msg_number.replace('_r','');
+	if(_dragArea.from_list) {	
+		if(! Element("check_box_message_"+msg_number).checked) {
+			if (is_ie)
+				changeBgColor(window.event,msg_number);
+			else
+				changeBgColor(e,msg_number);
+			Element("check_box_message_"+ msg_number).checked = true;	
+		}
+		id_messages_to_drag = get_selected_messages();
+		id_messages_to_drag = id_messages_to_drag ? id_messages_to_drag.split(',') : new Array();
+	
+		if(id_messages_to_drag.length > 1)
+			this.subject = id_messages_to_drag.length +" mensagens selecionadas";
+	}
+
+	this.div_dd.innerHTML = "<img align='center' src='"+this.envelope.src+"'>&nbsp;<span id='content_dd'><font color='red' weight='bold'><b>"+this.subject+"</b></span></font>";
+	this.div_dd.style.display ='';
+}
+
+DragArea.prototype.onSelectStart = function(value){
+	if(!value) {
+		document.body.onselectstart = function (e){return false;}
+		document.body.ondragstart = function (e){return false;}
+	}
+	else {
+		document.body.onselectstart = function (e){return true;}
+		document.body.ondragstart = function (e){return true;}
+	}
+}
+
+DragArea.prototype.mouseMoveDrag = function(e){		
+	
+	var	e  = is_ie ? window.event : e;
+	var	_target = is_ie ? e.srcElement : e.target;
+	if(is_ie)
+		this.onSelectStart(false);
+
+	this.div_dd.style.left	= e.clientX + 5 + document.body.scrollLeft;
+	this.div_dd.style.top 	= e.clientY + 10 + document.body.scrollTop;		
+
+	if(this.div_dd.style.display == 'none')
+		this.showLayerDrag(e);
+	
+	var reg = /^((n|l)(?!root))(.*)tree_folders$/;
+	var _color = this.color_dd;
+
+	if(reg.test(_target.parentNode.id) )
+		_color ='green';
+	else
+		_color ='red';
+	
+	if(this.color_dd != _color) {
+		Element('content_dd').innerHTML = "<font color='"+_color+"' weight='bold'><b>"+this.subject+"</b></font>";
+		this.color_dd = _color;
+	}
+
+	return false;
+}	
+
+var _dragArea = new DragArea();
+
+document.onmousemove = function(e) {
+	var	_target = is_ie ? window.event.srcElement : e.target;
+	if(_dragArea._mousemove)
+		_dragArea._mousemove(e);
+	
+	else if(_dragArea.msg_number && _target.type != 'checkbox') {
+		_dragArea.mouseMoveDrag(e);
+	}
+};
+
+document.onmouseup = function(e) {
+
+	var	_event  = is_ie ? window.event : e;
+	var	_target = is_ie ? _event.srcElement : _event.target;
+	var _button = is_ie ? _event.button : _event.which;
+	
+	if(_button != 2 && _button != 3) {		
+
+		if(Element("div_rightbutton") && Element("div_rightbutton").style.display != 'none') {
+						
+			if(!_target.id.match(/link_rightbutton_(.*)$/)){
+			
+				var id_messages_to_drag = get_selected_messages();
+				id_messages_to_drag = id_messages_to_drag ? id_messages_to_drag.split(',') : id_messages_to_drag;
+		
+				for(var i = 0; id_messages_to_drag && i < id_messages_to_drag.length; i++) {			
+					Element("check_box_message_"+id_messages_to_drag[i]).checked = false;				
+					changeBgColor(_event ,id_messages_to_drag[i]);				
+				}
+				Element("chk_box_select_all_messages").checked = false;
+				Element('div_rightbutton').style.display = 'none';
+				_dragArea.msg_number = false;
+				_dragArea.div_dd.style.display ='none';
+				return false;
+			}
+		}
+		if(is_ie)
+			_dragArea.onSelectStart(true);
+	}	
+
+
+	if(_dragArea.msg_number) {
+
+		var reg = /^((n|l)(?!root))(.*)tree_folders$/;
+		var new_folder;
+		
+		if(reg.test(_target.parentNode.id) ){
+			new_folder = _target.parentNode.id.substring(1,_target.parentNode.id.length).replace('tree_folders','');			
+			new_folder_name = new_folder.replace("INBOX"+cyrus_delimiter, "");
+			if(new_folder_name == 'INBOX')
+				new_folder_name = get_lang("Inbox");
+				
+			if(_dragArea.from_list)
+				move_msgs('null', 'selected', 'null', new_folder, new_folder_name);
+			else {
+				var msg_number = _dragArea.from_list ? _dragArea.msg_number : _dragArea.msg_number.replace('_r','');
+				move_msgs('null', msg_number, msg_number+"_r", new_folder, new_folder_name);
+			}
+		}
+		
+		else if(_dragArea.from_list && _target.type != 'checkbox' && _dragArea.div_dd.style.display !='none'){
+			var id_messages_to_drag = get_selected_messages();
+			if(id_messages_to_drag){
+				id_messages_to_drag = id_messages_to_drag.split(',');
+			
+				for(var i = 0; id_messages_to_drag && i < id_messages_to_drag.length; i++) {				
+					Element("check_box_message_"+id_messages_to_drag[i]).checked = false;				
+					changeBgColor(_event ,id_messages_to_drag[i]);				
+				}
+				Element("chk_box_select_all_messages").checked = false;			
+			}
+		}
+	
+		_dragArea.msg_number = false;
+		_dragArea.div_dd.style.display ='none';
+		if(is_ie)
+			_dragArea.onSelectStart(true);
+	}
+
+};
Index: tags/expressoMail1_2/1.2211/js/abas.js
===================================================================
--- tags/expressoMail1_2/1.2211/js/abas.js	(revision 271)
+++ tags/expressoMail1_2/1.2211/js/abas.js	(revision 271)
@@ -0,0 +1,257 @@
+var BordersArray = new Array();
+BordersArray[0] = new setBorderAttributes(0);
+
+function setBorderAttributes(ID)
+{
+	this.border_id = "border_id_"+ID;
+	this.sequence = ID; 
+}
+
+
+function alternate_border(ID)
+{
+	Element("footer_menu").style.display = (ID != "0" ? 'none' : '');
+	var len = BordersArray.length;
+	for (var i=0; i < len; i++)
+	{
+		m = document.getElementById(BordersArray[i].border_id);
+		if (m.className == 'menu-sel')
+		{
+			m.className = 'menu';
+			c = document.getElementById("content_id_"+BordersArray[i].sequence);
+			c.style.display = 'none';
+			if(Element("font_border_id_"+BordersArray[i].sequence))
+				Element("font_border_id_"+BordersArray[i].sequence).className = 'font-menu';	
+			var body = Element('body_'+BordersArray[i].sequence);
+			if (body)
+			{
+				try
+				{
+					if (Element('viewsource_rt_checkbox').checked)
+					{  
+						connector.loadScript("rich_text_editor");
+						RichTextEditor.viewsource(false);
+					}
+				}
+				catch(e)
+				{
+					//alert(e.message)
+				}
+			}
+		}
+	}
+
+	m = Element("border_id_"+ID);
+	m.className = 'menu-sel';
+	if(Element("font_border_id_" + ID))
+		Element("font_border_id_" + ID).className = 'font-menu-sel';
+	var c = Element("content_id_"+ID)
+	c.style.display = '';
+
+	body = document.getElementById('body_'+ ID);
+	if (body){
+		try{
+			if(ID){
+				connector.loadScript("rich_text_editor");
+				RichTextEditor.loadEditor(ID);
+			}
+			body.contentWindow.document.designMode="on";
+		}
+		catch(e){
+			//alert(e.message);
+		}
+	}
+
+	// hide the DropDrowContact, if necessary
+	window_DropDownContacts = Element('tipDiv');
+	if ((window_DropDownContacts)&&(window_DropDownContacts.style.visibility != 'hidden')){
+		window_DropDownContacts.style.visibility = 'hidden';
+	}
+	
+	return ID;
+}
+
+function create_border(borderTitle, id_value)
+{
+	var resize = false;	
+	var offWidth = Element('border_blank').offsetWidth ? Element('border_blank').offsetWidth : Element('border_blank').clientWidth;
+	if (offWidth < 200) {
+		resize = resize_borders();
+		if (!resize){
+			alert(get_lang('Reached maximum tab limit'));
+			return false;
+		}
+	}
+	Element("footer_menu").style.display = 'none';
+	
+	if (! id_value) // Is new message?
+		var ID = parseInt(BordersArray[(BordersArray.length-1)].sequence) + 1;
+	else{
+		var ID = id_value;
+		if (document.getElementById("border_id_"+id_value+"_r")) // Edit message? if yes treat like new
+					var id_value = null;
+	}
+	
+	td = document.createElement("TD");
+	td.id="border_id_" + ID;
+	if(resize) {
+		td.setAttribute("width", parseInt(resize)+"px");
+		td.style.width = parseInt(resize)+"px";
+	}
+	else
+		td.setAttribute("width", "200px");
+		
+	td.className = "menu";
+	td.setAttribute("align", "right");
+	td.onclick = function(){alternate_border(ID);};
+	td.setAttribute("noWrap","true");
+	var subject = borderTitle;
+	
+	borderTitle = borderTitle ?  borderTitle : id_value ? get_lang("No Subject") : "&nbsp;"	;
+	td.value = borderTitle;
+	if (borderTitle.length > 21){
+		borderTitle = borderTitle.substring(0,21) + "...";
+	}
+	
+	if (resize)
+		borderTitle = borderTitle.substring(0, resize*0.08);
+		
+	td.innerHTML = "<table width=100% border=0 cellspacing=0 cellpadding=0><tr><td id=font_border_id_" + ID+" class='font-menu' width=*>" + borderTitle + "</td><td width=1px><img onmousedown='javascript:return false' style='cursor:pointer' onclick=delete_border('" + ID + "','false') src='templates/default/images/close_button.gif'></td></tr></table>";
+
+	bb = document.getElementById("border_blank");
+	parent_bb = bb.parentNode; //Pego o tbody
+	parent_bb.insertBefore(td, bb);
+	
+	if(id_value && id_value.match(/_r$/))	
+		_dragArea.makeDragged(td, id_value,td.value);
+
+	BordersArray[BordersArray.length] = new setBorderAttributes(ID);
+	
+	var div = document.createElement("DIV");
+	div.id = "content_id_" + ID;
+	div.className = "conteudo";
+	div.style.display='';
+
+	var bar = document.getElementById("toolbar");
+	var offset = 0;
+	if(bar.style.visibility != 'hidden') 
+		offset = bar.offsetHeight ? bar.offsetHeight :  bar.clientHeight;
+		
+	div.style.height = document.body.clientHeight - offset - (is_ie ? 76 : 86);
+	div.style.overflow = "auto";
+
+	if(!is_ie) {
+		var menuHidden = Element("folderscol").style.display == 'none' ? true : false;
+		var defaultWidth = document.body.clientWidth - 27;
+		if(!menuHidden)
+			defaultWidth -= Element("folderscol").offsetWidth;
+
+		div.style.width = defaultWidth;
+//		div.style.width ="99.3%";
+	}
+	document.getElementById("exmail_main_body").appendChild(div);
+	alternate_border(ID);
+	
+	return ID;
+}
+
+function resize_borders()
+{
+	var children;
+	var	numBorders = 0;	
+	var widthTD = 0;
+	var newWidthTD = 0;		
+	children = Element('border_tr').childNodes;	
+	for (var i=0; i<children.length; i++) {
+		if ((children[i].nodeName === 'TD') && (children[i].id!=='border_id_0') && (children[i].id!=='border_blank')) {
+			numBorders++;
+			if(!widthTD)
+				widthTD = children[i].clientWidth;				
+		}
+	}
+	if (numBorders > 8)
+		return false;
+	
+	newWidthTD = ((numBorders*widthTD)+(Element("border_blank").clientWidth-20))/(numBorders+1);
+	for (var i=0; i<children.length; i++) {
+		if ((children[i].nodeName === 'TD') && (children[i].id!=='border_id_0') && (children[i].id!=='border_blank')){
+			children[i].style.width = newWidthTD;
+			Element("font_"+children[i].id).innerHTML = Element("font_"+children[i].id).innerHTML.substring(0, newWidthTD*0.08);
+		}
+	}
+	return newWidthTD;
+}
+
+function delete_border(ID, msg_sent)
+{
+	if(!ID)
+		return false;
+	
+	if (msg_sent == 'false')
+	{
+		var body = document.getElementById('body_'+ ID);
+		if (body)
+		{
+			try
+			{
+				var save_link = Element("save_message_options");
+				if ((body.contentWindow.document.designMode.toLowerCase() == 'on') && (save_link.onclick != ''))
+				{
+					var discard_msg = confirm(get_lang("Your message has not been sent. Discard your message?"), "");
+					if (!discard_msg)
+					{
+						return;
+					}
+					else
+					{
+						if (! newMessageTab.toPreserve[ID])
+							cExecute ("$this.imap_functions.delete_msgs&folder="+newMessageTab.imapBox[ID]+"&msgs_number="+newMessageTab.imapUid[ID],function(data){ return });
+						Element('to_'+ID).focus();
+					}
+				}
+			}
+			catch(e){
+				//alert(e.message);
+			}
+		}
+	}
+
+	newMessageTab.toPreserve[ID] = false;
+	newMessageTab.imapUid[ID] = 0;
+
+	hold_session = false;
+	for (i=0;i<BordersArray.length;i++)
+	{
+		m = document.getElementById(BordersArray[i].border_id);
+		if (m.className == 'menu-sel')
+			border_selected = BordersArray[i].border_id;
+	}
+	
+	if ('border_id_' + ID == border_selected)
+	{
+		if (BordersArray[i-2].sequence == ID)
+			this.alternate_border(0);
+		else
+			this.alternate_border(BordersArray[i-2].sequence);
+	}
+
+	// Remove TD, title
+	border = document.getElementById('border_id_' + ID);
+	border.parentNode.removeChild(border);
+	// Remove Div Content
+	content = document.getElementById('content_id_' + ID);
+	content.parentNode.removeChild(content);
+	
+	var new_BordersArray = new Array();
+	j = 0;
+	for (i=0;i<BordersArray.length;i++)
+	{
+		if (document.getElementById(BordersArray[i].border_id) != null){
+			new_BordersArray[j] = BordersArray[i];
+			j++;	
+		}
+	}
+	if(j == 1)
+		Element("footer_menu").style.display = '';
+	BordersArray = new_BordersArray;
+}
Index: tags/expressoMail1_2/1.2211/js/InfoContact.js
===================================================================
--- tags/expressoMail1_2/1.2211/js/InfoContact.js	(revision 72)
+++ tags/expressoMail1_2/1.2211/js/InfoContact.js	(revision 72)
@@ -0,0 +1,179 @@
+ function emInfoContact()
+{
+	this.email = "";
+	this.timeout = null;
+	this.timeout_hide = null;
+	this._mousemove = document.onmousemove;
+	this.td;
+	this.createCard();
+}
+
+emInfoContact.prototype.createCard = function(){
+	var pic= new Image(); 
+	pic.src="./templates/default/images/card.gif"; 
+	card = document.createElement("DIV");
+	card.id = "card_cc";
+	card.style.display = "none";
+	card.style.width = "244px";
+	card.style.backgroundImage = "url("+pic.src+")";
+	card.style.height = "134px";
+	card.style.position = "absolute";
+	card.innerHTML = "<table onmouseout='InfoContact.timeout_hide=setTimeout(\"InfoContact.hide()\",50);' onmouseover='clearTimeout(InfoContact.timeout_hide);' cellpadding=0 cellspacing=0 width='100%' height='100%'><tr><td valign='center' align='center' id='card_cc_td'></td></tr></table>";
+	document.body.appendChild(card);
+}
+emInfoContact.prototype.begin = function(td, email){
+
+	var card = Element("card_cc");
+	
+	if(this.td != td){
+		this.email = email;
+		this.td = td;
+		clearTimeout(this.timeout);
+		this.timeout = setTimeout("InfoContact.search('"+email+"')",1000);
+	}	
+}
+
+emInfoContact.prototype.label = function (text){
+	InfoContact.hide();
+	var div_label = Element("div_label");
+	if(!div_label) {
+		div_label = document.createElement("DIV");
+		div_label.id = "div_label";
+		div_label.style.padding = "2px";
+		div_label.style.display = "none";
+		div_label.style.position = "absolute";
+		div_label.style.border = "1px solid black";
+		div_label.style.backgroundColor="#FFFFDC";
+		document.body.appendChild(div_label);
+	}
+	div_label.innerHTML = text;
+	div_label.style.top = findPosY(this.td) + 20 - Element("divScrollMain").scrollTop;
+	div_label.style.left = findPosX(this.td) + 20;
+	div_label.style.display = '';
+	setTimeout("InfoContact.hide()",1000);
+}
+
+emInfoContact.prototype.connectVoip = function (phoneUser, typePhone){
+	var handler_connectVoip = function(data){
+		if(!data) {
+			alert(get_lang("Error contacting VoIP server."));
+		}
+		else{
+			alert(get_lang("Requesting a VoIP call")+":\n"+data);
+		}
+	}
+	cExecute ("$this.functions.callVoipConnect&to="+phoneUser+"&typePhone="+typePhone, handler_connectVoip);
+}
+
+emInfoContact.prototype.show = function (data){
+	var _this = this;
+	var card = Element("card_cc");
+
+	//if(card.style.display != '')
+	 {
+		card.style.left = findPosX(this.td) + 20;
+		var y = findPosY(this.td) + 20 - Element("divScrollMain").scrollTop;
+		var w_height = is_ie ? document.body.clientHeight + document.body.scrollTop : window.innerHeight + window.pageYOffset;
+		if(y + 160 > w_height)
+			card.style.top =  y - 160;	
+		else
+			card.style.top = y;		
+		card.style.display = '';
+		var cn = data.cn;
+		if(cn && cn.toString().length > 35)
+			cn = cn.toString().substring(0,30) + "...";
+		
+		var phoneUser = data.telefone;
+		if(preferences.voip_enabled && phoneUser) {
+			phoneUser = "<a title=\""+get_lang("Call to Comercial Number")+"\" href=\"#\" onclick=\"InfoContact.connectVoip('"+phoneUser+"', 'com')\">"+phoneUser+"</a>";
+			if(data.mobile){
+				phoneUser += " / <a title=\""+get_lang("Call to Mobile Number")+"\" href=\"#\" onclick=\"InfoContact.connectVoip('"+data.mobile+"', 'mob')\">"+data.mobile+"</a>";
+			}
+		}
+
+		Element("card_cc_td").innerHTML = "<table cellpadding=0 cellspacing=0 border=0 height='100%' width='100%'><tr><td width='70' height='93' style='padding-top:5px;padding-left:6px' align='center' valign='center'>"+
+											"<img src='./inc/show_img.php?email="+data.email+"'></td><td style='padding-left:2px' align='left' valign='top'>"+
+											"<br><img align='center' src='templates/default/images/"+(data.type)+"_catalog.png'><font size=1 color=BLACK>&nbsp;<b>"+get_lang("Sender's Information")+"</b></font>"+
+											_this.verifyIM(data.uid,data.email)+
+											"<br><img align='center' src='templates/default/images/phone.gif'>&nbsp;<font  size=1  color=BLACK>"+(phoneUser ? phoneUser : get_lang("None") )+"</font>"+
+											"</td></tr><tr><td valign='top' align='center' colspan='2'>"+
+											"<font size=1 color=BLACK>"+cn+"</font>"+
+											"<br><span title='"+get_lang("Write message")+"' style='cursor:pointer' onclick='InfoContact.sendMail(\""+cn+"\",\""+data.email+"\")'><font size=1 color=DARKBLUE><u>"+data.email+"</u></font></span>"+
+											"</td></tr></table>";
+
+
+	this.timeout_hide = setTimeout("InfoContact.hide()",1000);
+	}
+}
+
+emInfoContact.prototype.search = function (email){
+	var _this = this;
+	var ldapSearched = false;
+	var handler_search = function(data){
+		if(data != null){			
+			_this.show(data);
+		}
+		else if(!ldapSearched) {
+			ldapSearched = true;
+			cExecute ("$this.ldap_functions.getUserByEmail&email="+email, handler_search);
+		}
+		else
+			_this.label(email);
+			
+	}
+
+	if(findPosX(_this.td) == 0) {
+		_this.hide();
+		return;
+	}
+
+	handler_search();
+	//cExecute ("$this.db_functions.getUserByEmail&email="+email, handler_search);
+}
+
+emInfoContact.prototype.hide = function(){
+	this.email = "";
+	clearTimeout(this.timeout);
+	if(Element("div_label"))
+		Element("div_label").style.display = 'none';
+
+	if(Element("card_cc")) 
+		Element("card_cc").style.display = "none";	
+}
+
+emInfoContact.prototype.sendMail = function(name, email){
+	Element("msg_number").value = "\""+ name+"\" <"+email+">";
+	InfoContact.hide();
+	new_message("new","null");
+}
+
+emInfoContact.prototype.openChat = function(event, email){
+	IM.action_button(event, '1', email ,false);
+}
+
+emInfoContact.prototype.verifyIM = function(uid, email){
+
+	if ( !window.IM || !document.getElementById('myStatus') )
+		return  "<br/><br/>";
+
+	var status = IM.infoContact(uid);
+	var _return = '<br/>';
+
+	if ( status )
+	{
+		_return += '<img align="center" src="'+status.src+'" />';
+		_return	+= '<span onclick="IM.action_button(event,\''+status.jid+'\');"><font size="1" color=';
+		
+		if( status.src != img_unavailable.src)
+			_return 	+= '"DARKBLUE"><u style="cursor:pointer;">'+get_lang("User connected")+"</u>";
+		else
+			_return 	+= '"BLACK">'+get_lang("User not connected");
+
+		_return	+= "</font></span><br />";
+	}
+
+	return _return;
+}
+/* Build the Object */
+var emInfoContact;
+InfoContact = new emInfoContact();
Index: tags/expressoMail1_2/1.2211/js/sniff_browser.js
===================================================================
--- tags/expressoMail1_2/1.2211/js/sniff_browser.js	(revision 163)
+++ tags/expressoMail1_2/1.2211/js/sniff_browser.js	(revision 163)
@@ -0,0 +1,19 @@
+    var agt=navigator.userAgent.toLowerCase();
+    var is_major = parseInt(navigator.appVersion);
+    var is_minor = parseFloat(navigator.appVersion);    
+    var is_nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
+                && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
+                && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1));
+    var is_gecko = (agt.indexOf('gecko') != -1);
+    var is_gecko1_5 = (agt.indexOf('firefox/1.5') != -1 || agt.indexOf('firefox/2') != -1 || agt.indexOf('iceweasel/2') != -1);
+    var is_ie     = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
+    var is_ie3    = (is_ie && (is_major < 4));
+    var is_ie4    = (is_ie && (is_major == 4) && (agt.indexOf("msie 4")!=-1) );
+    var is_ie4up  = (is_ie && (is_major >= 4));
+    var is_ie5    = (is_ie && (is_major == 4) && (agt.indexOf("msie 5.0")!=-1) );
+    var is_ie5_5  = (is_ie && (is_major == 4) && (agt.indexOf("msie 5.5") !=-1));
+    var is_ie5up  = (is_ie && !is_ie3 && !is_ie4);
+    var is_ie5_5up =(is_ie && !is_ie3 && !is_ie4 && !is_ie5);
+    var is_ie6    = (is_ie && (is_major == 4) && (agt.indexOf("msie 6.")!=-1) );
+    var is_ie6up  = (is_ie && !is_ie3 && !is_ie4 && !is_ie5 && !is_ie5_5);    
+    var is_win   = ( (agt.indexOf("win")!=-1) || (agt.indexOf("16bit")!=-1) );
Index: tags/expressoMail1_2/1.2211/js/filters.js
===================================================================
--- tags/expressoMail1_2/1.2211/js/filters.js	(revision 246)
+++ tags/expressoMail1_2/1.2211/js/filters.js	(revision 246)
@@ -0,0 +1,191 @@
+var rules_limit = 200;
+
+	function cfilterSh(){
+		this.filter_Sh   = new Array;
+		this.qvfaf		 = "";
+		
+		// Images
+		this.grp_open_img = new Image();
+		this.grp_open_img.src = 'templates/default/images/filtro/group_open.gif';
+		this.grp_close_img = new Image();
+		this.grp_close_img.src = 'templates/default/images/filtro/group_close.gif';
+		this.filter_img = new Image();
+		this.filter_img.src = 'templates/default/images/filtro/filters.gif';
+		this.for_email_img = new Image();
+		this.for_email_img.src = 'templates/default/images/filtro/answered.gif';
+	}		
+
+	cfilterSh.prototype.Forms = function(){
+	
+		var form = document.createElement("DIV");
+		form.id  = "window_ffilter_ccform";
+		form.style.visibility = "hidden";
+		form.style.position = "absolute";
+		form.style.left = "0px";
+		form.style.top  = "0px"; 
+		form.style.width = "0px";
+		form.style.height = "0px";
+		document.body.appendChild(form);
+
+		var form_cont = document.createElement("SPAN");
+		form_cont.id = "form_status";
+		form_cont.style.display = "";			
+		form_cont.style.position = "absolute";
+		form_cont.style.top = "10px";
+		form_cont.style.left = "600px";
+		form_cont.innerHTML = "";
+		form.appendChild(form_cont);
+		
+		var form_buttons = document.createElement("DIV");
+		form_buttons.id = "form_buttons";
+		form_buttons.style.position = "absolute";
+		form_buttons.style.display = "";
+		form_buttons.style.top = "320px";
+		form_buttons.style.left = "5px";
+		form_buttons.style.width = "655px";
+		form_buttons.innerHTML = "<input type='button' value="+get_lang("Enable")+" onclick='filter.enabled_disabled(\"ENABLED\");'>"+
+								 "&nbsp;<input type='button' value="+get_lang("Disable")+" onclick='filter.enabled_disabled(\"DISABLED\");'>"+	
+								 "&nbsp;<input type='button' value="+get_lang("Remove")+" onclick='filter.delete_r();'>"+
+ 								 "&nbsp;<input type='button' value="+get_lang("Close")+" onclick='filter.close_frm();'>";
+
+		form.appendChild(form_buttons);
+		
+		var form_body = document.createElement("DIV");
+		form_body.id = "form_body";
+		form_body.style.position = "absolute";
+		form_body.style.left = "5px";
+		form_body.style.top = "5px";
+		form_body.style.width = "668px";
+		form_body.style.height = "310px";
+		form_body.style.borderStyle = "outset";
+		form_body.style.borderColor = "black";
+		form_body.style.borderWidth = "1px";
+		form_body.style.overflow = "auto";
+		form.appendChild(form_body);	
+
+		this.showWindow(form);
+		filter.load_rules();
+		this.list_rules();			
+	
+	}
+
+	cfilterSh.prototype.list_rules = function(){
+		if(filter.rulest.length == 0)
+			setTimeout("filters.mount_list()",2500);
+		else
+			this.mount_list();
+	}
+
+	cfilterSh.prototype.mount_list = function(){
+
+		Element('form_status').innerHTML = "";
+		var list = "";
+		// rules
+		if(filter.rulest.length == 0){
+			list = "<img id='set_rules_img' src='"+this.grp_close_img.src+"' border='0'>&nbsp;<span><b>"+get_lang('list of the filters') + " - ( " + filter.rulest.length + " ) </b></span> - " + "<a href='javascript:filters.n_rule()'>" + get_lang("new rule") + "</a>";		
+		}else{
+			if (filter.rulest.length < rules_limit ) //Limit of rules
+				list = "<img id='set_rules_img' src='"+this.grp_open_img.src+"' onclick=filters.hidden(\"set_rules\") border='0'>&nbsp;<span><b>"+get_lang('list of the filters') + " - ( " + filter.rulest.length + " ) </b></span> - " + "<a href='javascript:filters.n_rule()'>" + get_lang("new rule") + "</a>";
+			else
+				list = "<img id='set_rules_img' src='"+this.grp_open_img.src+"' onclick=filters.hidden(\"set_rules\") border='0'>&nbsp;<span><b>"+get_lang('list of the filters') + " - ( " + filter.rulest.length + " ) </b></span> - " + get_lang("You have reached the maximum number of rules");
+				
+			list += "<div id='set_rules'>";
+			for(var i=0; i < filter.rulest.length; i++){
+				list += "<input id=rule_"+i+" type='checkBox'>&nbsp;<img src='"+this.filter_img.src+"' width='16' height='16' border='0'>&nbsp;" + get_lang("Rule")+" : " + parseInt(i+1) + " -- " + this.vl_rule(filter.rulest[i],i) + "<br>";
+			}
+		}
+		list += "</div><br>";
+		// out office
+		if(!filter.out_officeR){
+			list += "<img id='set_out_img' src='"+this.grp_close_img.src+"' border='0'>&nbsp;";
+			list += "<span><b>"+get_lang('out office') + " - ( 0 ) </b></span> " + "<a href='javascript:filters.n_out_office()'>" + get_lang("new rule") + "</a>";			
+		}else{
+			list += "<img id='set_out_img' src='"+this.grp_open_img.src+"' onclick=filters.hidden(\"set_out\") border='0'>&nbsp;";
+			list += "<span><b>"+get_lang('out office') + " - ( 1 )</b></span>";
+			list += "<div id='set_out'>";
+			list += "<input id='out_0' type='checkBox'><img id='set_out_form_email_img' src='"+this.for_email_img.src+"' border='0'>";
+			list += " " + this.vl_outOffice(filter.out_officeR) + " " ;
+			list += "</div>";
+		}
+		Element("form_body").innerHTML = list;
+	}
+	
+	cfilterSh.prototype.vl_rule = function(rule,pos){
+		var aux = rule.split("&&");
+		return " <a href='javascript:void(0)' onclick=filter.form_r('"+pos+"')><b>" + get_lang("Status") + " : </b>" + "<font color='red'>" + get_lang(aux[2]) + "</font>" + " - <b>" + get_lang("E-mail rule") + ":</b> " + aux[3] + " - <b>" + get_lang("Action") + ":</b> " + aux[6] + "</a>";
+	}
+	
+	cfilterSh.prototype.vl_outOffice = function(outOffice){		
+		var aux = outOffice.split("&&");
+		return get_lang("Rule") + " - <a href='javascript:void(0)' onclick=filter.form_out()> " + "<b>" + get_lang("Status") + " : </b><font color='red'>" + (aux[4] == "off" ? get_lang("Disabled") : get_lang("Enabled")) + "</font></a>";
+	}
+	
+	cfilterSh.prototype.n_rule = function(){
+		Element('form_body').innerHTML = "";
+		Element('form_body').innerHTML = filter.forms_();	
+		Element('div_rule').style.display = "";
+		filter.ac_form = "new_rule";
+		Element('form_buttons').style.display = 'none';
+		filter.sel_boxes();
+
+	}
+
+	cfilterSh.prototype.n_out_office = function(){
+		Element('form_body').innerHTML = "";
+		Element('form_body').innerHTML = filter.forms_();	
+		Element('div_vacation').style.display = "";			
+		Element('form_buttons').style.display = 'none';
+		filter.ac_form = "new_out";	
+		}
+
+	cfilterSh.prototype.hidden = function(el){
+		var _this = this;
+		Element(el).style.display = "none";
+		Element(el+"_img").src = _this.grp_close_img.src;
+		Element(el+"_img").onclick = function(){filters.un_hidden(el);}
+	}
+
+	cfilterSh.prototype.un_hidden = function(el){
+		var _this = this;
+		Element(el).style.display = "";
+		Element(el+"_img").src = _this.grp_open_img.src;
+		Element(el+"_img").onclick = function(){filters.hidden(el);}
+	}
+
+	cfilterSh.prototype.showWindow = function (div){
+		if(! this.filter_Sh[div.id]) {
+			div.style.width = "680px";
+			div.style.height = "345px";
+			div.style.visibility = "hidden";
+			div.style.position = "absolute";
+			div.style.zIndex = "10000";			
+			var title = ':: ' + get_lang('Filters management') + ' - ' + get_lang('Filters maintenance') + ':: ';
+			var wHeight = div.offsetHeight + "px";
+			var wWidth =  div.offsetWidth   + "px";
+
+			win = new dJSWin({			
+				id: 'filter'+div.id,
+				content_id: div.id,
+				width: wWidth,
+				height: wHeight,
+				title_color: '#3978d6',
+				bg_color: '#eee',
+				title: title,						
+				title_text_color: 'white',
+				button_x_img: '../phpgwapi/images/winclose.gif',
+				border: true });
+			
+			this.filter_Sh[div.id] = win;
+			win.draw();
+		}else{
+			div.innerHTML = '';
+			win = this.filter_Sh[div.id];
+			filter.form_m();			
+		}
+		win.open();
+	}
+
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+// build object
+ 	var filters;
+	filters = new cfilterSh();
Index: tags/expressoMail1_2/1.2211/js/shortcut.js
===================================================================
--- tags/expressoMail1_2/1.2211/js/shortcut.js	(revision 163)
+++ tags/expressoMail1_2/1.2211/js/shortcut.js	(revision 163)
@@ -0,0 +1,492 @@
+/**
+ * http://www.openjs.com/scripts/events/keyboard_shortcuts/
+ * Version : 2.01.A
+ * By Binny V A
+ * License : BSD
+ */
+shortcut = {
+	'all_shortcuts':{},//All the shortcuts are stored in this array
+	'add': function(shortcut_combination,callback,opt) {
+		//Provide a set of default options
+		var default_options = {
+			'type':'keydown',
+			'propagate':false,
+			'disable_in_input':false,
+			'target':document,
+			'keycode':false
+		}
+		if(!opt) opt = default_options;
+		else {
+			for(var dfo in default_options) {
+				if(typeof opt[dfo] == 'undefined') opt[dfo] = default_options[dfo];
+			}
+		}
+
+		var ele = opt.target
+		if(typeof opt.target == 'string') ele = document.getElementById(opt.target);
+		var ths = this;
+		shortcut_combination = shortcut_combination.toLowerCase();
+
+		//The function to be called at keypress
+		var func = function(e) {
+			e = e || window.event;
+			
+			if(opt['disable_in_input']) { //Don't enable shortcut keys in Input, Textarea fields
+				var element;
+				if(e.target) element=e.target;
+				else if(e.srcElement) element=e.srcElement;
+				if(element.nodeType==3) element=element.parentNode;
+
+				if(element.tagName == 'INPUT' || element.tagName == 'TEXTAREA') return;
+			}
+	
+			//Find Which key is pressed
+			if (e.keyCode) code = e.keyCode;
+			else if (e.which) code = e.which;
+			var character = String.fromCharCode(code).toLowerCase();
+			
+			if(code == 188) character=","; //If the user presses , when the type is onkeydown
+			if(code == 190) character="."; //If the user presses , when the type is onkeydown
+	
+			var keys = shortcut_combination.split("+");
+			//Key Pressed - counts the number of valid keypresses - if it is same as the number of keys, the shortcut function is invoked
+			var kp = 0;
+			
+			//Work around for stupid Shift key bug created by using lowercase - as a result the shift+num combination was broken
+			var shift_nums = {
+				"`":"~",
+				"1":"!",
+				"2":"@",
+				"3":"#",
+				"4":"$",
+				"5":"%",
+				"6":"^",
+				"7":"&",
+				"8":"*",
+				"9":"(",
+				"0":")",
+				"-":"_",
+				"=":"+",
+				";":":",
+				"'":"\"",
+				",":"<",
+				".":">",
+				"/":"?",
+				"\\":"|"
+			}
+			//Special Keys - and their codes
+			var special_keys = {
+				'esc':27,
+				'escape':27,
+				'tab':9,
+				'space':32,
+				'return':13,
+				'enter':13,
+				'backspace':8,
+	
+				'scrolllock':145,
+				'scroll_lock':145,
+				'scroll':145,
+				'capslock':20,
+				'caps_lock':20,
+				'caps':20,
+				'numlock':144,
+				'num_lock':144,
+				'num':144,
+				
+				'pause':19,
+				'break':19,
+				
+				'insert':45,
+				'home':36,
+				'delete':46,
+				'end':35,
+				
+				'pageup':33,
+				'page_up':33,
+				'pu':33,
+	
+				'pagedown':34,
+				'page_down':34,
+				'pd':34,
+	
+				'left':37,
+				'up':38,
+				'right':39,
+				'down':40,
+	
+				'f1':112,
+				'f2':113,
+				'f3':114,
+				'f4':115,
+				'f5':116,
+				'f6':117,
+				'f7':118,
+				'f8':119,
+				'f9':120,
+				'f10':121,
+				'f11':122,
+				'f12':123
+			}
+	
+			var modifiers = { 
+				shift: { wanted:false, pressed:false},
+				ctrl : { wanted:false, pressed:false},
+				alt  : { wanted:false, pressed:false},
+				meta : { wanted:false, pressed:false}	//Meta is Mac specific
+			};
+                        
+			if(e.ctrlKey)	modifiers.ctrl.pressed = true;
+			if(e.shiftKey)	modifiers.shift.pressed = true;
+			if(e.altKey)	modifiers.alt.pressed = true;
+			if(e.metaKey)   modifiers.meta.pressed = true;
+                        
+			for(var i=0; k=keys[i],i<keys.length; i++) {
+				//Modifiers
+				if(k == 'ctrl' || k == 'control') {
+					kp++;
+					modifiers.ctrl.wanted = true;
+
+				} else if(k == 'shift') {
+					kp++;
+					modifiers.shift.wanted = true;
+
+				} else if(k == 'alt') {
+					kp++;
+					modifiers.alt.wanted = true;
+				} else if(k == 'meta') {
+					kp++;
+					modifiers.meta.wanted = true;
+				} else if(k.length > 1) { //If it is a special key
+					if(special_keys[k] == code) kp++;
+					
+				} else if(opt['keycode']) {
+					if(opt['keycode'] == code) kp++;
+
+				} else { //The special keys did not match
+					if(character == k) kp++;
+					else {
+						if(shift_nums[character] && e.shiftKey) { //Stupid Shift key bug created by using lowercase
+							character = shift_nums[character]; 
+							if(character == k) kp++;
+						}
+					}
+				}
+			}
+
+			if(kp == keys.length && 
+						modifiers.ctrl.pressed == modifiers.ctrl.wanted &&
+						modifiers.shift.pressed == modifiers.shift.wanted &&
+						modifiers.alt.pressed == modifiers.alt.wanted &&
+						modifiers.meta.pressed == modifiers.meta.wanted) {
+				callback(e);
+	
+				if(!opt['propagate']) { //Stop the event
+					//e.cancelBubble is supported by IE - this will kill the bubbling process.
+					e.cancelBubble = true;
+					e.returnValue = false;
+	
+					//e.stopPropagation works in Firefox.
+					if (e.stopPropagation) {
+						e.stopPropagation();
+						e.preventDefault();
+					}
+					return false;
+				}
+			}
+		}
+		this.all_shortcuts[shortcut_combination] = {
+			'callback':func, 
+			'target':ele, 
+			'event': opt['type']
+		};
+		//Attach the function with the event
+		if(ele.addEventListener) ele.addEventListener(opt['type'], func, false);
+		else if(ele.attachEvent) ele.attachEvent('on'+opt['type'], func);
+		else ele['on'+opt['type']] = func;
+	},
+
+	//Remove the shortcut - just specify the shortcut and I will remove the binding
+	'remove':function(shortcut_combination) {
+		shortcut_combination = shortcut_combination.toLowerCase();
+		var binding = this.all_shortcuts[shortcut_combination];
+		delete(this.all_shortcuts[shortcut_combination])
+		if(!binding) return;
+		var type = binding['event'];
+		var ele = binding['target'];
+		var callback = binding['callback'];
+
+		if(ele.detachEvent) ele.detachEvent('on'+type, callback);
+		else if(ele.removeEventListener) ele.removeEventListener(type, callback, false);
+		else ele['on'+type] = false;
+	}
+}
+
+/* ExpressMail Functions */
+var shift_up_count = 0;
+var shift_down_count = 0;
+shortcut.add("N",function(){ new_message("new","null"); },{'disable_in_input':true});
+
+shortcut.add("Esc",function(){
+	var window_closed = false;
+	for(var window in arrayJSWin)
+	{
+		if (arrayJSWin[window].visible)
+		{
+			arrayJSWin[window].close();
+			window_closed = true;
+		}
+	}
+	if (!window_closed)
+		delete_border(get_msg_id(), 'false');
+},{'disable_in_input':false});
+
+shortcut.add("I",function(){ exec_msg_action('print'); },{'disable_in_input':true});
+shortcut.add("E",function(){ exec_msg_action('forward'); },{'disable_in_input':true});
+shortcut.add("R",function(){ exec_msg_action('reply'); },{'disable_in_input':true});
+shortcut.add("Delete",function(){
+	if ( Element('border_id_0').className==='menu-sel' )
+	{
+		var selected_shortcut_msgs = '';
+		var current_folder = get_current_folder();
+		all_messages = Element('tbody_box').childNodes;
+		
+		for (var i=0; i < all_messages.length; i++)
+		{
+			if ( exist_className(all_messages[i], 'selected_shortcut_msg') )
+			{
+				selected_shortcut_msgs += all_messages[i].id + ',';
+			}
+		}
+		
+		selected_shortcut_msgs = selected_shortcut_msgs.substring(0,(selected_shortcut_msgs.length-1));
+		delete_msgs(current_folder, selected_shortcut_msgs, 'null');
+	}
+	else
+		exec_msg_action('delete');
+}
+,{'disable_in_input':true});
+
+shortcut.add("Ctrl+Up",function(){ exec_msg_action('previous'); select_msg('null', 'up', true);},{'disable_in_input':true});
+shortcut.add("Ctrl+Down",function(){ exec_msg_action('next'); select_msg('null', 'down', true);},{'disable_in_input':true});
+if (is_ie){
+	shortcut.add("down",function(){ select_msg('null', 'down'); },{'disable_in_input':false});
+	shortcut.add("up",function(){ select_msg('null', 'up'); },{'disable_in_input':false});
+	shortcut.add("Shift+down",function(){
+		if (shift_up_count > 0)
+			unselect_top_msg();
+		else
+			select_bottom_msg();
+	},{'disable_in_input':false, 'propagate':false});
+	shortcut.add("Shift+up",function(){
+		if (shift_down_count > 0)
+			unselect_bottom_msg();
+		else
+			select_top_msg();
+	},{'disable_in_input':false, 'propagate':false});
+}
+else{
+	shortcut.add("down",function(){ select_msg('null', 'down');},{'type':'keypress', 'disable_in_input':false});
+	shortcut.add("up",function(){ select_msg('null', 'up'); },{'type':'keypress', 'disable_in_input':false});
+	shortcut.add("Shift+down",function(){
+		if (shift_up_count > 0)
+			unselect_top_msg();
+		else
+			select_bottom_msg();
+	},{'type':'keypress','disable_in_input':false, 'propagate':false});
+	shortcut.add("Shift+up",function(){
+		if (shift_down_count > 0)
+			unselect_bottom_msg();
+		else
+			select_top_msg();
+	},{'type':'keypress','disable_in_input':false, 'propagate':false});
+}
+
+shortcut.add("return",function(){
+	if ( Element('border_id_0').className==='menu-sel' )
+	{
+		all_messages = Element('tbody_box').childNodes;
+		for (var i=0; i < all_messages.length; i++)
+		{
+			if ( exist_className(all_messages[i], 'selected_shortcut_msg') )
+			{
+				Element("td_who_" + all_messages[i].id).onclick();
+				return;
+			}
+		}
+	}
+}
+,{'disable_in_input':true});
+
+shortcut.add("f9",function(){
+	Element("em_refresh_button").onclick();
+	return;
+},{'disable_in_input':true});
+
+function exec_msg_action(action)
+{
+	var msg_id = get_msg_id();
+	if (msg_id)
+	{
+		var msg_id = 'msg_opt_' + action + '_' + msg_id;
+		try {Element(msg_id).onclick();}
+		catch(e){/*alert(e);*/}
+	}
+	return;
+}
+
+function get_msg_id()
+{
+	children = Element('border_tr').childNodes;
+	
+	for (var i=0; i<children.length; i++)
+	{
+		if ( (children[i].nodeName==='TD') && (children[i].className==='menu-sel') && children[i].id != 'border_id_0')
+		{
+			var border_selected = children[i];
+			var msg_id = border_selected.id.replace("border_id_","");
+			return msg_id;
+		}
+	}
+	return false;
+}
+
+function select_msg(msg_number, keyboard_action, force_msg_selection)
+{
+	//Select msg, even if the focus isn't the border_id_0
+	if ( (Element('border_id_0').className != 'menu-sel') && (!force_msg_selection) )
+		return;
+	
+	shift_up_count = 0;
+	shift_down_count = 0;
+
+	if (msg_number != 'null')
+	{
+		unselect_all_msgs();
+		add_className(Element(msg_number), 'selected_shortcut_msg')
+	}
+	else
+	{
+		all_messages = Element('tbody_box').childNodes;
+		if (keyboard_action == 'down')
+		{
+			// Ultimo elemento ja esta selecionado
+			if ( exist_className(all_messages[all_messages.length-1], 'selected_shortcut_msg') )
+			{
+				unselect_all_msgs();
+				add_className(all_messages[all_messages.length-1], 'selected_shortcut_msg')
+				return false;
+			}
+			
+			for (var i=all_messages.length-1; i >=0; i--)
+			{
+				if ( exist_className(all_messages[i], 'selected_shortcut_msg') )
+				{
+					add_className(all_messages[i+1], 'selected_shortcut_msg')
+					break;
+				}
+			}
+			for (; i>=0; i--)
+			{
+				remove_className(all_messages[i], 'selected_shortcut_msg');
+			}
+			return true;
+		}
+		else
+		{
+			if ( exist_className(all_messages[0], 'selected_shortcut_msg') )
+			{
+				unselect_all_msgs();
+				add_className(all_messages[0], 'selected_shortcut_msg')
+				return false;
+			}
+			
+			for (var i=0; i < all_messages.length; i++)
+			{
+				if ( exist_className(all_messages[i], 'selected_shortcut_msg') )
+				{
+					add_className(all_messages[i-1], 'selected_shortcut_msg')
+					break;
+				}
+			}
+			for (; i< all_messages.length; i++)
+			{
+				remove_className(all_messages[i], 'selected_shortcut_msg')
+			}
+			return true;
+		}
+	}
+}
+
+function select_bottom_msg()
+{
+	all_messages = Element('tbody_box').childNodes;
+	
+	if ( exist_className(all_messages[all_messages.length-1], 'selected_shortcut_msg') )
+		return;
+	
+	for (var i=all_messages.length-1; i >=0; i--)
+	{
+		if ( (exist_className(all_messages[i], 'selected_shortcut_msg')) && (i+1 <= all_messages.length-1) )
+		{
+			shift_down_count++;
+			add_className(all_messages[i+1], 'selected_shortcut_msg');
+			break;
+		}
+	}
+}
+
+function select_top_msg()
+{
+	all_messages = Element('tbody_box').childNodes;
+	
+	if ( exist_className(all_messages[0], 'selected_shortcut_msg') )
+		return;
+	
+	for (var i=0; i <=all_messages.length-1; i++)
+	{
+		if ( exist_className(all_messages[i], 'selected_shortcut_msg') )
+		{
+			shift_up_count++;
+			add_className(all_messages[i-1], 'selected_shortcut_msg');
+			break;
+		}
+	}
+}
+
+function unselect_bottom_msg()
+{
+	all_messages = Element('tbody_box').childNodes;
+	for (var i=all_messages.length-1; i >=0; i--)
+	{
+		if ( exist_className(all_messages[i], 'selected_shortcut_msg') )
+		{
+			shift_down_count--;
+			remove_className(all_messages[i], 'selected_shortcut_msg');
+			break;
+		}
+	}
+}
+
+function unselect_top_msg()
+{
+	all_messages = Element('tbody_box').childNodes;
+	for (var i=0; i <=all_messages.length-1; i++)
+	{
+		if ( exist_className(all_messages[i], 'selected_shortcut_msg') )
+		{
+			shift_up_count--;
+			remove_className(all_messages[i], 'selected_shortcut_msg');
+			break;
+		}
+	}
+}
+
+function unselect_all_msgs()
+{
+	all_messages = Element('tbody_box').childNodes;
+	for (var i=0; i <=all_messages.length-1; i++)
+	{
+		remove_className(all_messages[i], 'selected_shortcut_msg');
+	}
+}
Index: tags/expressoMail1_2/1.2211/js/sharemailbox.js
===================================================================
--- tags/expressoMail1_2/1.2211/js/sharemailbox.js	(revision 197)
+++ tags/expressoMail1_2/1.2211/js/sharemailbox.js	(revision 197)
@@ -0,0 +1,368 @@
+	function cShareMailbox()
+	{
+		this.arrayWin = new Array();
+		this.el;
+		this.alert = false;
+	}
+
+	cShareMailbox.prototype.get_available_users = function(context)
+	{
+		var handler_get_available_users = function(data)
+		{
+			select_available_users = document.getElementById('em_select_available_users');
+		
+			//Limpa o select
+			for(var i=0; i<select_available_users.options.length; i++)
+			{
+				select_available_users.options[i] = null;
+				i--;
+			}
+
+			if ((data) && (data.length > 0))
+			{
+				// Necessario, pois o IE6 tem um bug que retira o primeiro options se o innerHTML estiver vazio.
+				select_available_users.innerHTML = '#' + data;
+				select_available_users.outerHTML = select_available_users.outerHTML;
+			
+				select_available_users.disabled = false;
+				select_available_users_clone = document.getElementById('em_select_available_users').cloneNode(true);
+				document.getElementById('em_input_searchUser').value = '';
+			}
+		}
+		cExecute ("$this.ldap_functions.get_available_users2&context="+context, handler_get_available_users);
+	}
+
+	cShareMailbox.prototype.getaclfromuser = function(user)
+	{
+		var handler_getaclfromuser = function(data)
+		{
+			Element('em_input_readAcl').checked = false;
+			Element('em_input_deleteAcl').checked = false;
+			Element('em_input_writeAcl').checked = false;
+			Element('em_input_sendAcl').checked = false;
+			
+			if (data[user].indexOf('lrs',0) >= 0)
+			{
+				Element('em_input_sendAcl').disabled = false;
+				Element('em_input_readAcl').checked = true;
+			}
+			else
+				Element('em_input_sendAcl').disabled = true;
+				
+			if (data[user].indexOf('d',0) >= 0)
+			{
+				Element('em_input_deleteAcl').checked = true;
+			}
+			if (data[user].indexOf('wip',0) >= 0)
+			{
+				Element('em_input_writeAcl').checked = true;
+			}
+			if (data[user] != "false" && data[user].indexOf('a',0) >= 0)
+			{
+				Element('em_input_sendAcl').disabled = false;
+				Element('em_input_sendAcl').checked = true;
+			}
+		}
+		cExecute ("$this.imap_functions.getaclfromuser&user="+user, handler_getaclfromuser);
+	}
+	
+	cShareMailbox.prototype.setaclfromuser = function()
+	{
+		var acl		= '';
+		var select 	= Element('em_select_sharefolders_users');
+
+		if(select.selectedIndex == "-1"){
+			alert("Selecione antes um usuário!");
+			return false;
+		}
+		var user = select.options[select.selectedIndex].value;
+		
+		if (Element('em_input_readAcl').checked) {
+			Element('em_input_sendAcl').disabled = false;
+			acl = 'lrs';
+		}
+		else{
+			Element('em_input_sendAcl').disabled = true;
+			Element('em_input_sendAcl').checked = false;
+		}
+				
+		if (Element('em_input_deleteAcl').checked)
+			acl += 'd';
+
+		if (Element('em_input_writeAcl').checked)
+			acl += 'wip';
+
+		if (Element('em_input_sendAcl').checked)
+			acl += 'a';
+		
+		var handler_setaclfromuser = function(data) {
+			if (!data)
+				alert(data);	
+			return true;
+		}
+		cExecute ("$this.imap_functions.setaclfromuser&user="+user+"&acl="+acl, handler_setaclfromuser);
+	}
+	
+	cShareMailbox.prototype.makeWindow = function(options)
+	{
+		_this = this;
+	
+		var el = document.createElement("DIV");
+		el.style.visibility = "hidden";
+		el.style.position = "absolute";
+		el.style.left = "0px";
+		el.style.top = "0px";
+		el.style.width = "0px";
+		el.style.height = "0px";
+		el.id = 'dJSWin_sharefolders';
+		document.body.appendChild(el);
+
+		if (Element('em_select_sharefolders_users'))
+		{
+			var select_users = Element('em_select_sharefolders_users');
+			select_users.innerHTML = '#' + options;
+			select_users.outerHTML = select_users.outerHTML;
+			
+			Element('em_input_readAcl').checked = false;
+			Element('em_input_deleteAcl').checked = false;
+			Element('em_input_writeAcl').checked = false;
+			Element('em_input_sendAcl').checked = false;
+		}
+		else
+		{
+			el.innerHTML = "<table border=0><tbody><tr>"+
+							
+							"<td valign='bottom'>"+
+								'<font color="red">'+
+									get_lang('Note: This sharing will take action on all of your folders and messages.')+
+									'<br><br>'+
+								'</font>'+
+								get_lang('Your mailbox is shared with')
+								+":<br><br>"+
+								"<select onchange=sharemailbox.getaclfromuser(this.value); id='em_select_sharefolders_users' size='13' style='width:250px;height:200px'>" + options + "</select>"+
+							"</td>"+
+							
+							"<td>"+
+								'<br><br><br><br><br><br>'+
+								'<img onClick="javascript:sharemailbox.add_user();" src="templates/default/images/arrow_left.png" style="vertical-align:middle;cursor:pointer;">' +
+								'<br><br>'+
+								'<img onClick="javascript:sharemailbox.remove_user();" src="templates/default/images/arrow_right.png" style="vertical-align:middle;cursor:pointer;">' +
+							"</td>"+
+							
+							"<td valign='bottom'><br>"+
+								get_lang('Organization')+":&nbsp;" + 
+								"<select id='em_combo_org' onchange='javascript:sharemailbox.get_available_users(this.value);'></select>"+
+								
+								"<br><br>"+get_lang('Search user')+":<br>" +
+								'<input id="em_input_searchUser" size="35" autocomplete="off"  onkeyup="javascript:sharemailbox.optionFinderTimeout(this)"><br>'+
+								
+								'<font color="red"><span id="em_span_searching">&nbsp;</span></font><br>'+
+								
+								"<select id='em_select_available_users' style='width:250px;height:200px' multiple></select></td>"+
+							'</tr>'+
+							'<tr><td>'+
+								'<table border=0><tbody><tr><td colspan=2>'+
+									get_lang('Access right')+':'+
+								'</td></tr>'+
+								'<tr><td>'+get_lang('Read')+':</td><td><input id=\'em_input_readAcl\' onClick="return sharemailbox.setaclfromuser();" type="checkbox"><img title="'+get_lang("hlp_msg_read_acl")+'." src=\'./templates/default/images/ajuda.jpg\'></td></tr>'+
+								'<tr><td>'+get_lang('Exclusion')+':</td><td><input id=\'em_input_deleteAcl\' onClick="return sharemailbox.setaclfromuser();" type="checkbox"><img title="'+get_lang('hlp_msg_delmov_acl')+'." src=\'./templates/default/images/ajuda.jpg\'></td></tr>'+
+								'<tr><td>'+get_lang('Write')+':</td><td><input id=\'em_input_writeAcl\' onClick="return sharemailbox.setaclfromuser();" type="checkbox"><img title="'+get_lang('hlp_msg_addcreate_acl')+'." src=\'./templates/default/images/ajuda.jpg\'></td></tr>'+
+								'<tr><td>'+get_lang('Send')+':</td><td><input id=\'em_input_sendAcl\' onClick="return sharemailbox.setaclfromuser();" type="checkbox"><img title="'+get_lang('hlp_msg_sendlike_acl')+'." src=\'./templates/default/images/ajuda.jpg\'></td></tr></tbody></table>'+
+							'</td></tr>'+
+			"</tbody></table>";
+		}
+
+		var handler_organizations = function(data){
+			var user_organization = Element('user_organization').value;
+			
+			for(i = 0; i < data.length; i++) {
+				Element('em_combo_org').options[i] = new Option(data[i].ou,data[i].dn);
+				if(user_organization.toUpperCase() == data[i].ou.toUpperCase())
+				{
+					Element('em_combo_org').options[i].selected = true;
+					_this.get_available_users(data[i].dn);
+				}
+			}
+		}
+		cExecute ("$this.ldap_functions.get_organizations2&referral=false", handler_organizations);
+
+		var butt = Element('dJSWin_wfolders_bok')
+		if (!butt){
+			butt = document.createElement('INPUT');
+			butt.id = 'dJSWin_wfolders_bok';
+			butt.type = 'button';
+			butt.value = get_lang('Save');
+			el.appendChild(butt);
+		}
+		butt.onclick = function ()
+		{
+			// Needed select all options from select
+			var users_setacl = new Array();
+			select_users = Element('em_select_sharefolders_users');
+			for(var i=0; i<select_users.options.length; i++)
+			{
+				users_setacl[i] = select_users.options[i].value;
+			}
+			attributes = connector.serialize(users_setacl);
+			
+			var handler_save = function(data)
+			{
+				if (data)
+				{
+					alert(get_lang('Shared options saved with success'));
+					sharemailbox.arrayWin[el.id].close();
+				}
+			}
+
+			cExecute ("$this.imap_functions.setacl", handler_save, 'users='+attributes);
+
+		}
+		
+		var space = document.createElement('SPAN');
+		space.innerHTML = "&nbsp;&nbsp;";
+		el.appendChild(space);
+		
+		var butt = document.createElement('BUTTON');
+		var buttext = document.createTextNode(get_lang('Close'));
+		butt.appendChild(buttext);
+		butt.onclick = function () {sharemailbox.arrayWin[el.id].close();};
+		el.appendChild(butt);
+		
+		_this.showWindow(el);
+	}
+	
+	cShareMailbox.prototype.showWindow = function (div)
+	{
+		if(! div) {
+			alert(get_lang('This list has no participants'));
+			return;
+		}
+		
+		if(! this.arrayWin[div.id])
+		{
+			div.style.height = "460px";
+			div.style.width = "540px";
+			var title = ":: "+get_lang("Mailbox Sharing")+" ::";
+			var wHeight = div.offsetHeight + "px";
+			var wWidth =  div.offsetWidth   + "px";
+			div.style.width = div.offsetWidth - 5;
+
+			win = new dJSWin({
+				id: 'win_'+div.id,
+				content_id: div.id,
+				width: wWidth,
+				height: wHeight,
+				title_color: '#3978d6',
+				bg_color: '#eee',
+				title: title,
+				title_text_color: 'white',
+				button_x_img: '../phpgwapi/images/winclose.gif',
+				border: true });
+			
+			this.arrayWin[div.id] = win;
+			win.draw();
+		}
+		else {
+			win = this.arrayWin[div.id];
+		}
+		Element('em_input_sendAcl').disabled = true;
+		win.open();
+	}
+	
+	var finderTimeout = '';
+	cShareMailbox.prototype.optionFinderTimeout = function(obj)
+	{
+		clearTimeout(finderTimeout);	
+		var oWait = document.getElementById("em_span_searching");
+		oWait.innerHTML = get_lang('Searching')+"...";
+		var finderTimeout = setTimeout("sharemailbox.optionFinder('"+obj.id+"')",500);
+	}
+	
+	cShareMailbox.prototype.optionFinder = function(id)
+	{
+		var oWait = document.getElementById("em_span_searching");
+		var oText = document.getElementById(id);
+			
+		//Limpa todo o select
+		
+		var select_available_users_tmp = document.getElementById('em_select_available_users')
+		for(var i = 0;i < select_available_users_tmp.options.length; i++)
+			select_available_users_tmp.options[i--] = null;
+
+		var RegExp_name = new RegExp("\\b"+oText.value, "i");
+		
+		//Inclui usuário começando com a pesquisa
+		for(i = 0; i < select_available_users_clone.length; i++){
+			if (RegExp_name.test(select_available_users_clone[i].text))
+			{
+				sel = select_available_users_tmp.options;
+				option = new Option(select_available_users_clone[i].text,select_available_users_clone[i].value);				
+				sel[sel.length] = option;
+			}
+		}
+		oWait.innerHTML = '&nbsp;';
+	}
+	
+	cShareMailbox.prototype.add_user = function()
+	{
+		var select_available_users = document.getElementById('em_select_available_users');
+		var select_users = document.getElementById('em_select_sharefolders_users');
+
+		var count_available_users = select_available_users.length;
+		var count_users = select_users.options.length;
+		var new_options = '';
+	
+		for (i = 0 ; i < count_available_users ; i++)
+		{
+			if (select_available_users.options[i].selected)
+			{
+				if(document.all)
+				{
+					if ( (select_users.innerHTML.indexOf('value='+select_available_users.options[i].value)) == '-1' )
+					{
+						new_options +=  '<option value='
+									+ select_available_users.options[i].value
+									+ '>'
+									+ select_available_users.options[i].text
+									+ '</option>';
+					}
+				}
+				else
+				{
+					if ( (select_users.innerHTML.indexOf('value="'+select_available_users.options[i].value+'"')) == '-1' )
+					{
+						new_options +=  '<option value='
+									+ select_available_users.options[i].value
+									+ '>'
+									+ select_available_users.options[i].text
+									+ '</option>';
+					}
+				}
+			}
+		}
+
+		if (new_options != '')
+		{
+			select_users.innerHTML = '#' + new_options + select_users.innerHTML;
+			select_users.outerHTML = select_users.outerHTML;
+		}
+	}
+
+	cShareMailbox.prototype.remove_user = function()
+	{
+		select_users = document.getElementById('em_select_sharefolders_users');
+	
+		for(var i = 0;i < select_users.options.length; i++)
+			if(select_users.options[i].selected)
+				select_users.options[i--] = null;
+				
+		Element('em_input_readAcl').checked = false;
+		Element('em_input_deleteAcl').checked = false;
+		Element('em_input_writeAcl').checked = false;
+		Element('em_input_sendAcl').checked = false;
+	}
+	
+	
+/* Build the Object */
+	var sharemailbox;
+	sharemailbox = new cShareMailbox();
Index: tags/expressoMail1_2/1.2211/js/common_functions.js
===================================================================
--- tags/expressoMail1_2/1.2211/js/common_functions.js	(revision 271)
+++ tags/expressoMail1_2/1.2211/js/common_functions.js	(revision 271)
@@ -0,0 +1,668 @@
+// BEGIN: FUNCTION RESIZE WINDOW
+var _showBar = showBar;
+var _hideBar = hideBar;
+
+function __showBar(){
+	_showBar();
+	resizeWindow();
+}
+
+function __hideBar(){
+	_hideBar();
+	resizeWindow();
+}
+showBar = __showBar;
+hideBar = __hideBar;
+
+window.onresize = resizeWindow;
+
+function resizeWindow(){
+
+	var bar = Element("toolbar");
+	var offset = 0;
+	if(bar.style.visibility != 'hidden') 
+		offset = (bar.offsetHeight ? bar.offsetHeight :  bar.clientHeight);	
+
+	var screenHeight = document.body.clientHeight ? document.body.clientHeight : document.body.offsetHeight;
+	var defaultHeight = screenHeight - offset;
+
+	if(BordersArray) {
+		for(var i = 1; BordersArray.length > 1 && i < BordersArray.length;i++) {
+			var div_scroll = Element("div_message_scroll_"+BordersArray[i].sequence);
+			if(div_scroll)
+				div_scroll.style.height = defaultHeight - 122;
+			var div = Element("content_id_"+BordersArray[i].sequence);
+			if(div)
+				div.style.height = defaultHeight - 73;
+		}
+	}
+	Element('content_folders').style.height = defaultHeight - (is_ie ? 165 : 150);
+	if(Element("divScrollMain"))
+		Element("divScrollMain").style.height 	= defaultHeight - (is_ie ? 111 : 110);	
+}
+// END: FUNCTION RESIZE WINDOW
+
+// onUnload edit message
+if(!is_ie)
+{
+	var beforeunload = window.onbeforeunload;
+	window.onbeforeunload = function()
+	{
+		if ( typeof beforeunload == 'function' )
+			beforeunload();
+
+		return unloadMess();
+	};
+}
+function unloadMess(){
+	var mess = get_lang("Your message has not been sent and will be discarted.");
+	for(var i = 0; i < BordersArray.length;i++) {
+		var body = Element('body_'+BordersArray[i].sequence);
+		if (body && body.contentWindow && body.contentWindow.document.designMode.toLowerCase() == 'on')	{
+			return mess;
+		}
+	}
+}
+// Translate words and phrases using user language from eGroupware.
+function get_lang(_key,_arg1,_arg2,_arg3,_arg4) {
+
+	if(!array_lang[0]){		
+		return _key+"*";
+	}
+	_value = "";	
+	for(i = 0; i < array_lang[0].length;i++){
+		if(array_lang[0][i] == _key.toLowerCase()) {
+			_value = array_lang[1][i];					
+			break;
+		}
+	}	
+	
+	if(!_value)
+		return _key+"*";
+			
+	if(_arg1 || _arg2 ||_arg3 || _arg4) {
+		for(j = 1; j <= 4; j++){
+			if(eval("_arg"+j)) {
+				var regExp = new RegExp("%"+j+"");		
+				_value = _value.replace(regExp,eval("_arg"+j));
+			}
+		}
+	}
+	
+	return _value;
+}
+
+// Make decimal round, using in size message
+function round(value, decimal){
+	var return_value = Math.round( value * Math.pow( 10 , decimal ) ) / Math.pow( 10 , decimal );
+	return( return_value );
+}
+
+// Change the class of message.
+// In refresh, the flags UnRead and UnSeen don't exist anymore. 
+function set_msg_as_read(msg_number, selected){
+	tr_message = Element(msg_number);
+	if (exist_className(tr_message, 'tr_msg_unread'))
+		decrement_folder_unseen();
+	remove_className(tr_message, 'tr_msg_unread');
+	remove_className(tr_message, 'selected_msg');
+	add_className(tr_message, 'tr_msg_read');
+	return true;
+}
+
+function set_msg_as_unread(msg_number){
+	tr_message = Element(msg_number);
+	if (exist_className(tr_message, 'tr_msg_read'))
+		increment_folder_unseen();
+	remove_className(tr_message, 'tr_msg_read');
+	remove_className(tr_message, 'selected_msg');
+	add_className(tr_message, 'tr_msg_unread');
+}
+
+function set_msg_as_flagged(msg_number){
+	var msg = Element(msg_number);
+	remove_className(msg, 'selected_msg');
+	add_className(msg, 'flagged_msg');
+	Element("td_message_important_"+msg_number).innerHTML = '<img src=templates/default/images/important.gif title=Importante!>';
+}
+
+function set_msg_as_unflagged(msg_number){
+	var msg = Element(msg_number);
+	remove_className(msg, 'selected_msg');
+	remove_className(msg, 'flagged_msg');
+	Element("td_message_important_"+msg_number).innerHTML = '';
+}
+
+function get_current_folder(){
+	return current_folder;
+}
+
+// Kill current box (folder or page).
+function kill_current_box(){
+	var box = document.getElementById("table_box");
+	if (box != null)
+		box.parentNode.removeChild(box);
+}
+
+// Kill current paging.
+function kill_current_paging(){
+	var paging = Element("span_paging");
+	if (paging != null)
+		paging.parentNode.removeChild(paging);
+}
+
+//Get the current number of messages in a page.
+function get_messages_number_in_page(){
+	//Get element tBody.
+	main = document.getElementById("tbody_box");
+		
+	// Get all TR (messages) in tBody.
+	main_list = main.childNodes;
+	
+	return main_list.length;
+}
+
+function download_attachments(msg_folder, msg_number, idx_file, msg_part, encoding, new_file_name, show_iframe){
+	div_attachment = document.getElementById("id_div_attachment");
+	var params = '';
+	
+	if (div_attachment == null){
+		var div_attachment = document.createElement("DIV");
+		div_attachment.id="id_div_attachment";
+		document.body.appendChild(div_attachment);
+	}
+	if(new_file_name)
+		params = "&newfilename="+new_file_name;
+	if(encoding)
+		params += "&encoding="+encoding;
+
+	div_attachment.innerHTML="<iframe style='display:none;width:0;height:0' name='attachment' src='inc/gotodownload.php?msg_folder="+msg_folder+"&msg_number="+msg_number+"&idx_file="+idx_file+"&msg_part="+msg_part+params+"'></iframe>";
+}
+
+function download_all_attachments(msg_folder, msg_number){
+	var handler_source = function(data){		
+		download_attachments(null, null, data, null,null,'anexos.zip');
+	}
+	cExecute("$this.exporteml.download_all_attachments",handler_source,"folder="+msg_folder+"&num_msg="+msg_number);
+}
+// Add Input File Dynamically.
+function addFile(id_border){
+	divFiles = document.getElementById("divFiles_"+id_border);
+	
+	if (divFiles.lastChild)
+		var countDivFiles = parseInt(divFiles.lastChild.id.split('_')[2]) + 1;
+
+	if (! countDivFiles)
+		var countDivFiles = 1;
+	
+	divFile = document.createElement('DIV');
+	
+	var inputFile = document.createElement("INPUT");
+	
+	var tmp_id_border = document.createAttribute('id_border');
+	tmp_id_border.value = id_border;
+	
+	inputFile.setAttributeNode(tmp_id_border);
+	inputFile.id = "inputFile_"+id_border+"_"+countDivFiles;
+	inputFile.onchange = function () {validateFileExtension(this.value, this.id.replace("input","div"), this.getAttribute('id_border'));};
+	inputFile.type = 'file';
+	inputFile.size = 50;
+	inputFile.maxLength = 255;
+	inputFile.name='file_'+countDivFiles;
+	
+	divFile.appendChild(inputFile);
+	
+	var linkFile = document.createElement("A");
+	linkFile.id = "linkFile_"+id_border+"_"+countDivFiles;
+	linkFile.href='javascript:void(0)';
+	linkFile.onclick=function () {removeFile(this.id.replace("link","div"));};
+	linkFile.innerHTML=get_lang("Remove");	
+	//divFile.innerHTML += "&nbsp;&nbsp;";
+	divFile.appendChild(linkFile);
+	divFile.id = "divFile_"+id_border+"_"+countDivFiles;	
+	divFiles.appendChild(divFile);
+}
+//	Remove Input File Dynamically.
+function removeFile(id){
+	var border_id = id.substr(8,1);
+	var el = Element(id);
+	el.parentNode.removeChild(el);
+}
+
+function validateFileExtension(fileName, id, id_border){
+	var error_flag  = false;
+	if (fileName[0] != '/'){ // file name is windows format?
+		var file = fileName.substr(fileName.lastIndexOf('\\') + 1, fileName.length);
+		if ((fileName.indexOf(':\\') != 1) && (fileName.indexOf('\\\\') != 0)) // Is stored in partition or a network file?
+			error_flag = true;	
+	}
+	else // is nix
+		var file = fileName.substr(fileName.lastIndexOf('/') + 1, fileName.length);						
+
+	var fileExtension = file.split(".");
+	fileExtension = fileExtension[(fileExtension.length-1)];
+	for(var i=0; i<denyFileExtensions.length; i++)
+	{
+		if(denyFileExtensions[i] == fileExtension)
+		{
+			error_flag = true;
+			break;
+		}
+			
+	}
+
+	if (error_flag == true){
+		alert(get_lang('File extension forbidden or invalid file') + '.');
+		removeFile(id);
+		addFile(id_border);
+		return false;
+	}
+	return true;
+	
+}
+
+var setTimeout_write_msg = 0;
+var old_msg = false;
+// Funcao usada para escrever mensagem
+// notimeout = True : mensagem nao apaga
+function write_msg(msg, notimeout){	
+	
+	if (setTimeout_write_msg)
+		clearTimeout(setTimeout_write_msg);
+	
+	var msg_div = Element('em_div_write_msg');
+	var old_divStatusBar = Element("divStatusBar");
+
+	if(!msg_div) {
+		msg_div = document.createElement('DIV');
+		msg_div.id = 'em_div_write_msg';
+		msg_div.style.height = is_ie ? '17px' : '15px';
+		msg_div.style.background = '#f7f8fa';
+		msg_div.style.display = 'none';
+		old_divStatusBar.parentNode.insertBefore(msg_div,old_divStatusBar);
+	}	
+	msg_div.innerHTML = '<table bgcolor="#f7f8fa" width=100% cellspacing="0" cellpadding="0" border="0"><tbody><tr><th width="40%"></th><th noWrap class="action_info_th">'+msg+'</th><th width="40%"></th></tr></tbody></table>';
+	old_divStatusBar.style.display = 'none';
+	msg_div.style.display = '';	
+	// Nao ponha var na frente!! jakjr
+	handle_write_msg = function(){
+		try{
+			if(!old_msg)
+				clean_msg();
+			else
+				write_msg(old_msg, true);			
+		}
+		catch(e){}
+	}
+	if(notimeout)
+		old_msg = msg;
+	else
+		setTimeout_write_msg = setTimeout("handle_write_msg();", 5000);
+}
+// Funcao usada para apagar mensagem sem timeout
+function clean_msg(){
+	old_msg = false;
+	var msg_div = Element('em_div_write_msg');
+	var old_divStatusBar = Element("divStatusBar");
+	if(msg_div)
+		msg_div.style.display = 'none';
+	old_divStatusBar.style.display = '';	
+}
+
+function make_body_reply(body, to, date_day, date_hour){
+	to = to.replace("<","&lt;");
+	to = to.replace(">","&gt;");
+	block_quoted_body ="<br><br>";
+	block_quoted_body += get_lang('At %1, %2 hours, %3 wrote:', date_day, date_hour, to);
+	block_quoted_body += "<blockquote style=\"border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;\">";
+	block_quoted_body += body;
+	block_quoted_body += "</blockquote>";
+	return block_quoted_body;
+}
+
+function make_forward_body(body, from, date, subject, to, cc){
+	from = from.replace(/</g,"&lt;");
+	from = from.replace(/>/g,"&gt;");
+	to = to.replace(/</g,"&lt;");
+	to = to.replace(/>/g,"&gt;");
+	var forward_body = '<BR><BR>---------- ' + get_lang('Forwarded message') + ' ----------<BR>';
+	forward_body += get_lang('From') + ': ' + from + '<BR>';
+	forward_body += get_lang('Date') + ': ' + date + '<BR>';
+	forward_body += get_lang('Subject') + ': ' + subject + '<BR>';
+	forward_body += get_lang('To') + ': ' + to+ '<BR>';
+	if(cc != undefined){
+		cc = cc.replace(/</g,"&lt;");
+		cc = cc.replace(/>/g,"&gt;");
+		forward_body += get_lang('CC') + ': ' + cc+ '<BR><BR>';
+	}
+	forward_body += body;
+	return forward_body;
+}
+
+function emMessageSearch(e,value){
+	var	e  = is_ie ? window.event : e;
+	if(e.keyCode == 13) {
+		search_emails(value);
+	}
+}
+
+function emQuickSearch(emailList, field, ID){
+	var quickSearchKeyBegin;
+	var quickSearchKeyEnd;
+	
+	var handler_emQuickSearch = function(data)
+	{
+		window_DropDownContacts = Element('tipDiv');
+		if (window_DropDownContacts.style.visibility != 'hidden'){
+			window_DropDownContacts.style.visibility = 'hidden';
+		}
+		
+		if ((!data.status) && (data.error == "many results")){
+			alert(get_lang('More than %1 results. Please, try to refine your search.',200));
+			return false;
+		}
+			
+		if (data.length > 0){
+			if ((field != 'null') && (ID != 'null'))
+			{
+				connector.loadScript("QuickCatalogSearch");
+				QuickCatalogSearch.showList(data, quickSearchKeyBegin, quickSearchKeyEnd);
+			}
+			else
+			{
+				connector.loadScript("QuickSearchUser");
+				QuickSearchUser.showList(data);
+			}
+		}
+		else
+			alert(get_lang('None result was found.'));
+		return true;
+	}
+	
+	if ((field != 'null') && (ID != 'null'))
+	{
+		Element(field +'_'+ ID).focus(); //necessário para o IE.
+		var i = getPosition(Element(field +'_'+ ID)); //inputBox.selectionStart;
+		var j = --i;
+
+		// Acha o inicio
+    	while ((j >= 0) && (emailList.charAt(j) != ',')){j--};
+	    quickSearchKeyBegin = ++j;
+
+	    // Acha o final
+    	while ((i <= emailList.length) && (emailList.charAt(i) != ',')){i++};
+	    quickSearchKeyEnd = i;
+
+	    // A Chave da Pesquisa
+    	var search_for = trim(emailList.substring(quickSearchKeyBegin, quickSearchKeyEnd));
+	}
+	else
+		var search_for = emailList;
+	
+	if (search_for.length < 4){
+		alert(get_lang('Your search argument must be longer than 4 characters.'));
+		return false;
+	}
+	
+	cExecute ("$this.ldap_functions.quicksearch&search_for="+search_for+"&field="+field+"&ID="+ID, handler_emQuickSearch);
+}
+
+function folderbox(){
+	connector.loadScript("TreeS");
+	ttree.make_Window();
+}
+
+function filterbox(){
+	connector.loadScript("filter");
+	connector.loadScript("filters");
+	filters.Forms();
+}
+
+function sharebox(){
+	var handler_imap_getacl = function(data)
+	{
+		var options = '';
+		for (var x in data)
+		{
+			options += "<option value='"+data[x].uid+"'>"+data[x].cn+"</option>";
+		}
+		connector.loadScript("sharemailbox");
+		sharemailbox.makeWindow(options);
+	}
+	cExecute ("$this.imap_functions.getacl", handler_imap_getacl);
+}
+
+function preferences_mail(){
+	connector.loadScript("preferences");
+	prefe.showList();
+}
+
+function search_emails(value){
+	connector.loadScript("search");
+	EsearchE.showForms(value);
+}
+
+function source_msg(id_msg,folder){
+	var num_msg = id_msg.substr(0,(id_msg.length - 2));
+	var handler_source = function(data){
+		download_attachments(null, null, data, null,null,'fonte_da_mensagem.txt');
+	}
+	cExecute("$this.exporteml.export_msg",handler_source,"folder="+url_decode(folder)+"&msgs_to_export="+num_msg);
+}
+
+function url_encode(str){
+    var hex_chars = "0123456789ABCDEF"; 
+    var noEncode = /^([a-zA-Z0-9\_\-\.])$/; 
+    var n, strCode, hex1, hex2, strEncode = ""; 
+
+    for(n = 0; n < str.length; n++) { 
+        if (noEncode.test(str.charAt(n))) { 
+            strEncode += str.charAt(n); 
+        } else { 
+            strCode = str.charCodeAt(n); 
+            hex1 = hex_chars.charAt(Math.floor(strCode / 16)); 
+            hex2 = hex_chars.charAt(strCode % 16); 
+            strEncode += "%" + (hex1 + hex2); 
+        } 
+    } 
+    return strEncode; 
+}  
+
+function url_decode(str) { 
+
+	var n, strCode, strDecode = ""; 
+	for (n = 0; n < str.length; n++) { 
+	    if (str.charAt(n) == "%") { 
+	        strCode = str.charAt(n + 1) + str.charAt(n + 2); 
+	        strDecode += String.fromCharCode(parseInt(strCode, 16)); 
+	        n += 2; 
+	    } else { 
+	        strDecode += str.charAt(n); 
+	    } 
+	} 
+	return strDecode; 
+}  
+
+
+function Element(element){
+	return document.getElementById(element);
+}
+
+function getPosition(obj)
+{
+	if(typeof obj.selectionStart != "undefined")
+	{
+    	return obj.selectionStart;
+	}
+	else if(document.selection && document.selection.createRange)
+	{
+		var M = document.selection.createRange();
+		try
+		{
+			var Lp = M.duplicate();
+			Lp.moveToElementText(obj);
+		}
+		catch(e)
+		{
+			var Lp=obj.createTextRange();
+		}
+		
+		Lp.setEndPoint("EndToStart",M);
+		var rb=Lp.text.length;
+		
+		if(rb > obj.value.length)
+		{
+			return -1;
+		}
+		return rb;
+	}
+}
+
+function trim(inputString) {
+   if (typeof inputString != "string") 
+   	return inputString;
+      
+   var retValue = inputString;
+   var ch = retValue.substring(0, 1);
+   while (ch == " ") { 
+	  retValue = retValue.substring(1, retValue.length);
+	  ch = retValue.substring(0, 1);
+   }
+   ch = retValue.substring(retValue.length-1, retValue.length);
+   while (ch == " ") { 
+	  retValue = retValue.substring(0, retValue.length-1);
+	  ch = retValue.substring(retValue.length-1, retValue.length);
+   }
+   while (retValue.indexOf("  ") != -1) { 
+	  retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); 
+   }
+   return retValue; 
+}
+
+function increment_folder_unseen(){
+	var folder_id = get_current_folder();
+	
+	var folder_unseen = Element('dftree_'+folder_id+'_unseen');
+	if (folder_unseen)
+	{
+		folder_unseen.innerHTML = (parseInt(folder_unseen.innerHTML) + 1);
+		Element('new_m').innerHTML = '<font face="Verdana" size="1" color="RED">'+folder_unseen.innerHTML+'</font>';
+	}
+	else
+	{
+		tree_folders.getNodeById(folder_id).alter({caption: tree_folders.getNodeById(folder_id).caption + '<font style=color:red>&nbsp(</font><span id="dftree_'+folder_id+'_unseen" style=color:red>1</span><font style=color:red>)</font>'});
+		tree_folders.getNodeById(folder_id)._refresh();
+		Element('new_m').innerHTML = '<font face="Verdana" size="1" color="RED">1</font>';
+	}
+}
+function decrement_folder_unseen(){
+	var folder_id = get_current_folder();
+	
+	var folder_unseen = Element('dftree_'+folder_id+'_unseen');
+	if(!folder_unseen)
+		return;
+
+	if ((folder_unseen) && (parseInt(folder_unseen.innerHTML) > 1))
+	{
+		folder_unseen.innerHTML = (parseInt(folder_unseen.innerHTML) - 1);
+		Element('new_m').innerHTML = '<font face="Verdana" size="1" color="RED">'+folder_unseen.innerHTML+'</font>';
+	}
+	else if (parseInt(folder_unseen.innerHTML) <= 1)
+	{
+		var tmp_folder_name = tree_folders.getNodeById(folder_id).caption.split('<');
+		var folder_name = tmp_folder_name[0];
+		tree_folders.getNodeById(folder_id).alter({caption: folder_name});
+		tree_folders.getNodeById(folder_id)._refresh();
+		Element('new_m').innerHTML = 0;
+	}
+}
+
+function LTrim(value){
+	var w_space = String.fromCharCode(32);
+	var strTemp = "";
+	var iTemp = 0;
+	
+	if(v_length < 1)
+		return "";
+
+	var v_length = value ? value.length : 0;
+	
+	while(iTemp < v_length){
+		if(value && value.charAt(iTemp) != w_space){
+			strTemp = value.substring(iTemp,v_length);
+			break;
+		}
+		iTemp++;
+	}	
+	return strTemp;
+}
+
+//changes MENU background color.
+function set_menu_bg(menu)
+{
+	menu.style.backgroundColor = 'white';
+	menu.style.border = '1px solid black';
+}
+//changes MENU background color.
+function unset_menu_bg(menu)
+{
+	menu.style.backgroundColor = '';
+	menu.style.border = '1px solid #f7f7f7';
+}
+
+function array_search(needle, haystack) {
+	var n = haystack.length;
+	for (var i=0; i<n; i++) {
+		if (haystack[i]==needle) {
+			return true;
+		}
+	}
+	return false;
+}
+
+ function lang_folder(fn) {
+ 	if (fn == "Inbox") return get_lang("Inbox");
+ 	if (special_folders[fn])
+ 		return get_lang(special_folders[fn]);
+ 	return fn;
+ }
+
+function add_className(obj, className){
+	if (!exist_className(obj, className))
+		obj.className = obj.className + ' ' + className;
+}
+
+function remove_className(obj, className){
+	var re = new RegExp("\\s*"+className);
+	obj.className = obj.className.replace(re, '');
+}
+
+function exist_className(obj, className){
+	if ( obj.className.indexOf(className) != -1 )
+		return true;
+	return false;
+}
+
+function select_all_messages(select)
+{
+	var main = Element("tbody_box");
+	var main_list = main.childNodes;
+	var len_main_list = main_list.length;
+	
+	if (select)
+	{
+		for (i=0; i<len_main_list; i++)
+		{
+			Element("check_box_message_"+main_list[i].id).checked = true;
+			add_className(Element(main_list[i].id), 'selected_msg');
+		}
+	}
+	else
+	{
+		for (i=0; i<len_main_list; i++)
+		{
+			Element("check_box_message_"+main_list[i].id).checked = false;
+			remove_className(Element(main_list[i].id), 'selected_msg');
+		}
+	}
+}
Index: tags/expressoMail1_2/1.2211/js/TreeS.js
===================================================================
--- tags/expressoMail1_2/1.2211/js/TreeS.js	(revision 197)
+++ tags/expressoMail1_2/1.2211/js/TreeS.js	(revision 197)
@@ -0,0 +1,188 @@
+/**************************************************************************\
+ Início 
+\**************************************************************************/
+
+	function treeS()
+	{
+		this.arrayW = new Array();
+		this.el;
+		this.FOLDER = "";
+	}
+
+	treeS.prototype.make_Window = function(){	
+		_this = this;
+		connector.loadScript("TreeShow");
+		var title = ':: '+get_lang("Manager your folders and export messages")+' ::';
+		tree 				  = document.createElement("DIV");
+		tree.style.visibility = "hidden";
+		tree.style.position   = "absolute";
+		tree.style.left 	  = "0px";
+		tree.style.top 		  = "0px";
+		tree.style.width 	  = "0px";
+		tree.style.height 	  = "0px";									
+		tree.id				  = "window_tree";
+		document.body.appendChild(tree);
+
+		tree.innerHTML = "&nbsp;&nbsp;&nbsp;<b><font color='BLACK' nowrap>"+title+"</font></b>"+
+		"&nbsp;&nbsp;<br><u></u>&nbsp;&nbsp;";
+
+		var div_buttons = document.createElement("DIV");
+		div_buttons.id = "div_buttons";
+		div_buttons.style.position = "absolute";		
+		div_buttons.style.left = "440px";
+		div_buttons.style.top = "20px"		
+		div_buttons.style.width = "130px";
+		div_buttons.style.height = "214px";
+		div_buttons.innerHTML = "<table border='0' cellpading='0' cellspacing='0'>"+
+							    "<tr>"+
+							    "<td><input type='button' value='"+get_lang('New folder')+"' onclick='ttreeBox.validate(\"newpast\")'></td>"+
+							    "</tr>"+
+							    "<tr>"+
+							    "<td><input type='button' value='"+get_lang('Delete folder')+"' onclick='ttreeBox.del()'></td>"+
+							    "</tr>"+
+							    "<tr>"+
+							    "<td><input type='button' value='"+get_lang('Rename folder')+"' onclick='ttreeBox.validate(\"rename\")'></td>"+
+							    "</tr>"+
+							    "<tr>"+
+							    "<td><input type='button' value='"+get_lang('Export messages')+"' onclick='ttreeBox.export_all_msg()'></td>"+
+							    "</tr>"+
+							    "<tr><td><br><br><br><br><br></td></tr>"+
+							    "<tr><td><input type='button' value='"+get_lang('Close')+"' onclick='ttree.close_win()'></td></tr>"+
+							    "</table>";
+		tree.appendChild(div_buttons);		
+
+		// Conf tree
+		var jo = document.createElement("DIV");
+		jo.id = "div_tree";
+		jo.style.position = "absolute";
+		jo.style.left = "10px";
+		jo.style.top = "20px";
+		jo.style.width = "420px";
+		jo.style.height = "215px";
+		jo.style.borderStyle = "outset";
+		jo.style.borderColor = "black";
+		jo.style.borderWidth = "2px";
+		jo.style.background  = "#F7F7F7";
+		jo.style.overflow    = "auto";
+		jo.innerHTML = "";
+		tree.appendChild(jo);
+
+		ttree.make_tree(folders,"div_tree","folders_tree","ttree.get_folder(\"root\")","","root",false);
+		_this.showWindow(tree);
+
+	}
+	
+	treeS.prototype.get_folder = function(param){
+		this.FOLDER = param;
+	}
+
+	treeS.prototype.showWindow = function (div){
+		if(! div) {
+			return;
+		}
+		
+		if(! this.arrayW[div.id]) {
+			div.style.width  = "580px";
+			div.style.height = "250px";
+			div.style.zIndex = "10000";			
+			var title = get_lang("Folder Management");
+			var wHeight = div.offsetHeight + "px";
+			var wWidth =  div.offsetWidth   + "px";
+			div.style.width = div.offsetWidth - 5;
+
+			win = new dJSWin({
+				id: 'win_'+div.id,
+				content_id: div.id,
+				width: wWidth,
+				height: wHeight,
+				title_color: '#3978d6',
+				bg_color: '#eee',
+				title: title,
+				title_text_color: 'white',
+				button_x_img: '../phpgwapi/images/winclose.gif',
+				border: true });
+			
+			this.arrayW[div.id] = win;
+			win.draw();
+		}
+		else {
+			win = this.arrayW[div.id];
+		}
+		win.open();
+	}
+	
+	treeS.prototype.close_win = function(){
+	
+		this.FOLDER = "";
+		this.arrayW['window_tree'].close();
+	
+	}
+
+	treeS.prototype.make_tree = function (data,destination,name_tree, click_root, opentomb, selected,menu_folder){
+		//Somente para teste
+		//alert("data: " + data.length + "\n" + "destination : " + destination + "\n" + "name_tree : " + name_tree + "\n" + "click_root : " + click_root + "\n" + "opentomb : " + opentomb + "\n" + "selected : " + selected + "\n" + "menu_folder : " + menu_folder);
+			
+		if(Element('dftree_' + name_tree)){
+			Element('dftree_' + name_tree).innerHTML = '';
+		}
+		
+		folders_tree = new dFTree({name: name_tree});
+		if(click_root != ""){
+			var n_root = new dNode({id:'root', caption:get_lang("My Folders"), onClick:click_root});
+		}else{
+			var n_root = new dNode({id:'root', caption:get_lang("My Folders")});		
+		}
+		folders_tree.add(n_root,'root'); //Places the root; second argument can be anything.
+		
+		if(data.length == 0){
+			alert("sem dados");
+			return false;
+		}
+	
+		for (var i=0; i<data.length; i++){
+			if(menu_folder){
+				if (data[i].folder_unseen > 0)
+					var nn = new dNode({id:data[i].folder_id, caption:lang_folder(data[i].folder_name) + '<font style=color:red>&nbsp(</font><span id="dftree_'+data[i].folder_id+'_unseen" style=color:red>'+data[i].folder_unseen+'</span><font style=color:red>)</font>', onClick:"change_folder('"+data[i].folder_id+"','"+data[i].folder_name+"')", plusSign:data[i].folder_hasChildren}); 
+				else
+					var nn = new dNode({id:data[i].folder_id, caption:lang_folder(data[i].folder_name), onClick:"change_folder('"+data[i].folder_id+"','"+data[i].folder_name+"')", plusSign:data[i].folder_hasChildren}); 
+			}else{
+				var nn = new dNode({id:data[i].folder_id, caption:lang_folder(data[i].folder_name), plusSign:data[i].folder_hasChildren});
+			}
+	
+			if (data[i].folder_parent == '')
+				data[i].folder_parent = 'root';
+			else if (data[i].folder_parent == 'user'){
+				if (!tree_folders.getNodeById('user')){
+					var n_root_shared_folders = new dNode({id:'user', caption:get_lang("Shared Folders"), plusSign:true}); 
+					folders_tree.add(n_root_shared_folders,'root');
+				}
+			}
+			folders_tree.add(nn,data[i].folder_parent);
+		}
+		
+/* 		if(folders_tree._folderPr.length > 0 && destination == "div_tree"){
+			var nw_rt = new dNode({id:'proble', caption:'<font style=color:red><b>' + get_lang('Problems') + '</b></font>', plusSign:true});		
+			folders_tree.add(nw_rt,'root');
+
+			for(var i=0; i < folders_tree._folderPr.length; i++){
+				var nm_fl = folders_tree._folderPr[i].split(cyrus_delimiter);
+				if( nm_fl[0] == "INBOX")
+					var nm = folders_tree._folderPr[i].substr(6,folders_tree._folderPr[i].length);
+				else
+					var nm = folders_tree._folderPr[i].substr(5,folders_tree._folderPr[i].length);
+				var nw_rm = new dNode({id:folders_tree._folderPr[i], caption:nm, plusSign:false});
+				folders_tree.add(nw_rm,'proble');
+			}
+			folders_tree._folderPr.splice(0,folders_tree._folderPr.length);
+		} 
+		*/
+		folders_tree.draw(Element(destination));
+		n_root.changeState();
+		if(opentomb != ""){folders_tree.openTo(opentomb);}
+		if(selected != "" && folders_tree.getNodeById(selected)){folders_tree.getNodeById(selected)._select();}
+
+	}
+
+/* Build the Object */
+	var ttree;
+	ttree = new treeS();
Index: tags/expressoMail1_2/1.2211/js/globals.js
===================================================================
--- tags/expressoMail1_2/1.2211/js/globals.js	(revision 248)
+++ tags/expressoMail1_2/1.2211/js/globals.js	(revision 248)
@@ -0,0 +1,44 @@
+var debug = false;
+var _bTime = new Date();
+_bTime = _bTime.getTime();
+var hold_session = false;
+var current_page = 1;
+var current_folder = 'INBOX';
+var id_menu_folders = '';
+var preferences = '';
+var contacts = '';
+var search_box_type = 'ALL';
+var sort_box_type = 'SORTARRIVAL';
+var sort_box_reverse = 1;
+var last_message_selected = '';
+var array_lang = new Array();
+var cyrus_delimiter = '';
+var ccaddress_array = new Array();
+var toaddress_array = new Array();
+var tree_folders = '';
+var folders = new Array();
+var title_app_menu = '<table height="16px" align=center border=0 width=100% cellspacing=0 cellpadding=2>'+
+	'<tr><td align=left height=16px width="1%" nowrap class="table_top">&nbsp;'+
+	'<a href=# onclick="javascript:new_message(\'new\',\'null\')" align=left>'+
+	'<img src="templates/default/images/menu/createmail.gif">'+
+	'&nbsp;Novo</a>&nbsp;&nbsp;'+
+	'<a href="#" onclick="javascript:wfolders.makeWindow(\'\', \'change_folder\')" align=left>'+
+	'<img src="templates/default/images/menu/editfolders.png">'+
+	'&nbsp;Trocar Pasta</a>&nbsp;&nbsp'+	
+	'<a href="#" onclick="javascript:refresh();" align=left>'+
+	'<img src="templates/default/images/menu/checkmail.gif">'+
+	'&nbsp;Atualizar</a>&nbsp;&nbsp;'+
+	'<a id="link_tools" href="#" align=left>'+
+	'<img height="16px" src="templates/default/images/menu/tools.gif">'+
+	'&nbsp;Ferramentas...</a>&nbsp;&nbsp;</td><td style="padding-left:17px" width="1%" id="content_quota" align=left nowrap></td><td width=* id="div_menu_c3" align="right"></td></tr></table>';
+
+var title_app = '<table height="16px" border=0 width=100% cellspacing=0 cellpadding=2>'+
+	'<tr>'+
+	'<td style="padding-left:17px" width=33% id="content_quota" align=left></td>'+
+	'<td width=33% height=16px align=center nowrap><font face=Verdana, Arial, Helvetica, sans-serif color=#000066 size=2>'+
+	'<b>ExpressoMail</b><font size=1><b> - Versão 1.2</b></font></td>'+
+	'<td width=33% id="div_menu_c3" align=right></td>'+
+	'</tr></table>';
+
+var divStatusBar = document.getElementById("divStatusBar");
+var denyFileExtensions = new Array('exe','com','reg','chm','cnf','hta','ins','jse','job','lnk','pif','src','scf','sct','shb','vbe','vbs','wsc','wsf','wsh','cer','its','mau','','mda','mar','mdz','prf','pst');
Index: tags/expressoMail1_2/1.2211/js/main.js
===================================================================
--- tags/expressoMail1_2/1.2211/js/main.js	(revision 271)
+++ tags/expressoMail1_2/1.2211/js/main.js	(revision 271)
@@ -0,0 +1,1365 @@
+// Tempo do auto refresh (em milisegundos)
+var time_refresh = 300000;
+var autosave_time = 60000;
+
+function init(){
+	if (!is_ie)
+		Element('tableDivAppbox').width = '100%';
+	
+	var save_contacts = function(data){
+		contacts = data;
+	}
+	var save_preferences = function(data){
+		preferences = data;
+		if(preferences.hide_folders == "1")
+			Element('divAppboxHeader').innerHTML =  title_app_menu;
+
+		if (preferences.delete_trash_messages_after_n_days != 0)
+			cExecute ("$this.imap_functions.automatic_trash_cleanness&before_date="+preferences.delete_trash_messages_after_n_days+"&cyrus_delimiter="+cyrus_delimiter, handler_automatic_trash_cleanness);
+
+		if(preferences.outoffice)
+			write_msg(get_lang("Attention, you are in out of office mode."), true);
+		ConstructMenuTools();
+		cExecute ("$this.imap_functions.get_folders_list", update_menu);
+	}
+	var handler_automatic_trash_cleanness = function(data){
+		if (data != false){
+			write_msg(data.length +' '+ Element('txt_clear_trash').value);
+		}
+	}
+	
+	// Versão
+	Element('divAppboxHeader').innerHTML = title_app;
+	
+	// Get cyrus delimiter
+	cyrus_delimiter = Element('cyrus_delimiter').value;
+	
+	alternate_border(0);
+	cExecute ("$this.db_functions.get_dropdown_contacts", save_contacts);
+	cExecute ("$this.functions.get_preferences", save_preferences);
+	setTimeout('auto_refresh()', time_refresh);
+}
+
+var away = false;
+var away_timer;
+function setAway ()
+{
+	away_timer = setTimeout("setAway()", 5000);
+	away=true;
+}
+
+function auto_save_msg(border_id)
+{
+	if (document.getElementById('border_id_'+border_id))
+	{	
+		var	 keypress_handler = function stop_counting ()
+		{
+			clearTimeout(away_timer);
+			away=false;
+			away_timer = setTimeout('setAway()',5000);
+		};
+		
+		var obj = document.getElementById('body_'+border_id).contentWindow.document;
+		if ( obj.addEventListener )
+				obj.addEventListener('keypress', keypress_handler, false);
+		else if ( obj.attachEvent )
+			obj.attachEvent('onkeypress', keypress_handler);
+
+		if (away)
+			{
+				var save_link = Element("save_message_options");
+				if (save_link.onclick !=  '')
+					save_msg(border_id);
+				else
+					setTimeout('auto_save_msg('+border_id+')',autosave_time);
+			}
+			else
+				setTimeout('auto_save_msg('+border_id+')',3000);
+	}
+}
+
+function watch_changes_in_msg(border_id)
+{
+	if (document.getElementById('border_id_'+border_id))
+	{	
+		function keypress_handler ()
+		{
+			away=false;
+			var save_link = Element("save_message_options");
+			save_link.onclick = function onclick(event) { newMessageTab.toPreserve[border_id] = true; save_msg(border_id); } ;
+			save_link.style.color = '#0000ff';
+		};
+		
+		var obj = document.getElementById('body_'+border_id).contentWindow.document;
+		if ( obj.addEventListener )
+				obj.addEventListener('keypress', keypress_handler, false);
+		else if ( obj.attachEvent )
+			obj.attachEvent('onkeypress', keypress_handler);
+			
+		var subject_obj = document.getElementById('subject_'+border_id);
+		if ( subject_obj.addEventListener )
+				subject_obj.addEventListener('keypress', keypress_handler, false);
+		else if ( subject_obj.attachEvent )
+			subject_obj.attachEvent('onkeypress', keypress_handler);
+			
+		var to_obj = document.getElementById('to_'+border_id);
+		if ( to_obj.addEventListener )
+				to_obj.addEventListener('keypress', keypress_handler, false);
+		else if ( to_obj.attachEvent )
+			to_obj.attachEvent('onkeypress', keypress_handler);
+		
+	}
+}
+
+
+
+function show_msg(msg_info){
+	if(!verify_session(msg_info))
+		return;
+	
+	if (msg_info.status_get_msg_info == 'false')
+	{
+		write_msg(get_lang("Problems reading your message")+ ".");
+		return;
+	}
+	
+	var handler_sendNotification = function(data){
+		if (data)
+			write_msg(get_lang("A read confirmation was sent."));
+		else
+			write_msg(get_lang("Error in SMTP sending read confirmation."));
+	}
+	
+	if (msg_info.status == 'false'){
+		eval(msg_info.command_to_exec);
+	}
+	else{
+		if (preferences.use_shortcuts == '1')
+			select_msg(msg_info.msg_number, 'null');
+		// Call function to draw message
+		var id_msg_read = msg_info.msg_number +"_r";
+		// If needed, delete old border
+		if (msg_info.reuse_border)
+			delete_border(msg_info.reuse_border,'false');
+
+		
+		if(Element("border_id_" + id_msg_read)) 
+			alternate_border(id_msg_read);		
+		else {
+			var border_id = create_border(msg_info.subject, id_msg_read);
+			if(border_id)
+				draw_message(msg_info,border_id);
+			else
+				return;
+		}
+
+		//Change msg class to read.
+		set_msg_as_read(msg_info['msg_number'], true);
+		
+		if ((msg_info.DispositionNotificationTo) && ((msg_info.Unseen == 'U') || (msg_info.Recent == 'N'))){
+			cExecute ("$this.imap_functions.send_notification&notificationto="+msg_info.DispositionNotificationTo+"&subject="+url_encode(msg_info.subject), handler_sendNotification);
+		}
+	}
+}
+
+function auto_refresh(){
+	refresh(preferences.alert_new_msg);
+	setTimeout('auto_refresh()', time_refresh);
+}
+
+function refresh(alert_new_msg){
+	var handler_refresh = function(data){
+		if(!verify_session(data))
+			return;
+		if (data.length > 0){
+			var msg_info = document.getElementById('msg_info')
+			if (msg_info != null)
+				main.removeChild(msg_info);
+
+			table_element = Element("table_box");
+			var box = Element("tbody_box");
+			table_element.appendChild(box);
+			for (var i=0; i<data.length; i++){
+				var new_msg = this.make_tr_message(data[i], current_folder);
+				_dragArea.makeDragged(new_msg, data[i].msg_number, data[i].subject, true);
+				eval(data[i].command);
+			}
+			
+			for (var i=0; i<data.msgs_to_delete.length; i++){
+				var remove_msg = document.getElementById(data.msgs_to_delete[i]);
+				if (remove_msg)
+					remove_msg.parentNode.removeChild(remove_msg);
+			}
+			if(parseInt(alert_new_msg) && data.new_msgs > 0)
+				alert(get_lang("You have %1 new", data['new_msgs'])+" "+(data['new_msgs'] > 1 ? get_lang("messages") : get_lang("message")) +"!");
+			if(data.new_msgs > 0){
+			Element('tot_m').innerHTML = parseInt(Element('tot_m').innerHTML) + parseInt(data.new_msgs); //refresh tab title
+			update_quota();
+			}
+		}
+		update_menu();
+	}
+
+	msg_range_end = (current_page*preferences.max_email_per_page);
+	msg_range_begin = (msg_range_end-(preferences.max_email_per_page)+1);
+	
+	
+	//Get element tBody.
+	main = Element("tbody_box");
+	if(!main)
+		return;	
+
+	// Get all TR (messages) in tBody.
+	main_list = main.childNodes;
+	var tmp = '';
+	var string_msgs_in_main = '';
+
+	var len = main_list.length; 
+	for (var j=0; j < len; j++)
+		tmp += main_list[j].id + ',';
+		
+	string_msgs_in_main = tmp.substring(0,(tmp.length-1));
+	cExecute ("$this.imap_functions.refresh&folder="+current_folder+"&msgs_existent="+string_msgs_in_main+"&msg_range_begin="+msg_range_begin+"&msg_range_end="+msg_range_end+"&sort_box_type="+sort_box_type+"&search_box_type="+search_box_type+"&sort_box_reverse="+sort_box_reverse, handler_refresh);
+}
+
+function delete_msgs(folder, msgs_number, border_ID)
+{
+	if (folder == 'null')
+		folder = get_current_folder();
+
+	if ((parseInt(preferences.save_deleted_msg)) && (folder!='INBOX'+cyrus_delimiter+trashfolder)){
+		move_msgs(folder, msgs_number, border_ID, 'INBOX'+cyrus_delimiter+trashfolder,trashfolder );
+		return;
+	}
+	
+	var handler_delete_msgs = function(data){
+		Element('chk_box_select_all_messages').checked = false;
+		mail_msg = Element("tbody_box");
+		
+		if ( preferences.use_shortcuts == '1') {
+			var all_messages = Element('tbody_box').childNodes;
+
+			//Last msg is selected
+			if ( exist_className(all_messages[all_messages.length-1], 'selected_shortcut_msg') ) {
+				select_msg('null', 'up', true);
+			}
+			else {
+				if (!select_msg('null', 'down', true)) {
+					select_msg('null', 'up', true);
+				}
+			}
+		}
+		
+		var msg_to_delete;
+		for (var i=0; i<data.msgs_number.length; i++){
+			msg_to_delete = Element(data.msgs_number[i]);
+			if (msg_to_delete){
+				mail_msg.removeChild(msg_to_delete);
+			}
+		}
+		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.border_ID != 'null'){
+			if (parseInt(preferences.delete_and_show_previous_message))
+				show_msg(data.previous_msg);
+			else
+				delete_border(data.border_ID,'false');
+		}
+		Element('tot_m').innerHTML = parseInt(Element('tot_m').innerHTML) - data.msgs_number.length;
+		refresh();
+	}
+
+	if (msgs_number == 'selected')
+		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+"&reuse_border="+border_ID+"&get_previous_msg="+preferences.delete_and_show_previous_message, handler_delete_msgs);
+	else
+		write_msg(get_lang('No selected message.'));		
+}
+
+function move_search_msgs(border_id, new_folder, new_folder_name){
+	var selected_messages = '';
+	var main_list = Element("tbody_resultsearch_"+border_id.substr(18)).childNodes;	
+	for (j = 0; j < main_list.length; j++)	{
+		var check_box = Element("check_box_search_message_"+main_list[j].id);
+		if(check_box && check_box.checked) {
+			selected_messages += main_list[j].id + ',';
+		}
+	}
+	selected_messages = selected_messages.substring(0,(selected_messages.length-1));
+	var handler_move_search_msgs = function(data){
+		if(!data || !data.msgs_number)
+			return;
+		else if(data.deleted) {			
+			if (data.msgs_number.length == 1)
+				write_msg(get_lang("The message was deleted."));
+			else
+				write_msg(get_lang("The messages were deleted."));			
+		}
+		else{
+			if (data.msgs_number.length == 1)
+				write_msg(get_lang("The message was moved to folder ") + lang_folder(data.new_folder_name));
+			else
+				write_msg(get_lang("The messages were moved to folder ") + lang_folder(data.new_folder_name));
+		}
+	
+		selected_messages = selected_messages.split(",");
+		for (i = 0; i < selected_messages.length; i++){
+			var tr = Element(selected_messages[i]);
+			tr.parentNode.removeChild(tr);
+		}			
+	}	
+
+	if (selected_messages){
+		var params = "";
+		if (!new_folder && parseInt(preferences.save_deleted_msg)){ 
+			new_folder = 'INBOX'+cyrus_delimiter+trashfolder;
+			new_folder_name = trashfolder;
+			params = "&delete=true";
+		}			
+		params += "&selected_messages="+url_encode(selected_messages);
+		if(new_folder) {
+			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);
+	}
+	else
+		write_msg(get_lang('No selected message.'));		
+}
+
+function move_msgs(folder, msgs_number, border_ID, new_folder, new_folder_name){
+
+	if (folder == 'null')
+		folder = Element("input_folder_"+msgs_number+"_r") ? Element("input_folder_"+msgs_number+"_r").value : get_current_folder();			
+
+	var handler_move_msgs = function(data){
+
+		if(typeof(data) == 'string' && data.match(/^(.*)TRYCREATE(.*)$/)){
+			var move_to_folder = data.match(/^(.*)Spam(.*)$/) ? "Spam" : "Lixeira";
+			alert(get_lang('Its %1 folder is not created. It is necessary to create so that it functions correctly.', move_to_folder));
+			return false;
+		}
+
+		Element('chk_box_select_all_messages').checked = false;
+		mail_msg = Element("tbody_box");
+		data.msgs_number = data.msgs_number.split(",");
+		
+		if ( preferences.use_shortcuts == '1') {
+			var all_messages = Element('tbody_box').childNodes;
+
+			//Last msg is selected
+			if ( exist_className(all_messages[all_messages.length-1], 'selected_shortcut_msg') ) {
+				select_msg('null', 'up', true);
+			}
+			else {
+				if (!select_msg('null', 'down', true)) {
+					select_msg('null', 'up', true);
+				}
+			}
+		}
+
+		var msg_to_delete;		
+		for (var i=0; i<data.msgs_number.length; i++)
+		{
+			msg_to_delete = Element(data.msgs_number[i]);
+			if (msg_to_delete)
+				mail_msg.removeChild(msg_to_delete);
+		}
+
+		if (data.msgs_number.length == 1)
+			write_msg(get_lang("The message was moved to folder ") + lang_folder(data.new_folder_name));
+		else
+			write_msg(get_lang("The messages were moved to folder ") + lang_folder(data.new_folder_name));
+
+		if (data.border_ID != '' && data.border_ID != 'null'){
+			if (parseInt(preferences.delete_and_show_previous_message) && folder == get_current_folder())
+				show_msg(data.previous_msg);
+			else
+				delete_border(data.border_ID,'false');
+		}
+		if(folder == get_current_folder())
+			Element('tot_m').innerHTML = parseInt(Element('tot_m').innerHTML) - data.msgs_number.length;			
+		refresh();
+	}
+
+	if (folder == new_folder){
+		write_msg(get_lang('The origin folder and the destination folder are the same.'));
+		return;
+	}
+
+	if (msgs_number == 'selected')
+		msgs_number = get_selected_messages();
+
+	if (parseInt(msgs_number) > 0 || msgs_number.length > 0)
+		cExecute ("$this.imap_functions.move_messages&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+"&reuse_border="+border_ID+"&new_folder="+new_folder+"&new_folder_name="+new_folder_name+"&get_previous_msg="+preferences.delete_and_show_previous_message, handler_move_msgs);
+	else
+		write_msg(get_lang('No selected message.'));		
+}
+
+function get_selected_messages(){
+	main = Element("tbody_box");
+	
+	// Get all TR (messages) in tBody.
+	main_list = main.childNodes;
+	
+	var selected_messages = '';
+	var selected_messages_by_shortcuts = '';
+	var j = 0;
+	for (j; j<(main_list.length); j++)
+	{
+		check_box = Element("check_box_message_"+main_list[j].id);
+		if ( (check_box) && (check_box.checked) )
+		{
+			selected_messages += main_list[j].id + ',';
+		}
+		
+		if (preferences.use_shortcuts == '1')
+		{
+			if ( exist_className(Element(main_list[j].id), 'selected_shortcut_msg') )
+			{
+				selected_messages_by_shortcuts += main_list[j].id + ',';
+			}
+		}
+	}
+	selected_messages = selected_messages.substring(0,(selected_messages.length-1));
+	
+	if (preferences.use_shortcuts == '1')
+	{
+		selected_messages_by_shortcuts = selected_messages_by_shortcuts.substring(0,(selected_messages_by_shortcuts.length-1));
+		
+		var array_selected_messages_by_shortcuts = selected_messages_by_shortcuts.split(",");
+		var array_selected_messages = selected_messages.split(",");
+		
+		if ((array_selected_messages.length <= 1) && (array_selected_messages_by_shortcuts.length > 1))
+		{
+			return selected_messages_by_shortcuts;
+		}
+	}
+	
+	if (selected_messages == '')
+		return false;
+	else
+		return selected_messages;
+}
+
+function new_message(type, border_ID){
+
+	var new_border_ID = draw_new_message(parseInt(border_ID));
+	if (preferences.auto_save_draft == 1)
+		setTimeout('auto_save_msg('+new_border_ID+')', autosave_time);		
+	
+	// Salva a pasta da mensagem respondida ou encaminhada:
+	var folder_message = Element("input_folder_"+border_ID);
+	if(folder_message) {
+		var input_current_folder = document.createElement('input');	
+		input_current_folder.id = "new_input_folder_"+border_ID;
+		input_current_folder.name = "input_folder";
+		input_current_folder.type = "hidden";
+		input_current_folder.value = folder_message.value;
+		Element("content_id_" + new_border_ID).appendChild(input_current_folder);
+	}//Fim.
+	var title = '';
+	data = [];
+	if (Element("from_" + border_ID)){
+		if (document.getElementById("reply_to_" + border_ID)){
+			data.to = document.getElementById("reply_to_values_" + border_ID).value;
+			data.to = data.to.replace(/&lt;/gi,"<");
+			data.to = data.to.replace(/&gt;/gi,">");
+		}
+		else {
+			data.to = document.getElementById("from_values_" + border_ID).value;
+			data.to = data.to.replace(/&lt;/gi,"<");
+			data.to = data.to.replace(/&gt;/gi,">");
+		}	
+		
+		data.to_all = document.getElementById("to_values_" + border_ID).value;
+		data.to_all = data.to_all.replace(/\n/gi," ");		
+		data.to_all = data.to_all.replace(/&lt;/gi,"<");
+		data.to_all = data.to_all.replace(/&gt;/gi,">");
+		// delete user email from to_all array.
+		var _array_to_all = data.to_all.split(",");
+		data.to_all = new Array();
+		var j = 0;
+		for(i = 0; i < _array_to_all.length; i++) {			
+			if(_array_to_all[i].lastIndexOf(Element("user_email").value) == "-1"){
+				data.to_all[j++] = _array_to_all[i];
+			}
+		}
+		data.to_all = data.to_all.join(",");
+	}
+	
+	if (document.getElementById("cc_" + border_ID)){
+		data.cc = document.getElementById("cc_values_" + border_ID).value;
+		data.cc = data.cc.replace(/&lt;/gi,"<");
+		data.cc = data.cc.replace(/&gt;/gi,">");
+	}
+	if (document.getElementById("subject_" + border_ID))
+		data.subject = document.getElementById("subject_" + border_ID).innerHTML;
+	if (document.getElementById("body_" + border_ID))
+		data.body = document.getElementById("body_" + border_ID).innerHTML;
+	
+	if (Element('date_' + border_ID)){
+		data.date = Element('date_' + border_ID).innerHTML;
+	}
+	
+	if (Element('date_day_' + border_ID)){
+		data.date_day = Element('date_day_' + border_ID).value;
+	}
+	if (Element('date_hour_' + border_ID)){
+		data.date_hour = Element('date_hour_' + border_ID).value;
+	}
+	
+	switch(type){
+		case "reply_without_history":			
+			Element("to_" + new_border_ID).value = data.to;
+			title = "Re: " + data.subject;
+			Element("subject_" + new_border_ID).value = "Re: " + data.subject;			
+			var body = Element("body_" + new_border_ID);
+			body.contentWindow.document.open();
+			body.contentWindow.document.write("<html><body bgcolor='#FFFFFF'></body></html>");
+			body.contentWindow.document.close();
+			body.contentWindow.document.designMode = "on";
+			//Focus
+			if (is_ie)
+				window.setTimeout('document.getElementById("body_'+new_border_ID+'").contentWindow.focus();', 300);
+			else
+				body.contentWindow.focus();
+			if (is_ie)
+				body.contentWindow.document.onkeypress = function(){if(body.contentWindow.event.keyCode == 13){changeEnterKey(body.contentWindow)}};
+			msg_reply_from = document.createElement('input');
+			msg_reply_from.id = "msg_reply_from_" + new_border_ID;
+			msg_reply_from.type = "hidden";
+			msg_reply_from.value = Element("msg_number_" + border_ID).value;
+			Element("content_id_" + new_border_ID).appendChild(msg_reply_from);
+			break;
+		case "reply_with_history":
+			title = "Re: " + data.subject;
+			Element("subject_" + new_border_ID).value = "Re: " + data.subject;
+			Element("to_" + new_border_ID).value = data.to;
+			block_quoted_body = make_body_reply(data.body, data.to, data.date_day, data.date_hour);
+			var body = Element("body_" + new_border_ID);
+			body.contentWindow.document.open();
+			body.contentWindow.document.write("<html><body bgcolor='#FFFFFF'>"+block_quoted_body+"</body></html>");
+			body.contentWindow.document.close();
+			body.contentWindow.document.designMode = "on";
+			//Focus
+			if (is_ie)
+				window.setTimeout('document.getElementById("body_'+new_border_ID+'").contentWindow.focus();', 300);
+			else
+				body.contentWindow.focus();
+			if (is_ie)
+				body.contentWindow.document.onkeypress = function(){if(body.contentWindow.event.keyCode == 13){changeEnterKey(body.contentWindow)}};
+			msg_reply_from = document.createElement('input');
+			msg_reply_from.id = "msg_reply_from_" + new_border_ID;
+			msg_reply_from.type = "hidden";
+			msg_reply_from.value = Element("msg_number_" + border_ID).value;
+			Element("content_id_" + new_border_ID).appendChild(msg_reply_from);
+			break;
+		case "reply_to_all_without_history":
+			title = "Re: " + data.subject;
+			Element("subject_" + new_border_ID).value = "Re: " + data.subject;
+			Element("to_" + new_border_ID).value = data.to;
+			Element("to_" + new_border_ID).value += ', ' + data.to_all;
+			if (data.cc){
+				Element("cc_" + new_border_ID).value = data.cc;
+				Element("a_cc_link_" + new_border_ID).style.display='none';
+				Element("tr_cc_" + new_border_ID).style.display='';
+				Element('space_link_' + new_border_ID).style.display='none';
+			}
+			var body = Element("body_" + new_border_ID);
+			body.contentWindow.document.open();
+			body.contentWindow.document.write("<html><body bgcolor='#FFFFFF'></body></html>");
+			body.contentWindow.document.close();
+			body.contentWindow.document.designMode = "on";
+			//Focus
+			if (is_ie)
+				window.setTimeout('document.getElementById("body_'+new_border_ID+'").contentWindow.focus();', 300);
+			else
+				body.contentWindow.focus();
+			if (is_ie)
+				body.contentWindow.document.onkeypress = function(){if(body.contentWindow.event.keyCode == 13){changeEnterKey(body.contentWindow)}};
+			msg_reply_from = document.createElement('input');
+			msg_reply_from.id = "msg_reply_from_" + new_border_ID;
+			msg_reply_from.type = "hidden";
+			msg_reply_from.value = Element("msg_number_" + border_ID).value;
+			Element("content_id_" + new_border_ID).appendChild(msg_reply_from);
+			break;
+		case "reply_to_all_with_history":
+			title = "Re: " + data.subject;
+			Element("to_" + new_border_ID).value = data.to;
+			Element("to_" + new_border_ID).value += ', ' + data.to_all;
+			if (data.cc){
+				document.getElementById("cc_" + new_border_ID).value = data.cc;
+				document.getElementById("a_cc_link_" + new_border_ID).style.display='none';
+				document.getElementById("tr_cc_" + new_border_ID).style.display='';
+				document.getElementById('space_link_' + new_border_ID).style.display='none';
+			}
+			document.getElementById("subject_" + new_border_ID).value = "Re: " + data.subject;
+			block_quoted_body = make_body_reply(data.body, data.to, data.date_day, data.date_hour);
+			var body = document.getElementById("body_" + new_border_ID);
+			body.contentWindow.document.open();
+			body.contentWindow.document.write("<html><body bgcolor='#FFFFFF'>"+block_quoted_body+"</body></html>");
+			body.contentWindow.document.close();
+			body.contentWindow.document.designMode = "on";
+			//Focus
+			if (is_ie)
+				window.setTimeout('document.getElementById("body_'+new_border_ID+'").contentWindow.focus();', 300);
+			else
+				body.contentWindow.focus();
+			if (is_ie)
+				body.contentWindow.document.onkeypress = function(){if(body.contentWindow.event.keyCode == 13){changeEnterKey(body.contentWindow)}};
+			msg_reply_from = document.createElement('input');
+			msg_reply_from.id = "msg_reply_from_" + new_border_ID;
+			msg_reply_from.type = "hidden";
+			msg_reply_from.value = Element("msg_number_" + border_ID).value;
+			Element("content_id_" + new_border_ID).appendChild(msg_reply_from);
+			break;
+		case "forward":
+			msg_forward_from = document.createElement('input');
+			msg_forward_from.id = "msg_forward_from_" + new_border_ID;
+			msg_forward_from.type = "hidden";
+			msg_forward_from.value = Element("msg_number_" + border_ID).value;
+			Element("content_id_" + new_border_ID).appendChild(msg_forward_from);			
+			title = "Fw: " + data.subject;
+			document.getElementById("subject_" + new_border_ID).value = "Fw: " + data.subject;
+			var divFiles = Element("divFiles_"+new_border_ID);
+			if (Element("attachments_" + border_ID)){
+				var attachments = document.getElementById("attachments_" + border_ID).childNodes;
+				for (var i = (attachments.length > 1 ? 1 : 0); i < attachments.length; i++){
+					var link_attachment = document.createElement("A");
+					link_attachment.setAttribute("href", attachments[i].href);
+					link_attachment.innerHTML = attachments[i].innerHTML;
+					var tmp = link_attachment.href.replace("javascript:download_attachments(", "").replace(")", "");
+					var a_tmp = tmp.split(',');
+					tmp = link_attachment.innerHTML.substring(0,link_attachment.innerHTML.lastIndexOf("("));
+					a_tmp[2] = "'"+tmp.substring(0,tmp.length-1)+"'";
+					s_tmp = escape(connector.serialize(a_tmp));
+					divFiles.innerHTML += "<input style='border:0' type='CHECKBOX' name='forwarding_attachments[]' checked value=\""+s_tmp+"\"/>";
+					divFiles.appendChild(link_attachment);
+				}
+			}
+			var body = Element("body_" + new_border_ID);
+			body.contentWindow.document.open();
+			body.contentWindow.document.write("<html><body bgcolor='#FFFFFF'>"+make_forward_body(data.body, data.to, data.date, data.subject, data.to_all, data.cc)+"</body></html>");
+			body.contentWindow.document.close();
+			body.contentWindow.document.designMode = "on";
+			if (is_ie)
+				body.contentWindow.document.onkeypress = function(){if(body.contentWindow.event.keyCode == 13){changeEnterKey(body.contentWindow)}};
+			Element("to_" + new_border_ID).focus();
+			break;
+		case "new":
+			title = get_lang("New Message");
+			if(Element('msg_number').value) {
+				var _to = Element('msg_number').value;
+				var reEmail = /^[A-Za-z\d_-]+(\.[A-Za-z\d_-]+)*@(([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}\])$/;				
+				if(!reEmail.test(_to)){
+					var array_contacts = contacts.split(',');
+					for(i = 0; i < array_contacts.length;i++) {
+						if(array_contacts[i].lastIndexOf(_to) != "-1"){
+							var _group = array_contacts[i].split(";");
+							_to = '"'+_group[0]+'" <'+_group[1]+'>';
+							break;
+						}
+					}
+				}
+				Element("to_" + new_border_ID).value = _to +',';
+				Element('msg_number').value = '';
+			}
+			var body = document.getElementById("body_" + new_border_ID);
+			body.contentWindow.document.open();
+			body.contentWindow.document.write("<html><body bgcolor='#FFFFFF'></body></html>");
+			body.contentWindow.document.close();
+			body.contentWindow.document.designMode = "on";
+			if (is_ie)
+				body.contentWindow.document.onkeypress = function(){if(body.contentWindow.event.keyCode == 13){changeEnterKey(body.contentWindow)}};
+			Element("to_" + new_border_ID).focus();			
+			break;
+		case "edit":
+			newMessageTab.imapBox[new_border_ID] = folder_message.value
+			newMessageTab.imapUid[new_border_ID] = parseInt(border_ID.substr(0,border_ID.indexOf("_")));
+			document.getElementById('font_border_id_'+new_border_ID).innerHTML = data.subject;
+			data.to = Element("to_values_" + border_ID).value;
+			data.to = data.to.replace(/&lt;/gi,"<");
+			data.to = data.to.replace(/&gt;/gi,">");
+			title = "Edição: "+data.subject;
+			
+			Element("to_" + new_border_ID).value = data.to;
+			if (data.cc){
+				Element("cc_" + new_border_ID).value = data.cc;
+				Element("space_link_" + new_border_ID).style.display = 'none';
+				Element("a_cc_link_" + new_border_ID).style.display = 'none';
+				Element("tr_cc_"+ new_border_ID).style.display = '';
+			}
+			Element("subject_" + new_border_ID).value = data.subject;
+			
+			var divFiles = Element("divFiles_"+new_border_ID);
+			if (Element("attachments_" + border_ID)){
+				var attachments = document.getElementById("attachments_" + border_ID).childNodes;
+				for (var i = (attachments.length > 1 ? 1 : 0); i < attachments.length; i++){
+					var link_attachment = document.createElement("A");
+					link_attachment.setAttribute("href", attachments[i].href);
+					link_attachment.innerHTML = attachments[i].innerHTML;
+					var tmp = link_attachment.href.replace("javascript:download_attachments(", "").replace(")", "");
+					var a_tmp = tmp.split(',');
+					tmp = link_attachment.innerHTML.substring(0,link_attachment.innerHTML.lastIndexOf("("));
+					a_tmp[2] = "'"+tmp.substring(0,tmp.length-1)+"'";
+					s_tmp = escape(connector.serialize(a_tmp));
+					divFiles.innerHTML += "<input style='border:0' type='CHECKBOX' name='forwarding_attachments[]' checked value=\""+s_tmp+"\"/>";
+					divFiles.appendChild(link_attachment);
+				}
+			}
+			var body = Element("body_" + new_border_ID);
+			body.contentWindow.document.open();
+			body.contentWindow.document.write("<html><body bgcolor='#FFFFFF'>"+data.body+"</body></html>");
+			body.contentWindow.document.close();
+			body.contentWindow.document.designMode = "on";
+			//Focus
+			if (is_ie)
+				window.setTimeout('document.getElementById("body_'+new_border_ID+'").contentWindow.focus();', 300);
+			else
+				body.contentWindow.focus();
+			if (is_ie)
+				body.contentWindow.document.onkeypress = function(){if(body.contentWindow.event.keyCode == 13){changeEnterKey(body.contentWindow)}};
+			break;
+		default:
+	}
+	
+	//BEGIN Tab event
+	if (preferences.use_shortcuts == '1')
+	{
+		if (is_ie)
+		{
+			body.contentWindow.document.attachEvent('onkeydown', function(event) { if(event.keyCode==27){delete_border(new_border_ID,'false');} if(event.keyCode==9) { Element('to_'+new_border_ID).focus(); Element('send_button_'+new_border_ID).focus(); return false;} }, false);
+		}
+		else
+		{
+			body.contentWindow.document.addEventListener('keypress', function(event) { if(event.keyCode==27){delete_border(new_border_ID,'false');} if(event.keyCode==9) { Element('send_button_'+new_border_ID).focus(); event.preventDefault(); } }, false);
+		}
+	}
+	// END Tab event
+	
+	var offWidth = Element('border_blank').offsetWidth ? Element('border_blank').offsetWidth : Element('border_blank').clientWidth;
+	var resize = false;
+	
+	if (offWidth < 200) {
+		resize = Element("border_id_" + new_border_ID).style.width;
+	}
+
+	if (title.length > 21){
+		title = title.substring(0,21) + "...";
+	}
+	
+	if(resize)
+		title = title.substring(0, parseInt(resize)*0.08);
+
+	Element("border_id_" + new_border_ID).innerHTML = "<table width=100% border=0 cellspacing=0 cellpadding=0><tr><td id=font_border_id_" + new_border_ID +" class='font-menu' width=*>" +title + "</td><td width=1px><img onmousedown='javascript:return false' style='cursor:pointer' onclick=delete_border('" + new_border_ID + "','false') src='templates/default/images/close_button.gif'></td></tr></table>";
+}
+
+// Change the tag <P> for the tag <BR> on IE
+function changeEnterKey(win) {
+	var oSel = win.document.selection.createRange();
+	oSel.pasteHTML("<br />");
+	win.event.cancelBubble = true;
+	win.event.returnValue=false;
+	oSel.select();
+	oSel.moveEnd("character",1);
+	oSel.moveStart("character",1);
+	oSel.collapse(false);
+	return false;
+}
+
+function send_message_return(data, ID){
+	if(data && data == true ){
+		// if send ok, set a flag as answered or forwarded
+		var msg_number_replied = Element('msg_reply_from_'+ID);
+		var msg_number_forwarded = Element('msg_forward_from_'+ID);
+
+		if (msg_number_replied){
+			set_message_flag(msg_number_replied.value, 'answered');
+		}
+		else if (msg_number_forwarded){
+			set_message_flag(msg_number_forwarded.value, 'forwarded');
+		}
+		delete_border(ID,'true');
+		if(wfolders.alert){
+			write_msg(get_lang('Your message was sent and save.'));
+			wfolders.alert = false;
+		}else{
+			write_msg(get_lang('Your message was sent.'));		
+		}
+	}
+	else{			
+		if(data == 'false')
+			write_msg(get_lang('The size of this message has exceeded  the limit (%1B).',Element('upload_max_filesize').value));
+		else if(data == null)
+			write_msg(get_lang("your session could not be verified."));
+		else
+			write_msg(data);
+	}
+	if ((! newMessageTab.toPreserve[ID]) && (newMessageTab.imapUid[ID] != 0))
+		cExecute ("$this.imap_functions.delete_msgs&folder="+newMessageTab.imapBox[ID]+"&msgs_number="+newMessageTab.imapUid[ID],function(data){ return });
+}
+
+function send_message(ID, folder, folder_name){
+	var save_link = Element("save_message_options");
+	save_link.onclick = '';
+	save_link.style.color = '#999';
+	
+	ID_tmp = ID;
+
+	var handler_send_message = function(data){
+		send_message_return(data, this.ID_tmp); // this is a hack to escape quotation form connector bug
+	};
+		
+	var textArea = document.createElement("TEXTAREA");
+	textArea.style.display='none';
+	textArea.name = "body";
+	body = document.getElementById("body_"+ID);
+	textArea.value += '<body>\r\n';
+	textArea.value += body.contentWindow.document.body.innerHTML;
+	textArea.value += '\r\n</body>';
+	var input_folder = document.createElement("INPUT");
+	input_folder.style.display='none';
+	input_folder.name = "folder";
+	input_folder.value = folder;
+	var msg_id = document.createElement("INPUT");
+	msg_id.style.display='none';
+	msg_id.name = "msg_id";
+	msg_id.value = newMessageTab.imapUid[ID];
+	
+	if (is_ie){
+		var i = 0;
+		while (document.forms(i).name != "form_message_"+ID){i++}
+		form = document.forms(i);
+	}
+	else
+		form = document.forms["form_message_"+ID];
+	
+	form.appendChild(textArea);
+	form.appendChild(input_folder);
+	form.appendChild(msg_id);
+
+	var _subject = trim(Element("subject_"+ID).value);
+	if((_subject.length == 0) && !confirm(get_lang("Send this message without a subject?"))) {
+		Element("subject_"+ID).focus();
+		return;
+	}
+	
+	cExecuteForm ("$this.imap_functions.send_mail", form, handler_send_message, ID);
+}
+
+function return_save(data,border_id,folder_name,folder_id,message_id)
+{
+	var handler_delete_msg = function(data){ refresh(preferences.alert_new_msg); };
+	RichTextEditor.saveFlag = 1;
+
+	if (! data)
+		write_msg('ERROR saving your message.');
+	else
+	{
+		newMessageTab.imapUid[border_id] = data.msg_no;
+		newMessageTab.imapBox[border_id] = data.folder_id;
+		
+		var newTitle = document.getElementById('subject_'+border_id).value;
+		if (newTitle.length > 18)
+			newTitle = newTitle.substr(18) + '...';
+		else if (newTitle == '')
+				newTitle = get_lang("No subject");
+		document.getElementById('font_border_id_'+border_id).innerHTML = newTitle;
+		
+		// Replace the embedded images for new uids
+		var mainField = document.getElementById('body_'+border_id).contentWindow;
+		var content_body =  mainField.document.getElementsByTagName('body').item(0).innerHTML;
+		var body_images = content_body.match(/msg_num=\d*/g);
+		if (body_images)
+		{
+			for (var i=0; i<body_images.length; i++){
+				content_body = 	content_body.replace(body_images[i],"msg_num="+newMessageTab.imapUid[border_id]);
+			}
+			mainField.document.getElementsByTagName('body').item(0).innerHTML = content_body;
+			// This is not just stupid, it refresh screen to avoid broken images
+			mainField.document.getElementsByTagName('body').item(0).innerHTML = mainField.document.getElementsByTagName('body').item(0).innerHTML;	
+		}	
+				
+		//Replace all files to new files
+		var divFiles = Element("divFiles_"+border_id);
+		var divParent = divFiles.parentNode;
+		divParent.removeChild(divFiles);
+		divFiles = document.createElement('DIV');
+		divFiles.id = "divFiles_"+border_id;
+		divParent.appendChild(divFiles);
+		
+		var attach_files = connector.unserialize(data.files);
+		if (attach_files != null) {
+			newMessageTab.countFile[border_id] = attach_files.length;
+		for (att_index = 0; att_index < attach_files.length; att_index++){
+	
+			var link_attachment = document.createElement("A");
+			var fileName = attach_files[att_index].substr(0,attach_files[att_index].indexOf('_SIZE_'));
+			var fileSize = parseInt(attach_files[att_index].substr(attach_files[att_index].indexOf('_SIZE_')+6))/1024
+			link_attachment.innerHTML = fileName + " ("+parseInt(fileSize)+" kb)";
+
+			var href = "'"+folder_id+"','"+data.msg_no+"','"+(att_index)+"','"+(att_index+2)+"','base64'";
+
+			link_attachment.setAttribute("href", "javascript:download_attachments("+href+")");
+
+			var a_tmp = href.split(',');
+			a_tmp[2] = fileName;
+			s_tmp = escape(connector.serialize(a_tmp));
+					
+			var check_attachment = document.createElement("INPUT");
+			check_attachment.type = 'CHECKBOX';
+			check_attachment.name = 'forwarding_attachments[]';
+			check_attachment.value = s_tmp;
+
+			divFiles.appendChild(check_attachment);
+			divFiles.appendChild(link_attachment);
+			divFiles.appendChild(document.createElement("BR"));
+
+			check_attachment.checked = true;
+		}
+	}
+		if (message_id)
+			cExecute ("$this.imap_functions.delete_msgs&folder="+newMessageTab.imapBox[border_id]+"&msgs_number="+message_id,handler_delete_msg);
+		
+		if (preferences.auto_save_draft == 1)
+				setTimeout('auto_save_msg('+border_id+')', autosave_time);		
+
+		var save_link = Element("save_message_options");
+		save_link.onclick = '';
+		save_link.style.color = '#999';
+		watch_changes_in_msg(border_id);
+		
+		write_msg(get_lang('Your message was save as draft in folder %1.', folder_name));
+	}		
+}
+
+function save_msg(border_id){
+	if (newMessageTab.imapBox[border_id]) //Gets the imap folder
+		var folder_id = newMessageTab.imapBox[border_id];
+	else
+		var	folder_id = "INBOX/"+draftsfolder;
+
+	if (folder_id == 'INBOX') // and folder name from border
+		var folder_name = get_lang(folder_id);
+	else
+		var folder_name = folder_id.substr(6);
+		
+	// hack to avoid form connector bug,  escapes quotation. Please see #179
+	tmp_border_id=border_id;
+	tmp_folder_name=folder_name;
+	tmp_folder_id=folder_id;
+	message_id = newMessageTab.imapUid[border_id];
+	var handler_save_msg = function(data){ return_save(data,this.tmp_border_id,this.tmp_folder_name,this.tmp_folder_id,this.message_id); }
+	
+	var textArea = document.createElement("TEXTAREA");
+	textArea.style.display='none';
+	textArea.name = "body";
+	body = document.getElementById("body_"+border_id);
+	textArea.value += '<body>\r\n';
+	textArea.value += body.contentWindow.document.body.innerHTML;
+	textArea.value += '\r\n</body>';
+	var input_folder = document.createElement("INPUT");
+	input_folder.style.display='none';
+	input_folder.name = "folder";
+	input_folder.value = folder_id;
+	
+	if (is_ie){
+		var i = 0;
+		while (document.forms(i).name != "form_message_"+border_id){i++}
+		form = document.forms(i);
+	}
+	else
+		form = document.forms["form_message_"+border_id];
+	form.appendChild(textArea);
+	form.appendChild(input_folder);
+
+	cExecuteForm ("$this.imap_functions.save_msg", form, handler_save_msg,border_id);	
+}
+
+function return_saveas(data,border_id,folder_name)
+{
+	if(!verify_session(data))
+		return;
+	if (data.append)
+	{
+		delete_border(border_id,null);
+		write_msg(get_lang('Your message was save as draft in folder %1.', folder_name));
+	}
+	else
+		write_msg('ERROR saving your message.');					
+}
+
+
+function save_as_msg(border_id, folder_id, folder_name){
+	// hack to avoid form connector bug,  escapes quotation. Please see #179
+	tmp_border_id=border_id;
+	tmp_folder_name=folder_name;
+	var handler_save_msg = function(data){ return_saveas(data,this.tmp_border_id,this.tmp_folder_name); }	
+	var textArea = document.createElement("TEXTAREA");
+	textArea.style.display='none';
+	textArea.name = "body";
+	body = document.getElementById("body_"+border_id);
+	textArea.value += '<body>\r\n';
+	textArea.value += body.contentWindow.document.body.innerHTML;
+	textArea.value += '\r\n</body>';
+	
+	var input_folder = document.createElement("INPUT");
+	input_folder.style.display='none';
+	input_folder.name = "folder";
+	input_folder.value = folder_id;
+	
+	if (is_ie){
+		var i = 0;
+		while (document.forms(i).name != "form_message_"+border_id){i++}
+		form = document.forms(i);
+	}
+	else
+		form = document.forms["form_message_"+border_id];
+	form.appendChild(textArea);
+	form.appendChild(input_folder);
+	
+	cExecuteForm ("$this.imap_functions.save_msg", form, handler_save_msg,border_id);
+}
+
+
+// Get checked messages
+function set_messages_flag(flag, msgs_to_set){
+	var handler_set_messages_flag = function (data){
+		
+		if(!verify_session(data))
+			return;
+		var msgs_to_set = data.msgs_to_set.split(",");
+
+		for (var i=0; i<msgs_to_set.length; i++){
+			if(Element("check_box_message_" + msgs_to_set[i])){
+				switch(data.flag){
+					case "unseen":
+						set_msg_as_unread(msgs_to_set[i]);
+						Element("check_box_message_" + msgs_to_set[i]).checked = false;
+						break;
+					case "seen":
+						set_msg_as_read(msgs_to_set[i], false);
+						Element("check_box_message_" + msgs_to_set[i]).checked = false;
+						break;
+					case "flagged":
+						set_msg_as_flagged(msgs_to_set[i]);
+						document.getElementById("check_box_message_" + msgs_to_set[i]).checked = false;
+						break;
+					case "unflagged":
+						set_msg_as_unflagged(msgs_to_set[i]);
+						Element("check_box_message_" + msgs_to_set[i]).checked = false;
+						break;
+				}
+			}
+		}
+		Element('chk_box_select_all_messages').checked = false;
+	}
+	
+	var folder = get_current_folder();
+	if (msgs_to_set == 'get_selected_messages')
+		var msgs_to_set = this.get_selected_messages();
+	else
+		folder = Element("input_folder_"+msgs_to_set+"_r").value;
+	
+	if (msgs_to_set)
+		cExecute ("$this.imap_functions.set_messages_flag&folder="+folder+"&msgs_to_set="+msgs_to_set+"&flag="+flag, handler_set_messages_flag);
+	else
+		write_msg(get_lang('No selected message.'));		
+}
+
+// By message number
+function set_message_flag(msg_number, flag){
+	var msg_number_folder = Element("new_input_folder_"+msg_number+"_r");
+	var handler_set_messages_flag = function (data){
+		if(!verify_session(data))
+			return;
+		if (data.status && Element("td_message_answered_"+msg_number)) {	
+			if(flag == 'answered')
+				Element("td_message_answered_"+msg_number).innerHTML = '<img src=templates/default/images/answered.gif title=Respondida>';
+			else if(flag == 'forwarded')
+				Element("td_message_answered_"+msg_number).innerHTML = '<img src=templates/default/images/forwarded.gif title=Encaminhada>';
+		}
+	}
+	cExecute ("$this.imap_functions.set_messages_flag&folder="+( msg_number_folder ?  msg_number_folder.value : get_current_folder() )+"&msgs_to_set="+msg_number+"&flag="+flag, handler_set_messages_flag);
+}
+
+function print_all(){
+	var folder= Element('border_id_0').innerHTML;
+	var body = Element('divScrollMain').innerHTML;
+	var print_width = screen.width - 200;
+	var x = ((screen.width - print_width) / 2);
+	var y = ((screen.height - 400) / 2) - 35;
+	var window_print = window.open('','ExpressoMail','width='+print_width+',height=400,resizable=yes,scrollbars=yes,left='+x+',top='+y);
+	var seekDot = /\<img /gi;
+	body = body.replace(seekDot, "<img style='display:none' ");
+	seekDot = /\<input /gi;
+	body = body.replace(seekDot, "<input style='display:none' ");
+	
+	while (1){
+		try{
+			var html = '<br>';
+			html += "<h4>ExpressoLivre - ExpressoMail</h4>";
+			html += folder+"<hr>";
+			
+			window_print.document.body.innerHTML = html + '<blockquote><font size="2">' +
+			'<table style="font-size:12" width="'+(is_ie ? "85%" : "99%" )+'"><TR><TD align="center" width="5%">&nbsp;</TD><TD width="30%" align="center">'+get_lang("Who")+'</TD><TD align="center" width="45%">'+get_lang("Subject")+'</TD><TD align="center" width="10%">'+get_lang("Date")+'</TD><TD width="10%">'+get_lang("Size")+'</TD></TR></table>'
+			+ body + '</font></blockquote>';
+			break;
+		}
+		catch(e){
+			//alert(e.message);
+		}
+	}
+	window_print.document.close();
+	window_print.print();
+}
+
+
+function print_msg(msg_folder, msg_number, border_ID){
+	var div_toaddress_full = Element("div_toaddress_full_"+border_ID);	
+	var div_ccaddress_full = Element("div_ccaddress_full_"+border_ID);
+	var printListTO = (div_toaddress_full && div_toaddress_full.style.display != 'none') || toaddress_array[border_ID].length == 1 ? true : false;	
+	var printListCC = (div_ccaddress_full && div_ccaddress_full.style.display != 'none') || !div_ccaddress_full ? true : false;	
+	var sender		= Element('sender_values_'+border_ID) ? Element('sender_values_'+border_ID).value : null;
+	var from		= Element('from_values_'+border_ID) ? Element('from_values_'+border_ID).value : null;
+	var to			= Element('to_values_'+border_ID) ? Element('to_values_'+border_ID).value :null;
+	var cc 			= Element('cc_values_'+border_ID) ? Element('cc_values_'+border_ID).value : null;		
+	var date		=  Element('date_'+border_ID);	
+	var subject		= Element('subject_'+border_ID);
+	var attachments	= Element('attachments_'+border_ID);
+	var body		= Element('body_'+border_ID);
+
+	var print_width = screen.width - 200;
+	var x = ((screen.width - print_width) / 2);
+	var y = ((screen.height - 400) / 2) - 35;
+	var window_print = window.open('','ExpressoMail','width='+print_width+',height=400,resizable=yes,scrollbars=yes,left='+x+',top='+y);
+	if(window_print == null) {
+		alert(get_lang("The Anti Pop-Up is enabled. Allow this site (%1) for print.",document.location.hostname));
+		return;
+	}
+	
+	while (1){
+		try{
+			var html = '<br><br>';
+			//html += "<input type='button' value='Imprimir' onclick='javascript:window.print();'>";
+			html += "<h4>ExpressoLivre - ExpressoMail</h4><hr>";
+			html += '<table><tbody>';
+			if(sender)
+				html += "<tr><td width=7% noWrap><font size='2'>" + get_lang('Sent by') + ": </font></td><td><font size='2'>"+sender+"</font></td></tr>";
+			if(from)
+				html += "<tr><td width=7%><font size='2'>" + get_lang('From') + ": </font></td><td><font size='2'>"+from+"</font></td></tr>";
+			if(to) {
+				if(!printListTO)
+					to = 'Os destinatários não estão sendo exibidos para esta impressão';
+				html += "<tr><td width=7%><font size='2'>" + get_lang('To') + ": </font></td><td><font size='2'>"+to+"</font></td></tr>";
+			}			
+			if (cc) {
+				if(!printListCC)
+					cc = 'Os destinatários não estão sendo exibidos para esta impressão';
+				html += "<tr><td width=7%><font size='2'>" + get_lang('Cc') + ": </font></td><td><font size='2'>"+cc+"</font></td></tr>";
+			}
+			if(date)
+				html += "<tr><td width=7%><font size='2'>" + get_lang('Date') + ": </font></td><td><font size='2'>"+date.innerHTML+"</font></td></tr>";			
+			html += "<tr><td width=7%><font size='2'>" + get_lang('Subject')+ ": </font></td><td><font size='2'>"+subject.innerHTML+"</font></td></tr>";
+			html += "</tbody></table><hr>";
+			window_print.document.body.innerHTML = html + '<blockquote><font size="2">' + body.innerHTML + '</font></blockquote>';
+			if(!is_ie){
+				var tab_tags = window_print.document.getElementsByTagName("IMG");			
+				for(var i = 0; i < tab_tags.length;i++){
+					var _img = document.createElement("IMG");
+					_img.src = tab_tags[i].src;
+					tab_tags[i].parentNode.replaceChild(_img,tab_tags[i]);
+				}
+			}
+			break;
+		}
+		catch(e){
+			//alert(e.message);
+		}
+	}
+	window_print.document.close();
+	window_print.print();
+}
+
+function empty_trash_imap(){
+	var handler_empty_trash = function(data){
+		Element('chk_box_select_all_messages').checked = false;
+		if(!verify_session(data))
+			return;
+		if (get_current_folder() == 'INBOX'+cyrus_delimiter+trashfolder){
+			draw_paging(0);
+			kill_current_box();
+		}
+		tree_folders.getNodeById('INBOX'+cyrus_delimiter+trashfolder).alter({caption: get_lang("Trash")});
+		tree_folders.getNodeById('INBOX'+cyrus_delimiter+trashfolder)._refresh();
+		update_quota();
+		if (data)
+			write_msg(get_lang('Your Trash folder was empty.'));
+		else
+			write_msg(get_lang('ERROR emptying your Trash folder.'));
+	}
+	var realyEmptyTrash=confirm(get_lang('Do you really want to empty your trash folder?'));
+	if (realyEmptyTrash)
+		cExecute ("$this.imap_functions.empty_trash", handler_empty_trash);
+}
+
+function export_all_selected_msgs(){
+	
+	var msgs_to_export = this.get_selected_messages();
+	
+	var handler_export_all_selected_msgs = function(data){
+	
+		if(!data){
+			write_msg(get_lang('Error compressing messages (ZIP). Contact the administrator.'));
+		}
+		else
+			download_attachments(null, null, data, null,null,'mensagens.zip');
+	}
+	
+	if (msgs_to_export) {
+		cExecute ("$this.exporteml.makeAll", handler_export_all_selected_msgs, "folder="+get_current_folder()+"&msgs_to_export="+msgs_to_export);
+		write_msg(get_lang('You must wait while the messages will be exported...'));
+	}
+	else
+		write_msg(get_lang('No selected message.'));
+}
+
+function select_all_search_messages(select, id){
+	var search_box = Element("table_resultsearch_" + id.substr(18)).firstChild;
+	var felement = search_box.firstChild;
+	while(felement)
+	{
+	if (select)
+		felement.firstChild.firstChild.checked = true;
+	else
+		felement.firstChild.firstChild.checked = false;
+	felement = felement.nextSibling;
+	}
+}
+
+/*function select_all_messages(select){
+	var main = Element("tbody_box");
+	var main_list = main.childNodes;
+	var len_main_list = main_list.length;
+	
+	var j = 0;
+	if (select){
+		for (j; j<len_main_list; j++){
+			var check_box = Element("check_box_message_"+main_list[j].id);
+			if (check_box){
+				check_box.checked = true;
+				var tr = Element(main_list[j].id);
+				switch(tr.className){
+					case "tr_msg_read":
+						tr.className = 'selected_seen_msg_bg';
+						break;
+					case "tr_msg_unread":
+						tr.className = 'selected_unseen_msg_bg';
+						break;
+					case "important_msg_read":
+						tr.className = 'selected_important_msg_read';
+						break;
+					case "important_msg_unread":
+						tr.className = 'selected_important_msg_unread';
+						break;
+				}
+			}
+		}
+	}
+	else{
+		for (j; j<len_main_list; j++){
+			var check_box = Element("check_box_message_"+main_list[j].id);
+			if (check_box){
+				check_box.checked = false;
+
+				var tr = Element(main_list[j].id);
+				switch(tr.className){
+					case "selected_seen_msg_bg":
+						tr.className = 'tr_msg_read';
+						break;
+					case "selected_unseen_msg_bg":
+						tr.className = 'tr_msg_unread';
+						break;
+					case "selected_important_msg_read":
+						tr.className = 'important_msg_read';
+						break;
+					case "selected_important_msg_unread":
+						tr.className = 'important_msg_unread';
+						break;
+				}
+			}
+		}
+	}
+}*/
+
+
+function verify_session(data){
+	if(data && data.imap_error) {
+		write_msg(get_lang("your session could not be verified."));
+		// Hold session for edit message.
+		if(!hold_session)
+			location.href="../login.php?cd=10&phpgw_forward=%2FexpressoMail1_2%2Findex.php";
+		return false;
+	}
+	else
+		return true;
+}
+
+// Save image file.
+function save_image(e,thumb){
+	thumb.oncontextmenu = function(e) {
+		return false;
+	}
+	var _button = is_ie ? window.event.button : e.which;
+	var	_target = is_ie ? event.srcElement : e.target;
+	
+	if(_button == 2 || _button == 3) {
+		var _params = _target.id.split(";;");
+		download_attachments(_params[0],_params[1],_params[2],_params[3],_params[4]);
+	}
+}
+
+function nospam(msgs_number, border_ID, folder){
+	if (folder == 'null')
+		folder = get_current_folder();
+	var new_folder 	= 'INBOX';
+	var new_folder_name = get_lang('INBOX');
+	var handler_move_msgs = function(data){
+		if (msgs_number == 'selected')	
+			set_messages_flag("unseen", "get_selected_messages");
+		else
+			set_message_flag(msgs_number, "unseen");
+   	    move_msgs(folder, msgs_number, border_ID, new_folder, new_folder_name);
+	}
+
+    if (msgs_number == 'selected')
+	   	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="+preferences.delete_and_show_previous_message+"&cyrus_delimiter="+cyrus_delimiter, handler_move_msgs);
+	else
+		write_msg(get_lang('No selected message.'));
+}
+
+function spam(folder, msgs_number, border_ID){
+	if (folder == 'null')
+		folder = get_current_folder();
+    var new_folder 		= 'INBOX'+cyrus_delimiter+'Spam';
+	var new_folder_name = 'Spam';
+	var handler_move_msgs = function(data){
+		// debug
+		// alert(data);
+		move_msgs(folder, msgs_number, border_ID, new_folder, new_folder_name);
+	}
+    if(msgs_number == 'selected')
+		msgs_number = get_selected_messages();
+	if(parseInt(msgs_number) > 0 || msgs_number.length > 0)
+		cExecute ("$this.imap_functions.spam&folder="+folder+"&spam=true"+"&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="+preferences.delete_and_show_previous_message+"&cyrus_delimiter="+cyrus_delimiter, handler_move_msgs);
+	else
+    	write_msg(get_lang('No selected message.'));
+}
Index: tags/expressoMail1_2/1.2211/js/wfolders.js
===================================================================
--- tags/expressoMail1_2/1.2211/js/wfolders.js	(revision 271)
+++ tags/expressoMail1_2/1.2211/js/wfolders.js	(revision 271)
@@ -0,0 +1,142 @@
+	function cWFolders()
+	{
+		this.arrayWin = new Array();
+		this.el;
+		this.alert = false;
+	}
+
+	cWFolders.prototype.makeWindow = function(border_id, type)
+	{
+		_this = this;
+	
+		var el = document.createElement("DIV");
+		el.style.visibility = "hidden";
+		el.style.position = "absolute";
+		el.style.left = "0px";
+		el.style.top = "0px";
+		el.style.width = "0px";
+		el.style.height = "0px";
+		el.id = 'dJSWin_wfolders';
+		document.body.appendChild(el);
+		
+		el.innerHTML = "<table><tbody><tr><td>&nbsp</td><td>"+
+		"<div id='wfolders_content_tree' style='height:200px; width:250px; overflow:auto; background:#F7F7F7'></div>"+
+		"</td></tr></tbody></table>";
+
+		var space = document.createElement('SPAN');
+		space.innerHTML = "<BR>&nbsp;&nbsp;";
+		el.appendChild(space);
+
+		var butt = Element('dJSWin_wfolders_bok')
+		if (!butt){
+			butt = document.createElement('INPUT');
+			butt.id = 'dJSWin_wfolders_bok';
+			butt.type = 'button';
+			el.appendChild(butt);
+		}
+		if (type == 'save')
+				butt.value = get_lang('Save'); 
+		else if (type == 'send_and_file')
+                butt.value = get_lang('Send and file'); 
+		else if (type == 'move_to')
+			butt.value = get_lang('Move');
+		else if (type == 'change_folder')
+			butt.value = get_lang('Change folder');	
+
+		butt.onclick = function () {
+			wfolders.arrayWin[el.id].close();
+			if (type == 'save'){
+				save_as_msg(border_id, wfolders_tree._selected.id, wfolders_tree._selected.caption,true);
+			}
+			else if (type == 'send_and_file'){
+				send_message(border_id, wfolders_tree._selected.id, wfolders_tree._selected.caption);
+				wfolders.alert = true;
+			}
+			else if (type == 'move_to')	{
+				var msg_number =  (border_id ? border_id.replace('_r','') : 'selected');
+				if (border_id.match('search'))
+					move_search_msgs(border_id, wfolders_tree._selected.id, wfolders_tree._selected.caption);	
+				else{
+					move_msgs('null', msg_number, border_id, wfolders_tree._selected.id, wfolders_tree._selected.caption);
+					wfolders.alert = true;
+				}
+			}
+			else if (type == 'change_folder'){
+				change_folder(wfolders_tree._selected.id, wfolders_tree._selected.caption);
+				wfolders.alert = true;
+			}
+		};
+		if (type == 'save')
+			butt.value = get_lang('Save');
+		else if (type == 'send_and_file')
+			butt.value = get_lang('Send and file');
+
+		var space = document.createElement('SPAN');
+		space.innerHTML = "&nbsp;&nbsp;";
+		el.appendChild(space);
+
+		var butt = document.createElement('BUTTON');
+		var buttext = document.createTextNode(get_lang('Close'));
+		butt.appendChild(buttext);
+		butt.onclick = function () {wfolders.arrayWin[el.id].close();};
+		el.appendChild(butt);
+
+		if (!Element('dftree_wfolders_tree'))
+		{
+			wfolders_tree = new dFTree({name: 'wfolders_tree'});
+			var n_root = new dNode({id:'root', caption:get_lang("My Folders")});
+			wfolders_tree.add(n_root,'anything'); //Places the root; second argument can be anything.
+
+			var folders = tree_folders.getNodesList(cyrus_delimiter);
+			for (var i=1; i<folders.length; i++)
+			{
+				var nn = new dNode({id:folders[i].id, caption:lang_folder(folders[i].caption), plusSign:folders[i].plusSign});
+				wfolders_tree.add(nn,folders[i].parent);
+			}
+			
+			wfolders_tree.draw(Element('wfolders_content_tree'));
+			n_root.changeState();
+			wfolders_tree.getNodeById('INBOX')._select();
+		}
+		_this.showWindow(el, type);
+	}
+	
+	cWFolders.prototype.showWindow = function (div, type)
+	{
+		if(! div) {
+			alert(get_lang("This list has no participants."));
+			return;
+		}
+		
+		if(! this.arrayWin[div.id]) {
+			div.style.width = "275px";
+			div.style.height = "250px";
+			var title = get_lang('Select a folder:');
+			var wHeight = div.offsetHeight + "px";
+			var wWidth =  div.offsetWidth   + "px";
+			div.style.width = div.offsetWidth - 5;
+
+			win = new dJSWin({
+				id: 'win_'+div.id,
+				content_id: div.id,
+				width: wWidth,
+				height: wHeight,
+				title_color: '#3978d6',
+				bg_color: '#eee',
+				title: title,
+				title_text_color: 'white',
+				button_x_img: '../phpgwapi/images/winclose.gif',
+				border: true });
+			
+			this.arrayWin[div.id] = win;
+			win.draw();
+		}
+		else {
+			win = this.arrayWin[div.id];
+		}
+		win.open();
+	}
+	
+/* Build the Object */
+	var wfolders;
+	wfolders = new cWFolders();
Index: tags/expressoMail1_2/1.2211/js/filter.js
===================================================================
--- tags/expressoMail1_2/1.2211/js/filter.js	(revision 271)
+++ tags/expressoMail1_2/1.2211/js/filter.js	(revision 271)
@@ -0,0 +1,544 @@
+function charCounter(form)
+{
+	if (form.value.length >= 300) {
+		alert(get_lang("You have exceeded the number of allowed characters"));
+		return false;
+	}
+
+}
+
+	function cfilter(){
+
+		this.mode_in   = "";
+		this.rulest		 = new Array;
+		this.out_officeR = "";
+		this.out_officeF = false;
+		this.email_deny  = new Array;
+		this.ac_form     = "";
+		this.ind		 = "";
+		this.email_deny  = new Array;
+		this.email_ld	 = "";
+		this.values = new Array("",
+					",checkBox1",
+					",select_size=1",
+					",checkBox1,select_size=1",
+					",select_rules=1",
+					",checkBox1,select_rules=1",				
+					",select_size=1,select_rules=1",				
+					",checkBox1,select_size=1,select_rules=1",
+					",checkBox2",				
+					",checkBox1,checkBox2",				
+					",checkBox2,select_size=1",
+					",ckeckBox1,checkBox2,select_size=1",
+					",checkBox2,select_rules=1",																				
+					",checkBox1,checkBox2,select_rules=1",				
+					",checkBox2,select_size=1,select_rules=1",				
+					",checkBox1,checkBox2,select_size=1,select_rules=1");
+		
+	}
+	
+	cfilter.prototype.load_rules = function(){
+		var _this = this;
+		if(_this.rulest.length == 0){
+			var handler_sieve = function(data){
+				if(data.rule.length > 0){
+					for(var i=0 ; i < data.rule.length; i++){
+						_this.rulest[_this.rulest.length] = data.rule[i];
+					}
+				}
+				_this.out_officeR = data.vacation[0];
+				_this.out_officeR = _this.out_officeR ? trim(_this.out_officeR.toString().replace("\n","")) : "";
+				if(data.mode.length > 0){_this.mode_in = data.mode[0];}
+			}
+			if(Element('form_status') != null)
+				Element('form_status').innerHTML = "<span style='background:#cc4444;'>&nbsp;&nbsp;<font color='WHITE'>Aguarde...</font>&nbsp;</span>";
+			cExecute("$this.ScriptS.init_a",handler_sieve);
+			_this.get_email();
+	    }
+	}
+	
+	cfilter.prototype.form_m = function(){
+		Element('form_body').innerHTML = "";
+		Element('form_buttons').style.display = '';
+		filters.mount_list();
+		this.ac_form = "";		
+	}
+	
+	cfilter.prototype.form_out = function(){
+		Element('form_body').innerHTML = "";
+		Element('form_body').innerHTML = this.forms_();
+		Element('div_vacation').style.display = "";
+		this.ac_form = "old_out";		
+		this.r_rules_out();		
+	}
+	
+	cfilter.prototype.form_r = function(pos){
+		Element('form_body').innerHTML = "";
+		Element('form_body').innerHTML = this.forms_();
+		Element('div_rule').style.display = "";	
+		this.ac_form = "old_rule";
+		this.ind = pos;
+		this.r_rules_form(pos);
+	}
+	
+	cfilter.prototype.get_email = function(){
+		var _this = this;
+		var handler_get_email = function(data){
+			_this.email_ld = data ? data : "";
+		}
+		cExecute("$this.user.get_email",handler_get_email);
+	}
+	
+	cfilter.prototype.sel_boxes = function(){
+		var nm_folders = tree_folders.getNodesList(cyrus_delimiter);
+		if(document.getElementById("select_mailboxes") != null){
+			var sel_nm = document.getElementById("select_mailboxes");
+			if(sel_nm.length > 0 ){
+				for(var i=0; i < sel_nm.options.length; i++){
+					sel_nm.options[i] = null;
+					i--;
+				}
+			}
+			for(var i=0; i < nm_folders.length; i++){
+				if(nm_folders[i].id != "root"){
+					var opt = new Option(nm_folders[i].caption,nm_folders[i].id,false,true);
+					sel_nm[sel_nm.length] = opt;
+				}
+			}
+			sel_nm[0].selected = true;
+		}
+	}
+
+	cfilter.prototype.box_select = function(param){
+		var aux = this.BoxSelection[param].split(",");
+		var ele1 = document.getElementById(aux[0]);
+		var ele2 = document.getElementById(aux[1]);
+		var noption = "";
+		if(param == 0 || param == 1){
+			if(ele1.selectedIndex != -1){
+				noption = new Option(ele1.value,ele1.value,false,false);
+				ele2.options[ele2.length] = noption;
+				ele1.options[ele1.selectedIndex] = null;
+				ele1.selectedIndex = 0;
+			}
+		}
+	}
+
+	cfilter.prototype.r_rules_form = function(ind){
+		
+		// hide buttons
+		Element('form_buttons').style.display = 'none';
+
+		this.sel_boxes();
+		var aux = new Array;
+		var _this = this;
+		if(this.rulest.length == 0){
+			return false;
+		}
+		aux = _this.rulest[ind].split("&&");
+		document.getElementById("field1").value = aux[3];
+		document.getElementById("field2").value = aux[4];
+		document.getElementById("field3").value = aux[5];
+		document.getElementById("field4").value = aux[11];				
+		
+		switch(aux[6]){
+			case "folder":
+				document.getElementById("radio1").checked  = true;
+				var name_mb = aux[7];
+				var sel_mb = document.getElementById("select_mailboxes");
+				for(var i=0; i < sel_mb.options.length; i++){if((sel_mb.options[i].value) ==  name_mb){sel_mb.options[i].selected = true;}}
+				break;
+			case "address":
+				document.getElementById("radio2").checked   = true;
+				document.getElementById("field5").value 	= aux[7];
+				break;
+			case "reject":
+				 document.getElementById("radio3").checked  = true;
+				 var text0 = aux[7].split("\\n");				 	
+				 for(var i=0; i < text0.length; i++){document.getElementById("field6").value += text0[i] + "\n";}
+				 break;
+			case "discard":
+				document.getElementById("radio4").checked 	= true;
+				break;
+		}
+		var mark_values = this.values[aux[8]].split(",");
+		for(var i=0; i < mark_values.length; i++){
+			if( mark_values[i] == "checkBox1" || mark_values[i] == "checkBox2"){
+				document.getElementById(mark_values[i]).checked = true;
+			}
+			if( mark_values[i] == "select_size=1" || mark_values[i] == "select_rules=1"){
+				var mark_val = mark_values[i].split("=");
+				document.getElementById(mark_val[0]).options[mark_val[1]].selected = true;
+			}
+		}
+	}
+
+	cfilter.prototype.r_rules_out = function(){
+	
+		var _this = this;
+		if(_this.out_officeR.length == 0){
+			return false;
+		}
+		
+		// hide buttons
+		Element('form_buttons').style.display = 'none';
+	
+		var aux = _this.out_officeR.split("&&");
+		var days   = aux[1];
+		var emails = aux[2];
+		var mens   = aux[3];		
+		var p_emails = new Array;
+		var d_emails = new Array;
+				
+		var p_aux = emails.split(", ");
+		for(var i=0; i < p_aux.length; i++){
+			p_emails[i] = p_aux[i].substr(0,(p_aux[i].length - 1));
+			p_emails[i] = p_emails[i].substr(1,(p_aux[i].length));
+		}
+		for(var i=0; i < _this.email_ld.length; i++){
+			d_emails[i] = _this.email_ld[i];
+		}
+
+		diff = function(vet, comp){
+			var sel1 = new Array;
+			for(var i=0; i < vet.length; i++){
+				for(var j=0; j < comp.length; j++){
+					if(vet[i] == comp[j]){
+						comp.splice(j,1);
+						j--;
+					}
+				}
+			}
+		};	
+		diff(p_emails,d_emails);
+		var text    = mens.split("\\n");
+		for(var i=0; i < text.length; i++){document.getElementById("field8").value += text[i] + " ";}
+		for(var i=0; i < _this.email_ld.length; i++){
+			d_emails[i] = _this.email_ld[i];
+		}
+
+	}
+
+	cfilter.prototype.forms_ = function(){
+			var form   = "";
+			form  	   = "<div id='div_rule' style='display:none'><table id='table_rule' border='0' cellpading='0' cellspacing='0' width='100%'>"+
+						 "<tr><td colspan='2'><input type='checkBox' id='checkBox1' name='checkb'>"+get_lang('Also check message against next rule') + "</td></tr>"+
+						 "<tr><td colspan='2'><input type='checkBox' id='checkBox2' name='checkb'>"+get_lang('Keep a copy of the message at your Inbox')+ "</td><tr>"+
+						 "<tr><td colspan='2'><hr size='1' width='100%'></td></tr><tr>"+
+						 "<td rowspan='4' width='20%'>"+get_lang('Coincident')+"<br><select id='select_rules' name='select_rules'>"+
+						 "<option value='0'>"+get_lang("with all")+"</option><option value='1'>"+get_lang("with some")+"</option>"+
+						 "</select></td><td>"+get_lang('The field \"%1\" of the message it contains',get_lang('From'))+".: <input type='text' id='field1' name='field1' size='35' maxlength='200'></td>"+
+						 "</tr><tr><td>"+get_lang('The field \"%1\" of the message it contains', get_lang('To'))+".: <input type='text' id='field2' name='field2' size='35' maxlength='200'></td>"+
+						 "</tr><tr><td>"+get_lang('The field \"%1\" of the message it contains', get_lang('Subject'))+".: <input type='text' id='field3' name='field3' size='35' maxlength='200'></td>"+
+						 "</tr><tr><td>"+get_lang('The size of the message is')+".: &nbsp<select id='select_size' name='select_size'>"+
+						 "<option value='0'>"+get_lang("Less than")+"</option><option value='1'>"+get_lang("Greater than")+"</option>"+						 
+						 "</select>&nbsp;<input type='text' id='field4' name='field4' size='8' maxlength='8'> Kb</td>"+
+						 "</tr><tr><td colspan='2'><hr size='1' width='100%'></td></tr>"+
+						 "</table><table id='table_rule1' border='0' cellpading='0' cellspacing='0' width='100%'>"+
+						 "<tr><td width='50%'><input type='radio' id='radio1' name='radio' value='folder'>"+get_lang('Store at')+".:</td>"+
+						 "<td width='50%'><select id='select_mailboxes' name='select_mailboxes'></select></td>"+
+						 "</tr><tr><td width='50%'><input type='radio' id='radio2' name='radio' value='address'>"+get_lang('Forward to the address')+".:</td>"+
+						 "<td width='50%'><input type='text' id='field5' name='field5' size='35' maxlength='70'></td>"+
+						 "</tr><tr><td width='50%'><input type='radio' id='radio3' name='radio' value='reject'>"+get_lang('Send a rejection message')+".:</td>"+
+						 "<td width='50%'><textarea id='field6' onkeypress='return charCounter(this);' name='field6' rows='3' cols='25'></textarea></td>"+
+						 "</tr><tr><td colspan='2'><input type='radio' id='radio4' name='radio' value='discard'>"+get_lang('Erase the message')+"</td>"+
+						 "</tr></table></div><div id='div_vacation' style='display:none'>"+
+						 "<table id='table_vacation' border='0' cellpading='0' cellspacing='0' width='100%'>"+
+ 						 "<tr><td colspan='3'><br><b>"+get_lang('out office')+"</b></td></tr>"+
+						 //"<tr><td colspan='3'><br>"+get_lang('Subject')+".: <input type='text' id='field7' name='field7' size='35' maxlength='200'/></td></tr>"+
+						 "<tr><td colspan='3'><br>"+get_lang('With the following message')+".:</td>"+
+	 					 "</tr><tr><td colspan='3'><textarea id='field8' onkeypress='return charCounter(this);' rows='8' cols='50'></textarea></td></tr></table></div>"+
+	 					 "<span align='right'><input type='button' value="+get_lang("Back")+" onclick='filter.form_m()'></span>"+
+	 					 "<span align='right'><input type='button' value="+get_lang("Save")+" onclick='filter.saved_rules()'></span>";	 					 
+		return form;
+	}
+
+	cfilter.prototype.enabled_disabled = function(param){
+
+		// Rules
+		if(Element("rule_0") != null){
+			for(var i=0; i < this.rulest.length; i++){
+				if(Element("rule_"+i).checked){
+					var aux_rul = this.rulest[i].split("&&");
+					if(aux_rul[2] != param){
+						aux_rul[2] = param;					
+						var rl = "";
+						for(var j=0; j < aux_rul.length; j++){
+							rl += aux_rul[j] + "&&";
+						}
+						rl = rl.substr(0,(rl.length - 2));
+						this.rulest[i] = rl;					
+					}
+				}
+			}
+		}
+		// Out Office
+		if(Element("out_0") != null){
+			if(Element("out_0").checked){
+				var aux_out = this.out_officeR.split("&&");
+				if(param == "ENABLED")
+					aux_out[4] = "on ";
+				else
+					aux_out[4] = "off";
+				var out = "";
+				for(var i=0; i < aux_out.length; i++){
+					out += aux_out[i] + "&&";
+				}				
+				out = out.substr(0,(out.length - 2));
+				this.out_officeR = out;
+			}
+		}
+		this.reload_rules();
+	}
+	
+	cfilter.prototype.new_rule = function(email){
+
+		if(this.email_deny.length > 0){
+			for(var i=0 ; i < this.email_deny.length; i++){
+				if(this.email_deny[i] == email){
+					alert(get_lang("Sender blocked!"));
+					return false;
+				}
+			}
+		}
+
+		// Verifica Email
+		var emailReg = /^[a-z][a-z-_0-9\.]+@[a-z-_=>0-9\.]+\.[a-z]{2,3}$/i
+    	if(!emailReg.test(email)){
+			alert(get_lang("Inform a valid e-mail!"));
+			return false;
+		}
+
+		this.load_rules();
+		if(confirm(get_lang("Do you want to block this e-mail?"))){
+			new_r = "&&ENABLED&&" + email + "&&&&&&discard&&&&0&&&&&&0";
+//			setTimeout("filter.e_newrule('" + new_r + "')",2000);		
+			if (filter.e_newrule(new_r)){
+				this.email_deny.push(email);
+				write_msg(get_lang("This sender was blocked"));							
+			}else
+				write_msg(get_lang("You have reached the maximum number of rules"));
+		}
+	}
+	
+	cfilter.prototype.e_newrule = function(nw_rule){
+
+		var new_rl = "";
+		if (this.rulest.length >= rules_limit)
+			return false;
+			
+		if(this.rulest.length == 0){
+			new_rl = "#rule&&1" + nw_rule;
+		}else{
+			var aux = this.rulest[this.rulest.length -1 ].split("&&");
+			new_rl = "#rule&&" + (parseInt(aux[1]) + parseInt(2)) + nw_rule;
+		}
+		this.rulest.push(new_rl);
+		this.saved_all();
+		return true;
+	}
+	
+	cfilter.prototype.delete_r = function(){
+	
+		// rule
+		var _this = this;
+		if(Element("rule_0") != null){
+			for(var i=0; i < _this.rulest.length; i++){
+				if(Element("rule_"+i).checked){_this.rulest[i] = "delete";}
+			}
+			for(var i=0; i < _this.rulest.length; i++){
+				if(_this.rulest[i] == "delete"){_this.rulest.splice(i,1);i--;}
+			}
+		}
+	
+		if(_this.rulest.length > 0){
+			var cont = parseInt(1);
+			for(var i=0; i < _this.rulest.length ; i++){
+				var n_rulest = _this.rulest[i].split("&&");
+				n_rulest[1] = cont;
+				cont = cont + parseInt(2);
+				var aux = "";
+				for(var j=0; j < n_rulest.length; j++){aux += n_rulest[j] + "&&";}
+				aux = aux.substr(0,(aux.length - 2));
+				_this.rulest[i] = aux;
+			}
+		} 
+		// out office
+		if(Element("out_0") != null){
+			if(Element("out_0").checked){
+				_this.out_officeR ='';
+				_this.out_officeF = false;
+				//Save outoffice in prefs:
+				connector.loadScript("preferences");
+				prefe.save("outoffice", _this.out_officeF);
+			}
+		}
+		_this.reload_rules();
+	}
+	
+	cfilter.prototype.reload_rules = function(){
+		this.saved_all();
+		Element('form_body').innerHTML = "";
+		this.load_rules();
+		
+		if(this.out_officeF){
+			write_msg(get_lang("Attention, you are in out of office mode."), true);
+		}else {
+			clean_msg();
+			this.out_officeF = false;
+		}
+		filters.mount_list();
+	}
+
+	cfilter.prototype.saved_rules = function(){
+
+		var mount_rule = "";
+		var form = this.ac_form.split("_");
+		var n_rule = "";
+
+		if(form[1] == "rule"){
+			mount_rule = "#rule&&";
+			if(form[0] == "new"){
+				n_rule = "1&&";
+				if(this.rulest.length > 0){
+					aux = this.rulest[this.rulest.length - parseInt(1)].split("&&");
+					n_rule = (parseInt(aux[1]) + parseInt(2)) + "&&";
+				}
+				mount_rule += n_rule + "ENABLED&&";
+			}else{
+				n_rule = this.rulest[this.ind].split("&&");
+				mount_rule += n_rule[1] + "&&";
+				mount_rule += n_rule[2] + "&&";
+			}
+
+			if(LTrim(Element("field1").value) == "" && LTrim(Element("field2").value) == "" && LTrim(Element("field3").value) == "" && Element("field4").value == "")
+			{
+				alert(get_lang("Define some criterion to the fields From, To and Subject with more than 3 characters!"));
+				return false;
+			}
+
+			if((LTrim(Element("field1").value).length <= 3) && (LTrim(Element("field2").value).length <= 3) && (LTrim(Element("field3").value).length <= 3 && Element("field4").value == "")){
+				alert(get_lang("Define some criterion to the fields From, To and Subject with more than 3 characters!"));
+				return false;
+			}
+			
+			for(var i=1; i < 4; i++){mount_rule += LTrim(Element("field"+i).value) + "&&";} 
+			var v_checked = false;
+			if(Element("radio1").checked){
+				mount_rule += "folder&&";
+				var sel_nameBox = Element("select_mailboxes");
+				for(var i=0; i < sel_nameBox.options.length; i++){if(sel_nameBox.options[i].selected == true){mount_rule += sel_nameBox.options[i].value + "&&";}}
+				v_checked = true;
+			}
+			if(Element("radio2").checked){
+				mount_rule += "address&&";
+				if(Element("field5").value == ""){
+					alert(get_lang("Inform a forwarding e-mail!"));
+					return false;
+				}else{
+					var emailReg = /^[a-z][a-z-_0-9\.]+@[a-z-_=>0-9\.]+\.[a-z]{2,3}$/i
+			    	if(emailReg.test(Element("field5").value)){
+						mount_rule += Element("field5").value + "&&";
+					}else{
+						alert(get_lang("Inform a valid e-mail!"));
+						return false;
+					}
+				}
+				v_checked = true;
+			}
+			if(Element("radio3").checked){
+				mount_rule += "reject&&";
+				if(Element("field6").value == ""){
+					alert(get_lang("Inform a text for rejection!"));
+					return false;
+				}else{
+					mount_rule += Element("field6").value + "&&";
+				}
+				v_checked = true;
+			}				
+			if(Element("radio4").checked){
+				mount_rule += "discard&&&&";
+				v_checked = true;
+			}
+			if(!v_checked){
+				alert(get_lang("No option marked!"));
+				return false;
+			}
+			var opts = "";
+			if(Element("checkBox1").checked == true){opts += ",checkBox1";}
+			if(Element("checkBox2").checked == true){opts += ",checkBox2";}
+			if(Element("select_size").options[1].selected == true){opts += ",select_size=1";}
+			if(Element("select_rules").options[1].selected == true){opts += ",select_rules=1";}
+			for(var i=0; i < this.values.length; i++){if(this.values[i] == opts){mount_rule += i + "&&";}}
+			mount_rule += "&&&&";
+			if(LTrim(Element("field4").value) != ""){
+				mount_rule += LTrim(Element("field4").value);
+			}else{
+				mount_rule += 0;
+			}
+			if(form[0] == "new")
+				this.rulest[this.rulest.length] = mount_rule;
+			else
+				this.rulest[this.ind] = mount_rule;
+		}else{
+			mount_rule = "";
+			var fld_emails = this.email_ld; // Get first email of list!
+			var fld_men	   = Element("field8");
+			mount_rule = "#vacation&&";
+			mount_rule += "1&&";
+			mount_rule += "\"" + fld_emails + "\", ";			
+			mount_rule = mount_rule.substr(0,(mount_rule.length - 2));
+			mount_rule += "&&";
+			mount_rule += fld_men.value + "&&on";
+			if(LTrim(fld_men.value) == ""){
+				alert(get_lang("Inform a message!"));
+				return false;
+			}
+			this.out_officeR = mount_rule;
+		}
+		Element('form_buttons').style.display = '';
+		this.reload_rules();
+	}
+
+	cfilter.prototype.close_frm= function(){
+		filters.filter_Sh['window_ffilter_ccform'].close();
+	}
+	
+	cfilter.prototype.saved_all = function(){
+		var aux_rul = "";
+		var _this = this;
+		if(_this.rulest.length > 0){
+			for(var i=0; i < _this.rulest.length; i++){
+				var aux = _this.rulest[i].split("&&");				
+				aux_rul += "_begin_##";
+				for(var j=0 ; j < aux.length; j++){
+					if( (j +1) > aux.length){aux_rul += url_encode(aux[j]);}
+					else{aux_rul += url_encode(aux[j]) + "##";}
+				}	
+				aux_rul += "_end_\n";
+			}
+		}
+		if(_this.out_officeR.length > 0){
+				var aux = _this.out_officeR.split("&&");				
+				aux_rul += "_begin_##";
+				for(var j=0 ; j < aux.length; j++){
+					if( (j +1) > aux.length){aux_rul += url_encode(aux[j]);}
+					else{aux_rul += url_encode(aux[j]) + "##";}
+				}	
+				aux_rul += "_end_\n";
+				_this.out_officeF = (aux[4].replace("\n","") == "off") ? false : true;
+				//Save outoffice in prefs:
+				connector.loadScript("preferences");
+				prefe.save("outoffice", _this.out_officeF);
+		}
+		var h_filter = function(data){
+			if(data != "Ok"){alert("Erro : \n" + data);}
+		}
+		var args   = "$this.ScriptS.rec_rules";
+		var params = "arfilter="+aux_rul;
+		cExecute(args,h_filter,params);
+	}
+
+// build object
+   var filter;
+   filter = new cfilter();
Index: tags/expressoMail1_2/1.2211/js/draw_api.js
===================================================================
--- tags/expressoMail1_2/1.2211/js/draw_api.js	(revision 271)
+++ tags/expressoMail1_2/1.2211/js/draw_api.js	(revision 271)
@@ -0,0 +1,2141 @@
+function draw_tree_folders(folders){
+	// Check if the tree folders alredy exist.
+
+	if (Element('dftree_tree_folders')){
+		var update_tree_folders = function(data){
+			for (var i=0; i<data.length; i++){
+				var folder_unseen = Element('dftree_'+data[i].folder_id+'_unseen');
+				
+				if ((folder_unseen) && (data[i].folder_unseen > 0))
+				{
+					folder_unseen.innerHTML = data[i].folder_unseen;
+				}
+				else if (data[i].folder_unseen > 0)
+				{
+					tree_folders.getNodeById(data[i].folder_id).alter({caption:lang_folder(data[i].folder_name) + '<font style=color:red>&nbsp(</font><span id="dftree_'+data[i].folder_id+'_unseen" style=color:red>'+data[i].folder_unseen+'</span><font style=color:red>)</font>'});
+					tree_folders.getNodeById(data[i].folder_id)._refresh();
+				}
+				else if (data[i].folder_unseen <= 0)
+				{
+					tree_folders.getNodeById(data[i].folder_id).alter({caption:lang_folder(data[i].folder_name)});
+					tree_folders.getNodeById(data[i].folder_id)._refresh();
+				}
+
+				if(data[i].folder_id == get_current_folder()){					
+					var old_new_m = isNaN(parseInt(Element('new_m').innerHTML)) ? parseInt(Element('new_m').firstChild.innerHTML) : parseInt(Element('new_m').innerHTML);
+					if(!isNaN(old_new_m) && old_new_m < data[i].folder_unseen){
+						Element('tot_m').innerHTML = parseInt(Element('tot_m').innerHTML) + (parseInt(data[i].folder_unseen)-old_new_m);
+					}
+					Element('new_m').innerHTML = data[i].folder_unseen ? '<font color="RED">'+data[i].folder_unseen+'</font>' : 0;
+					draw_paging(Element('tot_m').innerHTML);
+				}
+			}
+		}
+		cExecute ("$this.imap_functions.get_folders_list", update_tree_folders);
+		return;
+	}
+	else{
+		tree_folders = new dFTree({name: 'tree_folders'});
+
+		var n_root = new dNode({id:'root', caption: get_lang("My Folders")});
+		tree_folders.add(n_root,'anything'); //Places the root; second argument can be anything.
+	
+		for (var i=0; i<folders.length; i++){
+			if (folders[i].folder_unseen > 0)
+				var nn = new dNode({id:folders[i].folder_id, caption:lang_folder(folders[i].folder_name) + '<font style=color:red>&nbsp(</font><span id="dftree_'+folders[i].folder_id+'_unseen" style=color:red>'+folders[i].folder_unseen+'</span><font style=color:red>)</font>', onClick:"change_folder('"+folders[i].folder_id+"','"+folders[i].folder_name+"')", plusSign:folders[i].folder_hasChildren}); 
+
+			else
+				var nn = new dNode({id:folders[i].folder_id, caption:lang_folder(folders[i].folder_name), onClick:"change_folder('"+folders[i].folder_id+"','"+folders[i].folder_name+"')", plusSign:folders[i].folder_hasChildren}); 
+			
+			if (folders[i].folder_parent == '')
+				folders[i].folder_parent = 'root';
+			else if (folders[i].folder_parent == 'user'){
+				if (!tree_folders.getNodeById('user')){
+					var n_root_shared_folders = new dNode({id:'user', caption:get_lang("Shared folders"), plusSign:true}); 
+					tree_folders.add(n_root_shared_folders,'root');
+				}
+			}
+			tree_folders.add(nn,folders[i].folder_parent);
+		}
+		tree_folders.draw(Element('content_folders'));
+		n_root.changeState();
+		tree_folders.getNodeById('INBOX')._select();		
+		draw_paging(Element('tot_m').innerHTML);
+	}
+	
+	var folder_create = "";
+	var nm1 = "";
+	if(tree_folders._folderPr.length > 0){
+		var nm_folder = "";
+		for(var i=0; i < tree_folders._folderPr.length; i++){
+			nm_folder = tree_folders._folderPr[i].split(cyrus_delimiter);
+			if(nm_folder[0] == "INBOX"){
+				if(nm1 == ""){
+					nm1 = nm_folder[1];
+					folder_create = "INBOX" + cyrus_delimiter + nm_folder[1] + ";";
+				}else{
+					if( nm1 != nm_folder[1]){
+						folder_create += "INBOX" + cyrus_delimiter + nm_folder[1] + ";";
+						nm1 = nm_folder[1];
+					}
+				}
+			}
+		}
+	}
+	if(folder_create != ""){
+		if(confirm(get_lang("There are folders with invalid format. Do you want to fix them?"))){
+			var handler_correct_folders = function(data){
+				//Timeout to release HTTPRequest , loadScript and update tree folders.
+				if(data)
+					setTimeout("connector.loadScript('TreeShow');ttreeBox.update_folder();",500);
+			}
+			cExecute("$this.imap_functions.create_extra_mailbox",handler_correct_folders,"nw_folders="+folder_create);
+		}
+	}
+
+
+}
+
+function update_menu(data){
+		draw_tree_folders(data);
+		if(data) {
+			build_quota(data);			
+			var f_unseen = Element('dftree_'+get_current_folder()+'_unseen');
+			if(f_unseen && f_unseen.innerHTML)
+				Element('new_m').innerHTML = '<font face="Verdana" size="1" color="RED">'+f_unseen.innerHTML+'</font>';
+			else
+				Element('new_m').innerHTML = 0;			
+			folders = data;
+			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&sort_box_reverse=1", handler_draw_box);
+		}
+}
+
+var handler_draw_box = function(data){
+	draw_box(data, 'INBOX');
+}
+
+// Action on change folders.
+function change_folder(folder, folder_name){
+	if (get_current_folder()!= folder)
+	{
+		current_folder = folder;
+		var handler_draw_box = function(data)
+		{
+			if(!verify_session(data))
+				return;
+			Element("border_id_0").innerHTML = "&nbsp;" + lang_folder(folder_name) + '&nbsp;<font face="Verdana" size="1" color="#505050">[<span id="new_m">&nbsp;</span> / <span id="tot_m"></span>]</font>';
+			draw_box(data, current_folder);
+			draw_paging(data.num_msgs);
+			Element("tot_m").innerHTML = data.num_msgs;
+			update_menu();
+			alternate_border(0);
+		}
+		cExecute ("$this.imap_functions.get_range_msgs2&folder="+current_folder+"&msg_range_begin=1&msg_range_end="+preferences.max_email_per_page+"&sort_box_type="+sort_box_type+ "&search_box_type="+ search_box_type +"&sort_box_reverse="+sort_box_reverse+"", handler_draw_box);
+	}
+	else
+		alternate_border(0);
+}
+
+var lastPage = 1;
+var numPages = 5;
+var last_folder = 'INBOX';
+function draw_paging(num_msgs){	
+	num_msgs = parseInt(num_msgs);
+	total_pages = 1;
+
+	if(last_folder != get_current_folder()){
+		lastPage = 1;
+		current_page = 1;
+		last_folder = get_current_folder();
+  	}
+
+	if(num_msgs > parseInt(preferences.max_email_per_page)) {	
+		total_pages = parseInt(num_msgs/preferences.max_email_per_page);
+		if((num_msgs/preferences.max_email_per_page) > total_pages)
+			total_pages++;			
+	}
+
+	if(total_pages == 1) {
+		if(span_paging = document.getElementById("span_paging")) {
+			span_paging.parentNode.removeChild(span_paging);
+		}
+		return;
+	}
+  	
+  	span_paging = document.getElementById("span_paging");
+	if(!span_paging){
+		span_paging = document.createElement("DIV");
+		span_paging.id = "span_paging";
+		span_paging.align="right";
+		document.getElementById("div_menu_c3").appendChild(span_paging);	
+	}
+	span_paging.style.width="100%";		  	 		
+  	span_paging.innerHTML="";
+  	msg_range_begin = 1;
+	msg_range_end = preferences.max_email_per_page;
+  	if(current_page != 1) {
+	  	lnk_page = document.createElement("A");
+		lnk_page.setAttribute("href", "javascript:current_page=1;kill_current_box(); draw_paging("+num_msgs+"); cExecute ('$this.imap_functions.get_range_msgs2&folder='+get_current_folder()+'&msg_range_begin="+msg_range_begin+"&msg_range_end="+msg_range_end+"&sort_box_type="+sort_box_type+ "&search_box_type="+ search_box_type +"&sort_box_reverse="+sort_box_reverse+"', function handler(data){draw_box(data, get_current_folder());})");
+  	}
+  	else {
+  	 	lnk_page = document.createElement("SPAN");
+  	}
+  	span_paging.appendChild(lnk_page);
+
+  	lnk_page.innerHTML = "&lt;&lt;";
+	lnk_page.title = get_lang("First");
+  	span_paging.innerHTML += "&nbsp;";
+  		
+  	if(current_page == lastPage + numPages)
+  		lastPage = current_page - 1;  		
+  	else if((lastPage != 1 && lastPage == current_page) || current_page == total_pages)  		
+  		lastPage = current_page - (numPages - 1);
+  	else if(current_page == 1)
+  	 	lastPage = 1;
+
+	if(lastPage < 1)
+		lastPage = 1;
+	else if(lastPage > 1 && (lastPage > (total_pages -(numPages - 1))))
+		lastPage = total_pages -(numPages - 1);
+
+	var	hasMarked = false;
+
+  	for(i = lastPage; i <= total_pages; i++) {
+  			
+  		if(current_page == i || (i == total_pages && !hasMarked)) {	  		
+  			lnk_page = document.createElement("SPAN");
+  			span_paging.appendChild(lnk_page);
+  			lnk_page.innerHTML = "&nbsp;<b>"+i+"</b>&nbsp;";
+  			hasMarked = true;
+  			continue;
+  		}
+  		else{	  		
+  			lnk_page = document.createElement("A");
+  			span_paging.appendChild(lnk_page);
+  			msg_range_begin = ((i*preferences.max_email_per_page)-(preferences.max_email_per_page-1));
+			msg_range_end = (i*preferences.max_email_per_page);
+			lnk_page.setAttribute("href", "javascript:current_page="+i+";kill_current_box(); draw_paging("+num_msgs+"); cExecute ('$this.imap_functions.get_range_msgs2&folder='+get_current_folder()+'&msg_range_begin="+msg_range_begin+"&msg_range_end="+msg_range_end+"&sort_box_type="+sort_box_type+ "&search_box_type="+ search_box_type +"&sort_box_reverse="+sort_box_reverse+"', function handler(data){draw_box(data, get_current_folder());})");
+  		}
+  		
+  		lnk_page.innerHTML = "&nbsp;...&nbsp;";
+  		
+  		if(i == (lastPage + numPages))
+  				break;	  		
+  		else if(lastPage == 1 || i != lastPage)	  			  			
+  			lnk_page.innerHTML = "&nbsp;"+i+"&nbsp;";
+  		
+  		span_paging.innerHTML += "&nbsp;";	  			  			  			  			  			  			  		
+  	}
+  	
+ 	if(current_page != total_pages) {
+  		lnk_page = document.createElement("A");
+  		msg_range_begin = ((total_pages*preferences.max_email_per_page)-(preferences.max_email_per_page-1));
+		msg_range_end = (total_pages*preferences.max_email_per_page);  		
+		lnk_page.setAttribute("href", "javascript:current_page="+total_pages+";kill_current_box(); draw_paging("+num_msgs+"); cExecute ('$this.imap_functions.get_range_msgs2&folder='+get_current_folder()+'&msg_range_begin="+msg_range_begin+"&msg_range_end="+msg_range_end+"&sort_box_type="+sort_box_type+ "&search_box_type="+ search_box_type +"&sort_box_reverse="+sort_box_reverse+"', function handler(data){draw_box(data, get_current_folder());})");
+	}
+	else {
+		lnk_page = document.createElement("SPAN");
+	}
+  	span_paging.innerHTML += "&nbsp;";
+  	span_paging.appendChild(lnk_page);
+
+	lnk_page.title = get_lang("Last");
+  	lnk_page.innerHTML = "&gt;&gt;";
+}
+
+
+// Draw the inbox and another folders
+function draw_box(headers_msgs, msg_folder){
+	kill_current_box();
+	
+	if(is_ie)
+		document.getElementById("border_table").width = "99.5%";
+
+	var content_id_0 = document.getElementById("content_id_0");
+	
+	table_message_header_box = document.getElementById("table_message_header_box");
+	if (table_message_header_box == null){
+		var table_element = document.createElement("TABLE");
+		var tbody_element = document.createElement("TBODY");
+		table_element.setAttribute("id", "table_message_header_box");
+		table_element.className = "table_message_header_box";
+		
+		tr_element = document.createElement("TR");
+		tr_element.className = "message_header";
+		td_element1 = document.createElement("TD");
+		td_element1.setAttribute("width", "1%");
+		chk_box_element = document.createElement("INPUT");
+		chk_box_element.id  = "chk_box_select_all_messages";
+		chk_box_element.setAttribute("type", "checkbox");
+		chk_box_element.className = "checkbox";
+		chk_box_element.onclick = function(){select_all_messages(this.checked);};
+		chk_box_element.onmouseover = function () {this.title=get_lang('Select all messages.')};
+		chk_box_element.onkeydown = function (e){
+			if (is_ie)
+			{
+				if ((window.event.keyCode) == 46)
+					delete_msgs(get_current_folder(),'selected','null');
+			}
+			else
+			{
+				if ((e.keyCode) == 46)
+					delete_msgs(get_current_folder(),'selected','null');
+			}
+		};
+		
+		td_element1.appendChild(chk_box_element);
+		
+		td_element2 = document.createElement("TD");
+		td_element2.setAttribute("width", "2%");
+	
+		td_element3 = document.createElement("TD");
+		td_element3.setAttribute("width", "31%");
+		td_element3.onclick = function () {sort_box(search_box_type,'SORTFROM');};
+		td_element3.id = "message_header_SORTFROM";
+		td_element3.align = "left";
+		td_element3.innerHTML = get_lang("Who");
+		
+		td_element4 = document.createElement("TD");
+		td_element4.setAttribute("width", "41%");
+		td_element4.onclick = function () {sort_box(search_box_type,'SORTSUBJECT');};
+		td_element4.id = "message_header_SORTSUBJECT";
+		td_element4.align = "left";
+		td_element4.innerHTML = get_lang("Subject");
+	
+		td_element5 = document.createElement("TD");
+		td_element5.setAttribute("width", "14%");
+		td_element5.onclick = function () {sort_box(search_box_type,'SORTARRIVAL');};
+		td_element5.id = "message_header_SORTARRIVAL";
+		td_element5.align = "center";
+		td_element5.innerHTML = get_lang("Date");
+		td_element6 = document.createElement("TD");
+		td_element6.setAttribute("width", "14%");
+		td_element6.onclick = function () {sort_box(search_box_type,'SORTSIZE');}
+		td_element6.id = "message_header_SORTSIZE";
+		td_element6.align = "left";
+		td_element6.innerHTML = get_lang("Size");
+
+		tr_element.appendChild(td_element1);
+		tr_element.appendChild(td_element2);
+		tr_element.appendChild(td_element3);
+		tr_element.appendChild(td_element4);
+		tr_element.appendChild(td_element5);
+		tr_element.appendChild(td_element6);
+		tbody_element.appendChild(tr_element);
+		table_element.appendChild(tbody_element);
+		content_id_0.appendChild(table_element);
+	}
+	draw_header_box();
+	var table_element = document.createElement("TABLE");
+	var tbody_element = document.createElement("TBODY");
+	
+	table_element.id = "table_box";
+	table_element.className = "table_box";
+	table_element.borderColorDark = "#bbbbbb";
+	table_element.frame = "void";
+	table_element.rules = "rows";
+	table_element.cellPadding = "0";
+	table_element.cellSpacing = "0";
+	
+	table_element.onkeydown = function (e){
+		if (is_ie)
+		{
+			if ((window.event.keyCode) == 46)
+			{
+				//delete_all_selected_msgs_imap();
+				delete_msgs(get_current_folder(),'selected','null');
+			}
+		}
+		else
+		{
+			if ((e.keyCode) == 46)
+			{
+				//delete_all_selected_msgs_imap();
+				delete_msgs(get_current_folder(),'selected','null');
+			}
+		}
+	};
+	if (is_ie)
+		table_element.style.cursor = "hand";
+	
+	tbody_element.setAttribute("id", "tbody_box");
+	table_element.appendChild(tbody_element);
+
+	var _divScroll = Element("divScrollMain");
+	var bar = document.getElementById("toolbar");
+	var offset = 0;
+
+	if(!_divScroll){		
+		_divScroll = document.createElement("DIV");
+		_divScroll.id = "divScrollMain";
+	}
+	
+	if(is_ie) {
+		_divScroll.style.overflowY = "auto";								
+		_divScroll.style.overflowX = "hidden";
+		_divScroll.style.width	="100%";
+	}													
+	else{
+		_divScroll.style.overflow = "-moz-scrollbars-vertical";
+		_divScroll.style.width	="99.3%";
+	}
+	// Inicio: Redimensiona DIV SCROLL
+	var bar = Element("toolbar");
+	var offset = 0;
+	if(bar.style.visibility != 'hidden') 
+		offset = (bar.offsetHeight ? bar.offsetHeight :  bar.clientHeight);		
+	var screenHeight = document.body.clientHeight ? document.body.clientHeight : document.body.offsetHeight;
+	var defaultHeight = screenHeight - offset;		
+	_divScroll.style.height 	= defaultHeight - 110;
+	Element('content_folders').style.height = defaultHeight - (is_ie ? 165 : 150);
+	// Fim: Redimensiona DIV SCROLL
+	_divScroll.appendChild(table_element);
+	content_id_0.appendChild(_divScroll);
+	
+	var f_unseen = 0;
+
+		if (headers_msgs.num_msgs == 0){
+			td_info = document.createElement("H3");
+			td_info.setAttribute("height", "25%");
+			td_info.setAttribute("background", "#FFF");
+			td_info.setAttribute("id", "msg_info");
+			td_info.align = "center";
+			td_info.innerHTML = get_lang("This mail box is empty");
+			tbody_element.appendChild(td_info);
+		}
+	
+	
+	for (var i=0; i < headers_msgs.length; i++){
+			if ((headers_msgs[i].Unseen == 'U') || (headers_msgs[i].Recent == 'N'))
+				f_unseen++;
+			tr_element = this.make_tr_message(headers_msgs[i], msg_folder);
+			tbody_element.appendChild(tr_element);
+			_dragArea.makeDragged(tr_element, headers_msgs[i].msg_number, headers_msgs[i].subject, true);
+	}
+
+	if ((preferences.use_shortcuts == '1') && (headers_msgs[0]))
+		select_msg(headers_msgs[0].msg_number, 'null');
+
+	var tdFolders  =  Element("folderscol");
+	tdFolders.style.display = preferences.hide_folders == '1'  ? "none" : "";
+	alternate_border(0);
+	draw_footer_box(headers_msgs.num_msgs);	
+	Element('main_table').style.display = '';
+	if(debug) {
+		var _eTime = new Date();
+		_eTime = _eTime.getTime();
+		alert("Carregou em "+(_eTime - _bTime)+" ms");
+	}
+	var msg_folder = Element('msg_folder').value;
+	var msg_number = Element('msg_number').value;	
+	if(!msg_folder && msg_number) {
+		new_message('new','null');
+	}
+	else if(msg_folder && msg_number){
+		cExecute("$this.imap_functions.get_info_msg&msg_number="+ msg_number + "&msg_folder=" + msg_folder, show_msg);
+		Element('msg_folder').value = '';
+		Element('msg_number').value = '';
+	}
+
+	if(!is_ie) {
+		var scripts = new Array("ccQuickAdd",
+							"color_palette",
+							"filter",
+							"filters",
+							"html2xhtml",
+							"preferences",
+							"QuickCatalogSearch",
+							"QuickSearchUser",
+							"rich_text_editor",
+							"sharemailbox",
+							"search",
+							"TreeS",
+							"TreeShow");
+							
+		connector.loadAllScripts(scripts);
+	}
+}
+
+function make_tr_message(headers_msgs, msg_folder){
+		var tr_element = document.createElement("TR");
+		tr_element.style.height = preferences.line_height;
+		var _fontSize = preferences.font_size ? preferences.font_size : "11";
+		tr_element.id = headers_msgs.msg_number;
+
+		if ((headers_msgs.Unseen == 'U') || (headers_msgs.Recent == 'N'))
+			add_className(tr_element, 'tr_msg_unread');
+		else
+			add_className(tr_element, 'tr_msg_read');
+		
+		if (headers_msgs.Flagged == 'F')
+			add_className(tr_element,'flagged_msg');
+
+		td_element1 = document.createElement("TD");
+		td_element1.setAttribute("width", "1%");
+		chk_box_element = document.createElement("INPUT");
+		chk_box_element.setAttribute("type", "checkbox");
+		chk_box_element.className = "checkbox";
+		chk_box_element.setAttribute("id", "check_box_message_"+headers_msgs.msg_number);
+		chk_box_element.onclick = function(e){
+			if (is_ie)
+				changeBgColor(window.event,headers_msgs.msg_number);
+			else
+				changeBgColor(e,headers_msgs.msg_number);
+		};
+		td_element1.appendChild(chk_box_element);
+		
+		td_element2 = document.createElement("TD");
+		td_element2.setAttribute("width", "2%");
+		if (headers_msgs.attachment && headers_msgs.attachment.number_attachments > 0)
+			td_element2.innerHTML = "<img src ='templates/default/images/clip.gif' title='" + url_decode(headers_msgs.attachment.names) + "'>";
+			
+		td_element21 = document.createElement("TD");
+		td_element21.setAttribute("width", "1%");
+		td_element21.id = "td_message_answered_"+headers_msgs.msg_number;
+
+		if ((headers_msgs.Forwarded == 'F')  || (headers_msgs.Draft == 'X' && headers_msgs.Answered == 'A')){
+			td_element21.innerHTML += "<img src ='templates/default/images/forwarded.gif' title='"+get_lang('Forwarded')+"'>";
+			headers_msgs.Draft = '' 
+			headers_msgs.Answered = '';
+			headers_msgs.Forwarded == 'F';
+		}
+		else if (headers_msgs.Draft == 'X')
+			td_element2.innerHTML += "<img src ='templates/default/images/draft.gif' title='"+get_lang('Draft')+"'>";
+		else if (headers_msgs.Answered == 'A')
+			td_element21.innerHTML += "<img src ='templates/default/images/answered.gif' title='"+get_lang('Answered')+"'>";
+
+		td_element22 = document.createElement("TD");
+		td_element22.setAttribute("width", "1%");
+		td_element22.id = "td_message_important_"+headers_msgs.msg_number;
+
+		// preload image
+		var _img_important = new Image();
+		_img_important.src = "templates/default/images/important.gif";
+
+		if (headers_msgs.Flagged == 'F')
+			td_element22.innerHTML += "<img src ='templates/default/images/important.gif' title='"+get_lang('Important')+"'>";
+		else
+			td_element22.innerHTML += "&nbsp;&nbsp;&nbsp;";
+			
+			
+		td_element23 = document.createElement("TD");
+		td_element23.setAttribute("width", "1%");
+		td_element23.id = "td_message_sent_"+headers_msgs.msg_number;
+		td_element23.innerHTML = "&nbsp;&nbsp;&nbsp;";
+		// preload image
+		var _img_sent = new Image();
+		_img_sent.src 	 = "templates/default/images/sent.gif";
+
+		td_element3 = document.createElement("TD");
+		td_element3.id = "td_who_"+ headers_msgs.msg_number;
+		td_element3.setAttribute("width", "30%");
+		var _onclick = function(){InfoContact.hide();cExecute("$this.imap_functions.get_info_msg&msg_number="+ headers_msgs.msg_number + "&msg_folder=" + msg_folder, show_msg);};
+		td_element3.onclick = _onclick;
+		td_element3.innerHTML = '&nbsp;';
+		
+		if(headers_msgs.from.email.toLowerCase().match(Element("user_email").value))
+		{
+			td_element3.onmouseover = function () {this.title=headers_msgs.to.email;};
+			if (headers_msgs.Draft == 'X')
+				td_element3.innerHTML += "<span style=\"color:red\">("+get_lang("Draft")+") </span>";
+			else{
+				if(!headers_msgs.to.email.toLowerCase().match(Element("user_email").value))
+					td_element23.innerHTML = "<img valign='center' src ='templates/default/images/sent.gif' title='"+get_lang('Sent')+"'>";
+			
+				if ((headers_msgs.to)&&(headers_msgs.to.name != null))
+					td_element3.innerHTML += headers_msgs.to.name;
+				else if (headers_msgs.to){
+					td_element3.innerHTML += headers_msgs.to.email;
+				}
+			}
+		}
+		else{
+			td_element3.onmouseover = function (event) {try {InfoContact.begin(this,headers_msgs.from.email)} catch(e){};};
+			td_element3.onmouseout = function (){ try {clearTimeout(InfoContact.timeout);} catch(e){}};
+			if (headers_msgs.Draft == 'X'){
+				td_element3.innerHTML = "<span style=\"color:red\">("+get_lang("Draft")+") </span>";
+			}
+			else{
+				if (headers_msgs.from.name != null)
+					td_element3.innerHTML += headers_msgs.from.name;
+				else
+					td_element3.innerHTML += headers_msgs.from.email;
+			}
+		}	
+		if (td_element3.innerHTML.indexOf(" ") == '-1' && td_element3.innerHTML.length > 25){
+			td_element3.innerHTML = td_element3.innerHTML.substring(0,25) + "...";
+		}
+		else if (td_element3.innerHTML.length > 40 ){
+			td_element3.innerHTML = td_element3.innerHTML.substring(0,40) + "...";
+		}
+		
+		td_element4 = document.createElement("TD");
+		td_element4.setAttribute("width", "40%");
+		td_element4.onclick = _onclick;
+		td_element4.innerHTML = !is_ie ? "<a id='a_message_"+tr_element.id+"'>&nbsp;" : "&nbsp;";
+		
+		if ((headers_msgs.subject)&&(headers_msgs.subject.length > 50))
+			td_element4.innerHTML += headers_msgs.subject.substring(0,50) + "...";
+		else
+			td_element4.innerHTML += headers_msgs.subject;
+					
+		if(!is_ie){
+			td_element4.innerHTML += "</a>";
+			tr_element.onmouseover = function(){};
+		}
+		
+
+		td_element5 = document.createElement("TD");
+		td_element5.setAttribute("width", "14%");
+		td_element5.onclick = _onclick;
+		td_element5.setAttribute("align", "center");
+		td_element5.innerHTML = headers_msgs.udate;
+
+		td_element6 = document.createElement("TD");
+		td_element6.setAttribute("width", "14%");
+		td_element6.onclick = _onclick;
+		td_element6.setAttribute("noWrap","true");
+		td_element6.setAttribute("align", "center");
+		
+		td_element3.style.fontSize= _fontSize;
+		td_element4.style.fontSize= _fontSize;
+		td_element5.style.fontSize= _fontSize;
+		td_element6.style.fontSize= _fontSize;
+		msg_size = headers_msgs.Size;
+		if (msg_size < 1048576 && msg_size > 1024)
+			td_element6.innerHTML = this.round(msg_size / 1024, 0) + ' Kb';
+		else if(msg_size > 1024)
+			td_element6.innerHTML = this.round(msg_size / (1024*1024), 1) + ' Mb';
+		else
+			td_element6.innerHTML = "1 Kb";
+
+		tr_element.appendChild(td_element1);
+		tr_element.appendChild(td_element2);
+		tr_element.appendChild(td_element21);
+		tr_element.appendChild(td_element22);
+		tr_element.appendChild(td_element23);
+		tr_element.appendChild(td_element3);
+		tr_element.appendChild(td_element4);
+		tr_element.appendChild(td_element5);
+		tr_element.appendChild(td_element6);
+		return tr_element;
+}
+
+function sort_box(search, sort){
+	var message_header = Element("message_header_"+search);
+	var handler_draw_box = function(data){
+		draw_box(data, get_current_folder());
+		draw_paging(Element('tot_m').innerHTML);
+	}
+
+	if(sort_box_type == sort && search_box_type == search){
+		sort_box_reverse = sort_box_reverse ? 0 : 1;
+	}
+	else if(sort_box_type != sort){
+		if ( (sort == 'SORTFROM') || (sort == 'SORTSUBJECT') )
+			sort_box_reverse = 0;
+		else
+			sort_box_reverse = 1;
+	}
+		
+	// Global variable.
+	sort_box_type = sort;
+	search_box_type = search;
+
+	cExecute ("$this.imap_functions.get_range_msgs2&folder="+current_folder+"&msg_range_begin=1&msg_range_end="+preferences.max_email_per_page+"&search_box_type="+search+"&sort_box_type="+sort+"&sort_box_reverse="+sort_box_reverse+"", handler_draw_box);
+	current_page = 1;
+	update_menu();
+}
+function draw_header_box(){
+	switch(sort_box_type){
+		case 'SORTFROM':
+			type_name = get_lang("Who");
+			break;
+		case 'SORTSUBJECT':
+			type_name = get_lang("Subject");
+			break;
+		case 'SORTARRIVAL':
+			type_name = get_lang("Date");
+			break;
+		case 'SORTSIZE':
+			type_name = get_lang("Size");
+			break; 
+		default:
+			type_name = get_lang("Date");
+			break;
+	}
+	Element("message_header_SORTFROM").innerHTML 	= get_lang("Who");
+	Element("message_header_SORTSUBJECT").innerHTML = get_lang("Subject");
+	Element("message_header_SORTARRIVAL").innerHTML = get_lang("Date");
+	Element("message_header_SORTSIZE").innerHTML	= get_lang("Size");	
+	Element("message_header_"+(sort_box_type.lastIndexOf("SORT") != "-1" ? sort_box_type : "SORTARRIVAL") ).innerHTML = "<B>"+type_name+"</B><img src ='templates/default/images/arrow_"+(sort_box_reverse == 1 ? 'desc' : 'asc')+"endant.gif'>";
+}
+function draw_message(info_msg, ID){
+	var content = document.getElementById('content_id_' + ID);
+	var defaultWidth = document.body.offsetWidth - 37;
+	
+	var menuHidden = Element("folderscol").style.display == 'none' ? true : false;
+	if(!menuHidden)
+		defaultWidth -= Element("folderscol").offsetWidth;
+	 //////////////////////////////////////////////////////////////////////////////////////////////////////
+	//Make the next/previous buttom.
+	//////////////////////////////////////////////////////////////////////////////////////////////////////
+	var next_previous_msg_td = document.createElement("TD");
+	next_previous_msg_td.setAttribute("noWrap","true");
+	next_previous_msg_td.align = "right";
+	next_previous_msg_td.width = "40px";
+	var img_next_msg = document.createElement("IMG");
+	img_next_msg.id = 'msg_opt_next_' + ID;
+	img_next_msg.src = './templates/default/images/down.button.png';
+	img_next_msg.title = get_lang('Next');
+	img_next_msg.style.cursor = 'pointer';
+	img_next_msg.onclick = function () {cExecute ("$this.imap_functions.get_info_next_msg&msg_number="+ info_msg.msg_number + "&msg_folder="+ info_msg.msg_folder + "&sort_box_type="+ sort_box_type +  "&search_box_type="+ search_box_type +"&sort_box_reverse="+ sort_box_reverse +"&reuse_border="+ID, show_msg)};
+	var img_space = document.createElement("SPAN");
+	img_space.innerHTML = "&nbsp;";
+	var img_previous_msg = document.createElement("IMG");
+	img_previous_msg.id = 'msg_opt_previous_' + ID;
+	img_previous_msg.src = './templates/default/images/up.button.png';
+	img_previous_msg.title = get_lang('Previous');
+	img_previous_msg.style.cursor = 'pointer';
+	img_previous_msg.onclick = function () {cExecute ("$this.imap_functions.get_info_previous_msg&msgs_number="+ info_msg.msg_number + "&folder="+ info_msg.msg_folder + "&sort_box_type="+ sort_box_type+ "&search_box_type="+ search_box_type + "&sort_box_reverse="+ sort_box_reverse +"&reuse_border="+ID, show_msg)}
+	next_previous_msg_td.appendChild(img_previous_msg);
+	next_previous_msg_td.appendChild(img_space);
+	next_previous_msg_td.appendChild(img_next_msg);
+	//////////////////////////////////////////////////////////////////////////////////////////////////////
+	//Make the header message.
+	//////////////////////////////////////////////////////////////////////////////////////////////////////
+	var table_message = document.createElement("TABLE");
+	var tbody_message = document.createElement("TBODY");
+	table_message.border = "0";
+	table_message.width = defaultWidth ;
+
+	//////////////////////////////////////////////////////////////////////////////////////////////////////
+	//Make the options message.
+	//////////////////////////////////////////////////////////////////////////////////////////////////////
+	var tr0 = document.createElement("TR");
+	tr0.className = "tr_message_header";
+	var td0 = document.createElement("TD");
+	var table_message_options = document.createElement("TABLE");
+	table_message_options.width = "100%";
+	table_message_options.border = '0';
+	table_message_options.className = 'table_message';
+	var tbody_message_options = document.createElement("TBODY");
+	var tr = document.createElement("TR");
+	var td = document.createElement("TD");
+	td.setAttribute("noWrap","true");
+	var _name = '';
+	var _maxChar = menuHidden ? 40 : 15;
+	if (info_msg.from.name)
+		_name = info_msg.from.name.length > _maxChar ? info_msg.from.name.substring(0,_maxChar) + "..." : info_msg.from.name;	
+	else		
+		_name = info_msg.from.email.length > _maxChar ? info_msg.from.email.substring(0,_maxChar) + "..." : info_msg.from.email;
+
+	td.innerHTML = _name.bold() + ', ' + info_msg.smalldate;
+	if (info_msg.attachments.length > 0)
+		td.innerHTML += "&nbsp<img style='cursor:pointer' onclick='javascript:Element(\"option_hide_more_"+ID+"\").onclick()' src ='templates/default/images/clip.gif' title='"+info_msg.attachments.names+"'>";
+	
+	if (typeof(info_msg.signature) == 'string')
+	{	
+		if (info_msg.signature != "void")
+			td.innerHTML += '&nbsp;<img style="cursor:pointer" onclick="alert(\''+ get_lang("This message is signed, and you can trust.") + info_msg.signature +'\');" src="templates/default/images/signed.gif">';
+		else
+			td.innerHTML += "&nbsp;<img style='cursor:pointer' onclick='alert(\""+get_lang("This message is signed, but it is invalid. You should not trust on it.")+"\");' title='"+get_lang("Voided message")+"' src='templates/default/images/invalid.gif'>";
+	}
+	
+	// NORMAL MSG
+	if(info_msg.Draft != 'X')
+	{
+	var options = document.createElement("TD");
+	options.width = "100%";
+	options.setAttribute("noWrap","true");
+	var option_hide_more = document.createElement("SPAN");
+	option_hide_more.className = 'message_options';
+	options.align = 'right';
+	option_hide_more.value = 'more_options';
+	option_hide_more.id = 'option_hide_more_'+ID;
+	option_hide_more.onclick = function(){
+		var _height = Element("div_message_scroll_"+ID).style.height;
+		_height = parseInt(_height.replace("px",""));
+		var _offset = 35;
+		if (this.value == 'more_options'){
+			this.innerHTML = "<b><u>"+get_lang('Options')+"</u></b>";
+			this.value = 'hide_options';
+			Element("div_message_scroll_"+ID).style.height = (_height - _offset)+"px";
+			Element('table_message_others_options_'+ID).style.display = '';
+			Element('tr_other_options_'+ID).style.display = '';
+			
+		}
+		else{
+			this.innerHTML = get_lang('Options');
+			this.value = 'more_options';
+			Element("div_message_scroll_"+ID).style.height = (_height + _offset)+"px";
+			Element('table_message_others_options_'+ID).style.display = 'none';
+			Element('tr_other_options_'+ID).style.display = 'none';			
+		}
+	};
+
+	option_hide_more.innerHTML = get_lang('Options');
+	options.appendChild(option_hide_more);
+	
+	var space0 = document.createElement("SPAN");
+	space0.innerHTML = '&nbsp;';
+	var space1 = document.createElement("SPAN");
+	space1.innerHTML = '&nbsp;';
+	var space2 = document.createElement("SPAN");
+	space2.innerHTML = '&nbsp;';
+	var space3 = document.createElement("SPAN");
+	space3.innerHTML = '&nbsp;';
+	var space4 = document.createElement("SPAN");
+	space4.innerHTML = '&nbsp;';
+
+	var option_print = document.createElement("SPAN");
+	option_print.id = 'msg_opt_print_'+ID;
+	option_print.className = 'message_options';
+	option_print.onclick = function(){print_msg(info_msg.msg_folder,info_msg.msg_number,ID);};
+	option_print.innerHTML = get_lang('Print');
+	options.appendChild(space0);
+	options.appendChild(option_print);
+	var option_forward = document.createElement("SPAN");
+	option_forward.id = 'msg_opt_forward_'+ID;
+	option_forward.className = 'message_options';
+	option_forward.onclick = function(){new_message('forward', ID);};
+	option_forward.innerHTML = get_lang('Forward');
+	options.appendChild(space1);
+	options.appendChild(option_forward);
+	var option_reply = document.createElement("SPAN");
+	option_reply.id = 'msg_opt_reply_'+ID;
+	option_reply.className = 'message_options';
+	option_reply.onclick = function(){new_message('reply_with_history', ID);};
+	option_reply.innerHTML = get_lang('Reply');
+	options.appendChild(space2);
+	options.appendChild(option_reply);
+	var option_delete = document.createElement("SPAN");
+	option_delete.id = 'msg_opt_delete_'+ID;
+	option_delete.className = 'message_options';
+	option_delete.onclick = function(){delete_msgs(info_msg.msg_folder, info_msg.msg_number, ID);};
+	option_delete.innerHTML = get_lang('Delete');
+	options.appendChild(space3);
+	options.appendChild(option_delete);
+	
+	tr.appendChild(td);
+	tr.appendChild(options);
+	tr.appendChild(next_previous_msg_td);
+	tbody_message_options.appendChild(tr);
+	
+	////////// OTHER OPTIONS ////////////////////
+	var tr_other_options = document.createElement("TR");
+	tr_other_options.id = 'tr_other_options_' + ID;
+	tr_other_options.style.display = 'none';
+	
+	var td_other_options = document.createElement("TD");
+	td_other_options.colSpan = '3';
+	//td_other_options.align = 'right';
+	//td_other_options.setAttribute("noWrap","true");
+	var div_other_options = document.createElement("DIV");
+
+	var option_mark_as						= '<span>'+get_lang("Mark as")+'</span>: ';
+	var option_mark_as_unseen				= '<span class="message_options" onclick="set_messages_flag(\'unseen\','+info_msg.msg_number+');write_msg(\''+get_lang('Message marked as ')+get_lang("Unseen")+'.\');">'+get_lang("Unseen")+'</span>, ';
+	var option_mark_as_important			= '<span class="message_options" onclick="set_messages_flag(\'flagged\','+info_msg.msg_number+');write_msg(\''+get_lang('Message marked as ')+get_lang("Important")+'.\');">'+get_lang("Important")+'</span>, ';
+	var option_mark_as_normal				= '<span class="message_options" onclick="set_messages_flag(\'unflagged\','+info_msg.msg_number+');write_msg(\''+get_lang('Message marked as ')+get_lang("Normal")+'.\');">'+get_lang("Normal")+'</span> | ';
+	
+	var option_move							= '<span class="message_options" onclick=wfolders.makeWindow("'+ID+'","move_to");>'+get_lang("Move")+'</span> | ';
+	var option_reply_to_all					= '<span class="message_options" onclick=new_message("reply_to_all_with_history","'+ID+'");>'+get_lang("Reply to all")+'</span> | ';
+	var option_reply_without_history		= '<span class="message_options" onclick=new_message("reply_without_history","'+ID+'");>'+get_lang("Reply without history")+'</span> | ';
+	var option_reply_to_all_without_history	= '<span class="message_options" onclick=new_message("reply_to_all_without_history","'+ID+'");>'+get_lang("Reply to all without history")+'</span> | ';
+	var option_source_msg					= '<span class="message_options" onclick=source_msg("'+ID+'","'+url_encode(info_msg.msg_folder)+'");>'+get_lang("Message Font")+'</span>';	
+
+	div_other_options.innerHTML = option_mark_as + option_mark_as_unseen + option_mark_as_important + option_mark_as_normal + option_move + option_reply_to_all + option_reply_without_history + option_reply_to_all_without_history + option_source_msg;
+	if (use_spam_filter) {
+		if(info_msg.msg_folder == 'INBOX'+cyrus_delimiter+'Spam')
+			div_other_options.innerHTML += ' | <span class="message_options" onclick="nospam('+info_msg.msg_number+',\'null\', \''+info_msg.msg_folder+'\')";>'+get_lang("Not Spam")+'</span>';	
+		else
+			div_other_options.innerHTML += ' | <span class="message_options" onclick="spam(\''+info_msg.msg_folder+'\', '+info_msg.msg_number+',\'null\')";>'+get_lang("Mark as Spam")+'</span>';	
+	}
+	td_other_options.appendChild(div_other_options);
+	//td_other_options.innerHTML = option_print + option_reply_to_all + option_source_msg;
+	
+	tr_other_options.appendChild(td_other_options);
+	tbody_message_options.appendChild(tr_other_options);
+	////////// END OTHER OPTIONS ////////////////
+	table_message_options.appendChild(tbody_message_options);
+	td0.appendChild(table_message_options);
+	tr0.appendChild(td0);
+	tbody_message.appendChild(tr0);
+	}
+	// IF DRAFT
+	else
+	{
+		var options = document.createElement("TD");
+		options.width = "1%";
+		options.setAttribute("noWrap","true");
+		var option_edit	  = '<span class="message_options" onclick="new_message(\'edit\',\''+ID+'\');">'+get_lang('Edit')+'</span> | ';
+		var option_print = '<span class="message_options" onclick="print_msg(\''+info_msg.msg_folder+'\',\''+info_msg.msg_number+'\',\''+ID+'\');">'+get_lang('Print')+'</span> | ';
+		var option_delete = '<span class="message_options" onclick="delete_msgs(\''+info_msg.msg_folder+'\',\''+info_msg.msg_number+'\',\''+ID+'\');">'+get_lang('Delete')+'</span> | ';		
+		var option_hide_more = document.createElement("SPAN");
+		option_hide_more.className = 'message_options';
+		options.align = 'right';
+		option_hide_more.value = 'more_options';
+		option_hide_more.id = 'option_hide_more_'+ID;
+		option_hide_more.innerHTML = get_lang('Options');
+		option_hide_more.onclick = function(){
+			var _height = Element("div_message_scroll_"+ID).style.height;
+			_height = parseInt(_height.replace("px",""));
+			var _offset = 35;
+			if (this.value == 'more_options'){
+				this.innerHTML = "<b><u>"+get_lang('Options')+"</u></b>";
+				this.value = 'hide_options';
+				Element("div_message_scroll_"+ID).style.height = (_height - _offset)+"px";
+				Element('table_message_others_options_'+ID).style.display = '';
+			}
+			else{
+				this.innerHTML = get_lang('Options');
+				this.value = 'more_options';
+				Element("div_message_scroll_"+ID).style.height = (_height + _offset)+"px";
+				Element('table_message_others_options_'+ID).style.display = 'none';
+			}
+		};
+		options.innerHTML = option_edit + option_print + option_delete;
+		options.appendChild(option_hide_more);
+		tr.appendChild(td);
+		tr.appendChild(options);
+		tr.appendChild(next_previous_msg_td);
+		tbody_message_options.appendChild(tr);
+		table_message_options.appendChild(tbody_message_options);
+		td0.appendChild(table_message_options);
+		tr0.appendChild(td0);
+		tbody_message.appendChild(tr0);
+	}
+	//////////////////////////////////////////////////////////////////////////////////////////////////////
+	// END options message.
+	//////////////////////////////////////////////////////////////////////////////////////////////////////
+
+	var table_message_others_options = document.createElement("TABLE");
+	table_message_others_options.id = 'table_message_others_options_' + ID;
+	table_message_others_options.width =  defaultWidth - 30;
+	table_message_others_options.style.display = 'none';
+	table_message_others_options.className = "table_message";
+	var tbody_message_others_options = document.createElement("TBODY");
+	var tr1 = document.createElement("TR");
+	tr1.className = "tr_message_header";
+	var td1 = document.createElement("TD");
+	td1.innerHTML = get_lang("From: ");
+	td1.appendChild(deny_email(info_msg.from.email));
+	td1.width = "7%";
+	
+	if (info_msg.sender){
+		var tr111 = document.createElement("TR");
+		tr111.className = "tr_message_header";
+		var td111 = document.createElement("TD");
+		td111.innerHTML = get_lang("Sent by")+": ";
+		td111.appendChild(deny_email(info_msg.sender.email));
+		td111.setAttribute("noWrap","true");
+		var sender = document.createElement("TD");
+		sender.id = "sender_"+ID;
+		var sender_values = document.createElement("INPUT");
+		sender_values.id = "sender_values_"+ID;
+		sender_values.type = "HIDDEN";
+		sender_values.value = info_msg.sender.full; //Veio do IMAP, sem images nem links.
+		sender.innerHTML += draw_plugin_cc(ID, info_msg.sender.full);
+		sender.className = "header_message_field";
+		tr111.appendChild(td111);
+		tr111.appendChild(sender);
+		tr111.appendChild(sender_values);
+		tbody_message_others_options.appendChild(tr111);
+	}
+	
+	
+	var from = document.createElement("TD");
+	from.id = "from_"+ID;
+	from.innerHTML = info_msg.from.full;
+	if (info_msg.Draft != "X"){
+		from.innerHTML += draw_plugin_cc(ID, info_msg.from);
+		tbody_message_others_options.appendChild(tr1);
+	}
+	from.className = "header_message_field";
+	var from_values = document.createElement("INPUT");
+	from_values.id = "from_values_"+ID;
+	from_values.type = "HIDDEN";
+	from_values.value = info_msg.from.full; //Veio do IMAP, sem images nem links.
+	tr1.appendChild(td1);
+	tr1.appendChild(from);
+	tr1.appendChild(from_values);
+	if (info_msg.reply_to){
+		var tr11 = document.createElement("TR");
+		tr11.className = "tr_message_header";
+		var td11 = document.createElement("TD");
+		td11.innerHTML = get_lang("Reply to")+": ";
+		td11.setAttribute("noWrap","true");
+		var reply_to = document.createElement("TD");
+		reply_to.id = "reply_to_"+ID;
+		
+		var reply_to_values = document.createElement("INPUT");
+		reply_to_values.id = "reply_to_values_"+ID;
+		reply_to_values.type = "HIDDEN";
+		reply_to_values.value = info_msg.reply_to; //Veio do IMAP, sem images nem links.
+		reply_to.innerHTML = draw_plugin_cc(ID, info_msg.reply_to);
+		reply_to.className = "header_message_field";
+		tr11.appendChild(td11);
+		tr11.appendChild(reply_to);
+		tr11.appendChild(reply_to_values);
+		tbody_message_others_options.appendChild(tr11);
+	}
+	//////////////////////////////////////////////////////////////////////////////////////////////////////
+	var tr2 = document.createElement("TR");
+	tr2.className = "tr_message_header";
+	var td2 = document.createElement("TD");
+	td2.innerHTML = get_lang("To: ");
+	var to = document.createElement("TD");
+	to.id = "to_"+ID;
+
+	var to_values = document.createElement("INPUT");
+	to_values.id = "to_values_"+ID;
+	to_values.type = "HIDDEN";
+	to_values.value = info_msg.toaddress2; //Veio do IMAP, sem images nem links.	
+
+	// Salva a pasta da mensagem
+	var input_current_folder = document.createElement('input');	
+	input_current_folder.id = "input_folder_"+ID;
+	input_current_folder.name = "input_folder";
+	input_current_folder.type = "hidden";
+	input_current_folder.value = info_msg.msg_folder;
+	td2.appendChild(input_current_folder);	
+	// fim
+	toaddress_array[ID] = info_msg.toaddress2.split(",");
+	if (toaddress_array[ID].length > 1){
+		to.innerHTML += draw_plugin_cc(ID, toaddress_array[ID][0]);
+		var div_toaddress = document.createElement("SPAN");
+		div_toaddress.id = "div_toaddress_"+ID;
+		div_toaddress.style.display="";
+		div_toaddress.innerHTML += " (<a STYLE='color: RED;' onclick=javascript:show_div_address_full('"+ID+"','to');>"+get_lang('more')+"</a>)";
+		to.appendChild(div_toaddress);		
+	}
+	else {
+		to.innerHTML += draw_plugin_cc(ID,toaddress_array[ID]);
+	}
+	to.className = "header_message_field";
+	tr2.appendChild(td2);
+	tr2.appendChild(to);
+	tr2.appendChild(to_values);
+	tbody_message_others_options.appendChild(tr2);
+
+	if (info_msg.cc){
+		var tr3 = document.createElement("TR");
+		tr3.className = "tr_message_header";
+		var td3 = document.createElement("TD");
+		td3.innerHTML = "CC: ";
+		var cc = document.createElement("TD");
+		cc.id = "cc_"+ID;
+
+		var cc_values = document.createElement("INPUT");
+		cc_values.id = "cc_values_"+ID;
+		cc_values.type = "HIDDEN";
+		cc_values.value = info_msg.cc;
+		
+		ccaddress_array[ID] = info_msg.cc.split(",");		
+		if (ccaddress_array[ID].length > 1){
+			var div_ccaddress = document.createElement("SPAN");
+			div_ccaddress.id = "div_ccaddress_"+ID;
+			var div_ccaddress_full = document.createElement("SPAN");
+			div_ccaddress_full.id = "div_ccaddress_full_"+ID;		
+			div_ccaddress.style.display="";
+			cc.innerHTML = draw_plugin_cc(ID, ccaddress_array[ID][0]);
+			div_ccaddress.innerHTML += " (<a STYLE='color: RED;' onclick=javascript:show_div_address_full('"+ID+"','cc');>"+get_lang('more')+"</a>)";
+			cc.appendChild(div_ccaddress);
+		}
+		else{
+			cc.innerHTML = draw_plugin_cc(ID, info_msg.cc);
+		}
+		cc.className = "header_message_field";
+		tr3.appendChild(td3);
+		tr3.appendChild(cc);
+		tr3.appendChild(cc_values);
+		tbody_message_others_options.appendChild(tr3);
+	}
+	
+	var tr4 = document.createElement("TR");
+	tr4.className = "tr_message_header";
+	var td4 = document.createElement("TD");
+	td4.innerHTML = get_lang("Date: ");
+	var date = document.createElement("TD");
+	date.id = "date_"+ID;
+	date.innerHTML = info_msg.fulldate;
+	var date_day = document.createElement("INPUT");
+	date_day.id = "date_day_"+ID;
+	date_day.type = "HIDDEN";
+	date_day.value = info_msg.msg_day;
+	var date_hour = document.createElement("INPUT");
+	date_hour.id = "date_hour_"+ID;
+	date_hour.type = "HIDDEN";
+	date_hour.value = info_msg.msg_hour
+	
+	date.className = "header_message_field";
+	tr4.appendChild(td4);
+	tr4.appendChild(date);
+	tr4.appendChild(date_day);
+	tr4.appendChild(date_hour);
+	tbody_message_others_options.appendChild(tr4);
+	
+	var tr5 = document.createElement("TR");
+	tr5.className = "tr_message_header";
+	var td5 = document.createElement("TD");
+	td5.innerHTML = get_lang("Subject");
+	var subject = document.createElement("TD");
+	subject.id = "subject_"+ID;
+	subject.innerHTML = info_msg.subject;
+	subject.className = "header_message_field";
+	tr5.appendChild(td5);
+	tr5.appendChild(subject);
+	tbody_message_others_options.appendChild(tr5);
+
+	if (info_msg.attachments.length > 0){
+		var tr6 = document.createElement("TR");
+		tr6.className = "tr_message_header";
+		var td6 = document.createElement("TD");
+		td6.innerHTML = get_lang("Attachments: ");
+		
+		var attachments = document.createElement("TD");
+		td6.vAlign = "top";
+		attachments.align='left';
+		var zipped_attachments = '';
+		if(info_msg.attachments.length > 1){
+			var zipped_attachments 	= document.createElement("TABLE");
+			zipped_attachments.style.marginBottom = "4px";
+			zipped_attachments.cellPadding="0";
+			zipped_attachments.cellSpacing="0";
+			var tr = document.createElement("TR");
+			var td = document.createElement("TD");			
+			var link_attachment 	= document.createElement("A");
+			link_attachment.setAttribute("href", "javascript:download_all_attachments('"+info_msg.msg_folder+"','"+info_msg.msg_number+"')");
+			link_attachment.innerHTML = " "+info_msg.attachments.length+' '+get_lang('files')+' :: '+get_lang('Download all atachments');
+			link_attachment.innerHTML += '<BR>';
+			td.appendChild(link_attachment);
+			tr.appendChild(td);
+			zipped_attachments.appendChild(tr);
+		}
+		if(zipped_attachments)
+			attachments.appendChild(zipped_attachments);
+		attachments.id = "attachments_" + ID;
+		for (var i=0; i<info_msg.attachments.length; i++){
+			var link_attachment = document.createElement("A");
+			link_attachment.setAttribute("href", "javascript:download_attachments('"+info_msg.msg_folder+"','"+info_msg.msg_number+"',"+i+",'"+info_msg.attachments[i].pid+"','"+info_msg.attachments[i].encoding+"')");
+			link_attachment.innerHTML = url_decode(info_msg.attachments[i].name);
+			msg_size = info_msg.attachments[i].fsize;
+			if (msg_size < 1048576 && msg_size > 1024)
+				link_attachment.innerHTML += ' (' + this.round(msg_size / 1024, 0) + ' Kb)';
+			else if(msg_size > 1024)
+				link_attachment.innerHTML += ' (' + this.round(msg_size / (1024*1024), 1) + ' Mb)';
+			else
+				link_attachment.innerHTML += ' (' + msg_size + ' bytes)';
+			link_attachment.innerHTML += '<BR>';
+			attachments.appendChild(link_attachment);
+		}
+		tr6.appendChild(td6);
+		tr6.appendChild(attachments);
+		tbody_message_others_options.appendChild(tr6);
+	}
+
+
+	// BEGIN MAKE THE SCROLL HEIGHT
+	var bar = document.getElementById("toolbar");
+	var offset = 0;
+	if(bar.style.visibility != 'hidden') 
+		offset = bar.offsetHeight ? bar.offsetHeight :  bar.clientHeight;		
+	var div = document.createElement("DIV");
+	div.id = "div_message_scroll_"+ID;
+	div.style.background = 'WHITE';
+	div.style.height = document.body.clientHeight - offset - 125;
+	content.style.height = document.body.clientHeight - offset - 80;
+	div.style.overflow = "auto";
+	div.style.width = defaultWidth - (is_ie ? 5 : 0);
+	// END MAKE THE SCROLL HEIGHT
+	table_message_others_options.appendChild(tbody_message_others_options);
+	var tr = document.createElement("TR");
+	var td = document.createElement("TD");
+	td.colSpan = '2';
+	div.appendChild(table_message_others_options);
+	td.appendChild(div);
+	tr.appendChild(td)
+	tbody_message.appendChild(tr);
+
+
+	//////////////////////////////////////////////////////////////////////////////////////////////////////	
+	//Make the body message.
+	//////////////////////////////////////////////////////////////////////////////////////////////////////
+	var tr = document.createElement("TR");
+	tr.className = "tr_message_body";
+	var td = document.createElement("TD");
+	//td.setAttribute("colSpan","2");
+	info_msg.body = info_msg.body.replace("<body","<span");
+	info_msg.body = info_msg.body.replace("<BODY","<span");
+	div.innerHTML+= "<span id='body_"+ID+"'>"+info_msg.body+"</span><br><br>";
+	//////////////////////////////////////////////////////////////////////////////////////////////////////	
+	//Make the thumbs of the message.
+	//////////////////////////////////////////////////////////////////////////////////////////////////////
+	if ((info_msg.thumbs)&&(info_msg.thumbs.length > 0)){
+		var table_message_thumbs = document.createElement("TABLE");
+		table_message_thumbs.width = "80%";
+		table_message_thumbs.style.borderTop = "2px solid rgb(170, 170, 170)";
+		var tbody_message_thumbs = document.createElement("TBODY");
+		var tr = document.createElement("TR");
+		tr.className = "tr_message_body";
+		var td = document.createElement("TD");
+		td.setAttribute("colSpan","2");
+		td.id = "body_thumbs_"+ID;
+		td.innerHTML += "&nbsp;<font color='DARKBLUE' size='2'><b>"+info_msg.attachments.length+" "+get_lang("attachment")+(info_msg.attachments.length > 1 ? "s" : "")+" "+get_lang("in this message")+"</font></b>";
+		var _link_attachments = '';
+		if(info_msg.thumbs.length > 1){
+			_link_attachments 	= document.createElement("A");
+			_link_attachments.className = "message_options";
+			_link_attachments.setAttribute("href", "javascript:download_all_attachments('"+info_msg.msg_folder+"','"+info_msg.msg_number+"')");
+			_link_attachments.innerHTML = get_lang('Download all atachments');
+		}
+		
+		if(_link_attachments){
+			td.innerHTML +=	" :: ";
+			td.appendChild(_link_attachments);
+		}
+		
+		td.innerHTML +=	"<BR><img src='templates/default/images/menu/ktip.png'>"+get_lang("<b>Tip:</b> For faster save, click over the image with <u>right button</u>.");
+		td.innerHTML += "<BR>";
+
+		for (var i=0; i<info_msg.thumbs.length; i++){
+			if ((i % 4) == 0)
+				td.innerHTML += "<BR>";
+			td.innerHTML += info_msg.thumbs[i];
+			td.innerHTML += "&nbsp;&nbsp;";
+		}
+		tr.appendChild(td);
+		tbody_message_thumbs.appendChild(tr);
+		table_message_thumbs.appendChild(tbody_message_thumbs);
+		div.appendChild(table_message_thumbs);
+	}
+	//////////////////////////////////////////////////////////////////////////////////////////////////////
+	table_message.appendChild(tbody_message);
+	content.appendChild(table_message);
+	var msg_number = document.createElement('INPUT');
+	msg_number.id = "msg_number_" + ID;
+	msg_number.type = "hidden";
+	msg_number.value = info_msg.msg_number;
+	content.appendChild(msg_number);
+	//////////////////////////////////////////////////////////////////////////////////////////////////////
+}
+
+function draw_new_message(border_ID){
+	var ID = create_border("",border_ID);
+	hold_session = true;
+/////////////////////////////////////////////////////////////////////////////////////////////////////////
+	var form = document.createElement("FORM");
+	form.name = "form_message_"+ID;
+	form.method = "POST";
+	form.onsubmit = function(){return false;}
+	if(!is_ie)
+		form.enctype="multipart/form-data";
+	else
+		form.encoding="multipart/form-data";
+/////////////////////////////////////////////////////////////////////////////////////////////////////////
+	//ConstructMenuNewMessage(ID);
+////////////////////////////////////////////////////////////////////////////////////////////////////////	
+	var content = Element('content_id_' + ID);
+	var table_message = document.createElement("TABLE");
+	table_message.width = "100%";
+	var tbody_message = document.createElement("TBODY");
+	var tr0 = document.createElement("TR");
+	tr0.className = "tr_message_header";
+	var td0 = document.createElement("TD");
+	td0.colSpan = '3';
+	
+	var table_menu_new_message = document.createElement("TABLE");
+	table_menu_new_message.width = "100%";
+	table_menu_new_message.border = '0';
+	table_menu_new_message.className = 'table_message';
+	var tbody_menu_new_message = document.createElement("TBODY");
+	var tr_menu_new_message = document.createElement("TR");
+	var td_menu_new_message = document.createElement("TD");
+	td_menu_new_message.setAttribute("noWrap","true");
+	
+	if ((preferences.save_in_folder == '-1') || (preferences.save_in_folder == '')){
+		//var option_send = '<span class="message_options" onclick=send_message("'+ID+'","null","null");>'+get_lang("Send")+'</span> | ';
+		var option_send   = '<input type="button" id="send_button_'+ID+'" class="em_button_like_span" tabindex="1" value="'+get_lang("Send")+'" onclick=send_message("'+ID+'","null","null");>' + ' | ';
+		var option_send_and_file= '<span class="message_options" onclick=wfolders.makeWindow("'+ID+'","send_and_file");>'+get_lang("Send and file")+'</span> | ';
+	}
+	else{
+		//var option_send = '<span class="message_options" onclick="send_message(\''+ID+'\',\''+preferences.save_in_folder+'\',\'null\');">'+get_lang("Send")+'</span> | ';
+		var option_send   = '<input type="button" id="send_button_'+ID+'" class="em_button_like_span" tabindex="1" value="'+get_lang("Send")+'" onclick="send_message(\''+ID+'\',\''+preferences.save_in_folder+'\',\'null\');">' + ' | ';
+		var option_send_and_file='';
+		wfolders.alert = true;
+	}
+//	var option_save_as		= '<span class="message_options" onclick=wfolders.makeWindow("'+ID+'","save");>'+get_lang("Save as")+'</span> | ';
+	var option_save			= '<span id="save_message_options" class="message_options" onclick="newMessageTab.toPreserve['+ID+'] = true; save_msg('+ID+');">'+get_lang("Save")+'</span> | ';
+	var option_search		= '<span class="message_options" onclick=openListUsers("'+ID+'");>'+get_lang("Search")+'</span>';
+	td_menu_new_message.innerHTML = option_send + option_send_and_file + option_save + option_search;
+	
+	tr_menu_new_message.appendChild(td_menu_new_message);
+	tbody_menu_new_message.appendChild(tr_menu_new_message);
+	table_menu_new_message.appendChild(tbody_menu_new_message);
+	
+	content.appendChild(table_menu_new_message);
+	tr0.appendChild(td0);
+	tbody_message.appendChild(tr0);
+////////////////////////////////////////////////////////////////////////////////////////////////////////
+	var tr1_1 = document.createElement("TR");
+	tr1_1.style.display = 'none';
+	var td1_1 = document.createElement("TD");
+	td1_1.innerHTML = get_lang("From")+":";
+	td1_1.setAttribute("noWrap","true");
+	td1_1.style.width = "1%";
+	
+	var td_from = document.createElement("TD");
+	td_from.setAttribute("noWrap","true");
+	td_from.style.width = "100%";
+			
+	var sel_from = document.createElement('SELECT');	
+	sel_from.id = "from_"+ID;
+	sel_from.name = "input_from";
+	sel_from.style.width = "70%";
+	sel_from.setAttribute("wrap","soft");
+	td_from.appendChild(sel_from);	
+	tr1_1.appendChild(td1_1);
+	tr1_1.appendChild(td_from);
+	tbody_message.appendChild(tr1_1);	
+////////////////////////////////////////////////////////////////////////////////////////////////////////
+	var tr1 = document.createElement("TR");
+	var td1 = document.createElement("TD");
+	td1.innerHTML = get_lang("To")+":";
+	td1.setAttribute("noWrap","true");
+	td1.style.width = "1%";
+	
+	var td_to = document.createElement("TD");
+	td_to.setAttribute("noWrap","true");
+	td_to.style.width = "100%";
+	
+	var input_to = document.createElement('TEXTAREA');
+	input_to.id = "to_"+ID;
+	input_to.name = "input_to";
+	input_to.setAttribute("tabIndex","1");	
+	input_to.style.width = "100%";
+	input_to.setAttribute("wrap","soft");
+	input_to.onfocus = function(){clearTimeout(parseInt(setTimeOutLayer)); search_contacts('onfocus', this.id);};
+	input_to.onblur = function(){setTimeOutLayer=setTimeout('search_contacts("lostfocus","'+this.id+'")',100);};
+	if (!is_ie)
+	{
+		input_to.rows = 2;
+		input_to.onkeypress = function (e)
+		{
+			if ((e.keyCode) == 120) //F9
+			{
+				emQuickSearch(input_to.value, 'to', ID);
+			}
+			else
+			{ 
+				if (((e.keyCode == 13) || ((e.keyCode == 38)||(e.keyCode == 40))) && (document.getElementById('tipDiv').style.visibility!='hidden'))
+				{
+					e.preventDefault();
+					search_contacts(e.keyCode,this.id);
+				}
+			}
+		}
+		input_to.onkeyup = function (e)
+		{
+			if ((e.keyCode != 13) && (e.keyCode != 38) && (e.keyCode != 40))
+			{
+				search_contacts(e.keyCode,this.id);
+			}
+		}
+	}
+	else
+	{
+		input_to.rows = 3;
+		input_to.onkeyup = function (e)
+		{
+			if ((window.event.keyCode) == 120) //F9
+			{
+				emQuickSearch(input_to.value, 'to', ID);
+			}
+			else 
+			{ 
+				search_contacts(window.event.keyCode,this.id);
+			}	
+		}
+	}
+	td_to.appendChild(input_to);
+	
+	var img_search = document.createElement("IMG");
+	img_search.src = "./templates/default/images/search.gif";
+	img_search.title = get_lang('Search') + " | " + get_lang('Use F9 Key as shortcut.');
+	img_search.onclick = function () {emQuickSearch(document.getElementById('to_'+ID).value, 'to', ID);};
+	var span_search = document.createElement("SPAN");
+	span_search.innerHTML = get_lang('Search');
+	
+	var td1_img_search = document.createElement("TD");
+	td1_img_search.setAttribute("noWrap","true");
+	var td1_span_search = document.createElement("TD");
+	td1_span_search.setAttribute("noWrap","true");	
+	
+	td1_img_search.appendChild(img_search);
+	td1_span_search.appendChild(span_search);
+	
+	tr1.appendChild(td1);
+	tr1.appendChild(td_to);
+	tr1.appendChild(td1_img_search);
+
+	tbody_message.appendChild(tr1);
+//////////////////////////////////////////////////////////////////////////////////////////////////////
+	var tr2 = document.createElement("TR");
+	tr2.id = "tr_cc_"+ID;
+	tr2.style.display = 'none';
+	var td2 = document.createElement("TD");
+	td2.innerHTML = "Cc:";
+	td2.setAttribute("noWrap","true");	
+	td2.style.width = "1%";
+	
+	var td_cc = document.createElement("TD");
+	td_cc.setAttribute("noWrap","true");
+	td_cc.style.width = "100%";
+	
+	var input_cc = document.createElement('TEXTAREA');
+	input_cc.id = "cc_"+ID;
+	input_cc.name = "input_cc";
+	input_cc.setAttribute("tabIndex","1");
+	input_cc.style.width = "100%";
+	input_cc.onfocus = function(){clearTimeout(parseInt(setTimeOutLayer)); search_contacts('onfocus',this.id);};
+	input_cc.onblur = function(){setTimeOutLayer=setTimeout('search_contacts("lostfocus","'+this.id+'")',100);};
+	if (!is_ie)
+	{
+		input_cc.rows = 2;
+		input_cc.onkeypress = function (e)
+		{
+			if ((e.keyCode) == 120) //F9
+			{
+				emQuickSearch(input_cc.value, 'cc', ID);
+			}
+			else 
+			{ 
+				if (((e.keyCode == 13) || ((e.keyCode == 38)||(e.keyCode == 40))) && (document.getElementById('tipDiv').style.visibility!='hidden'))
+				{
+					e.preventDefault();
+					search_contacts(e.keyCode,this.id);
+				}
+			}
+		}
+		input_cc.onkeyup = function (e)
+		{
+			if ((e.keyCode != 13) && (e.keyCode != 38) && (e.keyCode != 40))
+			{
+				search_contacts(e.keyCode,this.id);
+			}
+		}
+	}
+	else if (is_ie)
+	{
+		input_cc.rows = 3;
+		input_cc.onkeyup = function (e)
+		{
+			if ((window.event.keyCode) == 120) //F9
+			{
+				emQuickSearch(input_cc.value, 'cc', ID);
+			}
+			else 
+			{ 
+				search_contacts(window.event.keyCode,this.id);
+			}	
+		}
+	}
+	td_cc.appendChild(input_cc);
+	var img_search = document.createElement("IMG");
+	img_search.src = "./templates/default/images/search.gif";
+	img_search.onclick = function () {emQuickSearch(document.getElementById('cc_'+ID).value, 'cc', ID)}
+	img_search.title = get_lang('Search') + " | " + get_lang('Use F9 Key as shortcut.');
+	var span_search = document.createElement("SPAN");
+	span_search.innerHTML = get_lang('Search');
+	
+	var td2_img_search = document.createElement("TD");
+	td2_img_search.setAttribute("noWrap","true");
+	var td2_span_search = document.createElement("TD");
+	td2_span_search.setAttribute("noWrap","true");	
+	
+	td2_img_search.appendChild(img_search);
+	td2_span_search.appendChild(span_search);
+		
+	tr2.appendChild(td2);
+	tr2.appendChild(td_cc);
+	tr2.appendChild(td2_img_search);
+	tbody_message.appendChild(tr2);
+//////////////////////////////////////////////////////////////////////////////////////////////////////
+	var tr3 = document.createElement("TR");
+	tr3.id = "tr_cco_"+ID;
+	tr3.style.display = 'none';
+	var td3 = document.createElement("TD");
+	td3.setAttribute("noWrap","true");
+	td3.innerHTML = get_lang("CCo")+":";
+	td3.style.width = "1%";
+	
+	var td_cco = document.createElement("TD");
+	td_cco.setAttribute("noWrap","true");
+	td_cco.style.width = "100%";
+	
+	var input_cco = document.createElement('TEXTAREA');
+	input_cco.id = "cco_"+ID;
+	input_cco.name = "input_cco";
+	input_cco.setAttribute("tabIndex","1");
+	input_cco.style.width = "100%";
+	input_cco.onfocus = function(){clearTimeout(parseInt(setTimeOutLayer)); search_contacts('onfocus',this.id);};
+	input_cco.onblur = function(){setTimeOutLayer=setTimeout('search_contacts("lostfocus","'+this.id+'")',100);};
+	if (!is_ie)
+	{
+		input_cco.rows = 2;
+		input_cco.onkeypress = function (e)
+		{
+			if ((e.keyCode) == 120) //F9
+			{
+				emQuickSearch(input_cco.value, 'cco', ID);
+			}
+			else 
+			{ 
+				if (((e.keyCode == 13) || ((e.keyCode == 38)||(e.keyCode == 40))) && (document.getElementById('tipDiv').style.visibility!='hidden'))
+				{
+					e.preventDefault();
+					search_contacts(e.keyCode,this.id);
+				}
+			}
+		}
+		input_cco.onkeyup = function (e)
+		{
+			if ((e.keyCode != 13) && (e.keyCode != 38) && (e.keyCode != 40))
+			{
+				search_contacts(e.keyCode,this.id);
+			}
+		}
+	}
+	else if (is_ie)
+	{
+		input_cco.rows = 3;
+		input_cco.onkeyup = function (e)
+		{
+			if ((window.event.keyCode) == 120) //F9
+			{
+				emQuickSearch(input_cco.value, 'cco', ID);
+			}
+			else 
+			{ 
+				search_contacts(window.event.keyCode,this.id);
+			}	
+		}
+	}
+	td_cco.appendChild(input_cco);
+	var img_search = document.createElement("IMG");
+	img_search.src = "./templates/default/images/search.gif";
+	img_search.title = get_lang('Search') + " | " + get_lang('Use F9 Key as shortcut.');	
+	img_search.onclick = function () {emQuickSearch(document.getElementById('cco_'+ID).value, 'cco', ID);};
+	var span_search = document.createElement("SPAN");
+	span_search.innerHTML = get_lang('Search');
+
+	var td3_img_search = document.createElement("TD");
+	td3_img_search.setAttribute("noWrap","true");
+	var td3_span_search = document.createElement("TD");
+	td3_span_search.setAttribute("noWrap","true");	
+	
+	td3_img_search.appendChild(img_search);
+	td3_span_search.appendChild(span_search);
+		
+	tr3.appendChild(td3);
+	tr3.appendChild(td_cco);
+	tr3.appendChild(td3_img_search);	
+	tbody_message.appendChild(tr3);
+//////////////////////////////////////////////////////////////////////////////////////////////////////
+	var tr_link = document.createElement("TR");
+	tr_link.id = "tr_link_"+ID;		
+	var td1_link = document.createElement("TD");
+	var td2_link = document.createElement("TD");
+	td1_link.innerHTML = "&nbsp;";
+	var a_cc_link = document.createElement('A');
+	a_cc_link.innerHTML = get_lang('Add CC');
+	a_cc_link.id = "a_cc_link_"+ID;
+	a_cc_link.setAttribute("href","javascript:void(0)");
+	a_cc_link.setAttribute("tabIndex","-1");
+	a_cc_link.onclick = function () {this.style.display='none';document.getElementById('tr_cc_'+ID).style.display='';document.getElementById('space_link_'+ID).style.display='none';input_cc.focus();}
+	td2_link.appendChild(a_cc_link);	
+	var space = document.createElement("span");
+	space.id ="space_link_"+ID;
+	space.innerHTML="&nbsp;|&nbsp;";
+	td2_link.appendChild(space);
+	var a_cco_link = document.createElement('A');
+	a_cco_link.innerHTML = get_lang('Add BCC');
+	a_cco_link.id = "a_cco_link_"+ID;
+	a_cco_link.setAttribute("href","javascript:void(0)");
+	a_cco_link.setAttribute("tabIndex","-1");
+	a_cco_link.onclick = function () {this.style.display='none';document.getElementById('tr_cco_'+ID).style.display='';document.getElementById('space_link_'+ID).style.display='none';input_cco.focus();}
+	td2_link.appendChild(a_cco_link);	
+	tr_link.appendChild(td1_link);
+	tr_link.appendChild(td2_link);
+	tbody_message.appendChild(tr_link);
+//////////////////////////////////////////////////////////////////////////////////////////////////////
+	var tr4 = document.createElement("TR");
+	var td4 = document.createElement("TD");
+	//td4.setAttribute("noWrap","true");	
+	td4.innerHTML = get_lang("Subject")+":";
+	var td_subject = document.createElement("TD");
+	var input_subject = document.createElement('input');
+	input_subject.id = "subject_"+ID;
+	input_subject.name = "input_subject";
+	input_subject.setAttribute("tabIndex","1");
+	input_subject.style.width = "90%";
+	input_subject.setAttribute("autocomplete","off");
+	td_subject.appendChild(input_subject);
+	tr4.appendChild(td4);
+	tr4.appendChild(td_subject);
+	tbody_message.appendChild(tr4);
+//////////////////////////////////////////////////////////////////////////////////////////////////////	
+	var tr5 = document.createElement("TR");
+	var td5 = document.createElement("TD");
+	td5.innerHTML = "&nbsp;";
+	var td_return_receipt = document.createElement("TD");
+	td_return_receipt.setAttribute("noWrap","true");
+	td_return_receipt.innerHTML = get_lang("Return receipt")+":";
+	var input_return_receipt = document.createElement('input');
+	input_return_receipt.type = "checkbox";
+	input_return_receipt.className = "checkbox";
+	input_return_receipt.id = "return_receipt_"+ID;
+	input_return_receipt.name = "input_return_receipt";
+	input_return_receipt.setAttribute("tabIndex","-1");
+	td_return_receipt.appendChild(input_return_receipt);	
+	tr5.appendChild(td5);
+	tr5.appendChild(td_return_receipt);
+	tbody_message.appendChild(tr5);
+//////////////////////////////////////////////////////////////////////////////////////////////////////
+	var add_files = document.createElement("A");
+	add_files.setAttribute("href", "javascript:void(0)");
+	add_files.onclick = function () {addFile(ID);};
+	add_files.innerHTML =  get_lang("Attachments: add+");
+	add_files.setAttribute("tabIndex","-1");
+	var divfiles = document.createElement("DIV");
+	divfiles.id = "divFiles_"+ID;
+	var tr5 = document.createElement("TR");
+	var td5_link = document.createElement("TD");
+	var td5_input = document.createElement("TD");	
+	td5_input.innerHTML = "&nbsp;"
+	td5_link.setAttribute("valign","top");
+	td5_link.setAttribute("colSpan","2");
+	td5_link.appendChild(add_files);
+	tr5.appendChild(td5_input);
+	tr5.appendChild(td5_link);
+	tbody_message.appendChild(tr5);
+	var tr6 = document.createElement("TR");
+	var td6_link  = document.createElement("TD");
+	var td6_input = document.createElement("TD");
+	tr6.appendChild(td6_link);
+	td6_input.appendChild(divfiles);
+	tr6.appendChild(td6_input);	
+	tbody_message.appendChild(tr6);
+//////////////////////////////////////////////////////////////////////////////////////////////////////
+	var tr5 = document.createElement("TR");
+	var td5 = document.createElement("TD");	
+	td5.innerHTML = "&nbsp;";
+	var td_body = document.createElement("TD");
+	td_body.setAttribute("colSpan","2");
+	var div_body_position = document.createElement("DIV");
+	div_body_position.id = "body_position_" + ID;
+	td_body.appendChild(div_body_position);
+	tr5.appendChild(td5);
+	tr5.appendChild(td_body);
+	tbody_message.appendChild(tr5);
+// BEGIN MAKE THE SCROLL HEIGHT
+	var defaultWidth = document.body.clientWidth - (is_ie ? 200 : 195);
+	var _bar = document.getElementById("toolbar");
+	var _offset = 0;
+	if(_bar.style.visibility != 'hidden') 
+		_offset = _bar.offsetHeight ? _bar.offsetHeight :  _bar.clientHeight;		
+	var _div = document.createElement("DIV");
+	_div.id = "div_message_scroll_"+ID;
+//	_div.style.background = 'WHITE';
+	_div.style.height = document.body.clientHeight - _offset - 105;
+	content.style.height = document.body.clientHeight - _offset - 80;
+	_div.style.overflow = "auto";
+	_div.style.width = defaultWidth;
+	// END MAKE THE SCROLL HEIGHT
+
+	// Hide the contac tips and re-position the pallete color.
+	_div.onscroll = function() {
+		var intElemScrollTop = Element("div_message_scroll_"+ID).scrollTop;
+		if (!is_ie)
+			ColorPalette.repos(intElemScrollTop);
+		Tooltip.scrollChanged();
+	};
+//////////////////////////////////////////////////////////////////////////////////////////////////////
+	_div.appendChild(form);
+	content.appendChild(_div);
+	table_message.appendChild(tbody_message);
+	form.appendChild(table_message);
+	connector.loadScript("rich_text_editor");
+	RichTextEditor.loadEditor(ID);
+//////////////////////////////////////////////////////////////////////////////////////////////////////
+	draw_from_field(sel_from,tr1_1);
+	return ID;
+}
+
+//	Verify if any user is sharing his name/email address
+//	for use in the new messages's "From " field.
+function draw_from_field(sel_from,tr1_1){
+
+	var el_shared_users = Element("el_shared_users");
+	// The element was loaded and populated...so return.
+	if(el_shared_users){	
+		tr1_1.style.display = '';
+		for (var x = 0; x < el_shared_users.options.length; x++) {
+			var _option = document.createElement("OPTION");
+			_option.text = el_shared_users.options[x].text;
+			_option.value = el_shared_users.options[x].value;
+			sel_from.options[sel_from.options.length] = _option	;
+		}
+		return;
+	}
+	// Get the shared folders.....
+	var RegExp_name = new RegExp("(user)"+cyrus_delimiter+"(.*)$", "i");
+ 	var sharedFolders = new Array();
+	for(var i = 0; i < folders.length; i++) {
+		var x = folders[i].folder_id;
+      	if (RegExp_name.test(x)){
+      		sharedFolders[sharedFolders.length] = x;
+      	}
+    }
+
+    var matchUser = '#';
+    var sharedUsers = new Array();
+  	// Filter the shared folders (only root folders) .....
+   	for(var i = 0; i < sharedFolders.length; i++) {
+      if(!sharedFolders[i].match(matchUser)) {
+		matchUser = sharedFolders[i];
+		sharedUsers[sharedUsers.length] = matchUser.substring(("user"+cyrus_delimiter).length,matchUser.length);
+      }
+    }
+	// Nothing to work...so return.
+	if(sharedUsers.length == 0) 
+		return;
+
+	// Handler function for cExecute
+	var h_user = function(data) {
+		if(data.length == 0) {
+			return false;			
+		}
+		tr1_1.style.display = '';
+		var _option = document.createElement("OPTION");
+		_option.text =  '"'+data.myname+'" <'+Element("user_email").value+'>';
+		_option.value  = data.myname+";"+Element("user_email").value;
+		sel_from.options[sel_from.options.length] = _option;
+	
+		var options = '';
+		for (var x = 0; x < data.length; x++)	{
+			var _option = document.createElement("OPTION");
+			_option.text = '"'+data[x].cn[0] + '" <'+data[x].mail[0]+'>';
+			_option.value = data[x].cn[0] + ';'+data[x].mail[0];
+			sel_from.options[sel_from.options.length] = _option	;
+		}
+		
+		var shared_users_from = Element("el_shared_users");
+		if(!shared_users_from) {
+			shared_users_from = sel_from.cloneNode(true);
+			shared_users_from.id = "el_shared_users";
+			shared_users_from.style.display = 'none';
+			document.body.appendChild(shared_users_from);
+		}
+	}
+	// First time, so execute.....
+	cExecute ("$this.ldap_functions.getSharedUsersFrom&uids="+sharedUsers.join(';'), h_user);
+}
+
+function changeBgColorToON(all_messages, begin, end){
+	for (begin; begin<=end; begin++)
+	{
+		add_className(all_messages[begin], 'selected_msg');
+		Element("check_box_message_" + all_messages[begin].id).checked = true;
+	}
+}
+
+function changeBgColor(event, msg_number){
+	actual_tr = Element(msg_number);
+
+	if (event.shiftKey)
+	{
+		last_tr = Element(last_message_selected);
+		if(!last_tr)
+			last_tr = actual_tr;
+
+		all_messages = actual_tr.parentNode.childNodes;
+		
+		for (var i=0; i < all_messages.length; i++)
+		{
+			if (actual_tr.id == all_messages[i].id)
+				first_order = i;
+			if (last_tr.id == all_messages[i].id)
+				last_order = i;
+		}
+		
+		if (parseInt(first_order) > parseInt(last_order))
+			changeBgColorToON(all_messages, last_order, first_order);
+		else
+			changeBgColorToON(all_messages, first_order, last_order);
+	}
+	else{
+		//if ( exist_className(actual_tr, 'selected_msg') )
+		if ( Element('check_box_message_' + msg_number).checked )
+			add_className(actual_tr, 'selected_msg');
+		else
+			remove_className(actual_tr, 'selected_msg');
+	}
+	last_message_selected = msg_number;
+}
+
+function build_quota(data){
+	id = "content_quota";
+	q_limit = data['quota_limit'];
+	var div	= document.getElementById(id);
+	if(!q_limit){
+	    div.innerHTML = '<span><font size="2" style="color:red"><strong>'+get_lang("Without Quota")+'</strong></font></span>';
+	}
+	else{
+	value = data['quota_percent'];
+	q_used = data['quota_used'];
+	table = document.getElementById("table_quota");
+	if(table)
+		table.parentNode.removeChild(table);
+	table = document.createElement("TABLE");	
+	tbody = document.createElement("TBODY");	
+	table.appendChild(tbody);
+	table.id = "table_quota";
+	table.width="102";
+	table.border="0";
+	table.cellSpacing = 0;
+	table.cellPadding = 0;
+	
+	//tr1 = document.createElement("TR");
+	td11 = document.createElement("TD");
+	td11.align="center";
+	td11.setAttribute("noWrap","true");
+	td11.innerHTML += '&nbsp;' + value+"% ("+q_used+"M/"+q_limit+"M)";
+	//tr1.appendChild(td11);
+	
+	tr2 = document.createElement("TR");
+	td21 = document.createElement("TD");
+	td21.setAttribute("noWrap","true");
+	td21.height="15";
+	td22 = document.createElement("TD");	
+	td21.setAttribute("background","templates/default/images/dsunused.gif");
+	table221 = document.createElement("TABLE");
+	tbody221 = document.createElement("TBODY");
+	table221.appendChild(tbody221);
+	table221.style.width=value+"%";	
+	td21.width="102";
+	table221.border="0";
+	table221.cellSpacing = 0;
+	table221.cellPadding = 0;
+	tr221 = document.createElement("TR");
+	td221 = document.createElement("TD");
+	td221.height="15";
+	if(value > 90) {
+		if(value >= 100)
+			write_msg(get_lang("Your Mailbox is 100% full! You must free more space or will not receive messages."));
+		else
+			write_msg(get_lang("Warning: Your Mailbox is almost full!"));
+		td221.setAttribute("background","templates/default/images/dsalert.gif");
+	}
+	else if(value > 80)
+		td221.setAttribute("background","templates/default/images/dswarn.gif");
+	else
+		td221.setAttribute("background","templates/default/images/dsused.gif");
+	
+	tr221.appendChild(td221);
+	tbody221.appendChild(tr221);
+	td21.appendChild(table221);	
+	tr2.appendChild(td21);
+	tr2.appendChild(td11);
+
+	//tr2.appendChild(td1);
+
+	tbody.appendChild(tr2); //Desenho
+	//tbody.appendChild(tr1); //Letras
+	div.appendChild(table);
+	}
+}
+
+function draw_quota(data){
+	build_quota(data);
+}
+
+function update_quota(){	
+	cExecute ("$this.imap_functions.get_quota",build_quota);
+}
+
+function draw_search(headers_msgs){
+	Element("border_id_0").innerHTML = "&nbsp;&nbsp;" + get_lang('Search Result') + "&nbsp;&nbsp;";
+
+	var tbody = Element('tbody_box');
+	for (var i=0; i<(headers_msgs.length); i++){
+		var tr = this.make_tr_message(headers_msgs[i], headers_msgs[i].msg_folder);
+		tbody.appendChild(tr);
+	}
+}
+
+function draw_search_header_box(){
+	var table_message_header_box = Element("table_message_header_box");
+	table_message_header_box.parentNode.removeChild(table_message_header_box);
+
+	var content_id_0 = Element("content_id_0");
+	var table_element = document.createElement("TABLE");
+	var tbody_element = document.createElement("TBODY");
+	table_element.setAttribute("id", "table_message_header_box");
+	table_element.className = "table_message_header_box";
+	tr_element = document.createElement("TR");
+	tr_element.className = "message_header";
+	td_element1 = document.createElement("TD");
+	td_element1.setAttribute("width", "1%");
+	chk_box_element = document.createElement("INPUT");
+	chk_box_element.id  = "chk_box_select_all_messages";
+	chk_box_element.setAttribute("type", "checkbox");
+	chk_box_element.className = "checkbox";
+	chk_box_element.onclick = function(){select_all_messages(this.checked);};
+	chk_box_element.onmouseover = function () {this.title=get_lang('Select all messages.')};
+	chk_box_element.onkeydown = function (e){
+		if (is_ie)
+		{
+			if ((window.event.keyCode) == 46)
+			{
+				//delete_all_selected_msgs_imap();
+				delete_msgs(get_current_folder(),'selected','null');
+			}
+		}
+		else
+		{
+			if ((e.keyCode) == 46)
+			{
+				//delete_all_selected_msgs_imap();
+				delete_msgs(get_current_folder(),'selected','null');
+			}
+		}
+	};
+	
+	td_element1.appendChild(chk_box_element);
+	td_element2 = document.createElement("TD");
+	td_element2.setAttribute("width", "3%");
+	td_element3 = document.createElement("TD");
+	td_element3.setAttribute("width", "30%");
+	td_element3.id = "message_header_SORTFROM";
+	td_element3.align = "left";
+	td_element3.innerHTML = get_lang("From");
+	td_element4 = document.createElement("TD");
+	td_element4.setAttribute("width", "49%");
+	td_element4.id = "message_header_SORTSUBJECT";
+	td_element4.align = "left";
+	td_element4.innerHTML = get_lang("Subject");	
+	td_element5 = document.createElement("TD");
+	td_element5.setAttribute("width", "10%");
+	td_element5.id = "message_header_SORTARRIVAL";
+	td_element5.align = "center";
+	td_element5.innerHTML = "<B>"+get_lang("Date")+"</B>";	
+	td_element5.innerHTML += "<img src ='templates/default/images/arrow_descendant.gif'>";
+	td_element6 = document.createElement("TD");
+	td_element6.setAttribute("width", "10%");
+	td_element6.id = "message_header_SORTSIZE";
+	td_element6.align = "right";
+	td_element6.innerHTML = get_lang("Size");
+	tr_element.appendChild(td_element1);
+	tr_element.appendChild(td_element2);
+	tr_element.appendChild(td_element3);
+	tr_element.appendChild(td_element4);
+	tr_element.appendChild(td_element5);
+	tr_element.appendChild(td_element6);
+	
+	tbody_element.appendChild(tr_element);
+	table_element.appendChild(tbody_element);
+	content_id_0.appendChild(table_element);
+}
+
+function draw_search_division(msg){
+	var tbody = Element('tbody_box');
+	var tr = document.createElement("TR");
+	var td = document.createElement("TD");
+	td.colSpan = '7';
+	td.width = '100%';
+
+	var action_info_table = document.createElement("TABLE");
+	var action_info_tbody = document.createElement("TBODY");
+	
+	action_info_table.className = "action_info_table";
+	action_info_table.width = "100%";
+	
+	var action_info_tr = document.createElement("TR");
+	
+	var action_info_th1 = document.createElement("TH");
+	action_info_th1.width = "40%";
+	action_info_th1.innerHTML = "&nbsp;";
+
+	var action_info_th2 = document.createElement("TH");
+	
+	action_info_th2.innerHTML = msg;
+	action_info_th2.className = "action_info_th";
+	action_info_th2.setAttribute("noWrap", "true");
+	
+	var action_info_th3 = document.createElement("TH");
+	action_info_th3.width = "40%";
+	action_info_th3.innerHTML = "&nbsp;";
+	
+	action_info_tr.appendChild(action_info_th1);
+	action_info_tr.appendChild(action_info_th2);
+	action_info_tr.appendChild(action_info_th3);
+	action_info_tbody.appendChild(action_info_tr);
+	action_info_table.appendChild(action_info_tbody);
+
+	td.appendChild(action_info_table);
+	tr.appendChild(td);
+	tbody.appendChild(tr);
+}
+
+function draw_search_box(){
+	var content_id_0 = Element("content_id_0");
+	var table = document.createElement("TABLE");
+	table.id = "table_box";
+	table.width = 'auto';
+	var tbody = document.createElement("TBODY");
+	tbody.id = "tbody_box";
+
+	table.className = "table_box";
+	table.setAttribute("frame", "below");
+	table.setAttribute("rules", "none");
+	table.setAttribute("cellpadding", "0");
+	table.onkeydown = function (e){
+		if (is_ie)
+		{
+			if ((window.event.keyCode) == 46)
+			{
+				//delete_all_selected_msgs_imap();
+				delete_msgs(get_current_folder(),'selected','null');
+			}
+		}
+		else
+		{
+			if ((e.keyCode) == 46)
+			{
+				//delete_all_selected_msgs_imap();
+				delete_msgs(get_current_folder(),'selected','null');
+			}
+		}
+	};
+	if (is_ie)
+		table.style.cursor = "hand";
+	
+	table.appendChild(tbody);
+	content_id_0.appendChild(table);
+}
+	var idx_cc = 0;
+function draw_plugin_cc(ID, addrs)	{
+	connector.loadScript("ccQuickAdd");
+
+	var array_addrs = '';
+	var array_name 	= '';	
+	var cc_data = new Array();
+	if(typeof(addrs.name) != 'undefined') {	
+		array_name 	= LTrim(addrs.name).split(" ");
+		array_addrs = new Array(addrs.email);		
+	}
+	else {
+		array_addrs = (typeof addrs == 'object' ? addrs.toString().split("\" ") : addrs.split("\" "));
+		array_name 	= LTrim(array_addrs[0]).replace('"','').split(" ");	
+	}
+
+	var _split = array_name[0].split('@');
+	cc_data[0] = _split[0];
+	cc_data[1] = _split[0];
+	cc_data[2] = '';
+
+	for (i=1; i < array_name.length; i++)
+		cc_data[2] += array_name[i] + " ";			
+	
+
+	if(array_addrs.length > 1)			
+		cc_data[3] = array_addrs[1] ? array_addrs[1].replace("&lt;",'').replace("&gt;",'') : '';		
+	else
+		cc_data[3] = array_addrs[0];
+	
+	var sm_envelope_img1 = '<img style="cursor:'+ (is_ie ? 'hand' : 'pointer') +'" title="' + get_lang("Add Contact") +
+	'" onclick="ccQuickAddOne.showList(\''+cc_data+'\')" src="./templates/default/images/user_card.gif">';
+	var to_addybook_add = "<SPAN id='insert_plugin_"+idx_cc+"_"+ID+"'>";
+	to_addybook_add += addrs;
+	to_addybook_add +=  sm_envelope_img1;
+	idx_cc++;
+	to_addybook_add += "</SPAN>";
+	return to_addybook_add;
+}
+function deny_email(email){
+	connector.loadScript("filter");
+	var dn_em 	= document.createElement("SPAN");
+		dn_em.id = "tt_d";
+		dn_em.onclick = function(){filter_rules.new_rule(email);};
+		dn_em.setAttribute("title",get_lang("Block Sender"));
+		dn_em.style.cursor = "pointer";		
+		dn_em.innerHTML = "<img align='top' onclick=filter.new_rule('"+email+"') src='./templates/default/images/deny.gif'>";
+	return dn_em;
+	
+}
+function show_div_address_full(id, type) {
+	var div_address_full = Element("div_"+type+"address_full_"+id);
+	if(!div_address_full) {
+		div_address_full = document.createElement("SPAN");
+		div_address_full.id = "div_"+type+"address_full_"+id;	
+		div_address_full.style.display="none";	
+		var _address = eval(type+"address_array['"+id+"']");
+		var isOverLimit = (_address.length > 100);
+		
+		if(isOverLimit) {
+			alert("Esse campo possui muitos endereços ("+_address.length+" destinatários).\r\n"+
+			"Para evitar o travamento do navegador, o botão 'Adicionar Contato' foi desabilitado!");
+		}
+
+		for(var idx = 1 ; idx  < _address.length;idx++) {
+			div_address_full.innerHTML += isOverLimit ?  '<br>'+_address[idx] : ','+draw_plugin_cc(id,_address[idx]);
+		}		
+		div_address_full.innerHTML += " (<a STYLE='color: RED;' onclick=document.getElementById('div_"+type+"address_full_"+id+"').style.display='none';document.getElementById('div_"+type+"address_"+id+"').style.display='';>"+get_lang('less')+"</a>)";
+		Element(type+"_"+id).appendChild(div_address_full);
+	}
+	Element('div_'+type+'address_'+id).style.display='none';
+	div_address_full.style.display='';
+}
+function draw_footer_box(num_msgs){
+	var span_R = Element("table_message");	
+	var span_options = Element("span_options");	
+	if(!span_options) {
+		span_options = document.createElement("TD");	
+		span_options.style.fontSize = "12";
+		span_options.id = "span_options";
+		span_R.appendChild(span_options);
+	}
+
+	span_options.innerHTML = 
+		'<span title="'+get_lang("Delete")+'" style="margin-left:8px" class="message_options" onclick=delete_msgs(\'null\',\'selected\',\'null\')>'+get_lang("Delete")+'</span> | '+
+		'<span title="'+get_lang("Move")+'" class="message_options" onclick=wfolders.makeWindow(\"\",\"move_to\")>'+get_lang("Move")+'</span> | '+
+   		'<span title="'+get_lang("Print")+'" class="message_options" onclick=print_all()>'+get_lang("Print")+'</span> | '+
+	   	'<span title="'+get_lang("Export")+'" class="message_options" onclick="export_all_selected_msgs()">'+get_lang("Export")+'</span>';
+	
+	if (use_spam_filter) {
+		if ( get_current_folder() == 'INBOX'+cyrus_delimiter+'Spam' )	{
+			span_options.innerHTML += ' | <span title="'+get_lang("Not Spam")+'" class="message_options" onclick="nospam(\'selected\',\'null\',\'null\')">'+get_lang("Not Spam")+'</span>';
+		}
+		else {
+			span_options.innerHTML += ' | <span title="'+get_lang("Mark as Spam")+'" class="message_options" onclick="spam(\'null\', \'selected\',\'null\')">'+get_lang("Mark as Spam")+'</span>';
+		}
+	}
+	var span_D = Element("span_D");	
+	if(!span_D){
+		span_D = document.createElement("TD");	
+		span_D.align = "right";
+		span_D.style.fontSize = "12";
+		span_D.id = "span_D";
+		span_R.appendChild(span_D);
+	}
+	span_D.innerHTML = 
+   		 get_lang("List")+': '+
+   	'<span id="span_flag_SORTARRIVAL" style="'+(search_box_type == 'ALL' ? 'font-weight:bold;text-decoration:underline' : '')+'" title="'+get_lang("All")+'" class="message_options" onclick="if(\'ALL\' == \''+search_box_type+'\') return false;sort_box(\'ALL\',\''+sort_box_type+'\')">'+get_lang("All")+'</span>, '+
+   	'<span id="span_flag_UNSEEN" style="'+(search_box_type == 'UNSEEN' ? 'font-weight:bold;text-decoration:underline' : '')+'" title="'+get_lang("l_unseen")+'" class="message_options" onclick="if(\'UNSEEN\' == \''+search_box_type+'\') return false;sort_box(\'UNSEEN\',\''+sort_box_type+'\')">'+get_lang("l_unseen")+'</span>, '+
+  	'<span id="span_flag_SEEN" style="'+(search_box_type == 'SEEN' ? 'font-weight:bold;text-decoration:underline' : '')+'" title="'+get_lang("l_seen")+'" class="message_options" onclick="if(\'SEEN\' == \''+search_box_type+'\') return false;sort_box(\'SEEN\',\''+sort_box_type+'\')">'+get_lang("l_seen")+'</span>, '+
+   	'<span id="span_flag_ANSWERED" style="'+(search_box_type == 'ANSWERED' ? 'font-weight:bold;text-decoration:underline' : '')+'" title="'+get_lang("l_answered")+'" class="message_options" onclick="if(\'ANSWERED\' == \''+search_box_type+'\') return false;sort_box(\'ANSWERED\',\''+sort_box_type+'\')">'+get_lang("l_answered")+'</span>, '+
+   	'<span id="span_flag_FLAGGED" style="'+(search_box_type == 'FLAGGED' ? 'font-weight:bold;text-decoration:underline' : '')+'" title="'+get_lang("l_important")+'" class="message_options" onclick="if(\'FLAGGED\' == \''+search_box_type+'\') return false;sort_box(\'FLAGGED\',\''+sort_box_type+'\')">'+get_lang("l_important")+'</span>&nbsp;&nbsp;';
+	draw_paging(num_msgs);
+	Element("tot_m").innerHTML = num_msgs;	
+}
Index: tags/expressoMail1_2/1.2211/js/doiMenuData.js
===================================================================
--- tags/expressoMail1_2/1.2211/js/doiMenuData.js	(revision 214)
+++ tags/expressoMail1_2/1.2211/js/doiMenuData.js	(revision 214)
@@ -0,0 +1,207 @@
+_icon_dir="templates/default/images/menu/";
+
+function ConstructMenuTools(){
+	// Layout padrão de menu = option1
+	var _divMenu = Element('menu_tools');
+	if(_divMenu)
+		return;
+	var _option1 = preferences.hide_folders == "1" ? false : true;
+								
+	var itens = new Array (
+							"preferences_mail()|"+get_lang("Preferences")+"|preferences.png",
+							"search_emails(\"\")|"+get_lang("Search")+"|search.png",
+							"filterbox()|"+get_lang("Edit filters")+"|filters.png",
+							"folderbox()|"+get_lang("Edit folders")+"|editfolders.png",
+							"sharebox()|"+get_lang("Share mailbox")+"|usersfolders.png",
+							"empty_trash_imap()|"+get_lang("Empty trash")+"|trash.png"
+							);
+
+	var _link = Element('link_tools');
+	_divMenu = document.createElement("DIV");
+	_divMenu.id = "menu_tools";
+	_divMenu.style.position = "absolute";
+	_divMenu.style.top =  findPosY(_link) + (_option1 ? 19 : 14);
+	_divMenu.style.left = findPosX(_link) + (_option1 ? 22 : 22);
+	_divMenu.style.width = "auto";
+	_divMenu.style.height = "auto";
+	_divMenu.style.padding = "1px";
+	_divMenu.style.paddingTop = "0px";
+	_divMenu.style.zIndex = "10000";
+	_divMenu.style.backgroundColor = "WHITE";
+	_divMenu.style.border = "1px solid #999999";
+	_divMenu.style.borderTop = "0px solid #FFFFFF";
+	_divMenu.style.visibility = "hidden";
+	var _timeout = false;
+	_hideMenuTools = function () {		
+		Element('menu_tools').style.visibility = "hidden";	
+	};
+	_viewMenuTools = function () {
+		Element('menu_tools').style.visibility = "visible";
+	};
+
+	var _mouseover = _link.onmouseover;
+	
+	_link.onmouseover = function () {	
+		var _option1 = preferences.hide_folders == "1" ? false : true;
+		var _link = Element('link_tools');
+		Element('menu_tools').style.top =  findPosY(_link) + (_option1 ? 19 : 14);
+		if(_timeout) {
+			clearTimeout(_timeout);
+			_timeout=false;
+		}	
+		if(_mouseover) 
+			_mouseover(); 
+	
+		_timeout = setTimeout("_viewMenuTools();",500);
+	};
+	
+	_link.onmouseout  = function () {
+		if(_timeout) {
+			clearTimeout(_timeout);
+			_timeout=false;
+		}
+		if(_option1)
+			unset_menu_bg(Element("link_tools"));	
+		_timeout = setTimeout("_hideMenuTools();",500);
+	}
+
+	var _t = document.createElement("TABLE");
+	_t.cellPadding="0";
+	_t.cellSpacing="0";
+	_t.onmouseover = function () {	
+		if(_timeout) {
+			clearTimeout(_timeout);
+			_timeout=false;
+		}	
+		if(_mouseover) 
+			_mouseover(); 
+	
+		Element('menu_tools').style.visibility = "visible";
+	};
+	var _tbody = document.createElement("TBODY");
+	
+	var buildTr = function(value) {
+		var item = value.split('|');
+		var _tr = document.createElement("TR");
+		var _td = document.createElement("TD");
+		_td.innerHTML = "<img height=\"16px\" src=\"templates/default/images/menu/"+item[2]+"\">&nbsp;"+item[1]+"&nbsp;";
+		_td.style.color = "DARKBLUE";
+		_td.style.cursor = "pointer";
+		if(_option1)
+			_td.style.border = '1px solid #f7f7f7';			
+		_td.onclick 	= function() { Element('menu_tools').style.visibility='hidden';eval(item[0]);};
+		_td.onmouseover = function () {
+			if(_timeout) {
+				clearTimeout(_timeout);
+				timeout=false;
+			}
+			
+			if(_option1)
+				set_menu_bg(this);
+			else {
+				this.style.textDecoration="underline";				
+				this.style.color = 'DARKORANGE';
+			}
+		};						
+		_td.onmouseout   = function () {
+			_timeout = setTimeout("_hideMenuTools();",500);
+			if(_option1){
+				unset_menu_bg(this);
+				unset_menu_bg(Element("link_tools"));
+			}else {		
+				this.style.backgroundColor = 'WHITE';
+				this.style.textDecoration="none";
+				this.style.color = 'DARKBLUE';
+			}
+		};		
+		_tr.appendChild(_td);
+		return _tr;
+	}
+	
+	for(i = 0; i < itens.length; i++)
+		_tbody.appendChild(buildTr(itens[i]));
+			
+	_t.appendChild(_tbody);
+	_divMenu.appendChild(_t);
+	document.body.appendChild(_divMenu);
+}
+
+function openListUsers(border_id) {
+	connector.loadScript("QuickCatalogSearch");
+	QuickCatalogSearch.showCatalogList(border_id);
+}
+
+function ConstructRightMenu(_event){
+
+	var div = Element("div_rightbutton");
+	if(!div){
+		div = document.createElement("DIV");
+		div.style.position = 'absolute';
+		div.style.zIndex = '15';
+
+		div.style.border = '1px outset BLACK';
+		div.style.background = "#EEEEE6";
+		div.id = 'div_rightbutton';
+		div.style.padding = "1px";
+		div.style.fontSize = is_ie || is_gecko1_5 || is_win ? "9pt" : "11pt";
+		div.style.width = "190px";
+		div.style.height = is_win && !is_ie ? "129px" : "139px";
+		div.style.display ='none';		
+		document.body.appendChild(div);
+		var _tab = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
+		var _sep = "<hr>";
+		var optionsMenu = new Array( 
+			_tab + get_lang("Mark as")+"&nbsp;"+get_lang('seen')+'|'+"set_messages_flag('seen','get_selected_messages')",
+			_tab + get_lang("Mark as")+"&nbsp;"+get_lang('unseen')+'|'+"set_messages_flag('unseen','get_selected_messages')",
+			_tab + get_lang("Mark as")+"&nbsp;"+get_lang('important')+'|'+"set_messages_flag('flagged','get_selected_messages')",
+			_tab + get_lang("Mark as")+"&nbsp;"+get_lang('normal')+'|'+"set_messages_flag('unflagged','get_selected_messages')",
+			_sep,
+			_tab + get_lang("Move to")+" ... |wfolders.makeWindow('', 'move_to')",
+			_tab + get_lang("Delete")+"|"+"delete_msgs('null','selected','null')",
+			_tab + get_lang("Export")+"|"+"export_all_selected_msgs()"
+		);
+
+		for(i = 0; i < optionsMenu.length; i++){
+			optionsMenu_l = optionsMenu[i].split('|');
+			var div_l = document.createElement("DIV");
+			div_l.style.padding = "1px";
+			div_l.style.width = "188px";
+			div_l.style.cursor = 'pointer';			
+			div_l.innerHTML = optionsMenu_l[0];
+			div_l.style.valign = 'top';
+			if(optionsMenu_l[0] != _sep) {
+				var attr = document.createAttribute('javascript');
+				attr.value = optionsMenu_l[1]+";Element('div_rightbutton').style.display = 'none';";
+				div_l.setAttributeNode(attr);
+				div_l.oncontextmenu = function(e) {	return false;};
+				div_l.onclick = function () {this.onmouseout();eval(this.getAttribute('javascript'));};
+				div_l.onmouseover = function () {this.style.color = 'WHITE';this.style.background = "#4a79cd";};
+				div_l.onmouseout = function ()  {this.style.color = 'BLACK';this.style.background = "#EEEEE6";};
+			}
+			else
+				div_l.style.height = "11px";
+				
+			div_l.id="link_rightbutton_"+i;
+			div.appendChild(div_l);
+		}
+	
+	}
+
+	var x = _event.clientX + document.body.scrollLeft +  2;
+	var y =  _event.clientY + document.body.scrollTop +  2;
+
+	var w_width  = is_ie ? document.body.clientWidth : window.innerWidth;
+	var w_height = is_ie ? document.body.clientHeight + document.body.scrollTop : window.innerHeight + window.pageYOffset;
+
+	if(x + 218 > w_width)
+		div.style.left = w_width - (is_ie ? 198 : 218);	
+	else
+		div.style.left = x;
+	
+	if(y + 131 > w_height)
+		div.style.top =  w_height - (is_ie ? 125 : 131);	
+	else
+		div.style.top = y;	
+
+	div.style.display ='';
+} 
Index: tags/expressoMail1_2/1.2211/js/connector.js
===================================================================
--- tags/expressoMail1_2/1.2211/js/connector.js	(revision 271)
+++ tags/expressoMail1_2/1.2211/js/connector.js	(revision 271)
@@ -0,0 +1,569 @@
+/****************************************** Public variables *************************************************/
+var debug_controller =false;
+var files = new Array();
+var progressBar;
+
+  if (document.all)
+	{
+		navigator.userAgent.toLowerCase().indexOf('msie 5') != -1 ? is_ie5 = true : is_ie5 = false;
+		is_ie = true;
+		is_moz1_6 = false;
+		is_mozilla = false;
+		is_ns4 = false;
+	}
+	else if (document.getElementById)
+	{
+		navigator.userAgent.toLowerCase().match('mozilla.*rv[:]1\.6.*gecko') ? is_moz1_6 = true : is_moz1_6 = false;
+		is_ie = false;
+		is_ie5 = false;
+		is_mozilla = true;
+		is_ns4 = false;
+	}
+	else if (document.layers)
+	{
+		is_ie = false;
+		is_ie5 = false
+		is_moz1_6 = false;
+		is_mozilla = false;
+		is_ns4 = true;
+	}	
+
+/****************************************** Connector Class *************************************************/
+	// Constructor
+	function cConnector()
+	{
+		this.requests = new Array();
+		this.oxmlhttp = null;
+		this.isVisibleBar = false;
+		this.tid = 0;
+		this.progressBar = null;
+		this.oldX = 0;
+		this.oldY = 0;
+		this.updateVersion = "";
+	}
+	
+	cConnector.prototype.buildBar = function()
+		{			
+			var div = document.getElementById('divProgressBar');
+		
+			if(! div) {												
+				div = document.createElement("DIV");
+				div.style.visibility	= "hidden";		
+				div.style.width = "103px";
+				div.id = 'divProgressBar';
+				div.align = "center";
+				div.innerHTML = '&nbsp;&nbsp;<font face="Verdana" size="2" color="WHITE">'+document.getElementById('txt_loading').value+'...</font>&nbsp;';
+				div.style.background = "#cc4444";
+				div.style.position = 'fixed';
+				div.style.top = '0px';
+				div.style.right = '0px';
+				document.body.appendChild(div);																
+				
+				if(is_ie) {
+					var elem = document.all[div.id]; 
+					elem.style.position="absolute";
+					var root = document.body;
+					var posX = elem.offsetLeft-root.scrollLeft;
+					var posY = elem.offsetTop-root.scrollTop;
+					root.onscroll = function() {
+						elem.style.right = '0px';
+						elem.style.top = (posY + root.scrollTop) + "px";
+					};					
+				}
+				
+				if(debug_controller) {
+					div = document.createElement("DIV");
+					div.style.width	= "800px";
+					div.style.height= "400px";
+					div.id = "debug_controller";
+					div.align='right';
+					document.body.appendChild(div);																
+				}
+			}								
+	}	
+//------------------------------------ BEGIN: Functions for Connector HTTPRequest  -------------------------------------------------//	
+	// Serialize Data Method
+	cConnector.prototype.serialize = function(data)
+	{	var _thisObject = this;		
+		var f = function(data)
+		{
+			var str_data;
+	
+			if (data == null || 
+				(typeof(data) == 'string' && data == ''))
+			{
+				str_data = 'N;';
+			}
+	
+			else switch(typeof(data))
+			{
+				case 'object':
+					var arrayCount = 0;
+	
+					str_data = '';
+	
+					for (i in data)
+					{
+						if (i == 'length')
+						{
+							continue;
+						}
+						
+						arrayCount++;
+						switch (typeof(i))
+						{
+							case 'number':
+								str_data += 'i:' + i + ';' + _thisObject.serialize(data[i]);
+								break;
+	
+							case 'string':
+								str_data += 's:' + i.length + ':"' + i + '";' + _thisObject.serialize(data[i]);
+								break;
+	
+							default:
+								showMessage(Element('cc_msg_err_serialize_data_unknown').value);
+								break;
+						}
+					}
+	
+					if (!arrayCount)
+					{
+						str_data = 'N;';	
+					}
+					else
+					{
+						str_data = 'a:' + arrayCount + ':{' + str_data + '}';
+					}
+					
+					break;
+			
+				case 'string':
+					str_data = 's:' + data.length + ':"' + data + '";';
+					break;
+					
+				case 'number':
+					str_data = 'i:' + data + ';';
+					break;
+	
+				case 'boolean':
+					str_data = 'b:' + (data ? '1' : '0') + ';';
+					break;
+	
+				default:
+					showMessage(Element('cc_msg_err_serialize_data_unknown').value);
+					return null;
+			}
+	
+			return str_data;
+		}
+	
+		var sdata = f(data);
+		return sdata;
+	}
+	cConnector.prototype.matchBracket = function(strG, iniPosG)
+	{
+		_thisObject = this;
+		var f = function (str, iniPos)
+		{
+			var nOpen, nClose = iniPos;
+		
+			do 
+			{
+				nOpen = str.indexOf('{', nClose+1);
+				nClose = str.indexOf('}', nClose+1);
+
+				if (nOpen == -1)
+				{
+					return nClose;
+				}
+			
+				if (nOpen < nClose )
+				{
+					nClose = _thisObject.matchBracket(str, nOpen);
+				}
+			
+			} while (nOpen < nClose);
+
+			return nClose;
+		}
+
+		return f(strG, iniPosG);
+	}
+	
+		
+	//Unserialize Data Method
+	cConnector.prototype.unserialize = function(str)
+	{
+		
+		_thisObject = this;
+		
+		var f = function (str)
+		{
+			switch (str.charAt(0))
+			{
+				case 'a':
+					
+					var data = new Array();
+					var n = parseInt( str.substring( str.indexOf(':')+1, str.indexOf(':',2) ) );
+					var arrayContent = str.substring(str.indexOf('{')+1, str.lastIndexOf('}'));
+				
+					for (var i = 0; i < n; i++)
+					{
+						var pos = 0;
+	
+						/* Process Index */
+						var indexStr = arrayContent.substr(pos, arrayContent.indexOf(';')+1);
+						var index = _thisObject.unserialize(indexStr);
+						pos = arrayContent.indexOf(';', pos)+1;
+						
+						/* Process Content */
+						var part = null;
+						switch (arrayContent.charAt(pos))
+						{
+							case 'a':
+								var pos_ = _thisObject.matchBracket(arrayContent, arrayContent.indexOf('{', pos))+1;
+								part = arrayContent.substring(pos, pos_);
+								pos = pos_;
+								data[index] = _thisObject.unserialize(part);
+								break;
+						
+							case 's':
+								var pval = arrayContent.indexOf(':', pos+2);
+								var val  = parseInt(arrayContent.substring(pos+2, pval));
+								pos = pval + val + 4;
+								data[index] = arrayContent.substr(pval+2, val);
+								break;
+	
+							default:
+								part = arrayContent.substring(pos, arrayContent.indexOf(';', pos)+1);
+								pos = arrayContent.indexOf(';', pos)+1;
+								data[index] = _thisObject.unserialize(part);
+								break;
+						}
+						arrayContent = arrayContent.substr(pos);
+					}
+					break;
+					
+				case 's':
+					var pos = str.indexOf(':', 2);
+					var val = parseInt(str.substring(2,pos));
+					var data = str.substr(pos+2, val);
+					str = str.substr(pos + 4 + val);
+					break;
+	
+				case 'i':
+				case 'd':
+					var pos = str.indexOf(';');
+					var data = parseInt(str.substring(2,pos));
+					str = str.substr(pos + 1);
+					break;
+				
+				case 'N':
+					var data = null;
+					str = str.substr(str.indexOf(';') + 1);
+					break;
+	
+				case 'b':
+					var data = str.charAt(2) == '1' ? true : false;
+					break;
+			}
+			
+			return data;
+		}
+	
+		return f(str);
+	}
+
+	//Create XMLHTTP object Method
+	cConnector.prototype.createXMLHTTP = function ()
+	{	
+		try
+		{ 
+			this.oxmlhttp = new XMLHttpRequest();
+			this.oxmlhttp.overrideMimeType('text/xml');
+		}
+		catch (e)
+		{ 
+			try
+			{
+				this.oxmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
+			}
+			catch (e1)
+			{ 
+				try
+				{
+					this.oxmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
+				}
+				catch (e2)
+				{
+					this.oxmlhttp = null;
+				}
+			}
+		}
+	
+	}
+	
+	// Request Constructor Connector	
+	cConnector.prototype.newRequest = function (id, target, method, handler, data)
+	{				
+		this.tid = id;
+		if (this.requests[id]) {
+			return false;
+		}
+	
+		this.createXMLHTTP();
+		var oxmlhttp = this.oxmlhttp;
+		var _thisObject = this;		
+		
+		if (! oxmlhttp)		
+			return false;
+				
+		this.requests[id] = oxmlhttp;
+		this.buildBar();		
+		this.showProgressBar();
+		
+		var sub_handler = function ()
+		{			
+			var progressBar = _thisObject.progressBar;
+			
+			try
+			{
+				if (oxmlhttp.readyState == 4 )
+				{
+					
+					switch (oxmlhttp.status)
+					{
+						
+						case 200:
+							if (typeof(handler) == 'function')
+							{																
+								_thisObject.hideProgressBar();																
+								var data = _thisObject.unserialize(oxmlhttp.responseText);
+								if(debug_controller) {
+									document.getElementById("debug_controller").innerHTML += oxmlhttp.responseText;
+									document.getElementById("debug_controller").innerHTML += "<br>-------------------------------------------------------------------------------------<br>";
+								}									
+								handler(data);
+								delete _thisObject.requests[id];								
+								_thisObject.requests[id] = null;
+							}
+
+							break;
+
+						case 404:
+							
+							alert(get_lang('Page Not Found!'));
+							break;
+
+						default:												
+					}
+				}
+			}
+			catch (e)
+			{			
+				_thisObject.hideProgressBar();
+				if(debug_controller)
+					alert(e+"\n"+oxmlhttp.responseText);
+				// View Exception in Javascript Console
+				throw(e);
+			}
+						
+		}
+
+		try
+		{ 
+			
+			if (method == '' || method == 'GET')
+			{								
+				oxmlhttp.open("GET",target,true);
+				if (typeof(handler) == 'function')
+				{	
+					oxmlhttp.onreadystatechange =  sub_handler;					
+					oxmlhttp.send(null);					
+				}		
+				
+			}
+			else if (method == 'POST')
+			{
+				oxmlhttp.open("POST",target, true);
+				oxmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
+				if (typeof(handler) == 'function')
+				{
+					oxmlhttp.onreadystatechange = sub_handler;
+					oxmlhttp.send(data);
+				}				
+				
+			}
+		}
+		catch(e)
+		{	
+			_thisObject.hideProgressBar();
+			if(debug_controller)
+				alert(e);
+			// View Exception in Javascript Console	 
+			throw(e);
+		}
+						
+		return true;
+	}
+	// Cancel Request Connector
+	cConnector.prototype.cancelRequest = function (){
+		if (!this.requests[this.tid]){
+			return false;
+		}
+		this.oxmlhttp.onreadystatechange = null;
+		this.requests[this.tid].abort();
+		this.hideProgressBar();
+	}
+//------------------------------------  END: Functions for Connector HTTPRequest  -------------------------------------------------//
+
+//	----------------------------------- BEGIN: Functions for build Bar Progress ---------------------------------------------------------//
+	cConnector.prototype.hideProgressBar = function ()
+	{
+		var div = document.getElementById('divProgressBar');
+		div.style.visibility = 'hidden';
+		this.isVisibleBar = false;
+	}
+	
+	cConnector.prototype.showProgressBar = function(){
+		var div = document.getElementById('divProgressBar');
+		div.style.visibility = 'visible';			
+
+		this.isVisibleBar = true;
+	}
+
+	cConnector.prototype.loadAllScripts = function(scripts) {	
+		for(var i = 0; i < scripts.length; i++){
+			this.loadScript(scripts[i]);
+		}
+	}
+
+	cConnector.prototype.loadScript = function(scriptPath)	{
+      	if (document.getElementById('uploadscript_'+scriptPath)) {
+      		return;
+      	}
+		var head = document.getElementsByTagName("head")[0];
+		var script = document.createElement("SCRIPT");
+		script.id = 'uploadscript_'+scriptPath;
+		script.type = 'text/javascript';
+  		
+  		if(is_ie) {
+		
+			this.oxmlhttp.open("GET", "js/"+scriptPath+".js?"+this.updateVersion, false);
+    	    this.oxmlhttp.setRequestHeader('Content-Type','text/plain');
+			this.oxmlhttp.send(null);
+			if(this.oxmlhttp.status != 0 && this.oxmlhttp.status != 200 || 	this.oxmlhttp.status == 0 && this.oxmlhttp.responseText.length == 0)
+				throw new Error("Error " + this.oxmlhttp.status + "("+this.oxmlhttp.statusText+") when loading script file '"+scriptPath+"'");
+			script.text = this.oxmlhttp.responseText;				
+		}
+		else {
+			script.src =  "js/"+scriptPath+".js?"+this.updateVersion;
+		}
+
+		head.appendChild(script);
+		return;	
+	}
+//------------------------------------  END: Functions for Progress Bar  -------------------------------------------------//
+	// Default Controller File
+	var DEFAULT_URL = 'controller.php?action=';
+	// connector object
+	var connector = new cConnector();
+	var _onmouseup = document.onmouseup;
+	var isExecuteForm = false;
+	var id = null;
+
+	// 	Function executes AJAX
+	// 	cExecute (url, handler, params)
+	//	url: 'module.class.method'
+	//  handle: function handle() receive response.
+	//  params: parameters for POST method
+	//	form: form element (for upload files)	
+	function cExecute(url, handler, params, form) {
+		if(isExecuteForm){
+			isExecuteForm = false;
+			document.onmouseup = _onmouseup;
+		}
+		if(form) {
+			cExecuteForm(url, form);
+			return;
+		}
+		
+		url = DEFAULT_URL + url;
+			
+		if(params)		 
+			method = "POST";
+			 	
+		 else 
+			method = "GET";
+			 
+		 id = url;
+		connector.newRequest(id, url, method, handler, params);
+	}
+	
+	// This function executes submit values to Controller (POST)
+	// The return is void.
+	// 	cExecuteForm (url, form)
+	//	url: 'module.class.method'
+	//	form: form element (for upload files)	
+	function cExecuteForm(url, form, handler,id){
+		connector.buildBar();
+		isExecuteForm = true;		
+		document.onmouseup = alertBut;
+
+		connector.showProgressBar();
+		if(! (divUpload = document.getElementById('divUpload'))) {
+			divUpload		= document.createElement('DIV');		
+			divUpload.id	= 'divUpload';
+			document.body.appendChild(divUpload);
+		}
+
+		if(! (el = document.getElementById('_action'))) {			
+			el			= document.createElement('input');
+			el.type	= 'hidden';
+			el.id		= '_action';	
+			el.name	= '_action';
+			form.appendChild(el);
+		}
+
+		var divFiles = Element("divFiles_"+id);		
+		if (divFiles.firstChild) {
+			el			= document.createElement('input');
+			el.type	= 'hidden';	
+			el.name	= 'countFiles';
+			var countDivFiles = 0;
+			try{
+				countDivFiles = parseInt(divFiles.lastChild.firstChild.id.split('_')[2]) + 1; // The id of last file 
+				}
+			catch (e) { var countDivFiles = 0; };
+			el.value	= countDivFiles ;
+			form.appendChild(el);						
+		}		
+
+		form._action.value = url;
+		divUpload.innerHTML= "<iframe onload=\"cExecute('$this.functions.getReturnExecuteForm',"+handler+");\"  style='display:"+(debug_controller ? "" : "none")+";width:"+(debug_controller ? 400 : 0)+";height:"+(debug_controller ? 400 : 0)+";' name='uploadFile'></iframe>";
+		form.action ="controller.php";
+		form.target ="uploadFile";		
+		form.submit();
+	}	
+	
+	
+	function alertBut(e) {
+	   	if(!e)
+			e = window.event;
+
+	    if(_onmouseup)
+			_onmouseup(e);
+
+		if(isExecuteForm) {
+	    	if(confirm(get_lang("There's an action processing. Do you want abort it?"))) {
+		    	connector.hideProgressBar();
+		    	isExecuteForm = false;
+		    	delete connector.requests[id];								
+				connector.requests[id] = null;
+	    		stop();		    		    		
+	    		return;
+	    	}
+    		else
+    			return false;
+	    }
+	}	
Index: tags/expressoMail1_2/1.2211/js/ccQuickAdd.js
===================================================================
--- tags/expressoMail1_2/1.2211/js/ccQuickAdd.js	(revision 197)
+++ tags/expressoMail1_2/1.2211/js/ccQuickAdd.js	(revision 197)
@@ -0,0 +1,153 @@
+	function cQuickAddContact ()
+	{
+		this.arrayWin = new Array();
+		this.el;
+		this._nFields = 5;
+	}
+
+	
+	cQuickAddContact.prototype.showList = function(data){
+		_this = this;
+
+		var	cc_data = (typeof data) == 'object' ? data : data.split(',');
+		
+		if (document.getElementById('cc_rectQuickAddContact') == null){		
+			el = document.createElement("DIV");
+			el.style.visibility = "hidden";									
+			el.style.position = "absolute";
+			el.style.left = "0px";
+			el.style.top = "0px";
+			el.style.width = "0px";
+			wHeight = 165;
+			el.style.height = wHeight + 'px';
+			el.className = "div_cc_rectQuickAddContact";
+			el.id = 'cc_rectQuickAddContact';
+			document.body.appendChild(el);																
+		}
+		else {
+			el = document.getElementById('cc_rectQuickAddContact');
+		}
+		el.innerHTML = "";
+		var fieldsTop = 10;
+		var fieldsSpace = 30;
+		var lang_save 	= get_lang('Save');
+		var lang_cancel = get_lang('Cancel');
+		
+		//função lang
+		fields = new Array(get_lang('Nickname')+":", get_lang('First Name')+":", get_lang('Last Name')+":", 'E-mail:');
+		for (i=0; i<fields.length; i++) {
+			el.innerHTML += '<span id="ccQuickAddCT' + i + '" style="position: absolute; top: ' +  (fieldsTop+i*fieldsSpace) + 'px; left: 5px; width: 100px; text-align: right; border: 0px solid #999;">' + fields[i] + '</span>';
+			el.innerHTML += '<input id="ccQuickAddCI' + i + '" type="text" value="' + cc_data[i] + '" maxlength="50" style="position: absolute; top: ' + (fieldsTop+i*fieldsSpace) + 'px; left: 110px; width: 135px;">';
+		}
+		el.innerHTML +='<div id="ccQAFunctions" style="border: 0px solid black; width: 220px; height: 20px">' +
+			'<input title="'+lang_save+'" type="button" onclick="ccQuickAddOne.send(\''+data+'\');" value="'+lang_save+'" style="position: absolute; top: ' + (fieldsTop+(i*fieldsSpace)) + 'px; left: 75px; width: 60px" />' +
+			'<input title="'+lang_cancel+'" type="button" onclick="ccQuickAddOne.fechar(\'' + id + '\');" value="'+lang_cancel+'" style="position: absolute; top: ' + (fieldsTop+(i*fieldsSpace)) + 'px; left: 140px; width: 60px" />' +
+			'</div>';
+		el.innerHTML +=	"<br>";
+		_this.showWindow(el);
+
+	}
+		
+	cQuickAddContact.prototype.showWindow = function (div)
+	{						
+		if(! this.arrayWin[div.id]) {
+			win = new dJSWin({			
+				id: 'ccQuickAddOne_'+div.id,
+				content_id: div.id,
+				width: '255px',
+				height: wHeight+'px',
+				title_color: '#3978d6',
+				bg_color: '#eee',
+				title: get_lang("Quick Add"),
+				title_text_color: 'white',
+				button_x_img: '../phpgwapi/images/winclose.gif',
+				border: true });
+			this.arrayWin[div.id] = win;
+			win.draw();			
+		}
+		else {
+			win = this.arrayWin[div.id];
+		}			
+		win.open();
+	}
+	
+	cQuickAddContact.prototype.send = function (data)
+	{
+		
+		var handler = function (responseText)
+		{
+			var data = responseText;
+			if (!data || typeof(data) != 'object')
+			{
+				write_msg("Problema ao contactar servidor");
+				return;
+			}
+			else if (data['status'] == 'alreadyExists')
+			{
+				alert(data['msg']);
+				return;
+			}
+			else if (data['status'] != 'ok')
+			{
+				return;
+			}
+			contacts += ',' + full_name + ';' + email;
+			write_msg("Contato adicionado com sucesso.");
+			win.close();
+
+			if (_this.afterSave)
+			{
+				switch (typeof(_this.afterSave))
+				{
+					case 'function':
+						_this.afterSave();
+						break;
+
+					case 'string':
+						eval(_this.afterSave);
+						break;
+				}
+			}
+		}
+				
+		var _this = this;
+		var sdata = data.split(",");
+		var temp = sdata[3];
+		sdata[3]='';
+		sdata[4]=temp;
+		sdata = new Array();
+
+		for (i=0; i< fields.length; i++) {			
+			if(i == 3){
+				sdata[i] = '';
+				sdata[i+1] = document.getElementById("ccQuickAddCI" + i).value;
+			}
+			else
+				sdata[i] = document.getElementById("ccQuickAddCI" + i).value;
+		}
+
+		var full_name = trim(sdata[1]) + ' ' + trim(sdata[2]);
+		var email = trim(sdata[4]);				
+		//Utiliza expressão regular para validar email
+		var reEmail = /^[A-Za-z\d_-]+(\.[A-Za-z\d_-]+)*@(([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}\])$/;
+
+		if(!reEmail.test(email)){
+			alert("O endereco de email '" + email + "' nao e valido!\n" +
+			"Por favor informe um endereco valido.");
+			return false;
+		}
+		
+		var sdata = 'add='+escape(connector.serialize(sdata));
+		var CC_url = '../index.php?menuaction=contactcenter.ui_data.data_manager&method=';
+		connector.newRequest('cQuickAdd.Send', CC_url+'quick_add', 'POST', handler, sdata);
+	}
+	
+	cQuickAddContact.prototype.fechar = function(id) {
+		var div = document.getElementById('cc_rectQuickAddContact');
+		win = this.arrayWin[div.id];
+		win.close();
+	}
+	
+	
+/* Build the Object */
+	var	ccQuickAddOne = new cQuickAddContact();
Index: tags/expressoMail1_2/1.2211/js/DropDownContacts.js
===================================================================
--- tags/expressoMail1_2/1.2211/js/DropDownContacts.js	(revision 2)
+++ tags/expressoMail1_2/1.2211/js/DropDownContacts.js	(revision 2)
@@ -0,0 +1,315 @@
+/**********************************************************************************\
+* Written by Joao Alfredo Knopik Junior (JakJr) <joao.alfredo@gmail.com>          *
+* ------------------------------------------------------------------------------- *
+*  This program is free software; you can redistribute it and/or modify it        *
+*  under the terms of the GNU General Public License as published by the	      *
+*  Free Software Foundation; either version 2 of the License, or (at your option) * 
+*  any later version.                                                             *
+\**********************************************************************************/
+// variavel global que salva o contato atual selecionado.
+var actualSelectedContact = 0;
+var setTimeOutLayer = 0;
+var div_message_scroll = 0;
+
+function search_contacts(key_pressed, fld_id)
+{
+	div_message_scroll = Element('div_message_scroll_'+ fld_id.substring(fld_id.length - 1, fld_id.length));
+
+	var string_contacts = contacts
+	if (Element(fld_id))
+		var mail = Element(fld_id).value;
+	else
+		return;
+	
+	var array_contacts = string_contacts.split(",");
+	var tmp = mail.split(",");
+	mail = trim(tmp[tmp.length - 1]);
+	tmp_mail = mail;
+	
+	seekDot = /\./gi;
+	mail = mail.replace(seekDot, "[.]");
+	mail = mail.replace('"', "&quot;");
+	mail = mail.replace("\n", "");
+	mail = mail.replace("\r", "");
+	mail = mail.replace("\t", "");
+	posX = findPosX(document.getElementById(fld_id));
+	posY = findPosY(document.getElementById(fld_id));
+
+	if ((!string_contacts) || (string_contacts.length==0) || (mail.length==0)){
+		hideTip();
+		return;
+	}
+		
+	if (mail.length == 0){
+		hideTip();
+		return;
+	}
+	
+	var RegExp_name = new RegExp("\\b"+mail, "i");
+	var RegExp_mail = new RegExp("^"+mail, "i");
+
+	var match_contacts = new Array();
+	var match_index = 0;
+	
+	for (var i=0; i<array_contacts.length; i++){
+		tmp = array_contacts[i].split(";");
+		if ( (RegExp_name.test(tmp[0])) || (RegExp_mail.test(tmp[1])) ){
+			tmp[1] = tmp[1].replace(tmp_mail, tmp_mail.bold());
+			tmp[0] = tmp[0].replace(tmp_mail, tmp_mail.bold());
+			match_contacts[match_index] = '&quot;' + tmp[0] + '&quot; &lt;' + tmp[1] + '&gt;';
+			match_index++;
+		}
+	}
+
+	if (match_contacts.length == 0){
+		hideTip();
+		return;
+	}
+
+	var table_contacts_header = "<table style='font-family:arial;font-size:12;color:#0000CF' border=0 cellpadding=0 cellspacing=0>";
+	var table_contacts_foot = "</table>";
+	var lines = '';
+	var REG_EXP = /^[^\#|^\$|^\%|^\!|^\?|^\"|^\']+$/;
+	var match_cont = "";
+	for (var i=0; i<match_contacts.length; i++)
+	{
+		var aux = match_contacts[i].split("");
+		for(var j in aux){
+			if(REG_EXP.test(aux[j])){
+				match_cont += aux[j];
+			}else{
+				match_cont += "";
+			}
+		}
+		//lines = lines + "<tr><td id=td_DD_"+i+" onClick=\"javascript:hideTip();makeMailList('"+match_contacts[i]+"','"+fld_id+"');document.getElementById('" + fld_id + "').focus();\" onmouseover=\"selectContact("+i+")\">" + match_contacts[i] + "</td></tr>"
+		lines = lines + "<tr><td id=td_DD_"+i+" onMouseDown=\"javascript:hideTip();makeMailList('"+match_cont+"','"+fld_id+"');document.getElementById('" + fld_id + "').focus();\" onmouseover=\"selectContact("+i+")\">" + match_cont + "</td></tr>"
+		match_cont = "";
+	}
+
+	// treat especials keys
+	// key ENTER
+	if ((key_pressed == 13) && (document.getElementById('tipDiv').style.visibility)){
+		makeMailList(document.getElementById('td_DD_' + actualSelectedContact).innerHTML,fld_id);
+		hideTip();
+		return;
+	}
+	// key lostfocus
+	if ((key_pressed == 'lostfocus') && (document.getElementById('tipDiv').style.visibility)){
+		hideTip();
+		return;
+	}
+	// key DOWN
+	if ((key_pressed == 40) && (document.getElementById('tipDiv').style.visibility)){
+		if (actualSelectedContact != (match_contacts.length - 1)){
+			selectContact(actualSelectedContact + 1);
+		}
+		return;
+	}
+	// key UP
+	if ((key_pressed == 38) && (document.getElementById('tipDiv').style.visibility)){
+		if (actualSelectedContact != 0){			
+			selectContact(actualSelectedContact - 1);
+			return;
+		}
+	}
+
+	if (lines != ''){
+		table_contacts = table_contacts_header + lines + table_contacts_foot
+		doTooltip(posX, posY, table_contacts)
+	}
+	else
+		hideTip();
+		
+	return true;
+}
+
+function makeMailList(mail,fld_id)
+{
+	list = Element(fld_id);
+	for (var i = list.value.length; ((i!=0) && (list.value.substring(i-1,i)!=',')); i--){}
+	mail = mail.replace(/&lt;/g,"<");
+	mail = mail.replace(/&gt;/g,">");
+	mail = mail.replace(/<[bB]>/g,"");
+	mail = mail.replace(/<\/[bB]>/g,"");
+	if (i == 0)
+		list.value = list.value.substring(0,i) + mail + ', ';
+	else
+		list.value = list.value.substring(0,i) + ' ' + mail + ', ';
+}
+
+function selectContact(newContact){	
+	//Desabilitar o atual
+	var elAtual = document.getElementById('td_DD_' + actualSelectedContact);
+	if(elAtual)
+		elAtual.bgColor = "#efefef";	
+		
+	//Habilitar o novo.		
+	var elNew = document.getElementById('td_DD_' + newContact).bgColor = "#c0e0ff";
+	if(elNew)
+		elNew.bgColor = "#c0e0ff";
+
+	actualSelectedContact = newContact;
+}
+
+function doTooltip(x,y,msg) {
+	if ( typeof Tooltip == "undefined" || !Tooltip.ready ) return;
+	Tooltip.show(x,y,msg);
+}
+
+function hideTip() {
+	if ( typeof Tooltip == "undefined" || !Tooltip.ready ) return;
+	actualSelectedContact=0;
+	Tooltip.hide();
+}
+
+function findPosX(obj)
+{
+	var curleft = 0;
+	if (obj.offsetParent)
+	{
+		while (obj.offsetParent)
+		{
+			curleft += obj.offsetLeft
+			obj = obj.offsetParent;
+		}
+	}
+	else if (obj.x)
+		curleft += obj.x;
+	return curleft;
+}
+
+function findPosY(obj)
+{
+	var curtop = 0;
+	if (obj.offsetParent)
+	{
+		while (obj.offsetParent)
+		{
+			curtop += obj.offsetTop
+			obj = obj.offsetParent;
+		}
+	}
+	else if (obj.y)
+		curtop += obj.y;
+	return curtop;
+}
+
+function trim(inputString) {
+   if (typeof inputString != "string") 
+   	return inputString;
+      
+   var retValue = inputString;
+   var ch = retValue.substring(0, 1);
+   while (ch == " ") { 
+	  retValue = retValue.substring(1, retValue.length);
+	  ch = retValue.substring(0, 1);
+   }
+   ch = retValue.substring(retValue.length-1, retValue.length);
+   while (ch == " ") { 
+	  retValue = retValue.substring(0, retValue.length-1);
+	  ch = retValue.substring(retValue.length-1, retValue.length);
+   }
+   while (retValue.indexOf("  ") != -1) { 
+	  retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); 
+   }
+   return retValue; 
+}
+
+var Tooltip = {
+    overlaySelects: true,  // iframe shim for select lists (ie win)
+    offX: 0,
+    offY: 50,
+    tipID: "tipDiv",
+    showDelay: 0,
+    hideDelay: 0,
+    
+    ovTimer: 0, // for overlaySelects
+    ready:false, timer:null, tip:null, shim:null, supportsOverlay:false,
+  
+    init: function() {
+            var el_dropdowncontact = document.createElement("DIV");
+			el_dropdowncontact.id = this.tipID;
+			document.body.appendChild(el_dropdowncontact);
+            this.supportsOverlay = this.checkOverlaySupport();
+            this.ready = true;
+    },
+    
+    show: function(x, y, msg) {
+        this.tip = document.getElementById( this.tipID );
+        this.writeTip(msg);
+        
+        this.positionTipStatic(x,y);
+   		this.handleOverlay(1, this.showDelay, x+this.offX,y+this.offY);
+		document.getElementById('td_DD_0').bgColor = "#c0e0ff";
+      	this.timer = setTimeout("Tooltip.toggleVis('" + this.tipID + "', 'visible')", this.showDelay);
+    },
+    
+    writeTip: function(msg) {
+        if ( this.tip && typeof this.tip.innerHTML != "undefined" ) this.tip.innerHTML = msg;
+        this.tip.style.width = 'auto';
+    },
+    
+    positionTipStatic: function(x,y) {
+        if ( this.tip && this.tip.style ) {
+			this.tip.style.left = x + this.offX + "px";
+			this.tip.style.top = y + this.offY + "px";
+        }
+     },
+
+	scrollChanged: function() {
+		Element('tipDiv').style.visibility = 'hidden';
+		Tooltip.hide();
+	},
+
+    hide: function() {
+        if (this.timer) { clearTimeout(this.timer);	this.timer = 0; }
+		this.handleOverlay(0, this.hideDelay);
+        this.timer = setTimeout("Tooltip.toggleVis('" + this.tipID + "', 'hidden')", this.hideDelay);
+        this.tip = null; 
+    },
+    
+  toggleVis: function(id, vis) { // to check for el_dropdowncontact, prevent (rare) error
+      var el_dropdowncontact = document.getElementById(id);
+      if (el_dropdowncontact) el_dropdowncontact.style.visibility = vis;
+  },
+
+	// check need for and support of iframe shim
+	checkOverlaySupport: function() {
+		return (is_ie);
+	}, 
+    
+	handleOverlay: function(bVis, d, x ,y) {
+		var _scrollY = div_message_scroll ? div_message_scroll.scrollTop : 0;
+        if(_scrollY > 0 && this.tip) {
+	        this.tip.style.top = (findPosY(this.tip) - _scrollY)+ "px";
+	    }
+		if ( this.overlaySelects && this.supportsOverlay ) {
+			if (this.ovTimer) { clearTimeout(this.ovTimer); this.ovTimer = 0; }
+			switch (bVis) {
+			case 1 :
+				if ( !document.getElementById('tipShim') ) 
+					document.body.insertAdjacentHTML("beforeEnd", '<iframe id="tipShim" src="about:blank" style="position:absolute; left:' + x + '; top:' + y + '; z-index:500; visibility:hidden" scrolling="no" frameborder="0"></iframe>');
+					this.shim = document.getElementById('tipShim'); 
+					if (this.shim && this.tip) {
+						this.shim.style.width = this.tip.offsetWidth + "px";
+                        this.shim.style.height = this.tip.offsetHeight + "px";
+                        this.shim.style.top = findPosY(this.tip)+ "px";
+					}
+					this.ovTimer = setTimeout("Tooltip.toggleVis('tipShim', 'visible')", d);
+				break;
+			case 0 :
+				this.ovTimer = setTimeout("Tooltip.toggleVis('tipShim', 'hidden')", d);
+				if (this.shim) this.shim = null;
+				break;
+			}
+		}
+	}
+}
+Tooltip.init();
+// Criar um estilo no html (tpl) com os seguintes parametros:
+//div#tipDiv {
+//  position:absolute; visibility:hidden; left:0; top:0; z-index:10000;
+//  background-color:#EFEFEF; border:1px solid #337;
+//  width:220px; padding:3px;
+//  color:#000; font-size:11px; line-height:1.2;
+//  cursor: default;
Index: tags/expressoMail1_2/1.2211/js/color_palette.js
===================================================================
--- tags/expressoMail1_2/1.2211/js/color_palette.js	(revision 51)
+++ tags/expressoMail1_2/1.2211/js/color_palette.js	(revision 51)
@@ -0,0 +1,96 @@
+// Inicializa palheta de cores;
+function cColorPalette(){
+	this.editor;
+	this.div;
+	this.parentDiv;
+	this.colors = new Array(	new Array("#FFFFFF","#FFCCCC","#FFCC99","#FFFF99","#FFFFCC","#99FF99","#99FFFF","#CCFFFF","#CCCCFF","#FFCCFF"),
+						new Array("#CCCCCC","#FF6666","#FF9966","#FFFF66","#FFFF33","#66FF99","#33FFFF","#66FFFF","#9999FF","#FF99FF"),
+						new Array("#C0C0C0","#FF0000","#FF9900","#FFCC66","#FFFF00","#33FF33","#66CCCC","#33CCFF","#6666CC","#CC66CC"),
+						new Array("#999999","#CC0000","#ff6600","#FFCC33","#FFCC00","#33CC00","#00CCCC","#3366FF","#6633FF","#CC33CC"),
+						new Array("#666666","#990000","#CC6600","#CC9933","#999900","#009900","#339999","#3333FF","#6600CC","#993399"),
+						new Array("#333333","#660000","#993300","#996633","#666600","#006600","#336666","#000099","#333399","#663366"),
+						new Array("#000000","#330000","#663300","#663333","#333300","#003300","#003333","#000066","#330099","#330033"));
+	this.buildPalette();
+}
+
+// funçoes
+cColorPalette.prototype.changeFontColor = function (color){	
+	var mainField = this.editor.contentWindow;
+	mainField.document.execCommand("forecolor", false, color);	
+	document.getElementById("palettecolor").style.visibility="hidden";
+	mainField.focus();
+}
+
+cColorPalette.prototype.repos = function (intElemScrollTop)
+{
+	var new_pos = findPosY(Element("forecolor")) - intElemScrollTop + 20;
+	this.div.style.top = new_pos;
+}
+
+cColorPalette.prototype.loadPalette = function (id)
+{
+	this.parentDiv = document.getElementById("body_position_"+id);
+	this.editor = document.getElementById("body_"+id);
+	if(this.div.parentNode)
+		this.div.parentNode.removeChild(this.div);	
+
+	this.parentDiv.appendChild(this.div);	
+	this.div.style.position = "absolute";
+
+	if(is_ie)
+	{
+		this.div.style.top = findPosY(Element("forecolor")) - 100;
+		this.div.style.left = findPosX(Element("forecolor"))- 200;
+	}
+	else
+	{
+		this.div.style.top = ColorPalette.repos(Element("div_message_scroll_"+id).scrollTop);
+		this.div.style.left = findPosY(Element("forecolor"))+ 227;
+	}
+}
+
+cColorPalette.prototype.buildPalette = function (){
+	
+  	this.div = document.createElement("DIV");
+	this.div.style.visibility="hidden";
+  	this.div.id= "palettecolor";
+  	this.div.style.top = "0px";
+  	this.div.style.left = "0px";
+  	this.div.style.width	= "auto";
+  	this.div.style.height= "auto";
+  	var t1 = document.createElement("TABLE");
+ 	var tb1 = document.createElement("TBODY");
+ 	t1.appendChild(tb1);
+  	t1.border ="1px";
+	t1.cellPadding ="0px";
+	t1.cellSpacing ="0px";
+ 	t1.style.width = "100px";
+ 	t1.bgcolor = "WHITE";
+  	this.div.appendChild(t1);
+  	_this = this;
+  	for( i = 0; i < 10; i++) {
+  		var _tr = document.createElement("TR");
+		tb1.appendChild(_tr);		
+  		for( j = 0; j < 7; j++) {
+			var _td = document.createElement("TD");
+  			_td.style.background =  this.colors[j][i];
+	  		_td.unselectable = "on";
+  			_td.style.width = "15px";
+  			_td.style.height = "15px";
+  			_td.title =   this.colors[j][i];
+  			_td.id =   this.colors[j][i];
+  			_td.className = "unsel_color";
+	  		_td.onclick= function(){ document.getElementById("palettecolor").style.visibility="hidden";ColorPalette.changeFontColor(this.id);};
+	  		_td.onmouseover = function(){ this.className = "sel_color";};
+	  		_td.onmouseout = function(){ this.className = "unsel_color";}
+			var p = new Image();
+  			p.style.width='1px';
+  			p.style.height='1px';
+			_td.appendChild(p);
+	  		_tr.appendChild(_td);
+  		}
+	}
+}
+
+/* Build the Object */
+var ColorPalette = new cColorPalette();
Index: tags/expressoMail1_2/1.2211/js/QuickCatalogSearch.js
===================================================================
--- tags/expressoMail1_2/1.2211/js/QuickCatalogSearch.js	(revision 271)
+++ tags/expressoMail1_2/1.2211/js/QuickCatalogSearch.js	(revision 271)
@@ -0,0 +1,496 @@
+	function emQuickCatalogSearch ()
+	{
+		this.arrayWin = new Array();
+		this.el;
+		this.cc_contacts = new Array();
+		this.cc_groups  = new Array();
+	}
+
+	emQuickCatalogSearch.prototype.showList = function(data, begin, end){
+		id = '1';
+		_this = this;
+
+		var el = document.createElement("DIV");
+		el.style.visibility = "hidden";
+		el.style.position = "absolute";
+		el.style.left = "0px";
+		el.style.top = "0px";
+		el.style.width = "0px";
+		el.style.height = "0px";
+		el.id = 'window_QuickCatalogSearch';
+		document.body.appendChild(el);
+		el.innerHTML = "";
+		
+		if (document.getElementById('select_QuickCatalogSearch') == null){
+
+			var title_innerHTML = get_lang('Select a name') + ':';
+			if (data.quickSearch_only_in_userSector)
+				title_innerHTML += "<font color='BLACK' nowrap> ("+get_lang('Showing only the results found in your organization')+".)</font>"
+
+			var title = document.createElement("SPAM");
+			title.id = 'window_QuickCatalogSearch_title';
+			title.innerHTML = "&nbsp;&nbsp;<b><font color='BLUE' nowrap>"+title_innerHTML+"</font></b><br>&nbsp;&nbsp;";
+			el.appendChild(title);
+			
+			var cmb = document.createElement("SELECT");
+			cmb.id = "select_QuickCatalogSearch";
+			cmb.style.width = "585px";
+			cmb.size = "12";
+			cmb.onkeypress = function (e)
+			{
+				if (is_ie)
+				{
+					if ((window.event.keyCode) == 13)
+					{
+						QuickCatalogSearch.transfer_result(data.field, data.ID, begin, end);
+					}
+					else if ((window.event.keyCode) == 27)
+					{
+						QuickCatalogSearch.close_QuickSearch_window(data.field, data.ID);
+					}
+				}
+				else
+				{
+					if ((e.keyCode) == 13)
+					{
+						QuickCatalogSearch.transfer_result(data.field, data.ID, begin, end);
+					}
+					else if ((e.keyCode) == 27)
+					{
+						QuickCatalogSearch.close_QuickSearch_window(data.field, data.ID);
+					}
+				}
+			};
+			el.appendChild(cmb);
+
+			var space = document.createElement('SPAN');
+			space.innerHTML = "<BR>&nbsp;&nbsp;";
+			el.appendChild(space);
+
+			var butt = document.createElement('BUTTON');
+			var buttext = document.createTextNode('OK');
+			butt.id = "QuickCatalogSearch_button_ok";
+			butt.appendChild(buttext);
+			butt.onclick = function () {QuickCatalogSearch.transfer_result(data.field, data.ID, begin, end);};
+			el.appendChild(butt);
+
+			var space = document.createElement('SPAN');
+			space.innerHTML = "&nbsp;&nbsp;";
+			el.appendChild(space);
+
+			var butt = document.createElement('BUTTON');
+			butt.id = "QuickCatalogSearch_button_close";
+			var buttext = document.createTextNode(get_lang('Close'));
+			butt.appendChild(buttext);
+			butt.onclick = function () {QuickCatalogSearch.close_QuickSearch_window(data.field, data.ID);};
+			el.appendChild(butt);
+		}
+		else{
+			var title_innerHTML = get_lang('Select a name') + ':';
+			if (data.quickSearch_only_in_userSector)
+				title_innerHTML += "<font color='BLACK' nowrap> ("+get_lang('Showing only the results found in your organization')+".)</font>"
+
+			var title = Element('window_QuickCatalogSearch_title');
+			title.innerHTML = "&nbsp;&nbsp;<b><font color='BLUE' nowrap>"+title_innerHTML+"</font></b><br>&nbsp;&nbsp;";
+			
+			var cmb = document.getElementById('select_QuickCatalogSearch');
+			cmb.onkeypress = function (e)
+			{
+				if (is_ie)
+				{
+					if ((window.event.keyCode) == 13)
+					{
+						QuickCatalogSearch.transfer_result(data.field, data.ID, begin, end);
+					}
+					else if ((window.event.keyCode) == 27)
+					{
+						QuickCatalogSearch.close_QuickSearch_window(data.field, data.ID);
+					}
+				}
+				else
+				{
+					if ((e.keyCode) == 13)
+					{
+						QuickCatalogSearch.transfer_result(data.field, data.ID, begin, end);
+					}
+					else if ((e.keyCode) == 27)
+					{
+						QuickCatalogSearch.close_QuickSearch_window(data.field, data.ID);
+					}
+				}
+			};
+
+			for (i=0; i<cmb.length; i++)
+				cmb.options[i--] = null;
+			
+			var butt_ok = document.getElementById("QuickCatalogSearch_button_ok");
+			var butt_close = document.getElementById("QuickCatalogSearch_button_close");
+			butt_ok.onclick = function () {QuickCatalogSearch.transfer_result(data.field, data.ID, begin, end);};
+			butt_close.onclick = function () {QuickCatalogSearch.close_QuickSearch_window(data.field, data.ID);};
+		}
+
+		for (i=0; i<data.length; i++){
+			var Op = document.createElement("OPTION");
+			Op.text = data[i].cn + ' (' + data[i].mail + ')';
+			if (data[i].phone != '')
+				Op.text += ' (tel: ' + data[i].phone + ')';
+			Op.value = '"' + data[i].cn + '" ' + '<' + data[i].mail + '>';
+			cmb.options.add(Op);
+		}
+		cmb.options[0].selected = true;
+		_this.showWindow(el);
+	}
+	
+	emQuickCatalogSearch.prototype.showWindow = function (div)
+	{
+		if(! div) {
+			alert(get_lang('The list has no participant.'));
+			return;
+		}
+							
+		if(! this.arrayWin[div.id]) {
+			div.style.width = "600px";
+			div.style.height = "230px";
+			var title = get_lang('The results were found in the Global Catalog')+':';
+			var wHeight = div.offsetHeight + "px";
+			var wWidth =  div.offsetWidth   + "px";
+			div.style.width = div.offsetWidth - 5;
+
+			win = new dJSWin({			
+				id: 'QuickCatalogSearch_'+div.id,
+				content_id: div.id,
+				width: wWidth,
+				height: wHeight,
+				title_color: '#3978d6',
+				bg_color: '#eee',
+				title: title,						
+				title_text_color: 'white',
+				button_x_img: '../phpgwapi/images/winclose.gif',
+				border: true });
+			
+			this.arrayWin[div.id] = win;
+			win.draw();
+		}
+		else {
+			win = this.arrayWin[div.id];
+		}
+		//document.getElementById('QuickCatalogSearch_window_QuickCatalogSearch').style.display = "";
+		win.open();
+		document.getElementById('select_QuickCatalogSearch').focus();
+	}
+	
+	emQuickCatalogSearch.prototype.transfer_result = function (field, ID, begin, end){
+		cm = document.getElementById('select_QuickCatalogSearch');
+		option_selected = cm.options[cm.selectedIndex].value + ", ";
+		emailList = document.getElementById(field + "_" + ID).value;
+		
+		new_emailList = emailList.substring(0, begin) + option_selected + emailList.substring((parseInt(end) + 2), emailList.length);
+		document.getElementById(field + "_" + ID).value = new_emailList;
+		document.getElementById(field + "_" + ID).focus();
+		
+		//document.getElementById('QuickCatalogSearch_window_QuickCatalogSearch').style.display = "none";
+		this.arrayWin['window_QuickCatalogSearch'].close();
+	}
+	
+	emQuickCatalogSearch.prototype.close_QuickSearch_window = function (field, ID){
+		//document.getElementById('QuickCatalogSearch_window_QuickCatalogSearch').style.display = "none";
+		document.getElementById(field + "_" + ID).focus();
+		this.arrayWin['window_QuickCatalogSearch'].close();
+	}
+
+	emQuickCatalogSearch.prototype.close_window = function(id) {
+		this.arrayWin[id].close();
+		var group_values = Element('list_values');
+		var user_values = Element('user_values');	
+	}
+	emQuickCatalogSearch.prototype.showCatalogList = function (border_id){
+		var el = Element('catalog_list');
+
+		if(el) {
+			Element('border_id').value = border_id;
+			win = this.arrayWin[el.id];
+			win.open();
+			return;		
+		}
+		var border_input   = document.createElement("INPUT");
+		border_input.type  = 'hidden';
+		border_input.id    = 'border_id';
+		border_input.value = border_id;
+		document.body.appendChild(border_input);
+		el = document.createElement("DIV");		
+		el.id = 'catalog_list';
+		document.body.appendChild(el);			
+		el.style.visibility = "hidden";
+		el.style.position = "absolute";
+		el.style.width = "495px";
+		el.style.height = is_ie ? "360px" : "375px";		
+		el.style.left = "0px";
+		el.style.top = "0px";			
+		el.innerHTML = "<table border='0' cellpading='0' cellspacing='0' width='100%'>"+
+					   "<tr><td id='td1' style='cursor:pointer' align='center' onclick='QuickCatalogSearch.select_div(\"tab1\")'><a href='#' class='catalog' onclick='QuickCatalogSearch.select_div(\"tab1\");'>"+get_lang('Global Catalog')+"</a></td>"+
+					   "<td id='td2' style='background:#cecece;cursor:pointer' onclick='QuickCatalogSearch.select_div(\"tab2\")' align='center'><a href='#' class='catalog' onclick='QuickCatalogSearch.select_div(\"tab2\");'>"+get_lang('Personal Catalog')+"</a></td></tr>"+
+					   '</table>'+
+					   '<div id="tab1" align="center"><br>'+
+					   '<table border="0" cellpading="0" cellspacing="0">'+
+					   '<tr><td>'+get_lang("Select an organization and click on button <b>Search</b>")+'&nbsp;:</td></tr>'+
+					   '<tr><td><select id="select_organization" name="select_organization"></select>&nbsp;'+
+  					   '<input type="text" id="search_for" name="search_for" value="" size="17" maxlength="20"/>&nbsp;<input type="button" onclick="QuickCatalogSearch.searchCatalogList(true)" class="button" value="'+get_lang('Search')+'">&nbsp;<input type="button" onclick="QuickCatalogSearch.searchCatalogList(false)" class="button" value="'+get_lang('List All')+'"></td></tr>'+
+					   '<tr><td><input onclick="javascript:QuickCatalogSearch.changeOptions(this.value)" id="type" type="radio" name="type" value="l"/>'+get_lang('Public Lists')+'&nbsp;&nbsp;<input type="radio" name="type" value="u" onclick="javascript:QuickCatalogSearch.changeOptions(this.value)" checked/>'+get_lang('Users')+'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+
+					   '<span style="visibility:hidden;background:#cc4444" id=msg_search>&nbsp;&nbsp;<font face="Verdana" size="1" color="WHITE">'+get_lang('Search in Catalog')+'...</font>&nbsp;</span></td></tr>'+
+					   '<tr><td>'+
+				  	   '<span id="list_span"><select multiple style="display:none;width:400px" size="14" id="list_values"></select></span>'+
+				  	   '<span id="user_span"><select multiple style="width:400px" size="14" id="user_values"></select></span>'+
+				 	   '</td></tr>'+
+					   '<tr><td nowrap><center>'+get_lang('Click here to add into the fields')+':&nbsp;<input type="button" class="button" value="'+get_lang('TO')+'" onClick="javascript:QuickCatalogSearch.addContacts(\'to\')">&nbsp;'+
+				  	   '<input type="button" class="button" value="'+get_lang('CC')+'" onClick="javascript:QuickCatalogSearch.addContacts(\'cc\')">&nbsp;'+
+				   	   '<input type="button" class="button" value="'+get_lang('CCo')+'" onClick="javascript:QuickCatalogSearch.addContacts(\'cco\')">'+
+				  	   '</center></td></tr><tr><td nowrap><center><input type="button" value="'+get_lang('Close')+'" onClick="javascript:QuickCatalogSearch.close_window(\'catalog_list\')"></center></td></tr>'+
+					   '</table>'+
+					   '</div>'+
+					   '<div style="display:none" id="tab2" align="center">'+
+					   '<br><br><br>'+
+					   '<table border="0" cellpading="0" cellspacing="0">'+
+					   '<tr><td>'+get_lang("Select the type of contact that you want to view")+'&nbsp;:</td></tr>'+
+					   '<tr><td><input onclick="javascript:QuickCatalogSearch.changeOptions(this.value)" id="type" type="radio" name="type" value="p"/>' + get_lang('People') + '&nbsp;&nbsp;<input type="radio" name="type" value="g" onclick="javascript:QuickCatalogSearch.changeOptions(this.value)"/>' + get_lang('Groups') + ' &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+
+					   '<tr><td>'+
+				  	   '<span id="personal_span"><select multiple style="width:400px" size="14" id="list_personal"></select></span>'+
+				  	   '<span id="groups_span"><select multiple style="display:none;width:400px" size="14" id="list_groups"></select></span>'+
+				 	   '</td></tr>'+
+					   '<tr><td nowrap><center>'+get_lang('Click here to add into the fields')+':&nbsp;<input type="button" class="button" value="'+get_lang('TO')+'" onClick="javascript:QuickCatalogSearch.addContacts(\'to1\')">&nbsp;'+
+				  	   '<input type="button" class="button" value="'+get_lang('CC')+'" onClick="javascript:QuickCatalogSearch.addContacts(\'cc1\')">&nbsp;'+
+				   	   '<input type="button" class="button" value="'+get_lang('CCo')+'" onClick="javascript:QuickCatalogSearch.addContacts(\'cco1\')">'+
+				  	   '</center></td></tr><tr><td nowrap><center><input type="button" value="'+get_lang('Close')+'" onClick="javascript:QuickCatalogSearch.close_window(\'catalog_list\')"></center></td></tr>'+
+					   '</table>'+
+					   '</div>';
+
+		var title = get_lang('Search in the Global Catalog');
+		var wHeight = el.offsetHeight - (is_ie ? 10 : 0) + "px";
+		var wWidth =  el.offsetWidth   + "px";
+		el.style.width = el.offsetWidth;
+		
+		Element('search_for').onkeypress = function (e) {
+			if ((is_ie && (window.event.keyCode == 13)) || (!is_ie && e.keyCode == 13)) {
+				QuickCatalogSearch.searchCatalogList(true);
+			}
+		};
+
+		win = new dJSWin({			
+			id: 'win_'+el.id,
+			content_id: el.id,
+			width: wWidth,
+			height: wHeight,
+			title_color: '#3978d6',
+			bg_color: '#eee',
+			title: title,						
+			title_text_color: 'white',
+			button_x_img: '../phpgwapi/images/winclose.gif',
+			border: true });
+			
+		this.arrayWin[el.id] = win;		
+		win.draw();
+		win.open();
+
+		var handler_organizations = function(data){
+			var user_organization = Element('user_organization').value;
+
+			for(i = 0; i < data.length; i++) {
+				Element('select_organization').options[i] = new Option(data[i],data[i]);
+				if(user_organization.toUpperCase() == data[i].toUpperCase())
+					Element('select_organization').options[i].selected = true;
+			}
+		}
+		cExecute ("$this.ldap_functions.get_organizations&referral=true", handler_organizations);
+		
+		var handler_cc_contacts= function(data){
+			if(data && data.length > 0){
+				var aux = data.split(",");
+				for(var i=0; i< aux.length; i++){
+					QuickCatalogSearch.cc_contacts[QuickCatalogSearch.cc_contacts.length] = aux[i];				
+				}
+			}
+		}
+		cExecute("$this.db_functions.get_cc_contacts",handler_cc_contacts);
+
+		var handler_cc_groups = function(data){
+			if(data && data.length > 0){
+				var aux = data.split(",");
+				for(var i=0; i < data.length; i++){
+					QuickCatalogSearch.cc_groups[QuickCatalogSearch.cc_groups.length] = aux[i];								
+				}	
+			}
+		}
+		cExecute("$this.db_functions.get_cc_groups",handler_cc_groups);
+	
+	}
+	
+	emQuickCatalogSearch.prototype.select_div = function(element){
+		if(element == 'tab1'){
+		   Element('tab1').style.display = '';
+		   Element('tab2').style.display = 'none';
+		   Element('td1').style.background = '#eee';	
+		   Element('td2').style.background = '#cecece';
+		}
+		if(element == 'tab2'){
+		   Element('tab1').style.display = 'none';
+		   Element('tab2').style.display = '';
+		   Element('td1').style.background = '#cecece';
+		   Element('td2').style.background = '#eee';		   
+
+		}
+	}
+	
+	emQuickCatalogSearch.prototype.load_catalog = function(){
+	
+		var _this = this;
+		var content = new Array;
+		var select = Element('list_personal').style.display == 'none'? Element('list_groups'): Element('list_personal');
+		
+		if(Element('list_personal').style.display == 'none'){
+			content = _this.cc_groups;
+		}else{
+			content = _this.cc_contacts;
+		}
+		if(select.options.length > 0){
+			for(var i=0; i < select.options.length; i++){
+				select.options[i] = null;
+				i--;
+			}
+		}
+		for(var i=0; i < content.length; i++){
+			if(content[i] != undefined){
+				var aux = content[i].split(";");
+				var opt = new Option(aux[0] + ' (' + aux[1] + ')','"' + aux[0] + '" ' + '<' + aux[1] + '>',false,false);
+				select[select.length] = opt;
+			}
+		}
+		content.splice(0,(content.lenght));
+	}
+
+	emQuickCatalogSearch.prototype.changeOptions = function(type){	
+
+		switch(type){
+			case 'u':
+				Element('list_values').style.display = 'none';
+				Element('user_values').style.display = '';
+				break;
+			
+			case 'l':		
+				Element('user_values').style.display = 'none';
+				Element('list_values').style.display = '';		
+				break;
+
+			case 'p':
+				Element('list_personal').style.display = '';
+				Element('list_groups').style.display = 'none'
+				QuickCatalogSearch.load_catalog();				
+				break;
+			
+			case 'g':
+				Element('list_personal').style.display = 'none';
+				Element('list_groups').style.display = ''
+				QuickCatalogSearch.load_catalog();
+				break;
+		}
+
+	}
+
+	emQuickCatalogSearch.prototype.addContacts = function(field) {
+		
+		var border_id 	= Element('border_id').value;
+ 		var select		= Element('user_values').style.display == 'none' ? Element('list_values') : Element('user_values');
+		if(field == "to1" || field == "cc1" || field == "cco1"){
+			field = field.substr(0,field.length - 1);
+			var select = Element('list_personal').style.display == 'none' ? Element('list_groups') : Element('list_personal');
+		}
+		var fieldOpener = Element(field+"_"+border_id);
+		var not_selected = true;		
+		for (i = 0 ; i < select.length ; i++) {			
+			if (select.options[i].selected && select.options[i].value != '-1') {
+				if(fieldOpener.value.length > 0 && (fieldOpener.value.lastIndexOf(',') != (fieldOpener.value.length -1))){
+					fieldOpener.value += ",";
+				}
+				fieldOpener.value += select.options[i].value + ",";
+				not_selected = false;
+				select.options[i].selected = false;
+			}
+		}
+		
+		if(not_selected)
+			return false;
+			
+		if(field != 'to'){
+ 			a_link = Element("a_"+field+"_link_"+border_id);
+ 			if(a_link)
+ 				a_link.onclick(); 			
+ 		}				
+	}
+	
+	emQuickCatalogSearch.prototype.searchCatalogList = function (itemSearch){
+
+		if(itemSearch && Element('search_for').value.length == 0){
+			alert(get_lang('No data to search'));
+			Element('search_for').focus();
+			return false;
+		}
+		var organization = Element('select_organization').value;		
+		var search		 = itemSearch ? Element('search_for').value : '';
+		var max_result 	 = 2000;
+
+		var handler_searchResults = function(data){
+
+			Element('msg_search').style.visibility = 'hidden';
+			if(data.error){
+				alert(get_lang('More than %1 results. Please, try to refine your search.',max_result));
+				return false;
+			}
+			
+			var group = Element('list_span');
+			var user  = Element('user_span');	
+			if(is_ie){
+				group.innerHTML = '';
+				user.innerHTML = '';
+			}
+			else {
+				group = Element('list_values');
+				user  = Element('user_values');	
+				for(var i = 0;i < group.options.length; i++)				
+					group.options[i--] = null;
+				for(var i = 0;i < user.options.length; i++)				
+					user.options[i--] = null;
+			}
+
+			var arr 	= new Array(max_result);
+			var display	= Element('type').value == 'l'? 'display:none;' : '';
+
+			for(i = 0; data.groups && i < data.groups.length; i++) {			
+				if(is_ie)
+					arr[i] = '<option value="'+'&quot;'+data.groups[i].name+'&quot; &lt;'+data.groups[i].email+'&gt;">'+data.groups[i].name+' ('+data.groups[i].email+')'+'</option>';
+				else
+					group.options[i] = new Option(data.groups[i].name+' ('+data.groups[i].email+')','"'+data.groups[i].name+'" <'+data.groups[i].email+'>');
+			}
+	
+			if(is_ie)
+				group.innerHTML = '<select multiple style="'+display+'width:400px" size="14" id="list_values">'+ arr.join() +'</select>';
+
+			arr = new Array(max_result);
+			display = display ? "" : "display:none;";
+			
+			for(i = 0; data.users && i < data.users.length; i++) {			
+				if(is_ie)
+					arr[i] = '<option value="'+'&quot;'+data.users[i].name+'&quot; &lt;'+data.users[i].email+'&gt;">'+data.users[i].name+' ('+data.users[i].email+')'+'</option>';
+				else
+					user.options[i] = new Option(data.users[i].name+' ('+data.users[i].email+')','"'+data.users[i].name+'" <'+data.users[i].email+'>');
+			}
+	
+			if(is_ie)
+				user.innerHTML = '<select multiple style="'+display+'width:400px" size="14" id="user_values">'+ arr.join() +'</select>';
+		}
+
+		Element('msg_search').style.visibility = 'visible';
+		cExecute ("$this.ldap_functions.catalogsearch&max_result="+max_result+"&organization="+organization+"&search_for="+search, handler_searchResults);
+	}
+
+	
+/* Build the Object */
+	var QuickCatalogSearch;
+	QuickCatalogSearch = new emQuickCatalogSearch();
Index: tags/expressoMail1_2/1.2211/js/rich_text_editor.js
===================================================================
--- tags/expressoMail1_2/1.2211/js/rich_text_editor.js	(revision 279)
+++ tags/expressoMail1_2/1.2211/js/rich_text_editor.js	(revision 279)
@@ -0,0 +1,473 @@
+var newMessageTab = {
+		'imapUid' : [], // Stores the imap email number of current tab
+		'countFile' : [0,0,0,0,0,0,0,0,0,0], // Stores the number of files attached in current tab
+		'imapBox' : [], // Stores the folder name
+		'toPreserve' : [] // Check if the message should be removed from draft after send
+		};
+
+function cRichTextEditor(){
+	this.emwindow   = new Array;
+	this.editor;
+	this.table;
+	this.id;
+	this.buildEditor();
+	this.saveFlag = 0;
+}
+
+cRichTextEditor.prototype.loadEditor = function(ID) {
+	this.id = ID;
+	parentDiv = document.getElementById("body_position_"+this.id);
+	this.editor = "body_"+this.id;
+	
+	if(this.table.parentNode)
+		this.table.parentNode.removeChild(this.table);	
+
+	if(parentDiv.firstChild){
+		parentDiv.insertBefore(this.table,parentDiv.firstChild);
+	}
+	else
+		parentDiv.appendChild(this.table);
+
+	if(!Element(this.editor)){
+		iframe = document.createElement("IFRAME");
+		iframe.id = this.editor;
+		iframe.name = this.editor;
+		iframe.width = "99%";
+		iframe.height = 300;
+		iframe.setAttribute("unselectable","on");
+		iframe.setAttribute("tabIndex","1");
+		var checkbox = document.createElement("INPUT");
+		checkbox.id = 'viewsource_rt_checkbox';
+		checkbox.type = "checkbox";
+		checkbox.setAttribute("tabIndex","-1");
+		checkbox.onclick = function () {RichTextEditor.viewsource(this.checked)};
+		var text = document.createTextNode(get_lang('View HTML source') + '.');
+		parentDiv.appendChild(iframe);
+		parentDiv.appendChild(checkbox);
+		parentDiv.appendChild(text);
+	}
+	else{
+		Element("viewsource_rt_checkbox").checked=false;
+	}
+
+	document.getElementById('fontname').selectedIndex = 1;
+	document.getElementById('fontsize').selectedIndex = 1;
+}
+
+cRichTextEditor.prototype.viewsource = function(source) {
+	var html;
+	var mainField = document.getElementById(this.editor).contentWindow;
+	if (source) {
+		if (is_ie){
+			connector.loadScript('html2xhtml');
+			html = frames[this.editor].document.body;
+			var xhtml = get_xhtml(html, 'en', 'iso-8859-1');
+			frames[this.editor].document.body.innerText = xhtml;
+			document.getElementById("table_richtext_toolbar").style.visibility="hidden";
+		}
+		else{
+			html = document.createTextNode(document.getElementById(this.editor).contentWindow.document.body.innerHTML);
+			document.getElementById(this.editor).contentWindow.document.body.innerHTML = "";
+			html = document.getElementById(this.editor).contentWindow.document.importNode(html,false);
+			document.getElementById(this.editor).contentWindow.document.body.appendChild(html);
+			document.getElementById("table_richtext_toolbar").style.visibility="hidden";
+		}		
+	} else {
+		if (is_ie){
+			var output = escape(frames[this.editor].document.body.innerText);
+			output = output.replace("%3CP%3E%0D%0A%3CHR%3E", "%3CHR%3E");
+			output = output.replace("%3CHR%3E%0D%0A%3C/P%3E", "%3CHR%3E");
+			frames[this.editor].document.body.innerHTML = unescape(output);
+			document.getElementById("table_richtext_toolbar").style.visibility="visible";  
+		}
+		else{
+			html = document.getElementById(this.editor).contentWindow.document.body.ownerDocument.createRange();
+			html.selectNodeContents(document.getElementById(this.editor).contentWindow.document.body);
+			document.getElementById(this.editor).contentWindow.document.body.innerHTML = html.toString();
+			document.getElementById("table_richtext_toolbar").style.visibility="visible";  
+		}
+	}
+}
+
+cRichTextEditor.prototype.buildEditor = function() {
+	this.table = document.createElement("TABLE");
+	this.table.id = "table_richtext_toolbar";
+	this.table.className = "richtext_toolbar";
+	this.table.width = "100%";
+	var tbody = document.createElement("TBODY");
+	var tr = document.createElement("TR");
+	var td = document.createElement("TD");
+	var div_button_rt = document.createElement("DIV");
+	
+	selectBox=document.createElement("SELECT");
+	selectBox.id="fontname";
+	selectBox.setAttribute("tabIndex","-1");
+	selectBox.onchange = function () {RichTextEditor.Select("fontname");};
+	selectBox.className = 'select_richtext';
+	var option1 = new Option(get_lang('Font'), 'Font');
+	var option2 = new Option('Arial', 'Arial');
+	var option3 = new Option('Courier', 'Courier');
+	var option4 = new Option('Times New Roman', 'Times');
+	if (is_ie){
+		selectBox.add(option1);
+		selectBox.add(option2);
+		selectBox.add(option3);
+		selectBox.add(option4);
+	}
+	else{
+		selectBox.add(option1, null);
+		selectBox.add(option2, null);
+		selectBox.add(option3, null);
+		selectBox.add(option4, null);
+	}
+	div_button_rt.appendChild(selectBox);
+
+	selectBox=document.createElement("SELECT");
+	selectBox.id="fontsize";
+	selectBox.setAttribute("tabIndex","-1");
+	selectBox.setAttribute("unselectable","on");
+	selectBox.className = 'select_richtext';
+	selectBox.onchange = function () {RichTextEditor.Select("fontsize");};
+	var option1 = new Option(get_lang('Size'), 'Size');
+	var option2 = new Option('1 (8 pt)','1' );
+	var option3 = new Option('2 (10 pt)','2');
+	var option4 = new Option('3 (12 pt)','3');
+	var option5 = new Option('4 (14 pt)','4');
+	var option6 = new Option('5 (18 pt)','5');
+	var option7 = new Option('6 (24 pt)','6');
+	var option8 = new Option('7 (36 pt)','7');
+	if (is_ie){
+		selectBox.add(option1);
+		selectBox.add(option2);
+		selectBox.add(option3);
+		selectBox.add(option4);
+		selectBox.add(option5);
+		selectBox.add(option6);
+		selectBox.add(option7);
+		selectBox.add(option8);
+	}
+	else{
+		selectBox.add(option1, null);
+		selectBox.add(option2, null);
+		selectBox.add(option3, null);
+		selectBox.add(option4, null);
+		selectBox.add(option5, null);
+		selectBox.add(option6, null);
+		selectBox.add(option7, null);
+		selectBox.add(option8, null);	
+	}
+	div_button_rt.appendChild(selectBox);
+	
+	var buttons = ['bold', 'italic', 'underline', 'forecolor', 'justifyleft', 'justifycenter', 'justifyright', 'justifyfull',
+				   'undo', 'redo', 'insertorderedlist', 'insertunorderedlist', 'outdent', 'indent', 'link', 'signature', 'image', 'table'];
+
+	for (var i=0; i<buttons.length; i++){
+		var img = document.createElement("IMG");
+		img.id = buttons[i];
+		img.className = 'imagebutton';
+		img.align = 'center';
+		img.src = './templates/default/images/'+buttons[i]+'.gif';
+		img.title = get_lang(buttons[i]);
+		img.style.cursor = 'pointer';
+
+		if (buttons[i] == 'forecolor')
+			img.onclick = function () {RichTextEditor.show_pc('forecolor')};
+		else if (buttons[i] == 'link')
+			img.onclick = function () {RichTextEditor.createLink();};
+		else if (buttons[i] == 'image')
+			img.onclick = function () {RichTextEditor.createImage();};
+		else if (buttons[i] == 'table')
+			img.onclick = function () {RichTextEditor.createTable();};
+		else
+			img.onclick = function () {RichTextEditor.editorCommand(this.id,'');};
+		
+		img.onmouseover = function () {this.style.border="outset 2px";};
+		img.onmouseout = function () {this.style.border="solid 2px #C0C0C0";};
+		div_button_rt.appendChild(img);
+	}
+
+	td.appendChild(div_button_rt);
+	tr.appendChild(td);
+	tbody.appendChild(tr);
+	this.table.appendChild(tbody);
+}
+
+cRichTextEditor.prototype.editorCommand = function(command, option) {
+	try {
+		var mainField = document.getElementById(this.editor).contentWindow;
+		mainField.focus();
+		if (command == 'signature'){
+			if (is_ie){
+				var sel = document.selection;
+				if (sel!=null)
+				{
+				    var rng = sel.createRange();
+				    if (rng!=null)
+			        rng.pasteHTML(preferences.signature.replace(/\n/g, "<br>"));
+				}
+			}
+			else{
+				mainField.document.execCommand('inserthtml', false, preferences.signature.replace(/\n/g, "<br>"));
+			}
+		}
+		else if (command == 'CreateLink')
+			mainField.document.execCommand('CreateLink', false, option);
+		else if (command == 'Table'){
+			if (is_ie){
+				var sel = document.selection;
+				if (sel!=null)
+				{
+				    var rng = sel.createRange();
+				    if (rng!=null)
+			        rng.pasteHTML(option);
+				}
+			}
+			else 
+				mainField.document.execCommand('inserthtml', false, option);
+			}
+		else if (command == 'Image')
+			mainField.document.execCommand('InsertImage', false, option);
+		else
+			mainField.document.execCommand(command, false, option);
+		//mainField.focus();
+    } catch (e) { alert(e.description); }
+}
+
+cRichTextEditor.prototype.createLink = function(){
+	var mainField = document.getElementById(this.editor).contentWindow;
+	if (is_ie){
+		if ((mainField.document.selection.createRange().text) == ''){
+				alert(get_lang('Chose the text you want transform in link before.')); 
+			return;
+		}
+	}
+	else{
+		if (mainField.window.getSelection() == ''){
+				alert(get_lang('Chose the text you want transform in link before.')); 
+			return;
+		}
+	}
+		var szURL = prompt(get_lang('Enter with link URL:'), 'http://'); 
+	if ((szURL != null) && (szURL != "")){
+		this.editorCommand("CreateLink", szURL);
+	}
+}
+
+// It include the image file in emails body
+// It saves and attach in drafts folder and open it
+cRichTextEditor.prototype.addInputFile = function()
+{
+	var id = this.editor.substr(5); // border_id
+	divFiles = document.getElementById("divFiles_"+id);
+	var countDivFiles = divFiles.childNodes.length + 1;
+
+	var inputFile = document.getElementById('inputFile_img');
+	var divFiles = document.getElementById('divFiles_'+id);
+	inputFile.id = 'inputFile_'+id +"_"+countDivFiles;
+	inputFile.name = 'file_'+countDivFiles;
+	divFile = document.createElement('DIV');
+	divFile.appendChild(inputFile);
+	divFiles.appendChild(divFile);
+
+	var form_upload = document.getElementById('form_upload');
+	form_upload.parentNode.removeChild(form_upload);
+	win.close();
+	
+	if (! validateFileExtension(inputFile.value, inputFile.id , id))
+	return false;
+
+	RichTextEditor.saveFlag = 0; // See if save function finished
+	save_msg(id);
+	setTimeout("RichTextEditor.insertImgHtml("+id+")",1000);
+}
+
+cRichTextEditor.prototype.insertImgHtml = function (id){
+	if (RichTextEditor.saveFlag == 0)
+		setTimeout("RichTextEditor.insertImgHtml("+id+")",500);
+	else
+			this.editorCommand('Image', './inc/show_embedded_attach.php?msg_folder=INBOX/'+draftsfolder+'&msg_num='+newMessageTab.imapUid[id]+'&msg_part='+(newMessageTab.countFile[id]+1));
+			// this.editorCommand('Image', '.inc/gotodownload.php?msg_folder="+msg_folder+"&msg_number="+msg_number+"&idx_file="+idx_file+"&msg_part="+msg_part+params'));
+}
+
+cRichTextEditor.prototype.insertTableHtml = function (){
+	var id = this.editor.substr(5); // border_id
+	var	rows = document.getElementById('rows').selectedIndex;
+	var	cols = document.getElementById('cols').selectedIndex;
+	var insertTable = '<table border="1px"><tbody>';
+	for (var i = 0; i <= rows; i++){
+		insertTable += "<tr>";	
+		for (var j = 0; j <= cols; j++)
+			insertTable += "<td>&nbsp;</td>";	
+		insertTable += "</tr>";
+	}
+	insertTable += "</tbody></table>";
+	this.editorCommand('Table', insertTable);
+}
+
+cRichTextEditor.prototype.createTable = function(){
+	var form = document.getElementById("table_window");
+	if (form == null){
+		form = document.createElement("DIV");
+		form.id  = "table_window";
+		form.style.visibility = "hidden";
+		form.style.position = "absolute";
+		form.style.background = "#eeeeee";
+		form.style.left = "0px";
+		form.style.top  = "0px"; 
+		form.style.width = "0px";
+		form.style.height = "0px";
+		document.body.appendChild(form);
+	}
+		
+		var form_table = document.createElement("DIV");
+		form_table.id = "form_table";
+		form_table.style.position = "absolute";
+		form_table.style.top = "5px";
+		form_table.style.left = "5px";
+		form_table.style.width = "170px";
+		form_table.style.height = "120px";
+		form_table.name = get_lang("Insert Table");
+		form_table.innerHTML = get_lang('Select the table size')+':<br><br>'+
+								get_lang('Rows')+':&nbsp;&nbsp;&nbsp;'+	get_lang('Cols')+':<br>'+
+									'<select name="rows" id="rows"><option value="1">1</option>'+
+									'<option value="2">2</option>'+
+									'<option value="3">3</option>'+
+									'<option value="4">4</option>'+
+									'<option value="5">5</option>'+
+									'<option value="6">6</option>'+
+									'<option value="7">7</option>'+
+									'<option value="8">8</option>'+
+									'<option value="9">9</option></select>&nbsp;&nbsp;&nbsp;'+
+									'<select name="cols" id="cols"><option value="1">1</option>'+
+									'<option value="2">2</option>'+
+									'<option value="3">3</option>'+
+									'<option value="4">4</option>'+
+									'<option value="5">5</option>'+
+									'<option value="6">6</option>'+
+									'<option value="7">7</option>'+
+									'<option value="8">8</option>'+
+									'<option value="9">9</option></select><br><br>'+
+  								'<input title="Close"  value="' + get_lang('Close') + '" type="button" onclick="win.close()">&nbsp;'+
+								'<input title="Include"  value="' + get_lang('Include') + '" type="button" onclick="RichTextEditor.insertTableHtml();win.close();">';
+		form.appendChild(form_table);
+		
+		this.showWindow(form);
+		}
+
+cRichTextEditor.prototype.createImage = function(){
+	var form = document.getElementById("attachment_window");
+	if (form == null){
+		form = document.createElement("DIV");
+		form.id  = "attachment_window";
+		form.style.visibility = "hidden";
+		form.style.position = "absolute";
+		form.style.background = "#eeeeee";
+		form.style.left = "0px";
+		form.style.top  = "0px"; 
+		form.style.width = "0px";
+		form.style.height = "0px";
+		document.body.appendChild(form);
+	}
+		
+		var form_upload = document.createElement("DIV");
+		form_upload.id = "form_upload";
+		form_upload.style.position = "absolute";
+		form_upload.style.top = "5px";
+		form_upload.style.left = "5px";
+		form_upload.name = get_lang("Upload File");
+		form_upload.style.width = "450px";
+		form_upload.style.height = "75px";
+		form_upload.innerHTML = get_lang('Select the desired image file')+':<br>'+
+								'<input name="image_at" maxlength="255" size="50" id="inputFile_img" type="file"><br>' +
+								'<input title="Include"  value="' + get_lang('Include') + '"' + 'type="button" onclick="RichTextEditor.addInputFile();">&nbsp;' +
+								'<input title="Close"  value="' + get_lang('Close') + '"' +
+								' type="button" onclick="win.close()">';
+		form.appendChild(form_upload);
+		
+		this.showWindow(form);
+}
+cRichTextEditor.prototype.showWindow = function (div){
+
+		if(! div) {
+			return;
+		}
+		
+		if(! this.emwindow[div.id]) {
+			div.style.width  =  div.firstChild.style.width;
+			div.style.height = div.firstChild.style.height;
+			div.style.zIndex = "10000";			
+			var title = div.firstChild.name;
+			var wHeight = div.offsetHeight + "px";
+			var wWidth =  div.offsetWidth   + "px";
+			div.style.width = div.offsetWidth - 5;
+
+			win = new dJSWin({
+				id: 'win_'+div.id,
+				content_id: div.id,
+				width: wWidth,
+				height: wHeight,
+				title_color: '#3978d6',
+				bg_color: '#eee',
+				title: title,
+				title_text_color: 'white',
+				button_x_img: '../phpgwapi/images/winclose.gif',
+				border: true });
+			
+			this.emwindow[div.id] = win;
+			win.draw();
+		}
+		else
+			win = this.emwindow[div.id];
+		win.open();	
+}
+
+cRichTextEditor.prototype.Select = function(selectname)
+{
+	var mainField = Element(this.editor).contentWindow;
+	var cursel = document.getElementById(selectname).selectedIndex;
+
+	if (cursel != 0) {
+		var selected = document.getElementById(selectname).options[cursel].value;
+		mainField.document.execCommand(selectname, false, selected);
+		document.getElementById(selectname).selectedIndex = cursel;
+	}
+	mainField.focus();
+}
+
+cRichTextEditor.prototype.show_pc = function(command)
+{
+	connector.loadScript("color_palette");
+	ColorPalette.loadPalette(this.id);
+  	if (ColorPalette.div.style.visibility != "visible")
+		ColorPalette.div.style.visibility="visible";
+	else
+		this.hide_pc();
+}
+
+cRichTextEditor.prototype.hide_pc = function()
+{
+	document.getElementById("palettecolor").style.visibility="hidden";
+}
+
+cRichTextEditor.prototype.getOffsetTop = function(elm) {
+  var mOffsetTop = elm.offsetTop;1
+  var mOffsetParent = elm.offsetParent;
+  while(mOffsetParent){
+    mOffsetTop += mOffsetParent.offsetTop;
+    mOffsetParent = mOffsetParent.offsetParent;
+  }
+  return mOffsetTop;
+}
+
+cRichTextEditor.prototype.getOffsetLeft = function(elm) {
+  var mOffsetLeft = elm.offsetLeft;
+  var mOffsetParent = elm.offsetParent;
+  while(mOffsetParent){
+    mOffsetLeft += mOffsetParent.offsetLeft;
+    mOffsetParent = mOffsetParent.offsetParent;
+  }
+  return mOffsetLeft;
+}
+
+//Build the Object
+RichTextEditor = new cRichTextEditor();
Index: tags/expressoMail1_2/1.2211/js/TreeShow.js
===================================================================
--- tags/expressoMail1_2/1.2211/js/TreeShow.js	(revision 197)
+++ tags/expressoMail1_2/1.2211/js/TreeShow.js	(revision 197)
@@ -0,0 +1,291 @@
+/**************************************************************************\
+ Início 
+\**************************************************************************/
+
+	function Tree_Box(){
+		
+		this.name_folder = "";
+		this.name_func   = "";
+		connector.loadScript("TreeS");
+	}
+	Tree_Box.prototype.update_folder = function(){
+
+		var handler_update_folders = function(data){
+			folders = data;
+			// update element dftree_folders_tree;
+			ttree.make_tree(data,"div_tree","folders_tree","ttree.get_folder(\"root\")",ttreeBox.name_folder,ttreeBox.name_folder,false);
+			
+			// update element dftree_tree_folders;
+			if(Element('content_folders')){Element('content_folders').innerHTML = "";}
+			draw_tree_folders(folders);
+			
+			// update element dftree_wfolders_tree;
+			if (Element('dftree_wfolders_tree')){
+				Element('dftree_wfolders_tree').innerHTML = '';
+				ttree.make_tree(data,"wfolders_content_tree","wfolders_tree","","","",false);	
+			}
+			ttree.FOLDER = ttreeBox.name_folder;
+			tree_folders.getNodeById(get_current_folder())._select();
+		}
+		cExecute ("$this.imap_functions.get_folders_list", handler_update_folders);		
+	}
+
+	Tree_Box.prototype.verify_children = function(param){
+		var aux;
+		var aux1;
+		var cont = parseInt(0);
+		for(var i=0 ; i < folders.length; i++){
+			aux = folders[i].folder_id.split(cyrus_delimiter);
+			aux.pop();
+			for(var j=0; j < aux.length; j++){
+				if(j == 0)
+					aux1 = aux[j];
+				else
+					aux1 += cyrus_delimiter + aux[j];
+			}
+			if( aux1 == param){
+				cont++;
+			}
+		}
+		if( cont == 0){
+			ttreeBox.del_past(param);
+		}else{
+                       alert(get_lang("Delete your sub-folders first"));
+		}
+		cont = parseInt(0);
+	}
+	
+	// Função para verificar ponto e espacos;
+	Tree_Box.prototype.verify = function(exp)
+ 	{
+		var reTipo = /^(.*)(\/)(.*)$/;
+		
+		if(reTipo.test(exp)){
+			return false;
+		}
+		return true;
+ 	}
+
+ 	// Função para verificar o nome da caixa;
+ 	Tree_Box.prototype.verify_names = function(name_folder){
+	    var arr_nm_folder = new Array("INBOX",trashfolder,draftsfolder,sentfolder,spamfolder);
+ 		for(var i=0 ; i < arr_nm_folder.length; i++){
+ 			if(name_folder == arr_nm_folder[i]){
+				ttree.FOLDER = "";
+				return true;
+ 			}
+ 		}
+		return false;
+ 	}
+	
+	// Valida os nomes das pastas
+	Tree_Box.prototype.validate = function(func){
+	
+		var aux = ttree.FOLDER.split(cyrus_delimiter);
+		var aux2;
+
+		if(ttree.FOLDER != ""){
+			if(aux.length > 1){aux2 = aux[1];}
+			else{aux2 = aux[0];}
+			if(this.verify_names(aux2)){
+				if(func == "newpast")
+                   alert(get_lang("It's not possible create inside: ") + (get_lang(special_folders[aux2])));
+				if(func == "rename")
+                   alert(get_lang("It's not possible rename the folder: ") + (get_lang(special_folders[aux2])));
+				return false;
+			}else{
+				if(func == "newpast"){
+                    var button = prompt(get_lang('Enter the name of the new folder:'),"");
+					if(trim(button) == "" || trim(button) == null){
+						return false;
+					}else{
+						ttreeBox.new_past(button);
+					}
+				}
+				if(func == "rename"){
+					if(ttree.FOLDER == "root"){
+	                	alert(get_lang("It's not possible rename this folder!"));
+						return false;
+					}
+					if(ttree.FOLDER == get_current_folder()){
+                        alert(get_lang("It's not possible rename this folder, because it is being used in the moment!"));
+						return false;
+					}
+                    var button1 = prompt(get_lang("Enter a name for the box"), "");
+					if(trim(button1) == "" || trim(button1) == null){
+						return false;
+					}else{
+						ttreeBox.rename(button1);
+					}
+				}
+			}
+		}else{
+            alert(get_lang("Select a folder!"));
+			return false;
+		}
+	}
+ 	
+ 	// Para criar a nova pasta;
+ 	Tree_Box.prototype.new_past = function(newp){
+
+	var aux   = ttree.FOLDER.split(cyrus_delimiter);
+	var newp2 = "";
+		
+		if(aux.length == 1 && aux[0] != "root"){
+            alert(get_lang("It's not possible create inside: ") + aux[0]);
+			newp = "";
+		}else{
+			if( aux[0] == "root"){
+				if(!this.verify(newp)){
+                    alert(get_lang("Type without spaces, dots or special characters!"));
+					newp = "";
+					return false;
+				}else{
+					newp2 = newp;
+					newp = "INBOX" + cyrus_delimiter + newp;
+				}
+			}else{
+				if(!this.verify(newp)){
+                    alert(get_lang("Type without spaces, dots or special characters!"));
+					newp = "";
+					return false;
+				}else{
+					newp2 = newp;
+					newp = ttree.FOLDER + cyrus_delimiter + newp;
+				}
+			}
+		}
+		if(newp != ""){
+			var handler_return = function(data){		
+				if(data != "Ok"){
+					alert(data);
+				}else{
+					ttreeBox.name_folder = newp;
+					this.name_func = "newpast";
+					ttreeBox.update_folder();
+				}
+			}
+			var args = "$this.imap_functions.create_mailbox";
+			var params = "newp="+newp;
+			cExecute(args,handler_return,params);
+		}	
+	}
+	
+	// Funcao para renomear a pasta;
+	Tree_Box.prototype.rename = function(rename){
+		var old_box  = ttree.FOLDER;
+		var aux = old_box.split(cyrus_delimiter);
+		var rename_new = "";
+		
+		if(old_box == "root"){
+            alert(get_lang("Select a folder!"));
+			return false;
+		}
+		if(aux.length == 1){
+            alert(get_lang("It's not possible rename the folder: ") + aux[0]);
+			rename = "";
+			return false;
+		}else{
+			if(this.verify_names(aux[1])){
+                alert(get_lang("It's not possible rename the folder: ") + aux[1]);
+				rename = "";
+				return false;
+			}else{
+				if(!this.verify(rename)){
+                    alert(get_lang("Type without spaces, dots or special characters!"));
+					rename = "";
+					return false;
+				}else{
+					aux.pop();
+					aux.push(rename);
+					for(var i=0; i< aux.length; i++){
+						if( i == 0)
+							rename_new = aux[i];
+						else
+							rename_new += cyrus_delimiter + aux[i];
+					}
+				}	
+			}
+		}
+		if(rename != ""){
+			var handler_return = function(data)
+			{		
+				ttree.FOLDER = "";
+				ttreeBox.update_folder();				
+			}
+			var args = "$this.imap_functions.ren_mailbox";
+			var params = "rename="+rename_new+"&current="+old_box;
+			cExecute(args,handler_return,params);
+		}
+	}
+	//
+	Tree_Box.prototype.export_all_msg = function(){
+			
+		if(ttree.FOLDER == "root"){return false;}
+		var nm_bx = ttree.FOLDER.split(cyrus_delimiter);
+		var name_f = nm_bx[nm_bx.length -1];
+		var hand_export = function(data){
+			if(!data){
+				write_msg(get_lang('Error compressing messages (ZIP). Contact the administrator.'))
+			}else
+			  download_attachments(null, null, data, null,null, name_f +'.zip');
+		}
+		cExecute("$this.exporteml.export_all",hand_export,"folder="+ttree.FOLDER);	
+		write_msg(get_lang('You must wait while the messages will be exported...'));			
+	}
+	
+	// Função para deletar a pasta;
+	Tree_Box.prototype.del = function(){
+	
+		var aux = ttree.FOLDER.split(cyrus_delimiter);
+
+		if(aux[0] == "root" || ttree.FOLDER == ""){
+                        alert(get_lang("Select a folder!"));
+			return false;
+		}
+		
+		if(aux.length == 1){
+            alert(get_lang("It's not possible delete the folder: ") + get_lang("Inbox"));
+			return false;
+		}else{
+			if(this.verify_names(aux[1])){
+	            alert(get_lang("It's not possible delete the folder: ") + get_lang(special_folders[aux[1]]));	 
+      			return false;
+			}else{
+				this.verify_children(ttree.FOLDER);
+			}
+		}	
+	}
+	
+	Tree_Box.prototype.del_past = function(param){
+
+		var aux = param.split(cyrus_delimiter);
+		var aux1 = aux.pop();
+
+		if(ttree.FOLDER == get_current_folder()){
+            alert(get_lang("It's not possible rename this folder, because it is being used in the moment!"));
+			return false;
+		}
+        if(confirm(get_lang("Do you wish to exclude the folder ") + aux1+ "?")){
+			var handler_return = function(data)
+			{		
+				if(data != "Ok")
+				{
+					alert(data);
+				}else{
+					ttree.FOLDER = "";
+					ttreeBox.update_folder();
+                    alert(get_lang("The folder %1 was successfully removed", aux1));
+				}
+			}
+			var args = "$this.imap_functions.delete_mailbox";
+			var params = "del_past="+param;
+			cExecute(args,handler_return,params);
+		}else{
+			alert(get_lang("The folder was not deleted!"));
+		}
+	
+	}
+/* - Build Object -*/
+ 	var ttreeBox;
+	ttreeBox = new Tree_Box();
Index: tags/expressoMail1_2/1.2211/js/QuickSearchUser.js
===================================================================
--- tags/expressoMail1_2/1.2211/js/QuickSearchUser.js	(revision 118)
+++ tags/expressoMail1_2/1.2211/js/QuickSearchUser.js	(revision 118)
@@ -0,0 +1,91 @@
+	function emQuickSearchUser ()
+	{
+		this.arrayWin = new Array();
+		this.el;
+		this.cc_contacts = new Array();
+		this.cc_groups  = new Array();
+	}
+
+	emQuickSearchUser.prototype.showList = function(data)
+	{
+		id = '1';
+		_this = this;
+
+		var el = document.createElement("DIV");
+		el.style.visibility = "hidden";
+		el.style.position = "absolute";
+		el.style.left = "0px";
+		el.style.top = "0px";
+		el.style.width = "0px";
+		el.style.height = "0px";
+		el.id = 'window_QuickSearchUser';
+		document.body.appendChild(el);
+		el.innerHTML = '<br>';
+		
+		if (document.getElementById('div_QuickSearchUser') == null)
+		{
+			el.innerHTML += '<div id="div_QuickSearchUser" class="quicksearchcontacts">' + 
+			'<table class="quicksearchcontacts"><tbody id="table_QuickSearchUser">' + data + '</tbody></table>' +
+			'</div>';
+			el.innerHTML += '&nbsp;&nbsp;<input type="button" value=' + get_lang("Close")+ ' id="QuickSearchUser_button_close" onClick="QuickSearchUser.close_window();">';
+		}
+		else{
+			var div_QuickSearchUser = document.getElementById('div_QuickSearchUser');
+			div_QuickSearchUser.style.display = "";
+			div_QuickSearchUser.innerHTML = '<table class="quicksearchcontacts"><tbody id="table_QuickSearchUser">' + data + '</tbody></table>';
+			var butt_close = document.getElementById("QuickSearchUser_button_close");
+			butt_close.onclick = function () {QuickSearchUser.close_window();};
+		}
+		_this.showWindow(el);
+	}
+
+	emQuickSearchUser.prototype.showWindow = function (div)
+	{
+		if(! div) {
+			alert(get_lang('The list has no participant.'));
+			return;
+		}
+							
+		if(! this.arrayWin[div.id]) {
+			div.style.width = "600px";
+			div.style.height = "350px";
+			var title = get_lang('The results were found in the Global Catalog')+':';
+			var wHeight = div.offsetHeight + "px";
+			var wWidth =  div.offsetWidth   + "px";
+			div.style.width = div.offsetWidth - 5;
+
+			win = new dJSWin({			
+				id: 'QuickSearchUser_'+div.id,
+				content_id: div.id,
+				width: wWidth,
+				height: wHeight,
+				title_color: '#3978d6',
+				bg_color: '#eee',
+				title: title,						
+				title_text_color: 'white',
+				button_x_img: '../phpgwapi/images/winclose.gif',
+				border: true });
+			
+			this.arrayWin[div.id] = win;
+			win.draw();
+		}
+		else {
+			win = this.arrayWin[div.id];
+		}
+		win.open();
+	}
+
+	emQuickSearchUser.prototype.close_window = function() {
+		Element("em_message_search").value = "";
+		this.arrayWin['window_QuickSearchUser'].close();
+	}
+	
+	emQuickSearchUser.prototype.create_new_message = function (cn, mail) {
+		_this.close_window();
+		Element("msg_number").value = cn+" <"+mail+">";
+		new_message("new","null");
+	}
+
+/* Build the Object */
+	var QuickSearchUser;
+	QuickSearchUser = new emQuickSearchUser();
Index: tags/expressoMail1_2/1.2211/js/preferences.js
===================================================================
--- tags/expressoMail1_2/1.2211/js/preferences.js	(revision 271)
+++ tags/expressoMail1_2/1.2211/js/preferences.js	(revision 271)
@@ -0,0 +1,258 @@
+/**************************************************************************\
+ Início 
+\**************************************************************************/
+	function Preferences(){
+		this.prefeW 		= new Array;
+	}
+	// Cria as divs;
+	Preferences.prototype.showList = function(){
+	
+		id = '1';
+		_this = this;
+		
+		form_pref = document.createElement("DIV");
+		form_pref.style.visibility = "hidden";
+		form_pref.style.position = "absolute";
+		form_pref.id = "window_confexp";
+		document.body.appendChild(form_pref);
+		prefe.showWindow(form_pref);
+		var form = Element("form_preferences");
+		
+		if(!form) {
+			form = document.createElement("FORM");
+			form.id  = "form_preferences";
+			form.innerHTML = 	"<table border='0' cellpading='0' cellspacing='0'>"+
+				"<tr><td colspan='2'><center>" + get_lang('Config for expressoMail') + "</center></td></tr>"+
+				"<tr><td nowrap> - " + get_lang('What is the maximum number of messages per page?') + "</td>"+
+				"<td>&nbsp;<select id='sel_num_max' name='sel_num_max'>"+
+				"<option value='25'>25</option>"+
+				"<option value='50'>50</option>"+
+				"<option value='75'>75</option>"+
+				"<option value='100'>100</option>"+														
+				"</select></td>"+
+				"</tr>"+
+				"<tr><td nowrap> - " + get_lang('Save deleted messages in trash folder?') + "</td>"+
+				"<td><input type='checkBox' id='check_save_men' name='check_save_men'></td>"+
+				"</tr>"+
+				"<tr><td nowrap> - " + get_lang('Delete trash messages after how many days?') + "</td>"+
+				"<td>&nbsp;<select id='sel_del_men' name='sel_del_men'>"+
+				"<option value='0'>" + get_lang('None') + "</option>"+
+				"<option value='1'>"+get_lang("1 day")+"</option>"+
+				"<option value='2'>"+get_lang("2 days")+"</option>"+												
+				"<option value='3'>"+get_lang("3 days")+"</option>"+							
+				"<option value='4'>"+get_lang("4 days")+"</option>"+							
+				"<option value='5'>"+get_lang("5 days")+"</option>"+							
+				"</select></td>"+
+				"</tr>"+
+				"<tr><td nowrap> - " + get_lang('Show previous message, after delete actual message?') + "</td>"+
+				"<td><input type='checkBox' id='check_show_previous' name='check_show_previous'></td>"+
+				"</tr>"+
+				"<tr><td nowrap> - " + get_lang('Do you wanna receive an alert for new messages?') + "</td>"+
+				"<td><input type='checkBox' id='check_alert' name='check_alert'></td>"+
+				"</tr>"+
+				"<tr><td nowrap> - " + get_lang('Show default view on main screen?') + "</td>"+
+				"<td><input type='checkBox' id='check_view' name='check_view'></td>"+
+				"</tr>"+
+				"<tr><td nowrap> - " + get_lang('Save sent messages in folder') + "</td>"+				
+				"<td>&nbsp;<select style='width:125px' id='sel_name_box' name='sel_name_box'></select></td>"+
+				"</tr>"+
+				"<tr><td> - " + get_lang('Hide menu folders?') + "</td>"+
+				"<td><input type='checkBox' id='check_menu' name='check_menu'></td>"+
+				"</tr>"+
+				"<tr><td> - " + get_lang('What is the height of the lines in the list of messages?') + "</td>"+
+				"<td>&nbsp;<select id='sel_height_line' name='sel_height_line'>"+
+				"<option value='20'>"+get_lang("Normal")+"</option>"+
+				"<option value='30'>"+get_lang("Medium")+"</option>"+
+				"<option value='40'>"+get_lang("Big")+"</option>"+														
+				"</select></td>"+
+				"</tr>"+
+				"<tr><td> - " + get_lang('What the font size in the list of messages?') + "</td>"+
+				"<td>&nbsp;<select id='sel_size_font' name='sel_size_font'>"+
+				"<option value='10'>"+get_lang("Small")+"</option>"+
+				"<option value='11'>"+get_lang("Normal")+"</option>"+							
+				"<option value='15'>"+get_lang("Big")+"</option>"+
+				"</select></td></tr>"+
+				"<tr><td> - " + get_lang("Auto save draft") + "?</td>"+
+				"<td><input type='checkBox' id='auto_save_draft' name='auto_save_draft'></td></tr>"+
+				"<tr><td> - " + get_lang("Use shortcuts?") + "</td>"+
+				"<td><input type='checkBox' id='use_shortcuts' name='use_shortcuts'></td></tr>"+
+				"<tr><td colspan='2'> - " + get_lang('Signature') + "<br>"+
+				"<textarea id='txt_signature' name='txt_signature' rows='3' cols='59'></textarea></td>"+
+				"</tr>"+
+				"<tr><td><input type='button' value='"+get_lang("Cancel")+"' onclick='prefe.close_win();'>"+
+				"<td align='left'><input type='button' value='"+get_lang("Save")+"' onclick='prefe.save_form()'>"+
+				"</tr>"+
+				"</table>";
+			form_pref.appendChild(form);
+			var sel_nm = Element("sel_name_box");
+			var opt = new Option(get_lang("Select the user"),"-1",true,true);
+			sel_nm.options[sel_nm.length] = opt;
+			for(var i=0; i < folders.length; i++){
+				var opt = new Option(lang_folder(folders[i].folder_name),folders[i].folder_id,false,true);
+				sel_nm.options[sel_nm.length] = opt;
+			}
+			sel_nm.options[0].selected = true;
+			_this.clean_all();
+		}
+		_this.load_form();
+	}
+	
+	// Preenche os campos no form;
+	Preferences.prototype.load_form = function(){
+		var sel_num_max = Element("sel_num_max");
+			for(var i=0; i < sel_num_max.options.length; i++){
+				if(sel_num_max.options[i].value == preferences.max_email_per_page){sel_num_max.options[i].selected = true;}
+			}
+		var check_save_men = Element("check_save_men");
+			if( preferences.save_deleted_msg == 1){check_save_men.checked = true;}
+		var sel_del_men = Element("sel_del_men");
+			for(var i=0; i < sel_del_men.options.length; i++){
+				if(sel_del_men.options[i].value == preferences.delete_trash_messages_after_n_days){sel_del_men.options[i].selected = true;}
+			}
+		var check_show_previous = Element("check_show_previous");
+			if( preferences.delete_and_show_previous_message == 1){check_show_previous.checked = true;} 
+		var check_alert = Element("check_alert");
+			if( preferences.alert_new_msg == 1){check_alert.checked = true;}
+		var check_view = Element("check_view");
+			if( preferences.mainscreen_showmail == 1){check_view.checked = true;}
+		var sel_name_box = Element("sel_name_box");
+			for(var i=0; i < sel_name_box.options.length; i++){
+				if(sel_name_box.options[i].value == preferences.save_in_folder){sel_name_box.options[i].selected = true;}
+			}
+		var check_menu = Element("check_menu");
+			if( preferences.hide_folders == 1){check_menu.checked = true;}
+		var sel_height_line = Element("sel_height_line");
+			for(var i=0; i < sel_height_line.options.length; i++){
+				if( sel_height_line.options[i].value == preferences.line_height){sel_height_line.options[i].selected = true;}
+			}
+		var sel_size_font = Element("sel_size_font");
+			for(var i=0; i < sel_size_font.options.length; i++){
+				if(sel_size_font.options[i].value == preferences.font_size){sel_size_font.options[i].selected = true;}
+			}
+		var txt_signature = Element("txt_signature");
+			txt_signature.value = preferences.signature;
+		
+		if( preferences.use_shortcuts == 1) Element("use_shortcuts").checked = true;
+		if( preferences.auto_save_draft == 1) Element("auto_save_draft").checked = true;
+	}
+	
+
+	// Salva as opções do form;
+	Preferences.prototype.save_form = function(){
+	
+	   //var prefe_string;			
+		var reload_page = false;
+
+		if(preferences.max_email_per_page != Element("sel_num_max").value)
+			reload_page = true;
+		else if(preferences.delete_trash_messages_after_n_days != Element("sel_del_men").value)
+		   	reload_page = true;
+		else if(preferences.hide_folders != Element("check_menu").checked)
+			reload_page = true;
+		else if(preferences.line_height != Element("sel_height_line").value)
+	    	reload_page = true;
+	    else if(preferences.font_size != Element("sel_size_font").value)
+			reload_page = true;
+	    else if(preferences.use_shortcuts != Element("use_shortcuts").checked)
+			reload_page = true;
+	    else if(preferences.auto_save_draft != Element("auto_save_draft").checked)
+			reload_page = true;
+				
+		preferences.max_email_per_page = Element("sel_num_max").value; 
+	 	preferences.save_deleted_msg = Element("check_save_men").checked ? 1 : 0;
+		preferences.delete_trash_messages_after_n_days = Element("sel_del_men").value;
+		preferences.delete_and_show_previous_message = Element("check_show_previous").checked ? 1 : 0;
+		preferences.alert_new_msg = Element("check_alert").checked ? 1 : 0;
+		preferences.mainscreen_showmail = Element("check_view").checked ? 1 : 0;
+	   	preferences.save_in_folder = Element("sel_name_box").value;
+		preferences.hide_folders = Element("check_menu").checked ? 1 : 0;
+	    preferences.line_height = Element("sel_height_line").value;
+		preferences.font_size = Element("sel_size_font").value;
+		preferences.signature = Element("txt_signature").value;
+		preferences.use_shortcuts = Element("use_shortcuts").checked ? 1 : 0;
+		preferences.auto_save_draft = Element("auto_save_draft").checked ? 1 : 0;
+		
+		var _this = this;
+		
+	   	var handler_preferences = function(data){
+	   		if(data && data.success){
+	   			if(reload_page)
+			   		window.location.reload(true);
+			   	else
+				   	_this.close_win();
+	   		}else{
+	   			alert(data);
+	   		}
+	   	}
+	   	var args   = "$this.db_functions.update_preferences";
+		var params = "prefe_string="+url_encode(connector.serialize(preferences));
+	   	cExecute(args,handler_preferences,params);
+	}	
+	//Fecha a janela
+	Preferences.prototype.close_win = function(){
+		this.prefeW['window_confexp'].close();
+	}
+	
+	// Salva uma unica preferencia
+	Preferences.prototype.save = function(key, value){
+		var _this = this;		
+	   	var handler_preferences = function(data){
+	   		if(data && data.success)
+	   			return;	   		
+	   		else
+	   			alert(data);
+	   	}
+	   	preferences[key] = value;
+	   	var args   = "$this.db_functions.update_preferences";
+		var params = "prefe_string="+url_encode(connector.serialize(preferences));
+	   	cExecute(args,handler_preferences,params);
+	}	
+
+	//Limpa os campos
+	Preferences.prototype.clean_all = function(){
+		document.getElementById('check_save_men').checked = false;
+		document.getElementById('check_show_previous').value = false;
+		document.getElementById('check_alert').checked = false;
+		document.getElementById('check_view').checked = false;
+		document.getElementById('check_menu').checked = false;
+		document.getElementById("sel_name_box").options[0].selected = true;
+		document.getElementById('txt_signature').value = "";
+	}
+
+	//Monta a janela principal da aplicação;
+	Preferences.prototype.showWindow = function(div){
+		
+		if(! this.prefeW[div.id]) {
+			div.style.height = is_ie ? "385px" : "370px";
+			div.style.width = "510px";
+			div.style.visibility = "hidden";
+			div.style.position = "absolute";
+			div.style.paddingLeft = "10px";			
+			var title = get_lang("ExpressoMail 1.2 Configuration");
+			var wHeight = div.offsetHeight + "px";
+			var wWidth =  div.offsetWidth   + "px";
+
+			win = new dJSWin({			
+				id: 'cc_'+div.id,
+				content_id: div.id,
+				width: wWidth,
+				height: wHeight,
+				title_color: '#3978d6',
+				bg_color: '#eee',
+				title: title,						
+				title_text_color: 'white',
+				button_x_img: '../phpgwapi/images/winclose.gif',
+				border: true });
+			
+			this.prefeW[div.id] = win;
+			win.draw();
+		}
+		else {
+			win = this.prefeW[div.id];
+
+		}
+		win.open();
+	}
+// Cria o objeto	
+	var prefe;
+	prefe = new Preferences();
Index: tags/expressoMail1_2/1.2211/js/html2xhtml.js
===================================================================
--- tags/expressoMail1_2/1.2211/js/html2xhtml.js	(revision 2)
+++ tags/expressoMail1_2/1.2211/js/html2xhtml.js	(revision 2)
@@ -0,0 +1,1 @@
+var need_nl_before='|div|p|table|tbody|tr|td|th|title|head|body|script|comment|li|meta|h1|h2|h3|h4|h5|h6|hr|ul|ol|option|';var need_nl_after='|html|head|body|p|th|style|';var re_comment=new RegExp();re_comment.compile("^<!--(.*)-->$");var re_hyphen=new RegExp();re_hyphen.compile("-$");function get_xhtml(node,lang,encoding,need_nl,inside_pre){var i;var text='';var children=node.childNodes;var child_length=children.length;var tag_name;var do_nl=need_nl?true:false;var page_mode=true;for(i=0;i<child_length;i++){var child=children[i];switch(child.nodeType){case 1:{var tag_name=String(child.tagName).toLowerCase();if(tag_name=='')break;if(tag_name=='meta'){var meta_name=String(child.name).toLowerCase();if(meta_name=='generator')break;}if(!need_nl&&tag_name=='body'){page_mode=false;}if(tag_name=='!'){var parts=re_comment.exec(child.text);if(parts){var inner_text=parts[1];text+=fix_comment(inner_text);}}else{if(tag_name=='html'){text='<?xml version="1.0" encoding="'+encoding+'"?>\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n';}if(need_nl_before.indexOf('|'+tag_name+'|')!=-1){if((do_nl||text!='')&&!inside_pre)text+='\n';}else{do_nl=true;}text+='<'+tag_name;var attr=child.attributes;var attr_length=attr.length;var attr_value;var attr_lang=false;var attr_xml_lang=false;var attr_xmlns=false;var is_alt_attr=false;for(j=0;j<attr_length;j++){var attr_name=attr[j].nodeName.toLowerCase();if(!attr[j].specified&&(attr_name!='selected'||!child.selected)&&(attr_name!='style'||child.style.cssText=='')&&attr_name!='value')continue;if(attr_name=='_moz_dirty'||attr_name=='_moz_resizing'||tag_name=='br'&&attr_name=='type'&&child.getAttribute('type')=='_moz')continue;var valid_attr=true;switch(attr_name){case"style":attr_value=child.style.cssText;break;case"class":attr_value=child.className;break;case"http-equiv":attr_value=child.httpEquiv;break;case"noshade":break;case"checked":break;case"selected":break;case"multiple":break;case"nowrap":break;case"disabled":break;attr_value=attr_name;break;default:try{attr_value=child.getAttribute(attr_name,2);}catch(e){valid_attr=false;}break;}if(attr_name=='lang'){attr_lang=true;attr_value=lang;}if(attr_name=='xml:lang'){attr_xml_lang=true;attr_value=lang;}if(attr_name=='xmlns')attr_xmlns=true;if(valid_attr){if(!(tag_name=='li'&&attr_name=='value')){text+=' '+attr_name+'="'+fix_attribute(attr_value)+'"';}}if(attr_name=='alt')is_alt_attr=true;}if(tag_name=='img'&&!is_alt_attr){text+=' alt=""';}if(tag_name=='html'){if(!attr_lang)text+=' lang="'+lang+'"';if(!attr_xml_lang)text+=' xml:lang="'+lang+'"';if(!attr_xmlns)text+=' xmlns="http://www.w3.org/1999/xhtml"';}if(child.canHaveChildren||child.hasChildNodes()){text+='>';text+=get_xhtml(child,lang,encoding,true,inside_pre||tag_name=='pre'?true:false);text+='</'+tag_name+'>';}else{if(tag_name=='style'||tag_name=='title'||tag_name=='script'){text+='>';var inner_text;if(tag_name=='script'){inner_text=child.text;}else{inner_text=child.innerHTML;}if(tag_name=='style'){inner_text=String(inner_text).replace(/[\n]+/g,'\n');}text+=inner_text+'</'+tag_name+'>';}else{text+=' />';}}}break;}case 3:{if(!inside_pre){if(child.nodeValue!='\n'){text+=fix_text(child.nodeValue);}}else{text+=child.nodeValue;}break;}case 8:{text+=fix_comment(child.nodeValue);break;}default:break;}}if(!need_nl&&!page_mode){text=text.replace(/<\/?head>[\n]*/gi,"");text=text.replace(/<head \/>[\n]*/gi,"");text=text.replace(/<\/?body>[\n]*/gi,"");}return text;}function fix_comment(text){text=text.replace(/--/g,"__");if(re_hyphen.exec(text)){text+=" ";}return"<!--"+text+"-->";}function fix_text(text){return String(text).replace(/\n{2,}/g,"\n").replace(/\&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\u00A0/g,"&nbsp;");}function fix_attribute(text){return String(text).replace(/\&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"&quot;");}
Index: tags/expressoMail1_2/1.2211/index.php
===================================================================
--- tags/expressoMail1_2/1.2211/index.php	(revision 271)
+++ tags/expressoMail1_2/1.2211/index.php	(revision 271)
@@ -0,0 +1,174 @@
+<?php
+
+	/* Begin: Check config needed for expressoMail */
+	/* Config need for expressoMail work */
+	$php_ini['session.auto_start'] = '1';
+	$php_ini['magic_quotes_gpc'] = '';
+	$php_ini['magic_quotes_runtime'] = '';
+	$php_ini['magic_quotes_sybase'] = '';
+	
+	/* Config from php.ini */
+	$php_ini_configs = array("session.auto_start","magic_quotes_gpc","magic_quotes_runtime","magic_quotes_sybase");
+	/* Checking */
+	$error = false;
+	foreach($php_ini_configs as $config)
+	{
+		if ( ($f_phpini=ini_get($config)) != $php_ini[$config])
+		{
+			$error = true;
+			echo "Erro: Config <font color=red>$config</font> from php.ini needs to be '" . $php_ini[$config] . "', but is set to '" . $f_phpini . "'.<br>";
+		}
+	}
+	if ($error)
+		exit;
+	/* End: Check config needed for expressoMail */
+		
+	$GLOBALS['phpgw_info']['flags'] = array(
+		'noheader' => False,
+		'nonavbar' => False,
+		'currentapp' => 'expressoMail1_2',
+		'update_version'	=> '1.2211',
+		'enable_nextmatchs_class' => True
+	);
+	
+	include('../header.inc.php');
+	$update_version = $GLOBALS['phpgw_info']['flags']['update_version'];
+	echo "<script src='js/globals.js?".$update_version."' type='text/javascript'></script>";
+	echo "<script src='js/sniff_browser.js?".$update_version."' type='text/javascript'></script>";
+	echo '<script type="text/javascript" src="../phpgwapi/js/wz_dragdrop/wz_dragdrop.js?'.$update_version.'"></script>
+		<script type="text/javascript" src="../phpgwapi/js/dJSWin/dJSWin.js?'.$update_version.'"></script>';
+	
+	//Enable/Disable VoIP Service
+	$voip_enabled = false;
+
+	// Get Data from ldap_manager and emailadmin.
+	$ldap_manager = CreateObject('contactcenter.bo_ldap_manager');
+	$boemailadmin	= CreateObject('emailadmin.bo');
+	$emailadmin_profile = $boemailadmin->getProfileList();
+	$_SESSION['phpgw_info']['expressomail']['email_server'] = $boemailadmin->getProfile($emailadmin_profile[0]['profileID']);
+	$_SESSION['phpgw_info']['expressomail']['user'] = $GLOBALS['phpgw_info']['user'];
+	$_SESSION['phpgw_info']['expressomail']['server'] = $GLOBALS['phpgw_info']['server'];
+	$_SESSION['phpgw_info']['expressomail']['ldap_server'] = $ldap_manager ? $ldap_manager->srcs[1] : null;
+	$_SESSION['phpgw_info']['expressomail']['user']['email'] = $GLOBALS['phpgw']->preferences->values['email'];
+	$_SESSION['phpgw_info']['user']['preferences']['expressoMail'] = array(
+			'voip_enabled'						=> $voip_enabled,
+			'outoffice'							=> $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['outoffice'],
+			'telephone_number'					=> $GLOBALS['phpgw_info']['user']['telephonenumber'],
+			'max_email_per_page' 				=> $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['max_email_per_page'],
+    		'save_deleted_msg' 					=> $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['save_deleted_msg'] ? $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['save_deleted_msg'] : "0",
+            'delete_trash_messages_after_n_days'=> $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['delete_trash_messages_after_n_days'],
+    		'delete_and_show_previous_message' 	=> $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['delete_and_show_previous_message'] ? $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['delete_and_show_previous_message'] : "0",
+    		'alert_new_msg' 					=> $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['alert_new_msg'] ? $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['alert_new_msg'] : "0",
+    		'mainscreen_showmail' 				=> $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['mainscreen_showmail'] ? $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['mainscreen_showmail'] : "0",
+    		'signature' 						=> $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['signature'],
+    		'hide_folders' 						=> $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['hide_folders'] ? $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['hide_folders'] : "0",    		
+    		'save_in_folder' 					=> $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['save_in_folder'] ? $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['save_in_folder'] : "-1",
+    		'line_height' 						=> $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['line_height'] ? $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['line_height'] : "30",
+    		'font_size' 						=> $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['font_size'] ? $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['font_size'] : "11",
+    		'use_shortcuts' 					=> $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['use_shortcuts'] ? $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['use_shortcuts'] : "0",
+    		'auto_save_draft'					=> $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['auto_save_draft'] ? $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['auto_save_draft'] : "0"
+    		
+	);
+	
+	$template = CreateObject('phpgwapi.Template',PHPGW_APP_TPL);
+	$template->set_var("txt_loading",lang("Loading"));
+	$template->set_var("txt_clear_trash",lang("message(s) deleted from your trash folder."));
+    $template->set_var("new_message", lang("New Message"));
+	$template->set_var("lang_inbox", lang("Inbox"));
+    $template->set_var("refresh", lang("Refresh"));
+    $template->set_var("tools", lang("Tools"));	
+	$template->set_var("lang_Open_Search_Window", lang("Open search window") . '...');
+	$template->set_var("lang_search_user", lang("Search user") . '...'); 
+	$template->set_var("upload_max_filesize",ini_get('upload_max_filesize'));
+	$template->set_var("msg_folder",$_GET['msgball']['folder']);
+	$template->set_var("msg_number",$_GET['msgball']['msgnum'] ? $_GET['msgball']['msgnum'] : $_GET['to']);
+	$template->set_var("user_email",$_SESSION['phpgw_info']['expressomail']['user']['email']);
+	$acc = CreateObject('phpgwapi.accounts');
+	$template->set_var("user_organization", $acc->get_organization($GLOBALS['phpgw_info']['user']['account_dn']));
+	$template->set_var("cyrus_delimiter",$_SESSION['phpgw_info']['expressomail']['email_server']['imapDelimiter']);	
+	// Fix problem with cyrus delimiter changes in preferences.
+	// Dots in names: enabled/disabled.
+	$save_in_folder = @eregi_replace("INBOX/", "INBOX".$_SESSION['phpgw_info']['expressomail']['email_server']['imapDelimiter'], $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['save_in_folder']);
+	$save_in_folder = @eregi_replace("INBOX.", "INBOX".$_SESSION['phpgw_info']['expressomail']['email_server']['imapDelimiter'], $save_in_folder);
+	$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['save_in_folder'] = $save_in_folder;
+	// End Fix.
+	
+	$template->set_file(Array('expressoMail' => 'index.tpl'));
+	$template->set_block('expressoMail','list');
+	$template->pfp('out','list');
+	$GLOBALS['phpgw']->common->phpgw_footer();
+    
+    // Loading Admin Config Module
+    $c = CreateObject('phpgwapi.config','expressoMail1_2');
+    $c->read_repository();
+    $current_config = $c->config_data;    
+    $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] = $current_config['expressoMail_enable_log_messages'];
+    // Begin Set Anti-Spam options.
+    $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_ham'] = $current_config['expressoMail_command_for_ham'];
+    $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_spam'] = $current_config['expressoMail_command_for_spam'];
+    $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_use_spam_filter'] = $current_config['expressoMail_use_spam_filter'];   
+    echo '<script> var use_spam_filter = \''.$current_config['expressoMail_use_spam_filter'].'\' </script>';
+	// End Set Anti-Spam options.
+
+
+       // Set Imap Folder names options
+
+    $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'] 	= $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']	? $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']		: lang("Trash");
+    $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder'] 	= $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder'] ? $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder'] 	: lang("Drafts");
+    $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder'] 	= $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder']	? $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder']		: lang("Spam");
+    $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder']	= $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder'] 	? $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder'] 		: lang("Sent");
+
+    echo '<script> var special_folders = new Array(4);
+   	special_folders["'.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'].'"] = \'Trash\';
+    special_folders["'.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder'].'"] = \'Drafts\';
+    special_folders["'.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder'].'"] = \'Spam\';
+    special_folders["'.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder'].'"] = \'Sent\';
+    var trashfolder = "'.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'].'";
+    var draftsfolder = "'.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder'].'";
+    var sentfolder = "'.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder'].'";
+    var spamfolder = "'.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder'].'";                      
+    </script>';
+
+    // End Set Imap Folder names options
+
+	$obj = createobject("expressoMail1_2.functions");
+	echo "<script src='inc/load_lang.php?".$update_version."' type='text/javascript'></script>";	
+	// INCLUDE these JS Files: 
+	echo $obj -> getFilesJs("js/abas.js," .
+							"js/common_functions.js," .
+							"js/doiMenuData.js," .
+							"js/drag_area.js," .
+							"js/draw_api.js," .
+							"js/DropDownContacts.js," .
+							"js/InfoContact.js," .
+							"js/main.js," .
+							"js/rich_text_editor.js," .
+							"js/wfolders.js,",
+							$GLOBALS['phpgw_info']['flags']['update_version']);
+
+	if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['use_shortcuts'])
+	{
+		echo $obj -> getFilesJs("js/shortcut.js", $GLOBALS['phpgw_info']['flags']['update_version']);
+	}
+
+	// Get Preferences or redirect to preferences page.
+	$GLOBALS['phpgw']->preferences->read_repository();
+	if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail'] == null){
+		echo '<script>alert("' . lang('Dear user,\nthis is your first time in the ExpressoMail, your preferences must be saved.\nPlease, choose your preferences and click on the button Save.') . '")</script>';
+		echo "<script>location.href='./preferences.php'</script>";
+	}	
+?>
+
+<html>
+<head>
+<title>ExpressoMail</title>
+<link rel="stylesheet" type="text/css" href="templates/default/main.css">
+<link rel="stylesheet" type="text/css" href="../phpgwapi/js/dftree/dftree.css">
+</head>
+<body scroll="no" style="overflow:hidden">
+</body>
+</html>
+<script src="js/connector.js?<?=$update_version?>" type="text/javascript"></script>
+<script src="../phpgwapi/js/dftree/dftree.js?<?=$update_version?>" type="text/javascript"></script>
+<script language="Javascript">connector.updateVersion = "<?=$update_version?>";init();</script>
+<!-----Expresso Mail - Version Updated:<?=$update_version?>-------->
Index: tags/expressoMail1_2/1.2211/templates/default/preferences.tpl
===================================================================
--- tags/expressoMail1_2/1.2211/templates/default/preferences.tpl	(revision 271)
+++ tags/expressoMail1_2/1.2211/templates/default/preferences.tpl	(revision 271)
@@ -0,0 +1,132 @@
+
+<center>
+
+<table width="50%" border="0" cellspacing="2" cellpadding="2">
+
+<form method="POST" action="{save_action}">
+<input type="hidden" name="try_saved" value="false">
+
+    <tr bgcolor="{th_bg}">
+        <td colspan="2" align="center">{lang_config_expressoMail}</td>
+    </tr>
+    <tr bgcolor="{tr_color1}">
+        <td>{lang_max_emails_per_page}</td>
+        <td align="center">
+			<select name="max_emails_per_page">
+				<option {option_25_selected} value="25">25</option>
+				<option {option_50_selected} value="50">50</option>
+				<option {option_75_selected} value="75">75</option>
+				<option {option_100_selected} value="100">100</option>
+			</select>
+        </td>
+    </tr>
+    <tr bgcolor="{tr_color2}">
+        <td>{lang_save_deleted_msg}</td>
+        <td align="center">
+        	<input type="checkbox" name="save_deleted_msg" value=1 {checked_save_deleted_msg}>
+        </td>
+    </tr>
+    <tr bgcolor="{tr_color1}">
+        <td>{lang_delete_trash_messages_after_n_days}</td>
+        <td align="center">
+			<select name="delete_trash_messages_after_n_days">
+				<option {delete_trash_messages_option_0_selected} value="0">{lang_none}</option>
+				<option {delete_trash_messages_option_1_selected} value="1">{one_day}</option>
+				<option {delete_trash_messages_option_2_selected} value="2">{two_days}</option>
+				<option {delete_trash_messages_option_3_selected} value="3">{three_days}</option>
+				<option {delete_trash_messages_option_4_selected} value="4">{four_days}</option>
+				<option {delete_trash_messages_option_5_selected} value="5">{five_days}</option>
+			</select>
+        </td>
+    </tr>
+    <tr bgcolor="{tr_color2}">
+        <td>{lang_delete_and_show_previous_message}</td>
+        <td align="center">
+        	<input type="checkbox" name="delete_and_show_previous_message" value=1 {checked_delete_and_show_previous_message}>
+        </td>
+    </tr>
+	<tr bgcolor="{tr_color1}">
+        <td>{lang_alert_new_msg}</td>
+        <td align="center">
+        	<input type="checkbox" name="alert_new_msg" value=1 {checked_alert_new_msg}>
+        </td>
+    </tr>
+    <tr bgcolor="{tr_color2}">
+        <td>{lang_hook_home}</td>
+        <td align="center">
+        	<input type="checkbox" name="mainscreen_showmail" value=1 {checked_mainscreen_showmail}>
+        </td>
+    </tr>
+    <tr bgcolor="{tr_color1}">
+        <td>{lang_save_in_folder}</td>
+        <td align="center">        	
+        	<select name="save_in_folder">{value_save_in_folder}</select>
+        </td>
+    </tr>
+    <tr bgcolor="{tr_color2}">
+        <td>{lang_hide_menu}</td>
+        <td align="center">        	
+			<input type="checkbox" name="check_menu" value=1 {checked_menu}>
+        </td>
+    </tr>
+    <tr bgcolor="{tr_color1}">
+        <td>{lang_line_height}</td>
+        <td align="center">
+			<select name="line_height">				
+				<option {line_height_option_20_selected} value="20">{normal}</option>
+				<option {line_height_option_30_selected} value="30">{medium}</option>
+				<option {line_height_option_40_selected} value="40">{big}</option>								
+			</select>
+        </td>
+    </tr>
+    <tr bgcolor="{tr_color2}">
+        <td>{lang_font_size}</td>
+        <td align="center">
+			<select name="font_size">
+				<option {font_size_option_10_selected} value="10">{small}</option>
+				<option {font_size_option_11_selected} value="11">{normal}</option>
+				<option {font_size_option_15_selected} value="15">{big}</option>								
+			</select>
+        </td>
+    </tr>
+    <tr bgcolor="{tr_color1}">
+        <td>
+			{lang_use_shortcuts}
+		</td>
+		<td align="center">
+			<input type="checkbox" name="use_shortcuts" value=1 {checked_shortcuts}>
+		</td>
+    </tr>
+    
+    <tr bgcolor="{tr_color1}">
+        <td>
+			{lang_auto_save_draft}
+		</td>
+		<td align="center">
+			<input type="checkbox" name="auto_save_draft" value=1 {checked_auto_save_draft}>
+		</td>
+    </tr>
+
+    <tr bgcolor="{tr_color2}">
+        <td colspan='2'>
+			{lang_signature}<BR>
+			<textarea name="signature" rows=4 cols=50>{text_signature}</textarea>
+        </td>
+    </tr>
+    
+    <tr bgcolor="{th_bg}">
+    	<td colspan="2" >
+    		<table width="100%" border="0" cellspacing="2" cellpadding="2">
+    			<tr>
+        			<td align="left">
+        				<input type="button" name="cancel" value="{lang_cancel}" onClick="javascript:document.location.href = '../expressoMail1_2/index.php'">
+        			</td>
+        			<td align="right">
+        				<input type="submit" name="submit" value="{lang_save}" onClick="try_saved.value='true';">
+        			</td>        			
+        		</tr>
+        </td>        
+    </tr>
+
+</table>
+</center>
Index: tags/expressoMail1_2/1.2211/templates/default/config.tpl
===================================================================
--- tags/expressoMail1_2/1.2211/templates/default/config.tpl	(revision 197)
+++ tags/expressoMail1_2/1.2211/templates/default/config.tpl	(revision 197)
@@ -0,0 +1,59 @@
+<!-- BEGIN header -->
+<form method="POST" action="{action_url}">
+<table border="0" align="center">
+   <tr bgcolor="{th_bg}">
+    <td colspan="2"><font color="{th_text}">&nbsp;<b>{title}</b></font></td>
+   </tr>
+<!-- END header -->
+<!-- BEGIN body -->
+   <tr bgcolor="{row_on}">
+    <td colspan="2">&nbsp;</td>
+   </tr>
+   <tr bgcolor="{row_off}">
+    <td colspan="2"><b>{lang_ExpressoMail_settings}</b></td>
+   </tr>
+   <tr bgcolor="{row_on}">
+    <td>{lang_Do_you_want_to_log_the_sent_messages?}</td>
+    <td>
+     <select name="newsettings[expressoMail_enable_log_messages]">
+      <option value=""{selected_expressoMail_enable_log_messages_False}>{lang_No}</option>
+      <option value="True"{selected_expressoMail_enable_log_messages_True}>{lang_Yes}</option>
+     </select>&nbsp;&nbsp;&nbsp;path: /home/expresso/mail_senders.log
+    </td>
+   </tr>
+   <tr bgcolor="{row_off}">
+    <td>{lang_Do_you_want_to_use_the_spam_filter?}</td>
+    <td>
+     <select name="newsettings[expressoMail_use_spam_filter]">
+      <option value=""{selected_expressoMail_use_spam_filter_False}>{lang_No}</option>
+      <option value="True"{selected_expressoMail_use_spam_filter_True}>{lang_Yes}</option>
+     </select>
+    </td>
+   </tr>
+   <tr bgcolor="{row_on}">
+    <td>{lang_Command_for_spam}</td>
+    <td>
+	<input type="text" name="newsettings[expressoMail_command_for_spam]" value="{value_expressoMail_command_for_spam}" size="60" /> 
+    </td>
+   <tr bgcolor="{row_off}">
+    <td>{lang_Command_for_unmark_spam}</td>
+    <td>
+	<input size="60" name="newsettings[expressoMail_command_for_ham]" value="{value_expressoMail_command_for_ham}"> 
+    </td>
+   </tr>
+<!-- END body -->
+<!-- BEGIN footer -->
+  <tr bgcolor="{th_bg}">
+    <td colspan="2">
+&nbsp;
+    </td>
+  </tr>
+  <tr>
+    <td colspan="2" align="center">
+      <input type="submit" name="submit" value="{lang_submit}">
+      <input type="submit" name="cancel" value="{lang_cancel}">
+    </td>
+  </tr>
+</table>
+</form>
+<!-- END footer -->
Index: tags/expressoMail1_2/1.2211/templates/default/index.tpl
===================================================================
--- tags/expressoMail1_2/1.2211/templates/default/index.tpl	(revision 139)
+++ tags/expressoMail1_2/1.2211/templates/default/index.tpl	(revision 139)
@@ -0,0 +1,66 @@
+<!-- BEGIN list -->
+<input type="hidden" value="{txt_loading}" id="txt_loading">
+<input type="hidden" value="{txt_clear_trash}" id="txt_clear_trash">
+<input type="hidden" value="{upload_max_filesize}" id="upload_max_filesize">
+<input type="hidden" value="{msg_folder}" id="msg_folder">
+<input type="hidden" value="{msg_number}" id="msg_number">
+<input type="hidden" value="{user_email}" id="user_email">
+<input type="hidden" value="{user_organization}" id="user_organization">
+<input type="hidden" value="{cyrus_delimiter}" id="cyrus_delimiter">
+<table id="main_table" width="100%" cellspacing="0" cellpadding="0" border="0" style="display:none">
+	<tbody>
+		<tr>
+			<td id="folderscol" width="162px" height="100%" valign="top">			
+				<table id="folders_tbl" width="162px" border="0" cellspacing="0" cellpadding="0" border="0">
+					<tbody>
+						<tr><td><div class='content-menu'>
+							<table border="0" cellspacing="0" cellpadding="0" border="0"><tbody>
+								<tr><td class='content-menu-td' onclick='javascript:new_message("new","null");' onmouseover='javascript:set_menu_bg(this);' onmouseout='javascript:unset_menu_bg(this);'><div class='em_div_sidebox_menu'><img src='./templates/default/images/menu/createmail.gif'><span class="em_sidebox_menu">{new_message}</span></div></td></tr>
+								<tr><td class='content-menu-td' id='em_refresh_button' onclick='javascript:refresh();' onmouseover='javascript:set_menu_bg(this);' onmouseout='javascript:unset_menu_bg(this);'><div class='em_div_sidebox_menu'><img src='./templates/default/images/menu/checkmail.gif'><span class="em_sidebox_menu">{refresh}</span></div></td></tr>
+								<tr><td id="link_tools" class='content-menu-td' onmouseover='javascript:set_menu_bg(Element("link_tools"));' onmouseout='javascript:unset_menu_bg(this);'><div class='em_div_sidebox_menu'><img height='16px' src='./templates/default/images/menu/tools.gif'><span class="em_sidebox_menu">{tools} ...</span></div></td></tr>								
+							</tbody></table>
+						</div></td></tr>
+						<tr><td height="2px"></td></tr>						
+						<tr><td class="content-folders" valign="top" style="padding:2px">
+							<div id="content_folders" style="height:100%;width:162px;overflow:auto"></div>
+						</td></tr>
+					</tbody>
+				</table>
+				<div style="height:4px"></div>
+				<div align="center">
+					<input type="text" id="em_message_search" size="18" maxlength="22"/>
+					<a class='' onMouseOut="window.status='';return true;" title='{lang_Open_Search_Window}' onMouseOver="window.status='{lang_Open_Search_Window}';return true;" href="javascript:void(0);"  onClick="javascript:search_emails(Element('em_message_search').value)">
+						<img valign="center" align="center" src="templates/default/images/search.gif">
+					</a>
+					<a class='' onMouseOut="window.status='';return true;" title='{lang_search_user}' onMouseOver="window.status='{lang_search_user}' ;return true;" href="javascript:void(0);"  onClick="javascript:emQuickSearch(Element('em_message_search').value, 'null', 'null')">
+						<img valign="center" align="center" src="templates/default/images/users.jpg">
+					</a>
+				</div>
+				
+			</td>			
+			<td width="2px">&nbsp;</td>			
+			<td width="*" valign="top" align="left">
+				<div id="exmail_main_body" class="messagescol">
+					<table id="border_table" width="auto" height="26" cellspacing="0" cellpadding="0" border="0">
+						<tbody id="border_tbody">
+							<tr id="border_tr">
+								<td nowrap class="menu" onClick="alternate_border(0);"  id="border_id_0">&nbsp;{lang_inbox}&nbsp;<font face="Verdana" size="1" color="#505050">[<span id="new_m">0</span> / <span id="tot_m">0</span>]</font>
+								</td>
+								<td nowrap id="border_blank" class="last_menu" width="100%">&nbsp;</td>								
+							</tr>
+						</tbody>
+					</table>
+					<div id="content_id_0" class="conteudo"></div>
+					<div id="footer_menu">
+						<table style="border-top:0px solid black" id="footer_box" cellpadding=0 cellspacing=0 border=0 width="100%" height="10px">
+							<tbody>
+								<tr id="table_message"></tr>
+							</tbody>
+						</table>
+					</div>
+				</div>
+			</td>
+		</tr>
+	</tbody>
+</table>
+<!-- END list -->
Index: tags/expressoMail1_2/1.2211/templates/default/main.css
===================================================================
--- tags/expressoMail1_2/1.2211/templates/default/main.css	(revision 220)
+++ tags/expressoMail1_2/1.2211/templates/default/main.css	(revision 220)
@@ -0,0 +1,424 @@
+* {
+	font-family: Verdana, Arial, Helvetica, sans-serif;
+}
+
+.checkbox {
+	border:none;
+}
+
+textarea{
+	font-family: Verdana, Arial, Helvetica, sans-serif;
+	font-size: 13px;
+}
+
+.table_box{
+	width: 100%;
+	color: black;
+	border-style: solid;
+	border-width: 1px;
+	border-color: #bbbbbb;
+	font-family: Arial;
+	font-size: 13px;
+	cursor: pointer;
+}
+
+/* begin class msgs */
+.tr_msg_unread {
+	color: black;
+	background-color: #e8eef7;
+	font-weight: bold;
+	border-bottom:1px solid #cfcfcf;
+    -moz-user-select: none;
+}
+.tr_msg_read {
+	color: black;
+	background-color: #ffffff;
+	border-bottom:1px solid #cfcfcf;
+    -moz-user-select: none;
+}
+.selected_msg{
+	background-color: #ffffcc;
+}
+.flagged_msg{
+	color: red;
+}
+.selected_shortcut_msg{
+	color: white;
+	background-color: #5194d2;
+}
+/* end class msgs */
+
+.action_info_table {
+	border-spacing: 0px 0px;
+}
+.action_info_th {
+	font-family: Verdana, Arial, Helvetica, sans-serif;
+	font-size: 11px;
+	border-width: 0px 0px 0px 0px;
+	padding: 1px 10px 0px 10px;	
+	border-style: inset inset inset inset;
+	border-color: gray gray gray gray;
+	background-color: rgb(250, 209, 99);
+	-moz-border-radius: 6px 6px 6px 6px;
+}
+
+.message_header{
+	background-color: #CCCCCC;
+}
+
+.table_message_header_box{
+	width: 100%;
+	color: black;
+	border-style: solid;
+	border-width: 0px;
+	border-collapse: collapse;
+	border-color: #bbbbbb;
+	font-family: Arial;
+	font-size: 13px;	
+	cursor: pointer;
+}
+.font-menu
+{
+    text-decoration: none;
+    text-align: center;
+    font: bold 13px Lucidatypewriter,monospace;
+    color: #505050;
+}
+
+.font-menu-sel
+{
+    text-decoration: none;
+    text-align: center;
+    font: bold 13px Lucidatypewriter,monospace;
+   	color:#0000FF;
+}
+
+.menu-sel
+{
+    text-decoration: none;
+    text-align: center;
+    font: bold 13px Lucidatypewriter,monospace;
+   	color:#0000FF;
+    height: 20px;
+	width:220px;
+    background-color: #F7F7F7;
+    margin-bottom: 0px;
+    border-left: 1px solid #000000;
+    border-top: 1px solid #000000;
+    border-right: 1px solid #000000;
+    padding:0px 5px 0px 0px;
+    -moz-border-radius: 9px 9px 0px 0px;
+    -moz-user-select: none;
+    cursor: pointer;	
+}
+.menu
+{
+    text-decoration: none;
+    text-align: center;
+    font: bold 13px Lucidatypewriter,monospace;
+    color: #505050;
+    height: 20px;    
+	width:220px;
+    background-color:#E5E5E5;
+    margin-bottom: 0px;
+    border-left: 1px solid #c0c0c0;
+    border-top: 1px solid #c0c0c0;
+    border-right: 1px solid #c0c0c0;       
+    border-bottom: 1px solid #000000;
+	padding:0px 5px 0px 0px;
+    -moz-border-radius: 9px 9px 0px 0px;
+    -moz-user-select: none;
+    cursor: pointer;
+}
+
+.last_menu
+{
+	border-bottom: 1px solid #000000;
+	-moz-border-radius: 0px 0px 0px 0px;
+}
+
+.conteudo {
+    font-family: Verdana, Arial, Helvetica, sans-serif;
+    font-size: 10px;
+    font-weight: normal;
+    color: #000033;
+	padding: 1px;
+    border-color: gray gray gray gray;
+   
+	border-right: 1px solid #000000;
+	border-left: 1px solid #000000;
+	border-bottom: 1px solid #000000;
+	width:99.5%;
+    -moz-border-radius: 0px 0px 6px 6px;
+}
+
+.table_message{
+	background-color: #CCCCCC;
+	padding: 1px;
+	cursor: default;
+	border-width: 1px 1px 1px 1px;
+	border-spacing: 0px 1px;
+	border-style: outset outset outset outset;
+	border-color: gray gray gray gray;
+	border-collapse: separate;
+	-moz-border-radius: 3px 3px 3px 3px;
+}
+.table_top{
+	background-color: #FFFFFF;
+	padding:1px 1px 1px 1px;
+	height:16px;
+	cursor: default;
+	margin: 0px 0px 0px 0px;
+	border-width: 0px 1px 1px 1px;
+	border-style: outset outset outset outset;
+	border-color: black black black black;	
+}
+
+.tr_message_header{
+	background-color: #EEEEEE;
+	cursor: default;
+	border-style: none none none none;
+	-moz-border-radius: 0px 0px 0px 0px;
+}
+
+.tr_message_body{
+	background-color: #FFFFFF;
+	cursor: default;
+	-moz-border-radius: 9px 9px 9px 9px;
+}
+
+.message_body{
+	background-color: #FFFFFF;
+	cursor: default;
+	-moz-border-radius: 9px 9px 9px 9px;
+}
+
+.header_message_field{
+	font-weight: bold;
+}
+
+.suggestion_list
+{
+background: white;
+border: 1px solid;
+padding: 4px;
+}
+        
+.suggestion_list ul
+{
+padding: 0;
+margin: 0;
+list-style-type: none;
+}
+
+.suggestion_list a
+{
+text-decoration: none;
+color: navy;
+}
+
+.suggestion_list .selected
+{
+background: navy;
+color: white;
+}
+        
+        
+.suggestion_list .selected a
+{
+color: white;
+}
+
+#autosuggest
+{
+display: none;
+} 
+
+div#tipDiv {
+  position:absolute; visibility:hidden; left:0; top:0; z-index:10000;
+  background-color:#EFEFEF; border:1px solid #337;
+  width:220px; padding:0px;
+  color:#000; font-size:11px; line-height:1.2;
+  cursor: pointer;
+}
+
+.richtext_toolbar {background-color: #C0C0C0;}
+.imagebutton {border: solid 2px #C0C0C0; background-color: #C0C0C0; float:left;}
+.select_richtext {float:left;}
+/*.image {position: relative; left: 1; top: 1; height:20; width:21; border:none;}*/
+/*.imagebutton_out: {border-style: solid 2px #C0C0C0;}*/
+/*.imagebutton_over: {border-style: outset 20px;}*/
+.sel_color{	border-width:1px;border-color:#FFFFFF;border-style:solid;cursor:pointer;}
+.unsel_color{border-width:1px;border-color:#BBBBBB;border-style:solid;}
+
+/* Conf tree	*/
+.dtree {
+	font-family: Verdana, Arial, Helvetica, sans-serif;
+	font-size: 8px;
+	color: #000000;
+	/*white-space: nowrap;*/
+	background-color: #FFFFFF;
+
+}
+.dtree img {
+	border: 0px;
+	vertical-align: middle;
+
+}
+.dtree a {
+	font-family: Verdana, Arial, Helvetica, sans-serif;
+	color: #000000;
+	white-space: nowrap;	
+}
+.dtree table{
+	margin-top: 0%;
+	padding: 0px 0px 0px 0px;
+}
+.dtree td{
+	padding: 0px 0px 0px 0px;
+}
+
+.folderscol{
+	/*width: 18%;*/
+	width: 100%;
+	/*float: left;*/
+	/*padding: 0px 0px 0px 0px;*/
+}
+
+.messagescol{
+	/*padding-left: 18.5%;*/
+	/*width: 85%;*/
+	width: 100%;
+	/*float: left*/
+	/*margin-rigth: 0px;*/
+	padding: 0px 0px 0px 0px;
+}
+
+.menu-folders
+{
+	text-align: center;
+    text-decoration: none;
+	font: bold 12px Verdana, Arial, Helvetica, sans-serif;
+	color: rgb(0, 102, 51);
+	width: 100%;
+	height: 20px;
+
+	border-right: 1px solid #000000;
+	border-left: 1px solid #000000;
+	border-top: 1px solid #000000;
+		
+	cursor: default;
+    -moz-border-radius: 9px 9px 0px 0px;
+}
+
+.content-menu {
+	padding: 3px 0px 3px 5px;
+	border-top: 1px solid #000000;
+    border-right: 1px solid #000000;
+    border-left: 1px solid #000000;
+	border-bottom: 1px solid #000000;
+	-moz-border-radius: 9px 9px 9px 9px;
+}
+.content-menu-td {
+	border: 1px solid #f7f7f7;
+}
+
+.content-folders {
+	padding: 0px 0px 0px 0px;
+
+	border-top: 1px solid #000000;
+    border-right: 1px solid #000000;
+    border-left: 1px solid #000000;
+	border-bottom: 1px solid #000000;
+    -moz-border-radius: 9px 9px 9px 9px;
+
+	position: relative;
+	overflow: auto;
+}
+
+/* Conf Filter	*/
+.filter {
+	font-family: Verdana, Arial, Helvetica, sans-serif;
+	font-size: 8px;
+	background-color : #FFFFFF;
+}
+.filter img {
+	border: 0px;
+	vertical-align: middle;
+}
+.filter a {
+	font-family: Verdana, Arial, Helvetica, sans-serif;
+	color: #000000;
+	white-space: nowrap;
+}
+
+.message_options {
+	cursor: pointer;
+	color: blue;
+	white-space: nowrap;
+}
+
+.em_sidebox_menu {
+	position: relative;
+	left: 2px;
+	padding: 0px 13px 0px 0px;
+	font-weight: bold;
+	font-size: 10px;
+	color: #666666;
+	text-decoration: none;
+	white-space: nowrap;
+	font-family: sans-serif;
+}
+
+.em_div_sidebox_menu {
+	position: relative;
+	left: 5px;
+	cursor: pointer;
+}
+.catalog{
+	font-family: Verdana, Arial, Helvetica, sans-serif;
+	font-size: 14px;
+	font-weight: bold;
+}
+
+div.quicksearchcontacts {
+	border-width: 1px;
+	border-style: solid;
+	broder-color: grey;
+	overflow: auto;
+	position: relative;
+	left: 10px;
+	height: 302px;
+	width: 577px;
+}
+
+table.quicksearchcontacts {
+	border-width: 0px 0px 0px 0px;
+	border-spacing: 0px;
+	background-color: white;
+	cursor: default;
+}
+
+tr.quicksearchcontacts_unselected {
+	background-color: white;
+}
+
+tr.quicksearchcontacts_selected {
+	background-color: #5598d7;
+	color: white;
+}
+
+td.quicksearchcontacts_cc {
+	border-style: none;
+}
+
+input.em_button_like_span {
+	border:0px none !important;
+	margin: 0px !important;
+	padding:0px !important;
+	color:blue !important;
+	background:transparent none repeat scroll 0% !important;
+	font-family:Verdana,Arial,Helvetica,sans-serif !important;
+	font-size:11px !important;
+	height:15px !important;
+}
