var info = {
    name        : 'Send to',
    description : 'Add context menu option to send current URL to contact',
    version     : '1.0.3',
    author      : 'Massimiliano Mirra <bard [at] hyperstruct [dot] net>',
    license     : 'GPLv2',
    home        : 'http://repo.hyperstruct.net/sameplace/scriptlets/send_to.js'
};

function init() {
    
    addContextSubmenu();
}   

function finish() {
    removeContextSubmenu();
}


// GUI REACTIONS
// ----------------------------------------------------------------------

function selectedContact(event) {
    var account = event.target.getAttribute('account');
    var address = event.target.getAttribute('address');
    var type = isMUC(account, address) ? 'groupchat' : 'normal';

    var node = document.popupNode;
    var url, text;
    if(node.nodeName.toLowerCase() == 'a' && ('href' in node)) {
        url = node.href;
        text = node.textContent.replace(/^\s*/, '').replace(/\s*$/, '');
    } else {
        url = getBrowser().currentURI.spec;
        text = getBrowser().contentDocument.title;
    }

    XMPP.send(account,
              <message to={address} type={type}>
              <body>{url}</body>
              <html xmlns="http://jabber.org/protocol/xhtml-im">
              <body xmlns="http://www.w3.org/1999/xhtml">
              <a href={url}>{text || url}</a>
              </body>
              </html>
              <x xmlns="jabber:x:oob">
              <url>{url}</url>
              </x>
              </message>);
}

function showingPopup(event) {
    const ns_muc = 'http://jabber.org/protocol/muc';
    const ns_muc_user = 'http://jabber.org/protocol/muc#user';
    var xulMenupopup = event.target;

    function makeContactItem(account, address, label) {
        var xulMenuitem = document.createElement('menuitem');
        xulMenuitem.setAttribute('account', account);
        xulMenuitem.setAttribute('address', address);
        xulMenuitem.setAttribute('label', label);
        xulMenuitem.setAttribute('availability', 'available');
        xulMenuitem.setAttribute('class', 'menuitem-iconic xmpp-presence');
        return xulMenuitem;
    }

    // Contacts

    XMPP.cache.fetch({
        event     : 'presence',
        direction : 'in',
        stanza    : function(s) {
            return s.@type == undefined && s.ns_muc_user::x == undefined;
        }
    }).forEach(function(presence) {
        var address = XMPP.JID(presence.stanza.@from).address;
        xulMenupopup.appendChild(makeContactItem(presence.account,
                                                 address,
                                                 XMPP.nickFor(presence.account, address)));
    });

    // Rooms

    XMPP.cache.fetch({
        event     : 'presence',
        direction : 'out',
        stanza    : function(s) {
            return s.ns_muc::x != undefined; // && s.@type == undefined ?
        }
    }).forEach(function(presence) {
        var address = XMPP.JID(presence.stanza.@to).address;
        xulMenupopup.appendChild(makeContactItem(presence.account,
                                                 address,
                                                 address));
    });
}

function hiddenPopup(event) {
    var xulPopup = event.target;
    while(xulPopup.firstChild)
        xulPopup.removeChild(xulPopup.firstChild);
}


// GUI ACTIONS
// ----------------------------------------------------------------------

function addContextSubmenu() {
    if(document.getElementById('sameplace-scriptlet-sendto'))
        return;

    var xulMenu = document.createElement('menu');
    var xulMenupopup = document.createElement('menupopup');

    xulMenu.setAttribute('id', 'sameplace-scriptlet-sendto');
    xulMenu.setAttribute('label', 'Send Link to...');
    xulMenu.setAttribute('accesskey', 'S');
    xulMenu.appendChild(xulMenupopup);

    xulMenupopup.addEventListener('command', function(event) {
        selectedContact(event);
    }, false);

    xulMenupopup.addEventListener('popupshowing', function(event) {
        showingPopup(event);
    }, false);

    xulMenupopup.addEventListener('popuphidden', function(event) {
        hiddenPopup(event);
    }, false);

    document.getElementById('contentAreaContextMenu').appendChild(xulMenu);
}

function removeContextSubmenu() {
    var xulMenu = document.getElementById('sameplace-scriptlet-sendto');
    if(xulMenu)
        xulMenu.parentNode.removeChild(xulMenu);
}


// UTILITIES
// ----------------------------------------------------------------------

function isMUC(account, address) {
    var ns_muc = 'http://jabber.org/protocol/muc';
    var ns_private = 'jabber:iq:private';
    var ns_bookmarks = 'storage:bookmarks';

    function isJoined() {
        return XMPP.cache.fetch({
            event     : 'presence',
            direction : 'out',
            account   : account,
            stanza    : function(s) {
                return (s.@to != undefined &&
                        XMPP.JID(s.@to).address == address &&
                        s.ns_muc::x != undefined);
            }}).length > 0
    }

    function isBookmarked() {
        return XMPP.cache.fetch({
            event     : 'iq',
            direction : 'in',
            account   : account,
            stanza    : function(s) {
                return (s.ns_private::query
                        .ns_bookmarks::storage
                        .ns_bookmarks::conference
                        .(@jid == address) != undefined);
            }}).length > 0;
    }

    return isJoined() || isBookmarked();
}
