(function() {

Components.utils.import('resource://livemargins/dao.jsm');
Components.utils.import('resource://livemargins/intent.jsm');
var pie;
var init = function(){
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://app.mozilla.com.cn/center/appintent/?type=text%2F*', true);
    xhr.onload = function(evt) {
        try {
            var intents = JSON.parse(xhr.responseText);
            intents.forEach(function(intent) {
                AppCenterDAO.updateAppIntent(intent);
            });
        } catch(e) {
        }
        refresh();
    };
    xhr.onerror = function(evt) {
    };
    xhr.send();
    if ("arguments" in window && window.arguments[1]) {
        document.querySelector('tabbox').selectedIndex = window.arguments[1];
    }
    document.getElementById('myDefault').addEventListener('command', function() {
        ['app_search',
         '{a09cf36d-abbc-48ed-b0cc-77c650eb164e}',
         '{72600762-7580-43d7-a991-7d05c3eed5ed}',
         '{6e881146-62e9-461d-884a-3e2caf10b0ab}',
         '$app-search-engine$',
         '$app-share-tool$'].forEach(function(action, idx) {
            AppCenterDAO.replaceTextIntent(idx, action);
        });
        refresh();
    }, false);
};
var refresh = function(){
    AppIntent.refreshIntents();
    if (pie) {
        pie.destroy();
    }
    // kind of faking piemenu
    var intents = AppIntent.getIntentsByText(null, null);
    var pieOptions = {
        placeIn: document.querySelector('div.livemargins-bubble-box'),
        radian: 360,
        left: 16,
        top: 16,
        radius: 42,
        items: [],
    };
    intents.forEach(function(i) {
        pieOptions.items.push({
            imgsrc: i.icon,
            tooltip: i.label,
            ondragenter: function(evt) {
                if (evt.dataTransfer.types.contains('application/x-moz-node')) {
                    evt.preventDefault();
                }
            },
            ondragover: function(evt) {
                evt.preventDefault();
            },
            ondragstart: function(evt) {
                evt.currentTarget.setAttribute('data-action', i.action);
                evt.dataTransfer.mozSetDataAt('application/x-moz-node', evt.currentTarget, 0);
                evt.dataTransfer.setData('text/plain', 'needs application/x-moz-node support');
                evt.dataTransfer.setDragImage(evt.currentTarget.querySelector('image'), 8, 8);
            },
            ondrop: function(evt) {
                var node = evt.dataTransfer.mozGetDataAt('application/x-moz-node', 0);
                if (node.hasAttribute('index') && node.getAttribute('index') == evt.currentTarget.getAttribute('index')) {
                    return;
                }
                AppCenterDAO.replaceTextIntent(evt.currentTarget.getAttribute('index'), node.getAttribute('data-action'));
                refresh();
            }
        })
    });
    pie = new PieMenu(pieOptions);
    pie.show();

    // waiting list
    var more = document.getElementById('more');
    more.innerHTML = '';
    // 'text/*' decides display orders for 'text/html' etc.
    var moreIntents = AppCenterDAO.getIntentsByType('text/*');
    moreIntents.splice(0, 6);
    moreIntents.reverse();
    moreIntents.forEach(function(i) {
        var li = document.createElementNS('http://www.w3.org/1999/xhtml', 'li');
        li.setAttribute('draggable', 'true');
        li.setAttribute('data-action', i.action);
        var img = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
        img.setAttribute('src', i.icon);
        li.appendChild(img);
        li.innerHTML += i.labelStr ? AppIntent.localize(i.labelStr) : i.label;
        li.addEventListener('dragstart', function(evt) {
            evt.dataTransfer.mozSetDataAt('application/x-moz-node', evt.currentTarget, 0);
            evt.dataTransfer.setData('text/plain', 'needs application/x-moz-node support');
            evt.dataTransfer.setDragImage(evt.currentTarget.querySelector('img'), 8, 8);
        }, false);
        more.appendChild(li);
    });
}
window.addEventListener('load', init, false);

})();
