register("Loaded", function() {
    var menu = globalContextMenus.attachments = new ContextMenu();
    var open = new MenuItem(_("Open"), function() {
        triggerEvent(menunestedmessage ? "OX_Attachment_Open_Nested"
                                       : "OX_Attachment_Open");
    });
    open.setIcon("img/menu/attachment_open.gif",
                 "img/menu/attachment_open_d.gif");
    menu.addItem(open);
    
    var save = new MenuItem(_("Save as"),
        function() { triggerEvent('OX_Attachment_Save'); });
    save.setIcon("img/menu/attachment_save.gif",
                 "img/menu/attachment_save_d.gif");
    menu.addItem(save);

    var info = new MenuItem(_("Save in InfoStore"),
        function() { triggerEvent('OX_Attachment_SaveInfoStore'); });
    info.setIcon("img/infostore/infostore_save.gif",
                 "img/infostore/infostore_save_d.gif");
    info.disabled_action = function() {
        if (configGetKey("modules.infostore.module")) return false;
        triggerEvent("Feature_Not_Available",
                     "modules/infostore/mail/save_to_infostore");
    };
    menu.addItem(info);
    
    menu.onShow = function() {
        var enabled = !menudisableattachment
                   && menucheckRight("READ");
        open.setEnabled(enabled);
        save.setEnabled(!menudisableattachment
                && menucheckRight("READ") && (activemodule == "mail" || activemodule == "mail_detail"));
        info.setEnabled(enabled && configGetKey("modules.infostore.module"));
    };
    
    ox.api.window.core.triggerEvent("OX_Context_Menu_Ready", window);
});

var mail_message, selectedAttachments = [];

function showIcalVcard(selAttach) { 
    var isIcal = true;
    if (isVcard(selAttach.content_type)) {
        var ds = "com.openexchange.mail.vcard";
        var dh = { identifier: "com.openexchange.contact.json", args: [] };
        isIcal = false;
    } else {
        var ds = "com.openexchange.mail.ical";
        var dh = { identifier: "com.openexchange.ical.json", args: [] };
    }
    var myObject = { datasource: { args: [
        { "com.openexchange.mail.conversion.fullname": mail_message.folder_id },
        { "com.openexchange.mail.conversion.mailid": mail_message.id },
        { "com.openexchange.mail.conversion.sequenceid": selAttach.id } 
    ], identifier: ds }, datahandler: dh };

    (new JSON()).put(AjaxRoot + "/conversion?action=convert&session=" +
        session, myObject, null,
        function (reply) {
            if (!isIcal) {
            	// open contact
            	ox.api.contact.compose({
            		data: reply.data[0]
            	});
            } else {
            	// open appointment
            	var data = {
            		oFromMail: reply.data[0],
                    sFromModule: "calendar"
            	};
            	ox.api.calendar.compose({
        			data: data
        		});
            }      
        }
    );
}

function isIcal(ct) {
    return ct && ct.match(/text\/(x\-)?(calendar|ical)/i); // || ct.match(/application\/(ics)/i);
}
function isVcard(ct) {
    return ct && ct.match(/text\/(x\-)?(vcard)|(directory)/i);
}

function createNewContactfromMail(mailAddressObject,folder) {
	function createContact(module,notneeded,object) {
		// open compose dialog with prefilled fields
		ox.api.contact.compose({
			params: jQuery.extend(object || {}, {
				folder: object.folder_id
			})
		});
//		var addParams = "";
//		for (i in object) {
//			addParams += "&"+i+"="+encodeURIComponent(object[i]);
//		}
//		corewindow.openContactPopup('modul=new&folder='+object.folder_id+addParams,'newContact.html');
	}
    corewindow.rightshandler.checkRights("contacts",(folder || configGetKey("folder.contacts")),mailAddressObject,createContact);
}

/**
 * Parse all <a> links within the node and replace any direct link which maches
 * to the current hostname with a new link to the local infostore.
 * @param ih The document node
 */
var hrefregexp = null;
function parseDirectLinksInMails(ih) {
    hrefregexp = hrefregexp || new RegExp((window.location.protocol+"//"+window.location.host).replace(/^https?:/, "https?:"));
	var ahref = ih.getElementsByTagName("a");
	for (var i=0; i < ahref.length;) {
		var link = ahref[i];		
		if (!link.getAttribute("href")) {
			// no valid href, continue
			i++; 
			continue;
		}
        link.removeAttribute("target");  // clean-up target first
        var module = link.href.match(/[#&]m=([^#&]+)/);
        var folder = link.href.match(/[#&]f=([^#&]+)/);
        var id = link.href.match(/[#&]i=([^#&]+)/);      
        if (link.href.match(hrefregexp) && module && folder) {
           	// ok, seems like we found a direct link pointing to the right ox 
            link.parentNode.insertBefore(newnode("img", { marginRight: "5px"}, { src: getFullImgSrc("img/menu/close_linking.gif"), align: "absmiddle"}, null, (ih.nodeType == 9 ? ih : null)), link);
            link.style.color="red";
            link.style.textDecoration="underline";
            link.style.cursor="pointer";
            link.removeAttribute("href")
            link.onclick = (function(mo, fo, io) {
	   			     return function(e) { 
	   				     parent.corewindow.setTimeout(
	   				         function() { 
	   				            parent.corewindow.triggerEvent("OX_Direct_Linking", mo, {"folder": fo, "id": io}) 
	   				         }, 0);
	   				     if (e) {
	   				     	stopEvent(e);
	   				     }
	   				     return false;
	   			     }
			     })(module[1], folder[1], id && id[1] ? id[1] : null);  
			              
        } else if (link.getAttribute("href").match(new RegExp("^(" + window.location.href + ")?#")) != null) {
            // due to an mozilla bug we run into problems with anchors in dynamic written pages 
            // mozilla doesn't recognize that and try to load the whole page instead
            // using this hack to jump to the anchors manually
            for (var ia=0; ia < ih.anchors.length; ia++) {
                if (link.getAttribute("href").match(new RegExp("^(" + window.location.href + ")?#"+ih.anchors[ia].name))) {
                	link.setAttribute("onclick", "function() { return false; }");                    
                    link.onclick = (function(myDoc, myAnchor) {
                        return function(e) {
                             myAnchor.scrollIntoView(true);
                             return false;
                        }
                    })(ih, ih.anchors[ia]);
                    break;
                }
            }
        } else {
        	// any other links should always open in a new window
        	link.target = "_blank";
        }
      i++;
	}
	corewindow.triggerEvent("ProcessMailContent", ih);
	return ih;
}

function getMailAccountIdByFolder(folder) {	
	var addr = null;
	if (String(folder).match(/^default(\d+)?/) != null) {
		var t = String(folder).match(/^default(\d+)?/)[0];
		addr = t.substring("default".length, t.length);
	}
	return addr;
}

function getMailAccountEmailAddress(id) {
	var addr = null;
	if (corewindow.mail_accounts && corewindow.mail_accounts.data.data[id]) {
		return corewindow.mail_accounts.data.data[id].primary_address;
	}
	return addr;
}

fileloaded();