// ==UserScript==
// @name del.icio.us display post
// @namespace http://opera.higeorange.com/
// @include http://del.icio.us/*
// ==/UserScript==


(function(){
    var t = location.href.split('/')
    var mwType = (window.opera) ? 'mousewheel' : 'DOMMouseScroll';

    var DelTA = {
        count: 200,
        pageCount: 15,
        page: 0,
        user: document.location.href.split('/')[3].split('?')[0].split('#')[0],
        nTag : (t[4] && t[3] != 'network')? t[4].split('?')[0] : null,
        tag: [],
        cache: {}
    };

    DelTA.createPostList = function(network) {
        if(document.getElementById('postList')) {
            document.body.removeChild(document.getElementById('postList'));
        }
        var tag = DelTA.tag.join('+');
        var scrollY = document.body.scrollTop || document.documentElement.scrollTop;
        var div = document.createElement('div');
            div.id = 'postList';
            div.style.position = 'absolute';
            div.style.top = scrollY + 150 + 'px';
            div.style.left = '5%';
            div.style.width = '40%';
            div.style.background = '#fff';
            div.style.border = '1px solid #000';
            div.style.zIndex = '3000'

        var h3 = document.createElement('h3');
            h3.style.padding = "3px"
            h3.style.background = "#333";
        var ra = document.createElement('a');
            ra.style.color = "#fff";
            ra.style.marginRight = "3px";
            ra.href = "javascript:void(0);"
            ra.addEventListener('click', function(){
                document.body.removeChild(document.getElementById('postList'));
            }, false);
            ra.innerHTML = 'x'
            h3.appendChild(ra);

        var h3a = document.createElement('a');
            h3a.style.color = "#fff";

        if(network) {
            h3a.href = 'http://del.icio.us/' + tag
        } else {
            h3a.href = 'http://del.icio.us/' + this.user + '/' + tag.replace(/\+/g, '%2B');
        }
            h3a.innerHTML = tag.replace(/\+/g, ' + ');
            h3.appendChild(h3a);
            div.appendChild(h3);

        var ul = document.createElement('ul');
            ul.id = 'postListUl'
            ul.style.margin = "5px"
            ul.style.fontSize = "11px"
            div.appendChild(ul);

        var nav = document.createElement('p');
            nav.id = 'navi';
            nav.style.padding = '0 10px';
            div.appendChild(nav);

// To be Draggable, dom-drag.js is needed ( http://www.youngpup.net/2001/domdrag/project )
//        Drag.init(h3, div);

        ul.addEventListener(mwType, function(evt) {
            evt.preventDefault();
            var chk = evt.detail
            if(chk > 0 && DelTA.page < Math.floor(DelTA.cache[tag].length / DelTA.pageCount)) {
                DelTA.page ++;
                DelTA.flipPage(tag, DelTA.page);
            } else if(chk < 0 && DelTA.page > 0){
                DelTA.page --;
                DelTA.flipPage(tag, DelTA.page);
            }
        }, false);
        
        document.body.appendChild(div);

        DelTA.getPostList(tag, network);
        if(DelTA.nTag)
            DelTA.tag = decodeURIComponent(DelTA.nTag).split('+');
    };
    DelTA.flipPage = function (tag, page) {
        var postListHtml = [];
        var postListLength = DelTA.cache[tag].length
        var s = page * DelTA.pageCount;
        var e = s + DelTA.pageCount;
        var len = e > postListLength ? postListLength : e;
        for(var i=s;i<len;i++) {
            postListHtml.push("<li style=\"margin:8px 5px;list-style-type:none;\"><a href=\"" + DelTA.cache[tag][i].u + "\">" + DelTA.cache[tag][i].d + "</a></li>");
        }
        document.getElementById('postListUl').innerHTML = postListHtml.join("");
        document.getElementById('navi').innerHTML = ""
        var prev = function() {
            var pa = document.createElement('a');
            pa.href = "javascript:void(0)";
            pa.addEventListener('click', function() {
                DelTA.page --;
                DelTA.flipPage(tag, DelTA.page)
            }, false);
            pa.innerHTML = "Prev"
            pa.style.marginRight = '5px';
            document.getElementById('navi').appendChild(pa);
        }
        var next = function() {
            var na = document.createElement('a');
            na.href = "javascript:void(0)";
            na.addEventListener('click', function() {
                DelTA.page ++;
                DelTA.flipPage(tag, DelTA.page)
            }, false);
            na.innerHTML = "Next";
            document.getElementById('navi').appendChild(na);
        }
        if(e <= DelTA.pageCount && postListLength > DelTA.pageCount) {
            next();
        } else if (e > DelTA.pageCount && e < postListLength) {
            prev();
            next();
        } else if (e >= postListLength && DelTA.pageCount < postListLength) {
            prev();
        }
    };
    DelTA.getPostList = function (tag, network) {
        DelTA.page = 0;
        var url;
        if(DelTA.cache[tag]) {
            DelTA.flipPage(tag, DelTA.page);
        } else {
            if(network)
                url = 'http://del.icio.us/feeds/json/' + tag + '?count=' + DelTA.count;
            else
                url = 'http://del.icio.us/feeds/json/' + this.user + '/' + encodeURIComponent(tag) + '?count=' + DelTA.count;
            var request = new XMLHttpRequest();
            request.open('GET', url);
            request.send("");
            request.onreadystatechange = function () {
                if(request.readyState == 4) {
                    eval(request.responseText);
                    DelTA.cache[tag] = [];
                    for(var i=0,len=Delicious.posts.length;i<len;i++) {
                        var post = {};
                        post.u = Delicious.posts[i].u;
                        post.d = Delicious.posts[i].d;
                        DelTA.cache[tag].push(post);
                    }
                    DelTA.flipPage(tag, DelTA.page);
                }
            }
        }
    };
    if(t[3] == 'network') {
        var networks = document.evaluate(
            '//div[@id="sidebar"]/div[@class="sidebar-inner"]/ul[@class="bundles"]/li[@class="bundle fold"]/ul/li',
            document,
            null,
            XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
            null);

        for(var i=0,len=networks.snapshotLength;i<len;i++) {
            var nwAnc = networks.snapshotItem(i).getElementsByTagName('a')[0];
            if(nwAnc) {
                nwAnc.href = "javascript:void(0)";
                nwAnc.addEventListener('click', function() {
                    DelTA.tag = [];
                    DelTA.tag.push(this.innerHTML);
                    DelTA.check = true;
                    DelTA.createPostList(1);
                }, false);
            }
        }
    } else {
        var tags = document.evaluate(
            '//div[@id="sidebar"]/div[@class="sidebar-inner"]/ul[@class="bundles"]/li[@class="bundle fold"]/ul/li',
            document,
            null,
            XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
            null);

        DelTA.plusTag = [];
        for(var i=0,len=tags.snapshotLength;i<len;i++) {
            var tagAnc = tags.snapshotItem(i).getElementsByTagName('a')[0];
            tagAnc.href = "javascript:void(0)";
            if(tags.snapshotItem(i).getElementsByTagName('a')[1]) {
                var multiTagAnc = tags.snapshotItem(i).getElementsByTagName('a')[1];
                multiTagAnc.href = "javascript:void(0)";
                multiTagAnc.addEventListener('click', function() {
                    DelTA.tag = [];
                    DelTA.tag.push(this.innerHTML);
                    DelTA.check = false;
                    DelTA.createPostList(0);
                }, false);
                tagAnc.id = i;
                DelTA.plusTag.push(multiTagAnc.innerHTML);
            }
            tagAnc.addEventListener('click', function() {
                if(!this.id) {
                    DelTA.tag = [];
                    DelTA.tag.push(this.innerHTML);
                    DelTA.check = false;
                } else {
                    if(DelTA.check && DelTA.tag.length == 0)
                        DelTA.tag.pop();
                    DelTA.tag.push(DelTA.plusTag[this.id]);
                    DelTA.check = true;
                }
                DelTA.createPostList(0);
            }, false);
        }
        if(document.getElementById('related-sidebar')) {
            DelTA.plusTag = [];
            var relTags = document.evaluate(
                '//div[@id="related-sidebar"]/div[@class="sidebar-inner"]/ul[@class="bundles"]/li[@class="bundle fold"]/ul/li',
                document,
                null,
                XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
                 null);

            for(var i=0,len=relTags.snapshotLength;i<len;i++) {
                var relTagAnc = relTags.snapshotItem(i).getElementsByTagName('a')[0];
                var relMultiTagAnc = relTags.snapshotItem(i).getElementsByTagName('a')[1];
                relTagAnc.id = i;
                DelTA.plusTag.push(relMultiTagAnc.innerHTML);
                relTagAnc.href = "javascript:void(0)";
                relTagAnc.addEventListener('click', function() {
                    if(DelTA.check && DelTA.tag.length == 0)
                        DelTA.tag.pop();
                    DelTA.tag.push(DelTA.plusTag[this.id]);
                    DelTA.check = true;
                    DelTA.createPostList(0);
                }, false);
                relMultiTagAnc.href = "javascript:void(0)";
                relMultiTagAnc.addEventListener('click', function() {
                    DelTA.tag = [];
                    DelTA.tag.push(this.innerHTML);
                    DelTA.check = false;
                    DelTA.createPostList(0);
                }, false);
            }
        }
    }
})();
