/**
 * 
 * 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) 2004-2010 Open-Xchange, Inc.
 * Mail: info@open-xchange.com 
 * 
 * @author Stefan Preuss <stefan.preuss@open-xchange.com>
 * @author Suphi Basdemir <suphi.basdemir@open-xchange.com>
 * 
 */

var refToMain = ox.api.window.core;
var session = refToMain.session;
var config = refToMain.config;
var isPrintableView = refToMain.isPrintableView;
var registerPrintView = refToMain.registerPrintView;
var OXMailMapping = refToMain.OXMailMapping, OXCache = refToMain.OXCache;
var oSel = -1, nested_msgs = "", detailmessage, propertiesPopUp;
var attachExists=false, mailFetchTimestamp, detailrequest, message = new Object();
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 regexps = [];
for (var i in smilies) regexps.push(i.replace(/([$^\\.*+?()[\]{}|])/, "\\$1"));
var regexpstr = "(^| |\\n|<br>)(" + regexps.join("|") + ")";
var regexp = new RegExp(regexpstr, "g");
var sortVsplitHeader;
var triggerReady = jQuery.noop;

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("");
		});
}

function getMailDetailObject() {
	var myobject = {};
	myobject.id = url["id"];
	myobject.folder_id = url["folder"] || url["folder_id"]; 
	return myobject;
}

var menucheckRight=function(right) {
	return refToMain.menuhasRight([getMailDetailObject()],right);	
}

registerPrintView("mail_detail");

//var oNestedMessage = null;
function loadDetailMail() {	
	activemodule="mail_detail";
	initContents("mail_detail");
	mail_message = getMailDetailObject();
	initAll();
}

//function getRefToMainForMailPopup() {	
//	return refToMain || window.opener;
//}

function triggerEventInOpener(eventToTrigger) {
	refToMain.triggerEvent(eventToTrigger);
}

function isStdFolder(folder) {
    return (url["folder"] == ox.api.config.get("mail.folder." + folder));
}

register("Loaded", initMailDetail);
register("OX_Attachment_Open", function() { openAttachment("OPEN"); });
register("OX_Attachment_Open_Nested", function(){ openNestedMessage() });
register("OX_Attachment_Save", function() { openAttachment("SAVE"); });
register("OX_Attachment_SaveInfoStore", mail_saveAttachmentInDocStore);
register("OX_Add_Flag", setFlagInMailView);
register("OX_Mail_Close", function() { ox.api.window.close(url.guid); });
register("OX_Cancel_Object", function() { ox.api.window.close(url.guid); });
register("OX_Mail_Delete", 
		function() {
			deleteMails(url["folder"], 
                    [ OXMailMapping.createKeyFromObject(
                        { module: "mail", 
                          folder_id: url["folder"], 
                          id: url["id"] }) 
                    ]);
		}
	);
register("OX_Mail_SaveMail", 
		function() {
			var tF = parent.frames["mail.detail.pop.attachment.save"];	
			var n_url = AjaxRoot + '/mail?action=get'
				+ '&session=' + session + '&folder=' + encodeURIComponent(url["folder"])
				+ '&id=' + encodeURIComponent(url["id"]);
			tF.location.href=n_url+"&src=1&save=1";
		}
	);	
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_Mark", mail_mark);
register("OX_Mail_Flag", markAsMail);
register("OX_Mail_Spam", markAsSpam);
registerView("mail_detail",
	null,
	function() { 
		register("OX_Print", mail_printDetailMail);
		register("OX_Mail_Show_Source", mail_showMailSource);
		triggerEvent("OX_Selected_Draft", isStdFolder("drafts"));
	}, 
	function () {
		unregister("OX_Print", mail_printDetailMail);
		unregister("OX_Mail_Show_Source", mail_showMailSource);
        triggerEvent("OX_Selected_Draft", false);
	},
	function () {
	    triggerEvent('OX_Delete_Search');
        triggerEvent("OX_Selected_Draft", false);
	},
	null
);

function mail_saveAttachmentInDocStore() {
    // get attachment
	var a = selectedAttachments[0].data;
	// compose from attachment
	ox.api.infostore.composeFromAttachment({
	    params: {
	        attachmail: a.id,
	        filename: a.filename,
	        mailid: url.id,
	        mailfolder: url.folder
	    },
	    id: { folder: message.folder_id, id: message.id, attach_id: a.id },
	    success: function (win) {
	        corewindow.propertiesPopUp = win;
	    }
	});
}
	
/**
 * Delete messages
 */ 
function deleteMails(folder, ids) {         
    // return if ids is empty or a delete is still in progress
    if (!ids || ids.length == 0) return;
    function cb() {
        if (corewindow.currentpath.join("/").match(/^mail\//) && corewindow.grid) {
            var focusPos = corewindow.grid.focus;
            var obj = corewindow.grid.collection.objects[focusPos];
            if(corewindow.grid.collection.objects.length) {
                corewindow.grid.selection.click(obj ? focusPos : 0);  
            }            
        }
        setTimeout(function() { 
        	ox.api.window.close(url.guid);
        }, 0);
    }
    if (configGetKey("mail.deletemail") || configGetKey("mail.folder.trash") == url["folder"]) {
        newConfirm(_("Delete E-Mails"),_('Are you sure you want to delete the selected E-Mails?'),AlertPopup.YESNO,null,null,
        function () {
            corewindow.OXMailMapping.deleteObjects(ids,true,cb)
        }, null);
    } else {
        corewindow.OXMailMapping.deleteObjects(ids,false,cb);
    }
}

/**
 * updates the flag image
 * @param - {int} new flag bitmask
 */
function setFlagImage(flagsMessage) {
    var fimg = "unread.gif";
    if (flagsMessage & 2) {
       fimg = "deleted.gif";
    } else if (flagsMessage & 1) {
        fimg = "reply.gif";
    } else if (flagsMessage & 256) {
        fimg = "forward.gif";
    } else if (flagsMessage & 32) {
        fimg = "read.gif";
    }   
    $('mail.detail.pop.detail.mailflag').src = getFullImgSrc("img/mail/" + fimg);
}

function mail_mark() {
	$("menu_mail_flags").style.display="block";
	if(refToMain.menucheckRight("READ")) {
		$("menu_mail_flags_seen").style.display="";
		$("menu_mail_flags_unseen").style.display="";
	} else {
		$("menu_mail_flags_seen").style.display="none";
		$("menu_mail_flags_unseen").style.display="none";
	}
	if(refToMain.menucheckRight("DELETE")) {
		$("menu_mail_flags_delete").style.display="";
		$("menu_mail_flags_undelete").style.display="";
	} else {
		$("menu_mail_flags_delete").style.display="none";
		$("menu_mail_flags_undelete").style.display="none";
	}
	if(refToMain.menucheckRight("WRITE")) {
		$("menu_mail_flags_answer").style.display="";
		$("menu_mail_flags_unanswer").style.display="";
	} else {
		$("menu_mail_flags_answer").style.display="none";
		$("menu_mail_flags_unanswer").style.display="none";
	}
}

/**
 * Marks message as Spam 
 */
function markAsSpam() {
    corewindow.oMailFunctions.markAsSpam({ module: "mail", folder_id: url["folder"], id: url["id"] });
    triggerEvent("OX_Mail_Close");
}

/**
 * Marks message as 'Answered, Read, Deleted, ...' 
 * @param - mailFlag
 */
function markAsMail(mailFlag) {
	OXMailMapping.setMailFlags(mailFlag, [ 
		       OXMailMapping.createKeyFromObject({ 
	       	       module: "mail", folder_id: url["folder"], id: url["id"] 
	           }) 
           ]); 
}

/**
 * Sets message color tag
 * @param - tag
 */
function setFlagInMailView(tag){
    OXMailMapping.setTag(tag, [ 
               OXMailMapping.createKeyFromObject({ 
                   module: "mail", folder_id: url["folder"], id: url["id"] 
               }) 
           ]);
}

/**
 * Open a new message window
 */
function newMail(action) {
    // use api
    ox.api.mail.open({ params: {
        folder: url.folder, id: url.id, action: action
    }});
}
	
function initMailDetail() {
	session = refToMain.session;
	
	var themeStyle = corewindow.oxThemeStyle || { name: "Default", path: "default" };
    removeCSSFilesForNewWindow(themeStyle.path);
	loadCSSFileForNewWindow("themes/"+themeStyle.path+"/css/popup.css");
	
	var detailedMail = {};
	detailedMail.id = url["id"];
	detailedMail.folder_id = url["folder"];
	detailedMail.type = url["type"];
	var aObjectMail = new Array(detailedMail);
	
    // adding new menu 
    ox.gui.initToolBarNewWindowMailDetail();
    
    // bind close button to "Window Close" events for intercom
    window.onunload = function () {
        ox.api.window.core.triggerEvent("OX_Window_Close", {
            handle: url.guid
        });
    };
    
    triggerReady = function () {
        
        // disable loading screen
        $("loading_data_bg").style.display = "none";

        // special intercom object
        var intercomWindowData = {
            handle: url.guid,
            type: "email",
            id: url.id ? url.id : null,
            folder_id: url.folder ? url.folder : null,
            title: window.document.title
        };
        
        // triggerEvent "Window Ready" for intercom with special intercom Object and whole window object
        ox.api.window.core.triggerEvent("OX_Window_Ready", intercomWindowData, window);
    };
    
    setTimeout(function () { 
        triggerEvent("OX_Switch_View","mail_detail");
        initMessageContent(corewindow.loadblockedimages);
        triggerEvent("Selected", aObjectMail); 
    }, 0);
}

var loadBlockedImages = function() {
    initMessageContent(true);
    // corewindow only needs to force upodate if the same 
    // message is still selected
    if (corewindow.mail_lastSelectedId.id == message.id) {
        setTimeout(corewindow.loadBlockedImages,0);
    }
}

function initMessageContent(loadblockedimages) {
	var oNestedMessage = ox.api.window.getData(url.guid).oNestedMessage;
	if (oNestedMessage && oNestedMessage.length) {
		message.id = oNestedMessage[0].id;
		message.folder_id = message.folder_id || url["folder"];
		oNestedMessage[0].folder_id = message.folder_id;
		fillContentsFromJson(oNestedMessage[0], message.folder_id);
	} else {
		message.id = url["id"]
		message.folder_id = url["folder"];
				
		var collection={};
        collection.objects=[OXMailMapping.createKeyFromObject(
	              { module: "mail", 
	                folder_id: message.folder_id, 
	                id: message.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;
        }
		
		if (detailrequest) { OXCache.unregister(detailrequest.uniqueName); }
		
		// get mail
		var cont = function (daten) {
            if (daten.objects[0]) {
                mailFetchTimestamp = daten.timestamp;
                fillContentsFromJson(daten.objects[0], message.folder_id);
            }
        };
            
		detailrequest = OXCache.newRequest(null, "mail", collection, cont, cont, false, triggerReady);
	}
}

function fillContentsFromJson(message, folder) {
	nested_msgs = "";
	if(message["nested_msgs"] && message["nested_msgs"].length) {
		nested_msgs = message["nested_msgs"];
		attachExists = true;
	}
	detailmessage=new Object();
	detailmessage["whole_message"]=message;
	if(message["from"])
		detailmessage["from"]=refToMain.getAdressString(message["from"], false);
	if(message["to"])  
		detailmessage["to"]=refToMain.getAdressString(message["to"], false);
	if(message["cc"])  
		detailmessage["cc"]=refToMain.getAdressString(message["cc"], false);
	if(message["bcc"])  
		detailmessage["bcc"]=refToMain.getAdressString(message["bcc"], false);
	detailmessage["date"]=message["sent_date"];
	detailmessage["subject"]=message["subject"];
	detailmessage["priority"]=message["priority"];
	detailmessage["color-label"]=message["color_label"];
	
	// set document title as well
	var title = message["subject"] || "";
	document.title = _("E-Mail") + (title ? ": " : "") + title;
	
	$("mail.detail.pop.detail.row.organization").style.display="none";
	if (message["headers"] && message["headers"]["Organization"]) {
		$("mail.detail.pop.detail.header.organization").firstChild.data=message["headers"]["Organization"];
		$("mail.detail.pop.detail.row.organization").style.display="";
	}
	
	var from = setAdressHeader("from", message["from"]);
	if (from && message["headers"] && message["headers"]["Sender"] && 
			message["from"] != message["headers"]["Sender"]) {
    	from.insertBefore(newtext(format(_("%1$s on behalf of"), [ message["headers"]["Sender"] ]) + " "), 
    			from.firstChild);
	}
	setAdressHeader("to", message["to"]);
	setAdressHeader("cc", message["cc"]);
	setAdressHeader("bcc", message["bcc"]);
	
	setColor_label(message["color_label"]);
	setSubject(message["subject"]);
	setPriority(message["priority"]);
	setDate(message["received_date"] || message["sent_date"]);
	setMessageText(message);
	msgref = message["msgref"];
	setFlagImage(message["flags"]);
	
    triggerReady();
}

function setColor_label(colorlabel) {
    $("mail.detail.pop.detail.flag").src = getFullImgSrc("img/menu/tag_"+(colorlabel||0)+".gif");
}

function setHeightOfEmailDiv(oDiv){
    oDiv.style.height = 1.6 + "em"; 
    if (oDiv.scrollHeight > 22) {
        oDiv.style.height = oDiv.clientHeight *2 + "px";
    }
}

function setAdressHeader(fType, address) {
    var oDivEmails = $("mail.detail.pop.detail.header." + fType);
    var rDivEmails = $("mail.detail.pop.detail.row." + fType);
    if (rDivEmails && address && address == "") {
        rDivEmails.style.display ="none";
        oDivEmails.firstChild.nodeValue = "";
    } else if (oDivEmails && address && address != "") {
        removeChildNodes(oDivEmails);
        if (rDivEmails != undefined) rDivEmails.style.display="";
        getAdressStringLinked(oDivEmails, address, false);
    }
    setTimeout(function() { 
        setHeightOfEmailDiv(oDivEmails); 
	}, 0);   
    
    return oDivEmails;
}

function setPriority(priority) {
    if ("mail.detail.pop.detail.header.prority") {
        var divPrio = $("mail.detail.pop.detail.header.prority");
        divPrio.style.display = "";
        if (priority < 3) {
            divPrio.src = getFullImgSrc("img/mail/email_priohigh.gif");      
        } else if (priority > 3) {
            divPrio.src = getFullImgSrc("img/mail/email_priolow.gif");
        } else {
            divPrio.style.display = "none";
        }
    }
}

function setSubject(subject) {
    if (subject)
        $("mail.detail.pop.detail.header.subject").firstChild.nodeValue = subject;  
}

function setDate(date) {
    if (date) {
        date = refToMain.formatDate(date, "datetime");
        $("mail.detail.pop.detail.header.received_date").firstChild.nodeValue = date;   
    }
}

var detailNestedMessage = null;
function setMessageText(message) {
	var mda = $("mail.detail.pop.detail.attachments");
	removeChildNodes(mda);
	
	var cnn = "", mdac = "";
    var attachmentParam=null;
    var newMessageTextType=null;
    var attachments = [];    
    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"; 
    } else if (message["attachments"]) {
        attachmentParam=message["attachments"]; 
        newMessageTextType="attachments";     	
    }
    
	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>";
			}			
		} else {	
			if(conArr["filename"]) {
				attachments.push(conArr);				
				
				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);
                    	menucountsubselected = 1;
                    }
                })({ node: oDOMDiv, data: conArr}); 
                mda.appendChild(oDOMDiv);
			} else {
				removeChildNodes(mda);
			}
		}		
	}
	detailmessage["message_text"]=cnn;
	
	if(nested_msgs && nested_msgs != "") {	
		for(var nMessage = 0; nMessage < nested_msgs.length; nMessage++) {
			(function(o) {
				var oNestedMessage = new Array(nested_msgs[o]);
				attachments.push({ filename: nested_msgs[o].filename || nested_msgs[o].subject, content_type: "message/rfc822", size: nested_msgs[o].size });
				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;
						if (!detailNestedMessage.sid) 
							detailNestedMessage.sid = !isNaN(url["sid"]) ? url["sid"] + nMessage : nMessage;
                	};
                    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;
                        if (!detailNestedMessage.sid) 
                            detailNestedMessage.sid = !isNaN(url["sid"]) ? url["sid"] + nMessage : nMessage;
                        globalContextMenus.attachments.display(e.clientX,
                                                               e.clientY);
                    });
					addDOMEvent(oDOMDiv, "dblclick", function(e) {
						cancelBubbling(e);							
						detailNestedMessage = selNested_msgs;
						if (!detailNestedMessage.sid) 
							detailNestedMessage.sid = !isNaN(url["sid"]) ? url["sid"] + nMessage : nMessage;
						openNestedMessage();	
					});
					if (menucountsubselected == 0) {
                    	selectAttachment({ node: oDOMDiv, data: selNested_msgs.length ? selNested_msgs[0] : selNested_msgs}, false, false);
                    	detailNestedMessage = selNested_msgs;
                    	if (!detailNestedMessage.sid) 
							detailNestedMessage.sid = !isNaN(url["sid"]) ? url["sid"] + nMessage : nMessage;
						menucountsubselected=1;
                    }
				})(oDOMDiv, oNestedMessage);
				mda.appendChild(oDOMDiv);
			})(nMessage)
		}
	}
	
	detailmessage["message_attachments"] = attachments;
    
    // do we have to enable pishing protection?
    $("mail.detail.pop.header.phishing_protection").style.display="none";
    if (configContainsKey("modules.mail.phishingheaders") && message["headers"]) {
        var psa = configGetKey("modules.mail.phishingheaders");
        for (ba in psa) {
            if (message["headers"][psa[ba]]) {
                $("mail.detail.pop.header.phishing_protection").style.display="";
                break;
            }
        }           
    }
    
    // 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.detail.pop.header.image_protection").style.display="";
    } else {
        $("mail.detail.pop.header.image_protection").style.display="none";
    }  	
		
	var ih = getFrameElement("mail.detail.pop.detail.content");
    if (ih && ih.document) {
        ih = ih.document;
        ih.open();
        ih.writeln(cnn);
        ih.close();
        setTimeout(function(){                                      
            var head = ih.getElementsByTagName("head");
            if (head && head.length) {
                head[0].appendChild(
                   newnode("link",null,{type : "text/css",  rel:"stylesheet", href : ox.gui.themePath + "css/iframe.css" },null,ih));
            }
            try {
				ih.getElementsByTagName("body")[0].style.margin=".5em";
			} catch (e) { }
            parseDirectLinksInMails(ih);
        }, 0);
    }
    setTimeout(function () { 
    	resizeSplit(mda.id, attachExists ? "3.19em" : "0em"); 
    }, 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.length);
}

function openNestedMessage() {
	// view mail
	var detailMail = ox.api.mail.view({
        params: {
            id: url.id,
            folder: url.folder,
            sid: detailNestedMessage.sid,
            type: "isNestedMessage"
        },
		data: {
            oNestedMessage: detailNestedMessage
        }
    });
	
	
	/*
	var detailMail=corewindow.newWindow("detailMail.html#type=isNestedMessage&id="
		+ encodeURIComponent(url["id"])
		+ "&folder="+ encodeURIComponent(url["folder"])
		+ "&sid=" + encodeURIComponent(detailNestedMessage.sid), getWindowOptions(), 
		{ "folder": encodeURIComponent(url["folder"]), "id": encodeURIComponent(detailNestedMessage.sid) });
	detailMail.window.oNestedMessage = detailNestedMessage;
	detailMail.oNestedMessage = detailNestedMessage;
	if (detailMail) {
		detailMail.focus();
	}*/
}

function openAttachment(action) {	
	var selAttach = selectedAttachments[0].data;
    if (action != "SAVE" && (isVcard(selAttach.content_type) || isIcal(selAttach.content_type))) {
        showIcalVcard(selAttach);
        return;
    }
	var tF = $("mail.detail.pop.attachment.save");
	var n_url = AjaxRoot + '/mail'
		 + '?action=' + (action == "SAVE" && 
				 selectedAttachments.length > 1 ? "zip_attachments" : "attachment")
		 + '&session=' + session 
		 + '&folder=' + encodeURIComponent(url["folder"])
		 + '&id=' + encodeURIComponent(url["id"])			 
	if (action == "OPEN") {
		var attachWin = corewindow.newWindow(
			n_url + "&attachment=" + selAttach.id + "&save=0&filter=1",
			getWindowOptions(null, null, "scrollbars=yes"),
			{ "folder": encodeURIComponent(url["folder"]), 
			  "id": encodeURIComponent(url["id"]), 
			  "attach_id": encodeURIComponent(selAttach.id) },
			window);
		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 mail_printDetailMail() {
	corewindow.mail_printDetailMail(detailmessage);
}

function mail_showMailSource() {
	corewindow.oMailFunctions.showMailSource(getMailDetailObject());
}

function callback_error(arg) {
	newServerError(arg);
}

/**
 * unregister from object cache before the window closes
 */
window.onbeforeunload = function() {
	if (detailrequest) { 
		OXCache.unregister(detailrequest.uniqueName);
		detailrequest=null; 
	}
};
