/**
 * 
 * All content on this website (including text, images, source
 * code and any other original works), unless otherwise noted,
 * is licensed under a Creative Commons License.
 * 
 * http://creativecommons.org/licenses/by-nc-sa/2.5/
 * 
 * Copyright (C) Open-Xchange Inc., 2006-2011
 * Mail: info@open-xchange.com 
 * 
 * @author Stefan Preuss <stefan.preuss@open-xchange.com>
 * @author Suphi Basdemir <suphi.basdemir@open-xchange.com>
 * 
 */

/* 
 * Main class to handle all the mail stuff
 * 
 * @todo: Make functions like delete, move, copy, etc. more abstract so they can
 * be used from outside! Remove any local references like grid. Such things must
 * be added to seperate functions. Code cleanup!!!
 */
var detailmessage;	 
var mail_lastSelectedId;
var mailFetchTimestamp;
var detailrequest;
var deleteMailIDs = emptyFunction;
var switchMailHeaderView, initVsplitSortMenu, loadBlockedImages, oMailFunctions;
var iMIPAccept;
var openAttachment;

function infostore_sendLink(obj) {
    function cb_openWindow(arg) {
        var editorEnabled = (!configGetKey("gui.mail.formatmessage").match(/text\/plain/i));
        var oInfoMailObj = new Object();    
        var content = "";
        var subject = "";
        for (var indx=0; indx < arg.length; indx++) {
            var obj = arg[indx].data;
            ox.api.folder.getPathString({
                folder: obj.folder_id,
                success: function(path) {
                	var dLink = getDirectLinkLocal(obj);
                    if (!obj.id) {
                        dLink = dLink.replace(/[#&]i=([^#&]+)/, "");
                    }
                    if (obj.title) {
                        content += pgettext("description", "Title") + ": " + obj.title + "<br/>";   
                        if (arg.length == 1) subject = obj.title;
                    }               
                    content += _("Folder") + ": " + path + "<br/>";
                    content += _("Direct link") + ": " + (editorEnabled ? "<a href=\""+dLink+"\">"+dLink+"</a>" : dLink) + "<br/>";
                    if (indx < arg.length) content += "<br/>";
                }
            });   
        }
        oInfoMailObj["content"] = content;
        oInfoMailObj["content_type"] = "text/plain";
        
        // use new api
        ox.api.mail.compose({
            params: { subject: subject },
            data: {
                aInfoMailAttachmentLink: [oInfoMailObj] 
            }
        });
    }
    if (obj) {
        cb_openWindow(obj);
    } else { 
        doAjaxGetInfoItemMulti(oLastSelectedInfoObject,cb_openWindow);
    }
}

(function() {
	var mailSelection = new Selection2();
		
	var smilies = {
		";-)": "wink.gif",
		";)": "wink.gif",
		":-D": "big_smile.gif",
		":D": "big_smile.gif",
		":-)": "smile.gif",
		":)": "smile.gif",
		":-(": "sad.gif",
		":(": "sad.gif",
		"=(": "sad.gif",
		":|": "neutral.gif",
		":-|": "neutral.gif",
		":/": "hmm.gif",
		":-/": "hmm.gif"
	};
	
	var sortType;
	var mail_folderPath;
		
	register("Loaded", function() {
		sortType = {
			"from" : addTranslated(_("From")),
			"to" : addTranslated(_("To")),
			"subject" : addTranslated(_("Subject")),
			"size" : addTranslated(_("Size")),
			"sent_date" : addTranslated(_("Sent")),
			"received_date" : addTranslated(_("Received")),
			"flags_sort" : addTranslated(_("Read/Unread")),
			"color_label": addTranslated(_("Flag"))
		};	
		mail_folderPath = new FolderPath("mail");
	});
	
	var regexps = [];
	for (var i in smilies) regexps.push(i.replace(/([$^\\.*+?()[\]{}|])/, "\\$1"));
	var regexpstr = "(^| |\\n|<br>)(" + regexps.join("|") + ")";
	var regexp = new RegExp(regexpstr, "g");	
	
	function replaceSmilies(text) {
		return text.replace(regexp, function(_, space, match) {
			return space + "<img src=\"" + getFullImgSrc("img/smilies/" + smilies[match]) + "\">";
		});
	}
	
	function replaceLeadingSpaces(text) {
		return text.replace(/(^|<br>)([ \t]+)|([ \t]{2,}|\t)/g,
			function(_, prefix, m1, m2) {
				var match = (m1 || m2).replace(/\t/g, "        "); // TODO: real tabs
				var retval = new Array((match.length + 3) >> 1);
				retval[0] = prefix || "";
				var max = match.length >> 1;
				for (var i = 1; i <= max; i++) retval[i] = "&nbsp; ";
				if (match.length & 1) retval[retval.length - 1] = "&nbsp;";
				return retval.join("");
			});
	}

	deleteMailIDs = function(ids, nView) {
		var myView = nView || view;
		if (myView.grid && myView.grid.storage) { 
			myView.grid.deleteIDs(ids);
		}
	};
	
	/*
	 * Notes:
	 * selection.getSelectedIDs(storageCache.current)
	 */
	var json = new JSON();
	function setAttachments(present) {
			resizeSplit("mail." + this.name + ".detail.attachments",
			            present ? "3.19em" : "0em");
	}
	var hsplit = {name: "hsplit", grid: null, attachments: false, setAttachments: setAttachments};
	var vsplit = {name: "vsplit", grid: null, attachments: false, setAttachments: setAttachments};
	var list = {name: "list", grid: null};
	var nSelId = -1, message, nested_msgs, old_focus;
	var clear = LiveGrid.makeClear("");
	var view = hsplit;
	var mailFetchTimestamp;
	var sort_id = "received_date";
	var sort_order = "desc";
    var numberOfMailsinFolder = [0,0];
    var finalFolderName = "";
	
	/******************* REGISTER EVENTS **********************/
	registerModule("mail", _("E-Mail"), 20);
	registerModuleView("mail","E-Mail",5,{x:1,y:0,ww:1,hw:1});
	registerPrintView("mail/list/unthreaded");
	registerPrintView("mail/list/threaded");
	registerPrintView("mail/vsplit/unthreaded");
	registerPrintView("mail/vsplit/threaded");
	registerPrintView("mail/hsplit/unthreaded");
	registerPrintView("mail/hsplit/threaded");
	
	register("OX_NEW_MAIL", function(){ newMail(""); });
	register("OX_Mail_Reply", function(){ newMail("reply"); });
	register("OX_Mail_ReplyAll", function(){ newMail("replyall"); });
	register("OX_Mail_Forward", function(){ newMail("forward"); });
	register("OX_Mail_Edit_Draft", function(){ newMail("draft"); });
	register("OX_Mail_Change_Structure", function(what){ } );
	
	// update headline whenever unread count changes
	register("OX_New_Unread_Mail", function () {
	    // in mail?
	    if (activemodule === "mail") {
	        // update mail header
            setMailHeaderLabel();
	    }
	});
	
	register("OX_Mail_Delete", 
		function() {
	      deleteMails(activefolder, view.grid.getSelectedIDs());
		}
	);
	register("OX_Mail_SaveMail", 
		function() {
			var tF = $("mail." + view.name + ".attachment.save");	
			var n_url = AjaxRoot + '/mail?action=get'
				+ '&session=' + session + '&folder=' + encodeURIComponent( activefolder )
				+ '&id=' + encodeURIComponent(view.grid.getSelectedIDs()[0].id);
			tF.src = n_url+"&src=1&save=1";
		}
	);
	register("OX_Attachment_Open", function(){ if (activemodule == "mail") openAttachment("OPEN"); });
	register("OX_Attachment_Open_Nested", function(){ if (activemodule == "mail") openNestedMessage(); });
	register("OX_Attachment_Save", function(){ if (activemodule == "mail") openAttachment("SAVE"); });
	
	function setFlagInMailView(tag){
		if(activemodule=="mail") {
		    if(view == "detail") {
		        OXMailMapping.setTag(tag,[mail_lastSelectedId]);	
		    } else {
			    OXMailMapping.setTag(tag,view.grid.selection.getSelected());
		    }
		}
	}
	
	registerView("mail",
		null,
		function() {
			register("OX_Add_Flag", setFlagInMailView);	
			register("OX_Mail_Flag", oMailFunctions.markAsFlag);
		    register("OX_Mail_Spam", oMailFunctions.markAsSpam);
            register("OX_Mail_Ham", oMailFunctions.markAsHam);
            register("OX_Mail_Show_Source", oMailFunctions.showMailSource);
           
            setSearch();
            
            ox.widgets.searchField.active().searchMenu.onChange = function() { };
            
		},
		function() {
			if(detailrequest) {
                OXCache.unregister(detailrequest.uniqueName);
                detailrequest=null;
            }
			unregister("OX_Add_Flag", setFlagInMailView);
			unregister("OX_Mail_Flag", oMailFunctions.markAsFlag);
	        unregister("OX_Mail_Spam", oMailFunctions.markAsSpam);
            unregister("OX_Mail_Ham", oMailFunctions.markAsFlag);
			triggerEvent("Selected",[]);
			ox.widgets.searchField.active().searchMenu.setFields();
		},
		null,
		null
	);

	// change the default selected fields checked
	// in the search menu depending on the folder
	function setSearch() {
	    ox.widgets.searchField.active().searchMenu.setFields(
                ["from", "to", "cc", "subject", "mailtext" ],
                [ "From" /*i18n*/, "To"/*i18n*/, "Cc"  /*i18n*/, "Subject" /*i18n*/, "Mailtext" /*i18n*/],
                { from: !isStdFolder("sent"), to: isStdFolder("sent"), cc: false, subject: false, mailtext: false }
        );
	    
	    // change header description if the folder is sent or draft
	    jQuery(".received").text(isStdFolder("sent") ||  isStdFolder("drafts") ? 
	            _("Sent").toString() : _("Received").toString());
	}
	
	/*
	 * The callback when reset the search
	 * @todo: needs to be optimized
	 */
	function updateAfterDeleteSearch() {
		view.grid.searchActive=false;
		if(currentpath[2] == "threaded")
			updateMailStorage("thread", null, "samefolder"); 
		else
			updateMailStorage(null, null, "samefolder");
	};

	registerList("mail/list/unthreaded", list);
	registerList("mail/list/threaded", list, "thread");
	registerList("mail/vsplit/unthreaded", vsplit);
	registerList("mail/vsplit/threaded", vsplit, "thread");
	registerList("mail/hsplit/unthreaded", hsplit);
	registerList("mail/hsplit/threaded", hsplit, "thread");
			   
	function registerList(name, viewObj, param) {
		registerView(name,
			function() {
				showNode("mail."+viewObj.name);
			},
			function(type) {
				view = viewObj;
				if (!view.grid) {
					view.grid = initLiveGrid(view);
				}
				switchGridHeaders(view.grid);
				if (viewObj == vsplit) {
					setVsplitSortEntry();
				} else {
					view.grid.setSort(sort_id, sort_order);
				}
				
				register("OX_New_Search",searchMail);
				setSearch();
				register("OX_Delete_Search",updateAfterDeleteSearch);
				register("OX_Print",mail_printList);
				if (viewObj != list) {
					register("OX_Attachment_SaveInfoStore",mail_saveAttachmentInDocStore);
					switchMailHeaderView(configGetKey("gui.mail.fullmailheader"));
				}
				
		        if (mail_lastSelectedId && mail_lastSelectedId.directLink &&
		            mail_lastSelectedId.id)
				{
		            delete(mail_lastSelectedId.directLink);
		            view.grid.selection.selectIDs([ Key.createfromObject(mail_lastSelectedId) ]);
		        } else {
		            view.grid.selection.selectIDs(
		                view.grid.selection.getSelected());
		        }
				updateMailStorage(param, undefined, type);
				
				// trigger selection event
		        triggerEvent("Selected", view.grid.selection.getSelected());
			}, 
			function() {
				if(detailrequest) {
                    OXCache.unregister(detailrequest.uniqueName);
                    detailrequest=null;
                }    
				if (viewObj !== list) {
					clearMailSplitDetail(view.name);
					unregister("OX_Attachment_SaveInfoStore",mail_saveAttachmentInDocStore);
				}
				unregister("OX_Print",mail_printList);
				unregister("OX_New_Search",searchMail);
				unregister("OX_Delete_Search",updateAfterDeleteSearch);
				if (view.grid && view.grid.storage) {
					old_focus = grid.focus;
                    view.grid.disable();
				} else if(view.grid && view.grid.collection) {
				    old_focus = view.grid.focus;
                    view.grid.disable();
				} 
				// reset iframe container to blank src
			    if ($("mail." + view.name + ".attachment.save")) {
				   $("mail." + view.name + ".attachment.save").src = urlify("newInfoItemHidden.html");
				}				
			},
			function() {
			    triggerEvent('OX_Delete_Search');
				hideNode("mail." + viewObj.name);
			},
			function(type) {
                if(detailrequest) {
                    OXCache.unregister(detailrequest.uniqueName);
                    detailrequest=null;
                }    
				switchGridHeaders(view.grid);				
                // note: do NOT user grid.setSort here as this results in 
                // useless request on the previous selected folder if grid
                // columns changed (eg. Inbox != Sent). The grid.enable followed
                // in updateMailStorage will do the rest! 
				if (sort_order != view.grid.sort_order || sort_id != view.grid.sort_id) {
					view.grid.sort_order = sort_order;
					view.grid.sort_id = sort_id;
				}				
				triggerEvent('OX_Delete_Search');
				setSearch();
				updateMailStorage(param, undefined, type);
			}
		);
	}

	/**
	 * in folder 'Sent' and 'Drafts' we have to use other fields then the
	 * default once. this function switch between these headers and sort parameter 
	 * within the given livegrid. combinations are: folder sent and
	 * drafts -> 'To' and 'Reveived Date', otherwise 'From' and 'Sent Date'
	 * @param grid - {LiveGrid} - the current livegrid 
	 */
	function switchGridHeaders(grid) {
        // update folder name and unread count information for grid header
        //setMailHeaderLabel();
        view.grid.searchActive=false; // set search to inactive, not sure if 

        var sent = isStdFolder("sent") || isStdFolder("drafts");
        if (sent == Boolean(grid.oldSent)) return;
        grid.oldSent = sent;
        
        if (sent) {
            columnFromTo.text = "To"; /*i18n*/
            columnReceivedSent.text = "Sent"; /*i18n*/
            change("from", "to");
            change("received_date", "sent_date");
        } else {
            columnFromTo.text = "From"; /*i18n*/
            columnReceivedSent.text = "Received"; /*i18n*/
            change("to", "from");
            change("sent_date", "received_date");
        }
        
        function change(oldCol, newCol) {
            if (sort_id == oldCol) sort_id = newCol;
            for (var i = 0; i < grid.columns.length; i++) {
                var name = grid.columns[i].name;
                for (var j = 0; j < name.length; j++) {
                    if (name[j] == oldCol) name[j] = newCol;
                }
                if (grid.columns[i].sort == oldCol) {
                    grid.columns[i].sort = newCol;
                }
            }
        }
		
        if (view === vsplit && grid.headers[3]
                            && grid.headers[3].firstChild
                            && grid.headers[3].firstChild.firstChild)
        {
            grid.headers[3].firstChild.firstChild.data = columnFromTo.text;
        }

        grid.recreate();
	}
	
	function mail_saveAttachmentInDocStore() {
	    // single element selected?
	    if (selectedAttachments && selectedAttachments.length == 1) {
	        // get attachment
	        var a = selectedAttachments[0].data;
	        // new dialog
	        ox.api.infostore.composeFromAttachment({
	            params: {
	                attachmail: a.id,
	                filename: a.filename,
	                mailid: message.id, // global magic var
	                mailfolder: message.folder || message.folder_id
	            }
	        });
	    }
	}	
	
	function mail_printList() {
		// if only one object has been selected, print the detail message, otherwise the list
		if (view.grid.selection.getSelected().length != 1) {
		    // print list
		    globalprint.printLiveGrid(view.grid);
		} else {
		    // print single mail
		    var collection={};
            collection.objects=[view.grid.selection.getSelected()[0]];
            // need to get mail out of cache, specially if we don't have all data (like on the list view)
            OXCache.newRequest(null, "mail", collection, null, function (data) {
                if (data.objects.length) {
                    mail_printSingleMail(data.objects[0]);
                }
            });
		}
	}
	
	// magic global function
	mail_printSingleMail = function (omsg, closer) { 
    	var cnn = "", attachmentParam=null;
    	var attachments = [];
        if(omsg["attachments_plain"] && !configGetKey("mail.inlineattachments")) { 
            attachmentParam = omsg["attachments_plain"]; 
        } else if (omsg["attachments_html"] && configGetKey("mail.inlineattachments")) { 
            attachmentParam = omsg["attachments_html"]; 
        } else if (omsg["attachments_html_noimage"] && configGetKey("mail.inlineattachments")) { 
            attachmentParam = omsg["attachments_html_noimage"];
        }
        for (idfield in attachmentParam) {
            var conArr = attachmentParam[idfield];
            var ct = conArr["content_type"] ? conArr["content_type"].toLowerCase() : "application/unknown";
            var con = conArr["content"];
            if (ct.search(/text\//) != -1 && con != null) {
                if (ct.search(/text\/plain/) != -1) {
                    var tmpcnn=(configGetKey("mail.emoticons") ? replaceSmilies(con) : con);
                    tmpcnn=replaceLeadingSpaces(tmpcnn);
                    cnn += "<div style=\"font-family: monospace; line-height: 1.5em;\">" + tmpcnn + "</div>";
                } else { 
                    cnn += "<div>" + con + "</div>";
                }           
            } else if(conArr["filename"]) {
            	attachments.push(conArr);
            }        
        }
        
        if (omsg["nested_msgs"] && omsg["nested_msgs"].length) {
            for (var nMessage = 0; nMessage < omsg["nested_msgs"].length; nMessage++) {
            	var nmg = omsg["nested_msgs"][nMessage];
            	attachments.push({ filename: nmg.filename || nmg.subject, content_type: "message/rfc822", size: nmg.size });	            
            }
        }
        var tmsg = new Object();
        //tmsg["whole_message"] = omsg;
        tmsg["message_text"] = cnn;
        tmsg["message_attachments"] = attachments;
        if (omsg.from) tmsg["from"] = getAdressString(omsg.from, false);
        if (omsg.to)  tmsg["to"] = getAdressString(omsg.to, false);
        if (omsg.cc)  tmsg["cc"] = getAdressString(omsg.cc, false);
        if (omsg.bcc) tmsg["bcc"] = getAdressString(omsg.bcc, false);
        tmsg["date"] = omsg.sent_date;
        tmsg["subject"] = omsg.subject;
        tmsg["priority"] = omsg.priority;
        tmsg["color-label"] = omsg.color_label;
        mail_printDetailMail(tmsg, closer); // closer is passed by ox.api
    };
	
	function clearMailSplitDetail(cview) {	
		$("mail." + view.name + ".detail.header.image_protection").style.display = "none";
		$("mail." + view.name + ".detail.header.phishing_protection").style.display = "none";
		$("mail." + view.name + ".detail.row.organization").style.display = "none";
		jQuery("#mail-" + view.name + "-image").hide();
		
		if($('mail.' + cview + '.detail.header.from'))
			removeChildNodes($('mail.' + cview + '.detail.header.from'));
			
		if($('mail.' + cview + '.detail.header.from_small'))
			removeChildNodes($('mail.' + cview + '.detail.header.from_small'));
	
		if($('mail.' + cview + '.detail.header.to'))
			removeChildNodes($('mail.' + cview + '.detail.header.to'));
				
		if($('mail.' + cview + '.detail.header.cc'))
			removeChildNodes($('mail.' + cview + '.detail.header.cc'));
			
		if($('mail.' + cview + '.detail.header.bcc'))
			removeChildNodes($('mail.' + cview + '.detail.header.bcc'));
	
		$('mail.' + cview + '.detail.header.subject').firstChild.data = "";
		$('mail.' + cview + '.detail.header.subject_small').firstChild.data = "";
		$('mail.' + cview + '.detail.content').src = urlify("newInfoItemHidden.html");
		$('mail.' + cview + '.detail.header.received_date').firstChild.data = "";
		$('mail.' + cview + '.detail.header.received_date_small').firstChild.data = "";
        $("mail." + cview + ".detail.header.imip").style.display = "none";
        $("mail." + cview + ".detail.header.imipreply").style.display = "none";
		var mda = $("mail." + cview + ".detail.attachments");
		removeChildNodes(mda);
		view.setAttachments(false);
		oldMessage = null;
        oldMessageTextType=null;
        selectedAttachments = [];
	}
			
	/**
	 * Update the storage
	 * @param id either "thread" for threaded sorting, or column id for sort
	 * (optional)
	 * @param order either "asc" or "desc" (optional)
	 * @param type type of event which caused the update.
	 * Can be "samefolder", "newfolder" or undefined.
	 */
	function updateMailStorage(id, order, type) {
		sort_id = id || sort_id;
		sort_order = order || sort_order;
		
		var folder = activefolder;
		var grid = view.grid;
						
     	var criteria= { "folder_id" : activefolder };
        grid.disablehover=!configGetKey("gui.effects.hover.mail");
        
        mailSelection.selectedIndex = configGetKey("gui.mail.select_first_message") ? 0 : undefined;
        
        //grid.enable(criteria,null,true); // forces an update each time you change the folder        
        grid.enable(criteria);
	}
	
	function searchMail(sModule, sPattern, field) {
		var criteria= { "folder_id" : activefolder };
        var search = {}; 
		for (var i in ox.widgets.searchField.active().searchMenu.checked) {
            if (ox.widgets.searchField.active().searchMenu.checked[i]) {
                search[i] = sPattern;
            }
        }
		search.operator = "or";
		view.grid.searchActive=true;
		view.grid.enable(criteria,search,false);
		mail_folderPath.drawSearch(sModule, sPattern);
	}

	function setMailHeaderLabel () {		
		if (view.grid && view.grid.searchActive) {
			return;
		}
		// get folder
		ox.api.folder.get({
		    folder: activefolder,
		    success: function (data) {
    		    var panelText = " (";
                if (data.unread !== 0) {
                    //#. Number of unread mails in the header of the mail view
                    //#. %1$s is the number of unread mails
                    //#. %2$s is the total number of mails
                    //#, c-format
                    panelText += format(_("%1$s of %2$s unread"), [data.unread, data.total]);
                } else {
                    panelText += data.total || 0;
                }
                panelText += ")";
    
        		mail_folderPath.additionalNode=document.createTextNode(panelText);
        		mail_folderPath.drawDOMNode("mail."+view.name+".foldername", activefolder);
		    }
		});
	}
	
    function mailHeaderLabelUpdate(data) {
        numberOfMailsinFolder[0] = data.objects.length;
        setMailHeaderLabel();
    }
    
    function mail_setFocus(data, changed) {
    	if (view.grid && view.grid.collection) {
    		if (corewindow.hasFocus) {
    			// do not steal other windows' focus
    			setFocus($("mail." + view.name + ".grid"));
    		}
    		if (mailSelection && mailSelection.count) {
	            var index = view.grid.collection.getIndex(mailSelection.getSelected()[0]);
	            view.grid.focus = index ? index-1 : 0;	            
	        } else if (changed) {
	        	var index = view.grid.focus || 0;
	        	if (index >= view.grid.collection.objects.length) {
	        		index--;
	        	}
	        	view.grid.focus = index;
	        	view.grid.selection.click(index);
	        }
	        view.grid.showFocus();
    	}
    }
	
	/**
	 * Initiate LiveGrid
	 * @param view
	 * @return grid
	 */
	function initLiveGrid(view) {
		var grid;
		if (view === vsplit) {
			grid = initGridHeaderVSplit();
			grid.lineHeight = 3.2;
			grid.getHeader();
			$("mail." + view.name + ".grid.header").appendChild($("mail.vsplit.sortOrderHead"));
		} else {
			grid = initGridHeader();
			$("mail." + view.name + ".grid.header").appendChild(grid.getHeader());
		}
		grid.sort = updateMailStorage;
        grid.getTable($("mail." + view.name + ".grid"));
		var hovercontent = createHoverContent();
		hovercontent.node.style.display="none";
		body.appendChild(hovercontent.node);
		var hv = grid.addHover(OXMailHover.getContent().node, function(id) {
			OXMailHover.accordion.setHover(hv);
			OXMailHover.refillContent(id.id,id.folder_id);
		});
		hv.setSize(OXMailHover.contentobject.node);
		grid.events.register("Activated", function(ids) {
			if (ids && ids.length > 0) {
			    // view mail
			    ox.api.mail.view({
			        params: {
			            id: ids[0].id, folder: ids[0].folder || ids[0].folder_id
			        },
			        data: [ ids[0].id, (ids[0].folder || ids[0].folder_id)]
			    });
			} else {
				triggerEvent("OX_NEW_MAIL");
			}
		});
		
		grid.events.register("Delete", function(ids){
			deleteMails(activefolder, ids) 
		});
		
		grid.events.register("Changed",mailHeaderLabelUpdate);
//		grid.events.register("Changed",mail_setFocus);
		
		// livegrid single click or selection
		grid.events.register("Selected", updateDetailView);
		
		mailSelection.selectedIndex = configGetKey("gui.mail.select_first_message") ? 0 : undefined;
		
		return grid;
	}
	
	function getMailText(mail) {
		for (var i = 0; i < mail.attachments.length; i++) {
			var part = mail.attachments[i];
			if (part.disp == "attachment") continue;
			switch (part.content_type.toLowerCase()) {
				case "text/plain": return part.content;
				case "text/html":  return _("HTML-only mail");
			}
		}
		return _("No text");
	}
	
	function updateDetailView(count, viewObj) {		
		if (!viewObj) viewObj = view;
		var ids = viewObj.grid.selection.getSelected();
		triggerEvent("Selected", ids);
        triggerEvent("SubSelected",  []); //disable attachments first
		if (count != 0) {
			mail_lastSelectedId = ids[0];
			if (viewObj !== list) {
				if(count == 1) {
					fetchMessage(viewObj, mail_lastSelectedId);
				} else
					clearMailSplitDetail(viewObj.name);
			} else {
				mail_message = message = mail_lastSelectedId;
			}
		} else if (viewObj !== list)
			clearMailSplitDetail(viewObj.name);
		
        triggerEvent("OX_Selected_Draft", isStdFolder("drafts"));
	}
    
    var columnFromTo, columnReceivedSent;
	temporary.lists.mail = temporary.MakeList({
        addIcon: function(icon) {
            if (icon.name) {
                for (var i = 0; i < icon.name.length; i++) {
                    var n = icon.name[i];
                    Search: {
                        for (var j = 0; j < vSplitColumn.name.length; j++) {
                            if (n == vSplitColumn.name[j]) break Search;
                        }
                        vSplitColumn.name.push(n);
                    }
                }
            }
            vSplitTemplate().getElementsByTagName("tr")[4].appendChild(
                newnode("td", 0, { className: "vsplitImg" }, [
                    newnode("img", 0, { src: getFullImgSrc("img/dummy.gif") })
                ]));
            vSplitColumn.icons.push(icon);
            temporary.MakeList.addIcon.call(this, icon);
            if (vsplit.grid) vsplit.grid.recreate();
        },
        updated: function() {
            if (list.grid) list.grid.recreate();
            if (hsplit.grid) hsplit.grid.recreate();
        },
        columns: [
            {
                text: "&#x00a0;",
                sortable: false,
                name : ["priority"],
                width: "20px",
                style: { padding:0, textAlign:"center" },
                set: function(div, content) {
                    var src;
                    switch (content) {
                        case 1:
                        case 2:
                            src = getFullImgSrc("img/mail/email_priohigh.gif");
                            break;
                        case 4:
                        case 5:
                            src = getFullImgSrc("img/mail/email_priolow.gif");
                            break;
                        default:
                            src = getFullImgSrc("img/mail/noattachment.gif");
                    }
                    if (!div.firstChild) {
                        div.appendChild(newnode("img", {height : "14px", width : "14px"}, {src: getFullImgSrc("img/mail/noattachment.gif"), align: "absmiddle"}));
                    }
                    div.firstChild.src = src;
                },
                clear: function(div) {
                    if (!div.firstChild) {
                        div.appendChild(newnode("img", {height : "14px", width : "14px"}, {src: getFullImgSrc("img/mail/noattachment.gif"), align: "absmiddle"}));
                    } else {
                        div.firstChild.src = getFullImgSrc("img/mail/noattachment.gif");
                    }
                }
            }, {
                name : ["attachment"],
                text: "&#x00a0;",
                sortable: false,
                width: "20px",
                style: { padding:0, textAlign:"center" },
                set: function(div, content) {
                    if (!div.firstChild) {
                        div.appendChild(newnode("img", {height : "14px", width : "7px"}, {src: getFullImgSrc("img/mail/noattachment.gif"), align: "absmiddle"}));
                    }
                    div.firstChild.src = getFullImgSrc("img/mail/" + (content ? "attachment.gif" : "noattachment.gif"));
                },
                clear: function(div) {
                    if (!div.firstChild) {
                        div.appendChild(newnode("img", {height : "14px", width : "7px"}, { src: getFullImgSrc("img/mail/noattachment.gif"), align: "absmiddle"}));
                    } else {
                        div.firstChild.src = getFullImgSrc("img/mail/noattachment.gif");
                    }
                }
            }, {
                text: "&#x00a0;",
                sortable: true,
                name : ["flags"],
                sort : "flags_sort",
                width: "26px",
                style: { padding:0, textAlign:"center" },
                set: function(div, content) {
                    if (!div.firstChild) {
                        div.appendChild(newnode("img", {height : "16px", width : "16px"}, {src: getFullImgSrc("img/mail/read.gif"), align: "absmiddle"}));
                    }
                    div.firstChild.src = getFullImgSrc("img/mail/" + getMailFlagImage(content));
                },
                clear: function(div) {
                    if (!div.firstChild) {
                        div.appendChild(newnode("img", {height : "16px", width : "16px"}, {src: getFullImgSrc("img/mail/read.gif"), align: "absmiddle"}));
                    } else {
                        div.firstChild.src = getFullImgSrc("img/mail/read.gif");
                    }
                }
            }, columnFromTo = {
                text: "From",  /*i18n*/
                name : ["from","level","flags"],
                sort : "from",
                i18n: true,
                sortable: true,
                width: "25%",
                set: function(div, content) {
                    if(isStdFolder("sent") || isStdFolder("drafts")) {
                        var aAddressToShow = content["to"] || [];
                    } else {                        
                        var aAddressToShow = content["from"] || [];
                    }              
                    // address string (remove quoting marks
                    var addressString = getAdressString(aAddressToShow, true);
                    addressString = addressString.replace(/(^"|"$)/g, '');
                    // div.style.paddingLeft = content.level + "em";
                    var padding = "";
                    for (var i = 0; i < 20 && i < content["level"]; i++)
                        padding += "\u00a0\u00a0\u00a0";
                    if (div.firstChild)
                        div.firstChild.data = padding + addressString;
                    else
                        div.appendChild(newtext(padding + addressString));
                    //deleted                                                   
                    div.style.textDecoration =  content["flags"] & 2 ? "line-through" : "none";
                    //unread
                    div.parentNode.style.fontWeight = content["flags"] & 32 ? "normal" : "bold";
                    //person
                    div.className = "cell font-style-person";
                },
                clear: clear
            }, {
                text: "Subject", /*i18n*/
                i18n: true,
                name : ["subject","flags","account_name"],
                sort : "subject",
                sortable: true,
                set: function(div, content) {
                    removeChildNodes(div);
                    if (content.account_name && ox.api.folder.is("unifiedmail", { id: content.folder_id })) {
                        div.appendChild(newnode("span", 0,
                            { className: "accountLabel" }, [newtext(content.account_name)]));
                    }
                    div.appendChild(newtext(content.subject || "\u00a0"));
                    //deleted
                    div.style.textDecoration =  content["flags"] & 2 ? "line-through" : "none";
                },
                clear: function(div) { removeChildNodes(div); }
            }, columnReceivedSent = {                
                text: "Received", /*i18n*/
                i18n: true,
                sortable: true,
                name : ["received_date","flags"],
                sort : "received_date",
                width: "11em",
                set: function(div, content) {
                    var dateToShow = content["received_date"];
                    if (isStdFolder("sent") || isStdFolder("drafts")) {
                        dateToShow = content["sent_date"];
                    }
                    dateToShow = dateToShow ? formatDate(dateToShow, isToday(dateToShow) ? "time" : "datetime") : "";
                    if (!div.firstChild) {
                        div.appendChild(div.ownerDocument.createTextNode(dateToShow));
                    } else {
                        div.firstChild.data = dateToShow;
                    }
                    //deleted       
                    div.style.textDecoration =  content["flags"] & 2 ? "line-through" : "none";
                },
                clear: clear
            }, {
                text: "Size", /*i18n*/
                i18n: true,
                sortable: true,
                name : ["size","flags"],
                sort : "size",
                width: "6em",
                style: {textAlign: "right"},
                set: function(div, content) {
                    var text = bytesToString(content["size"]);
                    if (!div.firstChild)
                        div.appendChild(div.ownerDocument.createTextNode(text));
                    else
                        div.firstChild.data = text;
                    //deleted       
                    div.style.textDecoration =  content["flags"] & 2 ? "line-through" : "none";
                },
                clear: clear
            }, {
                text: "Flag", /*i18n*/
                i18n: true,
                name : ["color_label"],
                sort : "color_label",
                sortable: true, 
                width: "4.5em",
                style: {textAlign: "center"},
                set: function(div, text) {
                    if (!div.firstChild)
                        div.appendChild(newnode("img", {height : "16px", width : "16px"},
                            { src: getFullImgSrc("img/menu/tag_" + (text || 0) + ".gif") }));
                    else
                        div.firstChild.src = getFullImgSrc("img/menu/tag_" + (text || 0) + ".gif");
                },
                clear: function(div) {
                    if (!div.firstChild)
                        div.appendChild(newnode("img", { height : "16px", width : "16px" },
                            { src: getFullImgSrc("img/menu/tag_0.gif"), align: "absmiddle" }));
                    else
                        div.firstChild.src = getFullImgSrc("img/menu/tag_0.gif");
                }
            }
        ]
    });
	
	/**
	 * init grid for normal views
	 */
	function initGridHeader() {
		var grid = new LiveGrid2(temporary.lists.mail.columns,
		                         mailSelection, "mail");
		grid.contextmenu = globalContextMenus.mail;
        
		return grid;
	}
		
	var vSplitTemplate = function() {
	    var template = $("mail.vsplit.row");
        template.parentNode.removeChild(template);
        template.id = "";
        template.style.display = "";
        vSplitTemplate = function() { return template; };
        return template;
    };
	
    var vSplitColumn = {
        text: "",
        name: ["level","attachment","from","subject","received_date","size","flags","priority","color_label", "account_name"],
        sortable: false,
        height: "3.2em",
        style: { borderBottom: "1px solid silver" },
        set: function(div, content) {
            if (!div.firstChild) {
                div.appendChild(vSplitTemplate().cloneNode(true));
            }
            var tds = div.getElementsByTagName("td");
            var sent = isStdFolder("sent") || isStdFolder("drafts");
            function setIcon(index, path, width) {
                var fullpath = path.charAt(0) == "/" ? path.substring(1)
                                                     : getFullImgSrc(path);
                if (tds[index].firstChild.src != fullpath) {
                    tds[index].firstChild.src = fullpath;
                    if (width) tds[index].style.width = width;
                }
            }

            // attachment
            setIcon(0, "img/mail/"+getMailFlagImage(content["flags"]));

            // to / from
            var aAddressToShow = content[sent ? "to" : "from"] || [];
            var addressString = getAdressString(aAddressToShow, true);
            // remove quoting marks
            addressString = addressString.replace(/(^"|"$)/g, '');
            tds[2].firstChild.data = addressString;    
            //deleted
            tds[2].style.textDecoration = content["flags"] & 2 ? "line-through" : "none";
            
            // date
            var dateToShow = content[sent ? "sent_date" : "received_date"];
            if (dateToShow && isToday(dateToShow)) {
                tds[3].className="vsplitDateShort"
            } else if (tds[3].className != "vsplitDate") {
                tds[3].className="vsplitDate";
            }
            tds[3].firstChild.data=dateToShow ? formatDate(dateToShow, isToday(dateToShow) ? "time" : "date") : "";
            tds[3].style.textDecoration = content["flags"] & 2 ? "line-through" : "none";
            
            //subject
            if (tds[5].firstChild.data != content["subject"]) {
            	removeChildNodes(tds[5]);
                if (content.account_name && ox.api.folder.is("unifiedmail", { id: content.folder_id })) {
                	var newChild = tds[5].appendChild(newnode("span", 0,
                        { className: "accountLabel" }, [newtext(content.account_name)]));
                	tds[5].appendChild(newtext(content["subject"]));
                } else {
                	tds[5].appendChild(newtext(content["subject"]));
                }
            	
                tds[5].style.textDecoration = content["flags"] & 2 ? "line-through" : "none";
            }
            
            for (var i = 0; i < this.icons.length; i++) {
                if (this.icons[i].isVisible(content)) {
                    setIcon(i + 6, this.icons[i].getIcon(content),
                                   this.icons[i].width);
                } else {
                    setIcon(i + 6, "img/dummy.gif", "0");
                }
            }
                                
            div.parentNode.style.fontWeight = (content["flags"] & 32) ? "normal" : "bold";                                  
            
        },
        icons: [
            {
                isVisible: function(d) {
                    return d.priority &&
                        d.priority != 0 && d.priority != 3;
                },
                getIcon: function(d) {
                    return "img/mail/email_prio" +
                        (d.priority <= 3 ? "high" : "low") + ".gif";
                },
                width: "12px"
            }, {
                isVisible: function(d) { return d.attachment; },
                getIcon: function(d) {
                    return "img/mail/attachment.gif";
                },
                width: "12px"
            }, {
                isVisible: function(d) { return d.color_label; },
                getIcon: function(d) {
                    return "img/menu/tag_" + (d.color_label || 0) +
                           ".gif";
                },
                width: "20px"
            }
        ],
        clear: function(div) {
            if (!div.firstChild) {
                div.appendChild(vSplitTemplate().cloneNode(true));
            }
            
            var tds = div.getElementsByTagName("td");
            var dummy = getFullImgSrc("img/dummy.gif");
            function clear(index, property, path, width) {
                if (tds[index].firstChild[property] != path) {
                    tds[index].firstChild[property] = path;
                    if (width) tds[index].style.width = 0;
                }
            }
            clear(0, "src", dummy);
            clear(2, "data", "");
            clear(3, "data", "");
            clear(5, "data", "");
            for (var i = 6; i < tds.length; i++) {
                clear(i, "src", dummy, true);
            }
        }
    };
    
    function initGridHeaderVSplit() {
		var grid = new LiveGrid2([vSplitColumn], mailSelection, "mail");
        grid.contextmenu = globalContextMenus.mail;
		
		return grid;
	}
	
	function getMailFlagImage(flag) {
	    if ((flag & 0x101) == 0x101) return "reply_forward.gif";
	    if (flag & 0x100) return "forward.gif";
	    if (flag & 0x001) return "reply.gif";
	    if (flag & 0x002) return "deleted.gif";
	    if (flag & 0x020) return "read.gif";
	    return "unread.gif";
    }
	
	/**
	 * Open a new message window
	 */
	function newMail(action) {

	    var data = { multiForward: [] };
	    
	    // fill object for multiple selected messages, eg. on a forward
	    var selection = mailSelection.getSelected(), i = 0, $l = selection.length;
	    for (; $l > 1 && i < $l; i++) {
	        data.multiForward.push({ folder: selection[i].folder_id, id: selection[i].id });
        }

        // compose message
	    ox.api.mail.open({
	        params: {
	            action: action
	        },
	        message: message || undefined,
	        data: data
	    });
	}

	/**
	 * Delete messages
	 */	
	function deleteMails(folder, ids, harddelete) {
		// update unread status after deleting a message
		function cb_delete() {
		    ox.api.folder.refresh({ folders: [folder] });
		}
        // return if ids is empty or a delete is still in progress
        if (!ids || ids.length == 0) return;
		if (harddelete || configGetKey("mail.deletemail") || configGetKey("mail.folder.trash") == folder) {
            newConfirm(_("Delete E-Mails"),_('Are you sure you want to delete the selected E-Mails?'),AlertPopup.YESNO,null,null,
            function () {
                OXMailMapping.deleteObjects(ids,true,cb_delete)
                if (corewindow.hasFocus) {
                    setFocus($("mail." + view.name + ".grid"));
                }
            }, null);
		} else {
            OXMailMapping.deleteObjects(ids,false,cb_delete);
		}
		
	}
	
	function callbackMailStyle(index, updatedData) {
		if(!(updatedData[8] & 32)) {
			updatedData[8] = updatedData[8] + 32;
			return updatedData;
		} else
			return null;
	}
	
	var fetchJSON = new JSON();
	var lastID = null, lastRequest = null;
	var detailNestedMessage = null;
	var oldMessage = null;
    var oldMessageTextType=null;
	var oldView=null;
	function fetchMessage(view, id, loadblocked) {
	    loadblockedimages = Boolean(loadblocked);
	    mail_message = message = id;
	    var collection={};
		collection.objects=[id];
		if (configGetKey("mail.inlineattachments")) {
			if(configGetKey("modules.mail.allowhtmlimages") || loadblockedimages) {
		        collection.columns=OXMailMapping.GETHTML;		
			} else {
				collection.columns=OXMailMapping.GETHTMLNOIMAGE;
			}
		} else {
			collection.columns=OXMailMapping.GETPLAIN;
		}
		
		/* fixed bug #11462 */
		function markRead(object) {
			if (view.name != "list" && !(object["flags"] & 32) && message != lastID) {
			     OXMailMapping.setMailFlags("seen",[object]);
			}
		}
		
		if (detailrequest) { 
			OXCache.unregister(detailrequest.uniqueName); 
		}
		detailrequest = OXCache.newRequest(null, "mail", collection,
			function(daten) {
				if (daten.objects.length) {
					mailFetchTimestamp = daten.timestamp;
			        updateMessage(view, daten.objects[0], id.folder_id);
			        lastID = id;
			    }
			},
			function(daten) {
			    if (daten.objects.length) {
					mailFetchTimestamp = daten.timestamp;
			        markRead(daten.objects[0]);
			        lastID = id;
			        if (daten.objects[0]["headers"]) {
		            	showMessage(view, daten.objects[0],id.folder_id);
		            }
		        }
			}
		);
	}
	function updateMessage(view, message, folder) {		
        if ("color_label" in message) {
            if ($('mail.' + view.name + '.detail.flag')) { 
                $('mail.' + view.name + '.detail.flag').src =
                    getFullImgSrc("img/menu/tag_" + message["color_label"] + ".gif");
            }
        }
        if ("flags" in message) {
            if ($('mail.' + view.name + '.detail.mailflag')) {
               $('mail.' + view.name + '.detail.mailflag').src =
                   getFullImgSrc("img/mail/" + getMailFlagImage(message["flags"]));
            }
        }
    }
	function showMessage(view, message, folder) {
        var attachExists = false, nested_msgs = null;		
		if (view != oldView) {
            oldMessage=null, oldMessageTextType=null;
        }
        for (idfield in message) {
			var newField = message[idfield];
			var oldField = (oldMessage) ? oldMessage[idfield] : null;
			if (newField == null && idfield != "subject") { continue; }
			if (newField == oldField) { continue; }
			if (equals(newField, oldField)) { continue; }
						
			var oDivEmails = $("mail." + view.name + ".detail.header." + idfield);          
            var oDivEmailsSmall = $("mail." + view.name + ".detail.header." + idfield + "_small");
			switch(idfield) {
				case "cc":
                case "bcc":
				    $("mail." + view.name + ".detail.content").style.visibility="hidden";
				    if (newField == "") { 
				    	$("mail." + view.name + ".detail.row." + idfield).style.display = "none"; 
				    } else if(newField != "") { 
				    	$("mail." + view.name + ".detail.row." + idfield).style.display = ""; 
				    }
				case "to":
				    $("mail." + view.name + ".detail.content").style.visibility="hidden";
				case "from":				
				    $("mail." + view.name + ".detail.content").style.visibility="hidden";
				    removeChildNodes(oDivEmails);
				    removeChildNodes(oDivEmailsSmall);
				    
                    getAdressStringLinked(oDivEmails, newField, configGetKey("gui.mail.showname"));
                    if (oDivEmails) {
                        oDivEmails.style.height = 1.6 + "em";
                        if (oDivEmails.scrollHeight > 22) { 
                            oDivEmails.style.height = oDivEmails.clientHeight * 2 + "px"; 
                        }                                                               
                    }
                    
                    if (oDivEmailsSmall) {
                        // in small view, always prefer name (-> true)
                        getAdressStringLinked(oDivEmailsSmall, newField, true);
                    }
                    
                    newField = null;
            	    break;
            	case "received_date" :
            	    dateToShow = newField;
            	    if (isStdFolder("sent") || isStdFolder("drafts")) {
                        dateToShow = message["sent_date"];
                    }            	    
				    $("mail." + view.name + ".detail.content").style.visibility="hidden";
				    if (dateToShow) {
				        newField = formatDate(dateToShow, isToday(dateToShow) ? "time" : "datetime");
				    } else {
				        newField = " ";
				    }
					break;
				case "color_label":
				    $("mail." + view.name + ".detail.content").style.visibility="hidden";
					if ($('mail.' + view.name + '.detail.flag')) { 
						$('mail.' + view.name + '.detail.flag').src = getFullImgSrc("img/menu/tag_" + (newField||0) + ".gif");
					}
					break;
				case "nested_msgs":
				    $("mail." + view.name + ".detail.content").style.visibility="hidden";
				    if(newField.length > 0) { nested_msgs = newField; attachExists = true; }
					break;
				case "flags":
				    $("mail." + view.name + ".detail.content").style.visibility="hidden";
					if ($('mail.' + view.name + '.detail.mailflag')) {
                       $('mail.' + view.name + '.detail.mailflag').src = getFullImgSrc("img/mail/"+getMailFlagImage(newField));
					}
					break;
				case "priority" :
				    $("mail." + view.name + ".detail.content").style.visibility="hidden";
				    if ("mail." + view.name + ".detail.header.prority") {
				    	var divPrio = $('mail.' + view.name + '.detail.header.prority');
				    	divPrio.style.display = "";
                        if (newField < 3) {
                            divPrio.src = getFullImgSrc("img/mail/email_priohigh.gif");      
                        } else if (newField > 3) {
                            divPrio.src = getFullImgSrc("img/mail/email_priolow.gif");
                        } else {
                        	divPrio.style.display = "none";
                        }
					}
					break;
				case "subject" :
				    $("mail." + view.name + ".detail.content").style.visibility="hidden";
					if (!newField) {
						oDivEmails.firstChild.data = " ";
                        oDivEmailsSmall.firstChild.data = " ";
					}
					break;
			 }
		     if (oDivEmails && newField) {
		         $("mail." + view.name + ".detail.content").style.visibility="hidden";
				 oDivEmails.firstChild.data = newField;	 	
			 }	
		     if (oDivEmailsSmall && newField) {
			 	 $("mail." + view.name + ".detail.content").style.visibility="hidden";
                 oDivEmailsSmall.firstChild.data = newField;
             }
        }
        
        if (configGetKey("gui.mail.showimage")) {
            ox.mail.drawContactImage(message.from[0][1]);
        }
        
        jQuery("#mail\\.hsplit\\.detail\\.header\\.from span.sender").remove();
    	jQuery("#mail\\.hsplit\\.detail\\.header\\.from_small span.sender").remove();
        
        // append or clear 'on behalf of' string if sender != from
        if (message["headers"] && message["headers"]["Sender"] &&
        		message["from"] != message["headers"]["Sender"]) {
        	var text = newtext(format(_("%1$s on behalf of"), [ message["headers"]["Sender"] ]) + " ");
        	jQuery("#mail\\.hsplit\\.detail\\.header\\.from span").
        		before(newnode("span", 0, { className: "sender" }, [ text.cloneNode(true) ]));
        	jQuery("#mail\\.hsplit\\.detail\\.header\\.from_small span").
        		before(newnode("span", 0, { className: "sender" }, [ text.cloneNode(true) ]));
        }
        
        // field organization
        if (message["headers"] && message["headers"]["Organization"]) {
        	$("mail." + view.name + ".detail.header.organization").firstChild.data = message["headers"]["Organization"];
            $("mail." + view.name + ".detail.row.organization").style.display = "";
        } else {
        	$("mail." + view.name + ".detail.row.organization").style.display = "none";
        }

        var mda = $("mail." + view.name + ".detail.attachments");        
        var cnn = "";
        var attachmentParam=null;
        var newMessageTextType=null;
		var mailtextchanged=false;
		if(message["attachments_plain"] && !configGetKey("mail.inlineattachments")) { 
			attachmentParam=message["attachments_plain"]; 
			newMessageTextType="attachments_plain"; 
		} else if (message["attachments_html"] && configGetKey("mail.inlineattachments")) { 
			attachmentParam=message["attachments_html"]; 
			newMessageTextType="attachments_html"; 
		} else if(message["attachments_html_noimage"] && configGetKey("mail.inlineattachments")) { 
			attachmentParam=message["attachments_html_noimage"]; 
			newMessageTextType="attachments_html_noimage"; 
		}
				
		if (!oldMessageTextType || !oldMessage || newMessageTextType!= oldMessageTextType || !equals(message[newMessageTextType], oldMessage[newMessageTextType])) {
			removeChildNodes(mda);
			mailtextchanged=true;
			$("mail." + view.name + ".detail.content").style.visibility="hidden";
			for (idfield in attachmentParam) {
                var conArr = attachmentParam[idfield];
                var ct = conArr["content_type"] ? conArr["content_type"].toLowerCase() : "application/unknown";
                var con = conArr["content"];
                if (ct.search(/text\//) != -1 && con != null) {
                    if (ct.search(/text\/plain/) != -1) {
                        var tmpcnn=(configGetKey("mail.emoticons") ? replaceSmilies(con) : con);
                        tmpcnn=replaceLeadingSpaces(tmpcnn);
                        cnn += "<div class=\"plainTextContent\">" + tmpcnn + "</div>";
                    } else {
                        cnn += "<div>" + con + "</div>";
                    }           
                }
                if (   conArr.disp != "inline"
                    || ct.search(/text\//) < 0 || con == null)
                {
                    if (conArr["filename"]) {
                        var aimg = getMimeImage(ct).match(/empty.png/g) ? getFullImgSrc("img/mail/attachment.gif") : getMimeImage(ct.toLowerCase());
                        attachExists = true;
                        
                        var oDOMDiv = newnode("div", { MozUserSelect: "none" }, { className: "mailDetailAttachmentsCont" },[
						  newnode("img", { verticalAlign: "middle" }, { src: aimg, padding: "3px" }),
                          //#. Displayed label for attachments
                          //#. %1$s is the file name.
                          //#. %2$s is the file size.
                          //#, c-format
                          newnode("span",0,{ className: "nothing" }, [ document.createTextNode(format(_(" %1$s (%2$s) "), 
                        		  conArr["filename"], bytesToString(conArr["size"]))) ])
                        ]); 
                        // prevent text selection on dbl click
                        oDOMDiv.onselectstart = function() { return false; };
                        (function(selAttach) {
                        	var wrapper = function(e) {                    		
                        		selectAttachment(selAttach, (Mac ? e.metaKey : e.ctrlKey), false);
                        	};
                            addDOMEvent(oDOMDiv, "click", wrapper);
                            addDOMEvent(oDOMDiv, "dblclick", function(e) { 
                                openAttachment("OPEN");
                            });
                            addDOMEvent(oDOMDiv, "contextmenu", function(e) {
                            	stopEvent(e);
                                selectAttachment(selAttach, false, true);
                                globalContextMenus.attachments.display(
                                    e.clientX, e.clientY);
                            });                            
                            if (menucountsubselected == 0) {
                            	selectAttachment(selAttach, false, false);
                            }
                        })({ node: oDOMDiv, data: conArr}); 
                        mda.appendChild(oDOMDiv);
                    } else {
                        removeChildNodes(mda);
                    }
                }               
            }
		
			if (nested_msgs && nested_msgs != null) {	
			    $("mail." + view.name + ".detail.content").style.visibility="hidden";
				mailtextchanged=true;
				for (var nMessage = 0; nMessage < nested_msgs.length; nMessage++) {
					(function(o) {
						var oNestedMessage = new Array(nested_msgs[o]);
						var textAttachment = newtext(nested_msgs[o].filename || nested_msgs[o].subject || "message/rfc822 Part" );
						var blank = document.createTextNode(" ");
						var oDOMDiv = newnode("div", { MozUserSelect: "none" }, { className: "mailDetailAttachmentsCont" },
							[ newnode("img",0,{ src: getFullImgSrc("img/mail/unread.gif"), align: "top", title: textAttachment.data, padding: "3px"}),
							  	newnode("span",0,{className: "_nothing"},
							  		[ blank ]
							  	),
							  	newnode("span", 0, {className: "_nothing", title: textAttachment.data },
							  		[ textAttachment ]
							  	)
							]
						);
						// prevent text selection on dbl click
                        oDOMDiv.onselectstart = function() { return false; };
						(function(oDOMDiv, selNested_msgs) {
							var wrapper = function(e) {
                        		selectAttachment({ node: oDOMDiv, data: selNested_msgs.length ? selNested_msgs[0] : selNested_msgs}, (Mac ? e.metaKey : e.ctrlKey), false);
								detailNestedMessage = selNested_msgs;
								detailNestedMessage.sid = o;
                        	};
                            addDOMEvent(oDOMDiv, "click", wrapper);
	                        addDOMEvent(oDOMDiv, "contextmenu", function(e) {
	                            stopEvent(e);
	                            selectAttachment({ node: oDOMDiv, data: selNested_msgs.length ? selNested_msgs[0] : selNested_msgs}, false, true);
	                            detailNestedMessage = selNested_msgs;
	                            detailNestedMessage.sid = o;
	                            globalContextMenus.attachments.display(e.clientX,
	                                                                   e.clientY);
	                        });
	    					addDOMEvent(oDOMDiv, "dblclick", function(e) {
	    						cancelBubbling(e);							
								detailNestedMessage = selNested_msgs;
								detailNestedMessage.sid = o;
								openNestedMessage();	
							});
	    					if (menucountsubselected == 0) {
	                        	selectAttachment({ node: oDOMDiv, data: selNested_msgs.length ? selNested_msgs[0] : selNested_msgs}, false, false);
	                        	detailNestedMessage = selNested_msgs;
								detailNestedMessage.sid = o;
								menucountsubselected=1;
	                        }
						})(oDOMDiv, oNestedMessage);
						mda.appendChild(oDOMDiv);
					})(nMessage)
				}	
			}
		
		}
		
        // pishing protection enabled?
		var showPhishingWarn=false;
		if (configContainsKey("modules.mail.phishingheaders") && message["headers"]) {
			var psa = configGetKey("modules.mail.phishingheaders");
			for (ba in psa) {
				if (message["headers"][psa[ba]]) {
					showPhishingWarn = true;
					break;
				}
			}			
		}		
        if (showPhishingWarn) {
            $("mail."+view.name+".detail.header.phishing_protection").style.display="";
        } else {
            $("mail."+view.name+".detail.header.phishing_protection").style.display="none";
        }
		// do we have to enable image protection?
		if (message["attachments_html_noimage"] && !message["attachments_html"] && message["blocked_images"]) {
			//TODO CHECK IF EXISTS IMAGE WHICH ARE REMOVED IN NOIMAGE-ATTACHMENTS
			$("mail."+view.name+".detail.header.image_protection").style.display="";
		} else {
			$("mail."+view.name+".detail.header.image_protection").style.display="none";
		}
		
		
		// iMIP
		var methodRE = /;\s*method\s*=\s*(?:([-!#-'*+.0-9A-Z^-~]*)|"([\cA-\b\cK\cL\cN-\x1f!#-[\]-\x7f]*)")/i;
		var iMIPRequest = $("mail." + view.name + ".detail.header.imip");
        var iMIPReply = $("mail." + view.name + ".detail.header.imipreply");
        
        var iMIPAttachments = message.attachments_html ||
            message.attachments_html_noimage || message.attachments_plain;
		checkiMIP: {
            if (iMIPAttachments) {
        		for (var i = 0; i < iMIPAttachments.length; i++) {
        		    var match = methodRE.exec(iMIPAttachments[i].content_type);
        		    if (match) switch ((match[1] || match[2]).toLowerCase()) {
        		        case "request":
        		            iMIPAccept = makeAccept(message.folder_id,
        		                                    message.id,
        		                                    iMIPAttachments[i].id);
                            $("mail." + view.name + ".detail.header.imip.note").value = "";
                            iMIPRequest.style.display = "";
                            iMIPReply.style.display = "none";
                            break checkiMIP;
        		        case "reply":
        		            iMIPUpdate = makeUpdate(message.folder_id,
                                                    message.id,
                                                    iMIPAttachments[i].id);
                            iMIPRequest.style.display = "none";
        		            iMIPReply.style.display = "";
        		            break checkiMIP;
        		    }
        		}
            }
    		iMIPRequest.style.display = "none";
            iMIPReply.style.display = "none";
		}
        function makeAccept(folder, id, cid) {
            return function(status) {
                ox.JSON.put(
                    AjaxRoot + "/conversion?action=convert&session=" + session,
                    {
                        datasource: {
                            identifier: "com.openexchange.mail.ical",
                            args: [
                                { "com.openexchange.mail.conversion.fullname":
                                    folder },
                                { "com.openexchange.mail.conversion.mailid":
                                    id },
                                { "com.openexchange.mail.conversion.sequenceid":
                                    cid }
                            ]
                        },
                        datahandler: {
                            identifier: "com.openexchange.ical",
                            args: [
                                   { "com.openexchange.groupware.calendar.folder":
                                       configGetKey("folder.calendar") },
                                   { "com.openexchange.groupware.task.folder":
                                       configGetKey("folder.tasks") },
                                   { "com.openexchange.groupware.calendar.confirmstatus":
                                       status },
                                   { "com.openexchange.groupware.calendar.confirmmessage":
                                       $("mail." + view.name + ".detail.header.imip.note").value },
                            ]
                        }
                    },
                    function() {
                        ox.Configuration.info(_("Confirmation sent."));
                    }
                );
            };
        }
        function makeUpdate(folder, id, cid) {
            return function() {
                ox.JSON.put(
                    AjaxRoot + "/conversion?action=convert&session=" + session,
                    {
                        datasource: {
                            identifier: "com.openexchange.mail.ical",
                            args: [
                                { "com.openexchange.mail.conversion.fullname":
                                    folder },
                                { "com.openexchange.mail.conversion.mailid":
                                    id },
                                { "com.openexchange.mail.conversion.sequenceid":
                                    cid }
                            ]
                        },
                        datahandler: {
                            identifier: "com.openexchange.ical.json",
                            args: [
                                { "com.openexchange.groupware.calendar.searchobject":
                                    true }
                            ]
                        }
                    },
                    function(reply) {
                        var map = {};
                        for (var i = 0; i < reply.data.length; i++) {
                            var o = { folder: reply.data[i].folder_id,
                                      id: reply.data[i].id };
                            if (!o.id || !o.folder) {
                                ox.Configuration.error(format(
                                    //#. %s is the title of the appointment
                                    //#, c-format
                                    _("Appointment '%s' not found."),
                                    reply.data[i].title));
                                return;
                            }
                            map[o.folder_id + "\0" + o.id] = o;
                        }
                        var objects = [];
                        for (var i in map) objects.push(map[i]);
                        ox.JSON.put(AjaxRoot +
                            "/calendar?action=list&columns=1&recurrence_master=true&session=" +
                            session, objects, handleList);
                        function handleList(reply2) {
                            var multiple = [];
                            function add(appt, list) {
                                for (var i = 0; i < list.length; i++) {
                                    multiple.push({
                                        module: "calendar",
                                        action: "confirm",
                                        id: appt.id,
                                        folder: appt.folder_id,
                                        timestamp: reply2.timestamp,
                                        data: list[i]
                                    });
                                }
                            }
                            for (var i = 0; i < reply.data.length; i++) {
                                var a = reply.data[i];
                                if (a.confirmations) add(a, a.confirmations);
                                if (a.users) add(a, a.users);
                            }
                            
                            ox.JSON.put(
                                AjaxRoot + "/multiple?session=" + session,
                                multiple, function() {
                                    ox.Configuration.info(
                                        _("Update successful"));
                                });
                        }
                    }
                );
            };
        }
        
        triggerEvent("OX_Mail_load", message, view.name);
		
		// get frame
		var ih = getFrameElement("mail." + view.name + ".detail.content");
		var ihf = ih;
		
		// set attachment display
		if (mailtextchanged) {
			$("mail." + view.name + ".detail.content").style.visibility = "hidden";			
			view.setAttachments(attachExists);
			if (ih && ih.document) {
				ih = ih.document;
				ih.open();
				// safari needs explicit head/body "around" the content
				ih.writeln("<html><head><title></title></head><body>" + cnn + "</body></html>");
				ih.close();
				setTimeout(function(){	
                    var head = ih.getElementsByTagName("head");
                    var body = ih.getElementsByTagName("body");
                    var colorQuoted = configGetKey("mail.colorquoted") === true;
					if (head && head.length) {
						// would not work for safari without explicit head tag
						head[0].appendChild(				   
					       newnode("link", null,{ type: "text/css", rel: "stylesheet", href: ox.gui.themePath + "css/iframe.css" }, null, ih));
					}
					try {
					    if (body && body.length) {
					        // set margin
					        body[0].style.margin = ".5em";
					        // colored quotes?
					        if (colorQuoted) {
					            body[0].className = "colored-quotes";
					        }
					    }
					} catch (e) {
					}
					parseDirectLinksInMails(ih);
					// reset scroll position
					if (ihf) ihf.scrollTo(0,0);
					
					// tracking hasFocus
					// using DOM level 0 events to overwrite previous handlers
					if (!IE) {
    					ih.onblur = function() { hasFocus = false; };
                        ih.onfocus = function() { hasFocus = true; };
					}
				}, 0);
			}
		} else {
			// reset scroll position
			if (ihf) ihf.scrollTo(0,0);
		}

        // do we have to send a disposition notification?
		if (!oldMessage || !equals(message["id"], oldMessage["id"])) {
			var dm = message["disp_notification_to"];
			if (configGetKey("gui.mail.notifyacknoledge") && 
			     !isStdFolder("drafts") && (dm && dm != null && dm != "")) {
				var cbyes = (function(from, id, folder_id) {
					return function() {
						var mail_pn = getPersonalFullName() ? "\"" + getPersonalFullName() + "\" " : "";
						var mail_sa = configGetKey("mail.sendaddress") ? configGetKey("mail.sendaddress") : "undefined";
						if (getMailAccountIdByFolder(activefolder) != 0) {
							mail_pn = "";
							mail_sa = getMailAccountEmailAddress(getMailAccountIdByFolder(activefolder));
						}						
						var dispObj = { "id": id, "folder": folder_id, "from": mail_pn + "<" + mail_sa + ">" };
						new JSON().put(AjaxRoot + "/mail?action=receipt_ack"
						   + "&folder=" + encodeURIComponent(folder_id) 
						   + "&session=" + session 
						   + "&id=" + encodeURIComponent(id), dispObj, null, function(result) {});
					   }					   
					})(message.from, message.id, message.folder_id);
				newConfirm(_('Do you want to send a delivery receipt?'), 
				    _("Subject:") + " " + (message["subject"] || ""), 
				    AlertPopup.YESNO, null, null, cbyes, null, null);
				// setting disposition_notif in cache to null to prevent showing this dialog again and again
				OXMailMapping.editObjectsInternal([{"module": "mail", "folder_id": message.folder_id, "id": message.id}], { "disp_notification_to": null });
			}
		}
		detailmessage=new Object();
		detailmessage["whole_message"]=message;
		detailmessage["message_text"]=cnn;
		if(message.from) detailmessage["from"]=getAdressString(message.from, false);
		if(message.to) detailmessage["to"]=getAdressString(message.to, false);
		if(message.cc) detailmessage["cc"]=getAdressString(message.cc, false);
		if(message.bcc) detailmessage["bcc"]=getAdressString(message.bcc, false);
		detailmessage["date"]=message.sent_date;
		detailmessage["subject"]=message.subject;
		detailmessage["priority"]=message.priority;
		detailmessage["color-label"]=message.color_label;
		oldMessageTextType=newMessageTextType;
		oldMessage=clone(message);
		oldView=view;
	    // enable content display
        setTimeout(function() { 
        	$("mail." + view.name + ".detail.content").style.visibility="visible"; 
        }, 0);
	}
	
	function selectAttachment(selAttach, multi, context) {
		// check if click is a context click and if click was on already selected item
		for (var i in selectedAttachments) {
			if (selectedAttachments[i].node == selAttach.node && context) {
				return;
			}			
		}
		var nAtt = [], found = false;
		for (var i in selectedAttachments) {
			var attach = selectedAttachments[i];
			if ((!multi || (multi && attach.node == selAttach.node)) && attach.node.className.match(/mailDetailAttachmentsContSel/)) {
				attach.node.className = "mailDetailAttachmentsCont";
				found = (multi && attach.node == selAttach.node);
			} else if (multi) {
				nAtt.push(attach);
			}
		}
		selectedAttachments = nAtt;
		if (!found) {
			selAttach.node.className = "mailDetailAttachmentsContSel background-color-PMG-selection-elements";
			selectedAttachments.push(selAttach);
		}
		
		triggerEvent("OX_Selected_Nested", false);
		triggerEvent("SubSelected", [ selectedAttachments ]);
	}
	
	function openNestedMessage() {
		// view mail
		var detailMail = ox.api.mail.view({
	        params: {
	            type: "isNestedMessage",
	            id: message.id,
	            folder: message.folder || message.folder_id,
	            sid: detailNestedMessage.sid
	        },
	        data: {
	        	oNestedMessage: detailNestedMessage
	        }
	    });
		
	}
	
	openAttachment = function(action) {		
		var selAttach = selectedAttachments[0].data;
		if (action != "SAVE" && (isVcard(selAttach.content_type) || isIcal(selAttach.content_type))) {
			showIcalVcard(selAttach);
			return;
		}
		var tF = $("mail." + view.name + ".attachment.save");
		var n_url = AjaxRoot + '/mail'
			 + '?action=' + (action == "SAVE" && 
					 selectedAttachments.length > 1 ? "zip_attachments" : "attachment")
			 + '&session=' + session 
			 + '&folder=' + encodeURIComponent(message.folder || message.folder_id)
			 + '&id=' + encodeURIComponent(message.id)			 
		if (action == "OPEN") {
			var attachWin = newWindow(
				n_url + "&attachment=" + selAttach.id + "&save=0&filter=1",
				getWindowOptions(null, null, "scrollbars=yes"),
				[(message.folder || message.folder_id), message.id, selAttach.id]);
			if (attachWin) {
				attachWin.focus();
			}
			try {
				attachWin.document.title = selAttach.filename;
			} catch (e) { }
		} else if (action == "SAVE" && tF && tF.src) {
			var mattachments = "&attachment="
			for (var i in selectedAttachments) {
				mattachments += selectedAttachments[i].data.id + ",";
			}
			tF.src = n_url + mattachments.substring(0, mattachments.length-1) + "&save=1";
		} else {
			//#. %s will be replaced with an internal error code
		    //#, c-format
			triggerEvent("OX_New_Error", 4, format(_("Internal Error: Unable to open the Attachment (%s)."), "MA01"));
		}
	}
		
	function MailFunctions() { }
	
	MailFunctions.prototype = {
		showMailSource : function(messageObj) {
			var mailSource = null;
			var mailViewSourceObject = null;
			if (messageObj)
				mailViewSourceObject = messageObj;
			else if (message)
				mailViewSourceObject = message;	
			else
			    mailViewSourceObject = mailSelection.getSelected()[0];						
			
			ox.api.mail.showSource({
			    params: {
			        folder: mailViewSourceObject.folder_id,
			        id: mailViewSourceObject.id
			    },
			    mail: mailViewSourceObject
			});
		},
		markAsFlag: function(mailFlag) {
            OXMailMapping.setMailFlags(mailFlag,menuselectedobjects);
        },
        /**
         * marks a message as spam
         * @param Object msg - an object containing message information, e.g. folder_id, id and module
         *                     if not set, current selected objects will be taken instead
         */
        markAsSpam: function(msg) {
        	if (msg) {
        		msg = [ OXMailMapping.createKeyFromObject(clone(msg)) ];
        	}
            OXMailMapping.setMailFlags("spam", msg || menuselectedobjects);
        },
        markAsHam: function() {
            OXMailMapping.setMailFlags("ham",menuselectedobjects);
        }
	}
	
	oMailFunctions = new MailFunctions();
	
	/**
	 * Switches between the full mail header and the small mail header in the
	 * current view. Note: the view object must be correctly set!
	 * @param fullHeader true = full mail header, otherwise false
	 */
	switchMailHeaderView = function (fullHeader) {
		var fh = $("mail." + view.name + ".detail.header.table");
		var sh = $("mail." + view.name + ".detail.header.table_small");				
		if (!fh.style.display && fullHeader)
			return; // nothing to do
		
		var img = $("mail." + view.name + ".detail.header.header_switch");
		img.src = fullHeader ? getFullImgSrc("img/minus.gif") : getFullImgSrc("img/plus.gif");
		fh.style.display = fullHeader ? "" : "none";
		sh.style.display = fullHeader ? "none" : "";
		
		// resize address fields (maybe it's better to use the resized event?!
		var fields = ["to","cc","bcc"];
		for (var i=0; i<fields.length; i++) {
			var mf = $("mail." + view.name + ".detail.header." + fields[i]);			
			if (mf && mf.scrollHeight > 22) { 
	            mf.style.height = mf.clientHeight * 2 + "px"; 
	        }
		}
		view.setAttachments($("mail." + view.name + ".detail.attachments").style.height != "0px");
		
		configSetKey("gui.mail.fullmailheader", fullHeader);
	}
	
	loadBlockedImages = function() {
		if (currentpath[1] != "list") {
		  fetchMessage(view, mail_lastSelectedId, true);
		}
	}
	
	/**
	 * Change sort order at the vsplit view
	 */
	function setVsplitSortEntry(field, order) {
		sort_id = field || sort_id;
		if (order) { 
			sort_order = (typeof order == "boolean" ? (sort_order == "asc" ? "desc" : "asc") : sort_order = order);
		}
		$("mail.vsplit.sortOrder").replaceChild(newnode("span",0,0,[sortType[sort_id]]), $("mail.vsplit.sortOrder").firstChild);
		$("mail.vsplit.sortType").firstChild.data=(sort_order == "asc" ? _("ascending") : _("descending"));
		$("mail.vsplit.sortTypeImg").src = getFullImgSrc(sort_order == "asc" ? "img/arrows/sort_up.gif" : "img/arrows/sort_down.gif");

        if (sort_id != view.grid.sort_id || sort_order != view.grid.sort_order) {
        	view.grid.setSort(sort_id, sort_order);
        }
	}
	
	/**
	 * Init sort menu at the vsplit view
	 */
	initVsplitSortMenu = function() {		
		var menu = new PulldownMenu($("mail.vsplit.sortOrder"));
        function newitem(text, field) {
            var item = new MenuItem(text,
                function() { setVsplitSortEntry(field); });
            menu.addItem(item);
            return item;
        }
        var from     = newitem(_("From"),        "from");
        var to       = newitem(_("To"),          "to");
                       newitem(_("Subject"),     "subject");
        var sent     = newitem(_("Sent"),        "sent_date");
        var received = newitem(_("Received"),    "received_date");
                       newitem(_("Size"),        "size");
                       newitem(_("Read/Unread"), "flags_sort");
                       newitem(_("Flag"),        "color_label");
        menu.onShow = function() {
            var sentFolder = isStdFolder("sent") || isStdFolder("drafts");
            from.setVisible(!sentFolder);
            to.setVisible(sentFolder);
            sent.setVisible(sentFolder);
            received.setVisible(!sentFolder);
        };
        
		addDOMEvent($("mail.vsplit.sortType"), "mousedown", function() {
						setVsplitSortEntry(null,true);
					});
	}
	
})();

function isStdFolder(folder) {
    return (activefolder == configGetKey("mail.folder." + folder));
}

function updateDraftsFolderCache(delid, newid) {
	if (delid)
		OXMailMapping.deleteObjectsInternal( 
		  [ OXMailMapping.createKeyFromObject(
		      { module: "mail", 
		        folder_id: configGetKey("mail.folder.drafts"), 
		        id: delid }) ], true);
	if (newid)
		OXMailMapping.createObjectsInternal( 
		  [ OXMailMapping.createKeyFromObject(
		      { module: "mail", 
		        folder_id: configGetKey("mail.folder.drafts"), 
		        id: newid }) ], true);
}

/**
 * Updates sytem flags of the given message in object cache
 * @param folder_id - The folder id
 * @param object_id - The object id
 * @param flags - {object} new system flags 
 */
function updateMailFlagsInternal(folder_id, object_id, flags) {
	OXMailMapping.editObjectsInternal([
	       OXMailMapping.createKeyFromObject({ 
	       	       module: "mail", folder_id: folder_id, id: object_id 
	       	   })], null,true, [flags]);
}

function deleteAutosaveMessage(folder, id, harddelete) {
	OXMailMapping.deleteObjects(
	       [ OXMailMapping.createKeyFromObject(
	           { module: "mail", 
	             folder_id: folder, 
	             id: id }) 
	       ], harddelete);
}

function jumpToMailConfiguration(divId){
	if(divId && $(divId))
		$(divId).style.display = 'none';
	triggerEvent("OX_Switch_View","configuration/mail/preferences");
}

function getRefToMainForMailPopup() {
	return window;
}

/**
 * Returns a formatted String of the given Address Array
 * @param Address Array (see HTTP-API specification)
 * @param personal flag, true = only add personal address informations
 */
function getAdressString(addresses, personal) {
	var retVal = "";
	for (a = 0; a < addresses.length; a++) {
		var q1 = "", q2 = "";
		if (addresses[a][0] != null) {
			retVal += addresses[a][0];
			q1 = " <", q2 = ">";
		}
		if ((!personal || addresses[a][0] == null) && addresses[a][1] != null)
			retVal += q1 + addresses[a][1] + q2;
				
		if ((addresses.length-1) > a)
			retVal += ", ";
	}
	return retVal;
}

function sendMailToRecipientMail(recipient) {
	if(recipient && recipient != "") {
		ox.api.mail.compose({
			data: {
				to: [[recipient]]
			}
		});
	}
}

function mail_quoteHTMLTags(val) {
	return val || val.replace(/</gi,"&lt;").replace(/"/gi,"&quot;"); 
}

function mail_printDetailMail(messageobject, closer) {	
	if(!messageobject)
		messageobject=detailmessage;

	var mailprintarray=new Array();
	mailprintarray.push(Print.createTitle(messageobject.subject));
	mailprintarray.push(Print.createLine("5px"));
	mailprintarray.push(Print.createEmpty());
	if(messageobject.from)
		mailprintarray.push(Print.createContent(_("From:"),mail_quoteHTMLTags(messageobject.from)));
	if(messageobject.to)
		mailprintarray.push(Print.createContent(_("To:"),mail_quoteHTMLTags(messageobject.to)));
	if(messageobject.cc)
		mailprintarray.push(Print.createContent(_("Cc:"),mail_quoteHTMLTags(messageobject.cc)));
	if(messageobject.bcc)
		mailprintarray.push(Print.createContent(_("Bcc:"),mail_quoteHTMLTags(messageobject.bcc)));
	mailprintarray.push(Print.createEmpty());
	if(messageobject.priority) {
		switch(messageobject.priority) {
			case 1:
				mailprintarray.push(Print.createContent(_("Priority:"),_("Very high")));
				break;
			case 2:
				mailprintarray.push(Print.createContent(_("Priority:"),_("High")));
				break;
			case 3:
				mailprintarray.push(Print.createContent(_("Priority:"),_("Normal")));
				break;
			case 4:
				mailprintarray.push(Print.createContent(_("Priority:"),_("Low")));
				break;
			case 5:
				mailprintarray.push(Print.createContent(_("Priority:"),_("Very low")));
				break;
		}
	}
	if(messageobject.date) {
		var datestring=formatDate(new Date(messageobject.date),"datetime");
		mailprintarray.push(Print.createContent(_("Date"),datestring));
	}
	mailprintarray.push(Print.createLine("2px"));
	mailprintarray.push(Print.createEmpty());
	mailprintarray.push(Print.createMail(messageobject.message_text));	
	
	mailprintarray.push({ type: "mailattachments", "mailattachments" : messageobject.message_attachments});
	
	//TODO MAIL
	var mailprint=new Print(messageobject.subject);
	mailprint.printDetail(mailprintarray, closer || jQuery.noop);
}

register("Loaded", function() {
    var ids = ["arrowForMailListOptions", "arrowForMailVSplitOptions",
               "arrowForMailHSplitOptions"];
    for (var i in ids) {
        var menu = new PulldownMenu($(ids[i]));
        menu.addItem((new MenuItem(_("Options"), showOptions))
                     .setIcon("img/folder/settings.gif"));
    }
	function showOptions() { 
		var elem=currentpath2.join("/");
		if(elem.indexOf("mail") == 0) {
			ox.UIController.setModule({
			    module: "configuration",
			    view :"configuration/mail/preferences",
			    success: function() {
			        ox.widgets.configTree.get("configuration/mail").open();
			        ox.widgets.configTree.selection.click("configuration/mail/preferences", false,
	                    false, true);
			    }
			});
	 	}	
	};
		
	initVsplitSortMenu();
});

// set some default config options, if not already set
register("OX_Configuration_Loaded_Complete",function () {
	if (!configContainsKey("gui.mail.fullmailheader")) {
		configSetKey("gui.mail.fullmailheader",true);
	}
});

register("OX_Plugins_Loaded",function () {

    // unread counter
    (function () {
        // figures
        var unread = 0;
        var total = 0;
        
        // fn
        var start, stop, getAttention, timer = null, toggle = true, previousTitle = "";

        var start = function () {
            if (timer === null) {
                previousTitle = document.title;
                timer = setInterval(getAttention, 1500);
            }
        };
        
        var stop = function () {
            clearInterval(timer);
            timer = null;
            document.title = previousTitle;
        };
        
        // blinking document title
        var getAttention = function () {
            // stop on focus
            if (hasFocus) {
                stop();
            } else {
                document.title = toggle ? _("New E-Mail") : previousTitle;
                toggle = !toggle;
            }
        };
        
        ox.api.folder.dispatcher.bind("update", function () {
            
            // feature active?
            if (configGetKey("mail.folder.inbox")) {
                
                // get folder statistics
                var stats = ox.api.folder.derive("stats");
                
                // changed?
                if (stats.unread > unread) {
                    // get attention
                    start();
                    // trigger event (with number of new mails)
                    triggerEvent("OX_New_Unread_Mail", stats.unread);
                }
                
                // remember stats
                unread = stats.unread;
                total = stats.total;
            }
        }, window);
    }());
});


fileloaded();